llvm-mc: Make sure we exit != 0 if any errors are encountered.
[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/SmallString.h"
15 #include "llvm/ADT/StringMap.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCParser/AsmCond.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
26 #include "llvm/MC/MCSectionMachO.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCDwarf.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetAsmParser.h"
35 #include <vector>
36 using namespace llvm;
37
38 namespace {
39
40 /// \brief Helper class for tracking macro definitions.
41 struct Macro {
42   StringRef Name;
43   StringRef Body;
44
45 public:
46   Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
47 };
48
49 /// \brief Helper class for storing information about an active macro
50 /// instantiation.
51 struct MacroInstantiation {
52   /// The macro being instantiated.
53   const Macro *TheMacro;
54
55   /// The macro instantiation with substitutions.
56   MemoryBuffer *Instantiation;
57
58   /// The location of the instantiation.
59   SMLoc InstantiationLoc;
60
61   /// The location where parsing should resume upon instantiation completion.
62   SMLoc ExitLoc;
63
64 public:
65   MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
66                      const std::vector<std::vector<AsmToken> > &A);
67 };
68
69 /// \brief The concrete assembly parser instance.
70 class AsmParser : public MCAsmParser {
71   friend class GenericAsmParser;
72
73   AsmParser(const AsmParser &);   // DO NOT IMPLEMENT
74   void operator=(const AsmParser &);  // DO NOT IMPLEMENT
75 private:
76   AsmLexer Lexer;
77   MCContext &Ctx;
78   MCStreamer &Out;
79   SourceMgr &SrcMgr;
80   MCAsmParserExtension *GenericParser;
81   MCAsmParserExtension *PlatformParser;
82
83   /// This is the current buffer index we're lexing from as managed by the
84   /// SourceMgr object.
85   int CurBuffer;
86
87   AsmCond TheCondState;
88   std::vector<AsmCond> TheCondStack;
89
90   /// DirectiveMap - This is a table handlers for directives.  Each handler is
91   /// invoked after the directive identifier is read and is responsible for
92   /// parsing and validating the rest of the directive.  The handler is passed
93   /// in the directive name and the location of the directive keyword.
94   StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
95
96   /// MacroMap - Map of currently defined macros.
97   StringMap<Macro*> MacroMap;
98
99   /// ActiveMacros - Stack of active macro instantiations.
100   std::vector<MacroInstantiation*> ActiveMacros;
101
102   /// Boolean tracking whether macro substitution is enabled.
103   unsigned MacrosEnabled : 1;
104
105   /// Flag tracking whether any errors have been encountered.
106   unsigned HadError : 1;
107
108 public:
109   AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
110             const MCAsmInfo &MAI);
111   ~AsmParser();
112
113   virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
114
115   void AddDirectiveHandler(MCAsmParserExtension *Object,
116                            StringRef Directive,
117                            DirectiveHandler Handler) {
118     DirectiveMap[Directive] = std::make_pair(Object, Handler);
119   }
120
121 public:
122   /// @name MCAsmParser Interface
123   /// {
124
125   virtual SourceMgr &getSourceManager() { return SrcMgr; }
126   virtual MCAsmLexer &getLexer() { return Lexer; }
127   virtual MCContext &getContext() { return Ctx; }
128   virtual MCStreamer &getStreamer() { return Out; }
129
130   virtual void Warning(SMLoc L, const Twine &Meg);
131   virtual bool Error(SMLoc L, const Twine &Msg);
132
133   const AsmToken &Lex();
134
135   bool ParseExpression(const MCExpr *&Res);
136   virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
137   virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
138   virtual bool ParseAbsoluteExpression(int64_t &Res);
139
140   /// }
141
142 private:
143   bool ParseStatement();
144
145   bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
146   void HandleMacroExit();
147
148   void PrintMacroInstantiations();
149   void PrintMessage(SMLoc Loc, const std::string &Msg, const char *Type) const;
150     
151   /// EnterIncludeFile - Enter the specified file. This returns true on failure.
152   bool EnterIncludeFile(const std::string &Filename);
153
154   /// \brief Reset the current lexer position to that given by \arg Loc. The
155   /// current token is not set; clients should ensure Lex() is called
156   /// subsequently.
157   void JumpToLoc(SMLoc Loc);
158
159   void EatToEndOfStatement();
160
161   /// \brief Parse up to the end of statement and a return the contents from the
162   /// current token until the end of the statement; the current token on exit
163   /// will be either the EndOfStatement or EOF.
164   StringRef ParseStringToEndOfStatement();
165
166   bool ParseAssignment(StringRef Name);
167
168   bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
169   bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
170   bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
171
172   /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
173   /// and set \arg Res to the identifier contents.
174   bool ParseIdentifier(StringRef &Res);
175   
176   // Directive Parsing.
177   bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
178   bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
179   bool ParseDirectiveFill(); // ".fill"
180   bool ParseDirectiveSpace(); // ".space"
181   bool ParseDirectiveSet(); // ".set"
182   bool ParseDirectiveOrg(); // ".org"
183   // ".align{,32}", ".p2align{,w,l}"
184   bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
185
186   /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
187   /// accepts a single symbol (which should be a label or an external).
188   bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
189   bool ParseDirectiveELFType(); // ELF specific ".type"
190
191   bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
192
193   bool ParseDirectiveAbort(); // ".abort"
194   bool ParseDirectiveInclude(); // ".include"
195
196   bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
197   bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
198   bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
199   bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
200
201   /// ParseEscapedString - Parse the current token as a string which may include
202   /// escaped characters and return the string contents.
203   bool ParseEscapedString(std::string &Data);
204 };
205
206 /// \brief Generic implementations of directive handling, etc. which is shared
207 /// (or the default, at least) for all assembler parser.
208 class GenericAsmParser : public MCAsmParserExtension {
209   template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
210   void AddDirectiveHandler(StringRef Directive) {
211     getParser().AddDirectiveHandler(this, Directive,
212                                     HandleDirective<GenericAsmParser, Handler>);
213   }
214
215 public:
216   GenericAsmParser() {}
217
218   AsmParser &getParser() {
219     return (AsmParser&) this->MCAsmParserExtension::getParser();
220   }
221
222   virtual void Initialize(MCAsmParser &Parser) {
223     // Call the base implementation.
224     this->MCAsmParserExtension::Initialize(Parser);
225
226     // Debugging directives.
227     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
228     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
229     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
230
231     // Macro directives.
232     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
233       ".macros_on");
234     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
235       ".macros_off");
236     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
237     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
238     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
239   }
240
241   bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
242   bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
243   bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
244
245   bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
246   bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
247   bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
248 };
249
250 }
251
252 namespace llvm {
253
254 extern MCAsmParserExtension *createDarwinAsmParser();
255 extern MCAsmParserExtension *createELFAsmParser();
256
257 }
258
259 enum { DEFAULT_ADDRSPACE = 0 };
260
261 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
262                      MCStreamer &_Out, const MCAsmInfo &_MAI)
263   : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
264     GenericParser(new GenericAsmParser), PlatformParser(0),
265     CurBuffer(0), MacrosEnabled(true) {
266   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
267
268   // Initialize the generic parser.
269   GenericParser->Initialize(*this);
270
271   // Initialize the platform / file format parser.
272   //
273   // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
274   // created.
275   if (_MAI.hasSubsectionsViaSymbols()) {
276     PlatformParser = createDarwinAsmParser();
277     PlatformParser->Initialize(*this);
278   } else {
279     PlatformParser = createELFAsmParser();
280     PlatformParser->Initialize(*this);
281   }
282 }
283
284 AsmParser::~AsmParser() {
285   assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
286
287   // Destroy any macros.
288   for (StringMap<Macro*>::iterator it = MacroMap.begin(),
289          ie = MacroMap.end(); it != ie; ++it)
290     delete it->getValue();
291
292   delete PlatformParser;
293   delete GenericParser;
294 }
295
296 void AsmParser::PrintMacroInstantiations() {
297   // Print the active macro instantiation stack.
298   for (std::vector<MacroInstantiation*>::const_reverse_iterator
299          it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
300     PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
301                  "note");
302 }
303
304 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
305   PrintMessage(L, Msg.str(), "warning");
306   PrintMacroInstantiations();
307 }
308
309 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
310   HadError = true;
311   PrintMessage(L, Msg.str(), "error");
312   PrintMacroInstantiations();
313   return true;
314 }
315
316 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg, 
317                              const char *Type) const {
318   SrcMgr.PrintMessage(Loc, Msg, Type);
319 }
320                   
321 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
322   int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
323   if (NewBuf == -1)
324     return true;
325   
326   CurBuffer = NewBuf;
327   
328   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
329   
330   return false;
331 }
332
333 void AsmParser::JumpToLoc(SMLoc Loc) {
334   CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
335   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
336 }
337
338 const AsmToken &AsmParser::Lex() {
339   const AsmToken *tok = &Lexer.Lex();
340   
341   if (tok->is(AsmToken::Eof)) {
342     // If this is the end of an included file, pop the parent file off the
343     // include stack.
344     SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
345     if (ParentIncludeLoc != SMLoc()) {
346       JumpToLoc(ParentIncludeLoc);
347       tok = &Lexer.Lex();
348     }
349   }
350     
351   if (tok->is(AsmToken::Error))
352     Error(Lexer.getErrLoc(), Lexer.getErr());
353   
354   return *tok;
355 }
356
357 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
358   // Create the initial section, if requested.
359   //
360   // FIXME: Target hook & command line option for initial section.
361   if (!NoInitialTextSection)
362     Out.SwitchSection(Ctx.getMachOSection("__TEXT", "__text",
363                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
364                                       0, SectionKind::getText()));
365
366   // Prime the lexer.
367   Lex();
368
369   HadError = false;
370   AsmCond StartingCondState = TheCondState;
371
372   // While we have input, parse each statement.
373   while (Lexer.isNot(AsmToken::Eof)) {
374     if (!ParseStatement()) continue;
375   
376     // We had an error, validate that one was emitted and recover by skipping to
377     // the next line.
378     assert(HadError && "Parse statement returned an error, but none emitted!");
379     EatToEndOfStatement();
380   }
381
382   if (TheCondState.TheCond != StartingCondState.TheCond ||
383       TheCondState.Ignore != StartingCondState.Ignore)
384     return TokError("unmatched .ifs or .elses");
385
386   // Check to see there are no empty DwarfFile slots.
387   const std::vector<MCDwarfFile *> &MCDwarfFiles =
388     getContext().getMCDwarfFiles();
389   for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
390     if (!MCDwarfFiles[i])
391       TokError("unassigned file number: " + Twine(i) + " for .file directives");
392   }
393   
394   // Finalize the output stream if there are no errors and if the client wants
395   // us to.
396   if (!HadError && !NoFinalize)  
397     Out.Finish();
398
399   return HadError;
400 }
401
402 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
403 void AsmParser::EatToEndOfStatement() {
404   while (Lexer.isNot(AsmToken::EndOfStatement) &&
405          Lexer.isNot(AsmToken::Eof))
406     Lex();
407   
408   // Eat EOL.
409   if (Lexer.is(AsmToken::EndOfStatement))
410     Lex();
411 }
412
413 StringRef AsmParser::ParseStringToEndOfStatement() {
414   const char *Start = getTok().getLoc().getPointer();
415
416   while (Lexer.isNot(AsmToken::EndOfStatement) &&
417          Lexer.isNot(AsmToken::Eof))
418     Lex();
419
420   const char *End = getTok().getLoc().getPointer();
421   return StringRef(Start, End - Start);
422 }
423
424 /// ParseParenExpr - Parse a paren expression and return it.
425 /// NOTE: This assumes the leading '(' has already been consumed.
426 ///
427 /// parenexpr ::= expr)
428 ///
429 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
430   if (ParseExpression(Res)) return true;
431   if (Lexer.isNot(AsmToken::RParen))
432     return TokError("expected ')' in parentheses expression");
433   EndLoc = Lexer.getLoc();
434   Lex();
435   return false;
436 }
437
438 /// ParsePrimaryExpr - Parse a primary expression and return it.
439 ///  primaryexpr ::= (parenexpr
440 ///  primaryexpr ::= symbol
441 ///  primaryexpr ::= number
442 ///  primaryexpr ::= '.'
443 ///  primaryexpr ::= ~,+,- primaryexpr
444 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
445   switch (Lexer.getKind()) {
446   default:
447     return TokError("unknown token in expression");
448   case AsmToken::Exclaim:
449     Lex(); // Eat the operator.
450     if (ParsePrimaryExpr(Res, EndLoc))
451       return true;
452     Res = MCUnaryExpr::CreateLNot(Res, getContext());
453     return false;
454   case AsmToken::Dollar:
455   case AsmToken::String:
456   case AsmToken::Identifier: {
457     EndLoc = Lexer.getLoc();
458
459     StringRef Identifier;
460     if (ParseIdentifier(Identifier))
461       return false;
462
463     // This is a symbol reference.
464     std::pair<StringRef, StringRef> Split = Identifier.split('@');
465     MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
466
467     // Mark the symbol as used in an expression.
468     Sym->setUsedInExpr(true);
469
470     // Lookup the symbol variant if used.
471     MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
472     if (Split.first.size() != Identifier.size())
473       Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
474
475     // If this is an absolute variable reference, substitute it now to preserve
476     // semantics in the face of reassignment.
477     if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
478       if (Variant)
479         return Error(EndLoc, "unexpected modified on variable reference");
480
481       Res = Sym->getVariableValue();
482       return false;
483     }
484
485     // Otherwise create a symbol ref.
486     Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
487     return false;
488   }
489   case AsmToken::Integer: {
490     SMLoc Loc = getTok().getLoc();
491     int64_t IntVal = getTok().getIntVal();
492     Res = MCConstantExpr::Create(IntVal, getContext());
493     EndLoc = Lexer.getLoc();
494     Lex(); // Eat token.
495     // Look for 'b' or 'f' following an Integer as a directional label
496     if (Lexer.getKind() == AsmToken::Identifier) {
497       StringRef IDVal = getTok().getString();
498       if (IDVal == "f" || IDVal == "b"){
499         MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
500                                                       IDVal == "f" ? 1 : 0);
501         Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
502                                       getContext());
503         if(IDVal == "b" && Sym->isUndefined())
504           return Error(Loc, "invalid reference to undefined symbol");
505         EndLoc = Lexer.getLoc();
506         Lex(); // Eat identifier.
507       }
508     }
509     return false;
510   }
511   case AsmToken::Dot: {
512     // This is a '.' reference, which references the current PC.  Emit a
513     // temporary label to the streamer and refer to it.
514     MCSymbol *Sym = Ctx.CreateTempSymbol();
515     Out.EmitLabel(Sym);
516     Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
517     EndLoc = Lexer.getLoc();
518     Lex(); // Eat identifier.
519     return false;
520   }
521       
522   case AsmToken::LParen:
523     Lex(); // Eat the '('.
524     return ParseParenExpr(Res, EndLoc);
525   case AsmToken::Minus:
526     Lex(); // Eat the operator.
527     if (ParsePrimaryExpr(Res, EndLoc))
528       return true;
529     Res = MCUnaryExpr::CreateMinus(Res, getContext());
530     return false;
531   case AsmToken::Plus:
532     Lex(); // Eat the operator.
533     if (ParsePrimaryExpr(Res, EndLoc))
534       return true;
535     Res = MCUnaryExpr::CreatePlus(Res, getContext());
536     return false;
537   case AsmToken::Tilde:
538     Lex(); // Eat the operator.
539     if (ParsePrimaryExpr(Res, EndLoc))
540       return true;
541     Res = MCUnaryExpr::CreateNot(Res, getContext());
542     return false;
543   }
544 }
545
546 bool AsmParser::ParseExpression(const MCExpr *&Res) {
547   SMLoc EndLoc;
548   return ParseExpression(Res, EndLoc);
549 }
550
551 /// ParseExpression - Parse an expression and return it.
552 /// 
553 ///  expr ::= expr +,- expr          -> lowest.
554 ///  expr ::= expr |,^,&,! expr      -> middle.
555 ///  expr ::= expr *,/,%,<<,>> expr  -> highest.
556 ///  expr ::= primaryexpr
557 ///
558 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
559   // Parse the expression.
560   Res = 0;
561   if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
562     return true;
563
564   // Try to constant fold it up front, if possible.
565   int64_t Value;
566   if (Res->EvaluateAsAbsolute(Value))
567     Res = MCConstantExpr::Create(Value, getContext());
568
569   return false;
570 }
571
572 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
573   Res = 0;
574   return ParseParenExpr(Res, EndLoc) ||
575          ParseBinOpRHS(1, Res, EndLoc);
576 }
577
578 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
579   const MCExpr *Expr;
580   
581   SMLoc StartLoc = Lexer.getLoc();
582   if (ParseExpression(Expr))
583     return true;
584
585   if (!Expr->EvaluateAsAbsolute(Res))
586     return Error(StartLoc, "expected absolute expression");
587
588   return false;
589 }
590
591 static unsigned getBinOpPrecedence(AsmToken::TokenKind K, 
592                                    MCBinaryExpr::Opcode &Kind) {
593   switch (K) {
594   default:
595     return 0;    // not a binop.
596
597     // Lowest Precedence: &&, ||
598   case AsmToken::AmpAmp:
599     Kind = MCBinaryExpr::LAnd;
600     return 1;
601   case AsmToken::PipePipe:
602     Kind = MCBinaryExpr::LOr;
603     return 1;
604
605     // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
606   case AsmToken::Plus:
607     Kind = MCBinaryExpr::Add;
608     return 2;
609   case AsmToken::Minus:
610     Kind = MCBinaryExpr::Sub;
611     return 2;
612   case AsmToken::EqualEqual:
613     Kind = MCBinaryExpr::EQ;
614     return 2;
615   case AsmToken::ExclaimEqual:
616   case AsmToken::LessGreater:
617     Kind = MCBinaryExpr::NE;
618     return 2;
619   case AsmToken::Less:
620     Kind = MCBinaryExpr::LT;
621     return 2;
622   case AsmToken::LessEqual:
623     Kind = MCBinaryExpr::LTE;
624     return 2;
625   case AsmToken::Greater:
626     Kind = MCBinaryExpr::GT;
627     return 2;
628   case AsmToken::GreaterEqual:
629     Kind = MCBinaryExpr::GTE;
630     return 2;
631
632     // Intermediate Precedence: |, &, ^
633     //
634     // FIXME: gas seems to support '!' as an infix operator?
635   case AsmToken::Pipe:
636     Kind = MCBinaryExpr::Or;
637     return 3;
638   case AsmToken::Caret:
639     Kind = MCBinaryExpr::Xor;
640     return 3;
641   case AsmToken::Amp:
642     Kind = MCBinaryExpr::And;
643     return 3;
644
645     // Highest Precedence: *, /, %, <<, >>
646   case AsmToken::Star:
647     Kind = MCBinaryExpr::Mul;
648     return 4;
649   case AsmToken::Slash:
650     Kind = MCBinaryExpr::Div;
651     return 4;
652   case AsmToken::Percent:
653     Kind = MCBinaryExpr::Mod;
654     return 4;
655   case AsmToken::LessLess:
656     Kind = MCBinaryExpr::Shl;
657     return 4;
658   case AsmToken::GreaterGreater:
659     Kind = MCBinaryExpr::Shr;
660     return 4;
661   }
662 }
663
664
665 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
666 /// Res contains the LHS of the expression on input.
667 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
668                               SMLoc &EndLoc) {
669   while (1) {
670     MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
671     unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
672     
673     // If the next token is lower precedence than we are allowed to eat, return
674     // successfully with what we ate already.
675     if (TokPrec < Precedence)
676       return false;
677     
678     Lex();
679     
680     // Eat the next primary expression.
681     const MCExpr *RHS;
682     if (ParsePrimaryExpr(RHS, EndLoc)) return true;
683     
684     // If BinOp binds less tightly with RHS than the operator after RHS, let
685     // the pending operator take RHS as its LHS.
686     MCBinaryExpr::Opcode Dummy;
687     unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
688     if (TokPrec < NextTokPrec) {
689       if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
690     }
691
692     // Merge LHS and RHS according to operator.
693     Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
694   }
695 }
696
697   
698   
699   
700 /// ParseStatement:
701 ///   ::= EndOfStatement
702 ///   ::= Label* Directive ...Operands... EndOfStatement
703 ///   ::= Label* Identifier OperandList* EndOfStatement
704 bool AsmParser::ParseStatement() {
705   if (Lexer.is(AsmToken::EndOfStatement)) {
706     Out.AddBlankLine();
707     Lex();
708     return false;
709   }
710
711   // Statements always start with an identifier.
712   AsmToken ID = getTok();
713   SMLoc IDLoc = ID.getLoc();
714   StringRef IDVal;
715   int64_t LocalLabelVal = -1;
716   // GUESS allow an integer followed by a ':' as a directional local label
717   if (Lexer.is(AsmToken::Integer)) {
718     LocalLabelVal = getTok().getIntVal();
719     if (LocalLabelVal < 0) {
720       if (!TheCondState.Ignore)
721         return TokError("unexpected token at start of statement");
722       IDVal = "";
723     }
724     else {
725       IDVal = getTok().getString();
726       Lex(); // Consume the integer token to be used as an identifier token.
727       if (Lexer.getKind() != AsmToken::Colon) {
728         if (!TheCondState.Ignore)
729           return TokError("unexpected token at start of statement");
730       }
731     }
732   }
733   else if (ParseIdentifier(IDVal)) {
734     if (!TheCondState.Ignore)
735       return TokError("unexpected token at start of statement");
736     IDVal = "";
737   }
738
739   // Handle conditional assembly here before checking for skipping.  We
740   // have to do this so that .endif isn't skipped in a ".if 0" block for
741   // example.
742   if (IDVal == ".if")
743     return ParseDirectiveIf(IDLoc);
744   if (IDVal == ".elseif")
745     return ParseDirectiveElseIf(IDLoc);
746   if (IDVal == ".else")
747     return ParseDirectiveElse(IDLoc);
748   if (IDVal == ".endif")
749     return ParseDirectiveEndIf(IDLoc);
750     
751   // If we are in a ".if 0" block, ignore this statement.
752   if (TheCondState.Ignore) {
753     EatToEndOfStatement();
754     return false;
755   }
756   
757   // FIXME: Recurse on local labels?
758
759   // See what kind of statement we have.
760   switch (Lexer.getKind()) {
761   case AsmToken::Colon: {
762     // identifier ':'   -> Label.
763     Lex();
764
765     // Diagnose attempt to use a variable as a label.
766     //
767     // FIXME: Diagnostics. Note the location of the definition as a label.
768     // FIXME: This doesn't diagnose assignment to a symbol which has been
769     // implicitly marked as external.
770     MCSymbol *Sym;
771     if (LocalLabelVal == -1)
772       Sym = getContext().GetOrCreateSymbol(IDVal);
773     else
774       Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
775     if (!Sym->isUndefined() || Sym->isVariable())
776       return Error(IDLoc, "invalid symbol redefinition");
777     
778     // Emit the label.
779     Out.EmitLabel(Sym);
780    
781     // Consume any end of statement token, if present, to avoid spurious
782     // AddBlankLine calls().
783     if (Lexer.is(AsmToken::EndOfStatement)) {
784       Lex();
785       if (Lexer.is(AsmToken::Eof))
786         return false;
787     }
788
789     return ParseStatement();
790   }
791
792   case AsmToken::Equal:
793     // identifier '=' ... -> assignment statement
794     Lex();
795
796     return ParseAssignment(IDVal);
797
798   default: // Normal instruction or directive.
799     break;
800   }
801
802   // If macros are enabled, check to see if this is a macro instantiation.
803   if (MacrosEnabled)
804     if (const Macro *M = MacroMap.lookup(IDVal))
805       return HandleMacroEntry(IDVal, IDLoc, M);
806
807   // Otherwise, we have a normal instruction or directive.  
808   if (IDVal[0] == '.') {
809     // Assembler features
810     if (IDVal == ".set")
811       return ParseDirectiveSet();
812
813     // Data directives
814
815     if (IDVal == ".ascii")
816       return ParseDirectiveAscii(false);
817     if (IDVal == ".asciz")
818       return ParseDirectiveAscii(true);
819
820     if (IDVal == ".byte")
821       return ParseDirectiveValue(1);
822     if (IDVal == ".short")
823       return ParseDirectiveValue(2);
824     if (IDVal == ".long")
825       return ParseDirectiveValue(4);
826     if (IDVal == ".quad")
827       return ParseDirectiveValue(8);
828
829     if (IDVal == ".align") {
830       bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
831       return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
832     }
833     if (IDVal == ".align32") {
834       bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
835       return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
836     }
837     if (IDVal == ".balign")
838       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
839     if (IDVal == ".balignw")
840       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
841     if (IDVal == ".balignl")
842       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
843     if (IDVal == ".p2align")
844       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
845     if (IDVal == ".p2alignw")
846       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
847     if (IDVal == ".p2alignl")
848       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
849
850     if (IDVal == ".org")
851       return ParseDirectiveOrg();
852
853     if (IDVal == ".fill")
854       return ParseDirectiveFill();
855     if (IDVal == ".space")
856       return ParseDirectiveSpace();
857
858     // Symbol attribute directives
859
860     if (IDVal == ".globl" || IDVal == ".global")
861       return ParseDirectiveSymbolAttribute(MCSA_Global);
862     if (IDVal == ".hidden")
863       return ParseDirectiveSymbolAttribute(MCSA_Hidden);
864     if (IDVal == ".indirect_symbol")
865       return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
866     if (IDVal == ".internal")
867       return ParseDirectiveSymbolAttribute(MCSA_Internal);
868     if (IDVal == ".lazy_reference")
869       return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
870     if (IDVal == ".no_dead_strip")
871       return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
872     if (IDVal == ".private_extern")
873       return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
874     if (IDVal == ".protected")
875       return ParseDirectiveSymbolAttribute(MCSA_Protected);
876     if (IDVal == ".reference")
877       return ParseDirectiveSymbolAttribute(MCSA_Reference);
878     if (IDVal == ".type")
879       return ParseDirectiveELFType();
880     if (IDVal == ".weak")
881       return ParseDirectiveSymbolAttribute(MCSA_Weak);
882     if (IDVal == ".weak_definition")
883       return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
884     if (IDVal == ".weak_reference")
885       return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
886     if (IDVal == ".weak_def_can_be_hidden")
887       return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
888
889     if (IDVal == ".comm")
890       return ParseDirectiveComm(/*IsLocal=*/false);
891     if (IDVal == ".lcomm")
892       return ParseDirectiveComm(/*IsLocal=*/true);
893
894     if (IDVal == ".abort")
895       return ParseDirectiveAbort();
896     if (IDVal == ".include")
897       return ParseDirectiveInclude();
898
899     // Look up the handler in the handler table.
900     std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
901       DirectiveMap.lookup(IDVal);
902     if (Handler.first)
903       return (*Handler.second)(Handler.first, IDVal, IDLoc);
904
905     // Target hook for parsing target specific directives.
906     if (!getTargetParser().ParseDirective(ID))
907       return false;
908
909     Warning(IDLoc, "ignoring directive for now");
910     EatToEndOfStatement();
911     return false;
912   }
913
914   // Canonicalize the opcode to lower case.
915   SmallString<128> Opcode;
916   for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
917     Opcode.push_back(tolower(IDVal[i]));
918   
919   SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
920   bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
921                                                      ParsedOperands);
922
923   // Dump the parsed representation, if requested.
924   if (getShowParsedOperands()) {
925     SmallString<256> Str;
926     raw_svector_ostream OS(Str);
927     OS << "parsed instruction: [";
928     for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
929       if (i != 0)
930         OS << ", ";
931       ParsedOperands[i]->dump(OS);
932     }
933     OS << "]";
934
935     PrintMessage(IDLoc, OS.str(), "note");
936   }
937
938   // If parsing succeeded, match the instruction.
939   if (!HadError) {
940     MCInst Inst;
941     if (!getTargetParser().MatchInstruction(IDLoc, ParsedOperands, Inst)) {
942       // Emit the instruction on success.
943       Out.EmitInstruction(Inst);
944     } else
945       HadError = true;
946   }
947
948   // Free any parsed operands.
949   for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
950     delete ParsedOperands[i];
951
952   return HadError;
953 }
954
955 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
956                                    const std::vector<std::vector<AsmToken> > &A)
957   : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
958 {
959   // Macro instantiation is lexical, unfortunately. We construct a new buffer
960   // to hold the macro body with substitutions.
961   SmallString<256> Buf;
962   raw_svector_ostream OS(Buf);
963
964   StringRef Body = M->Body;
965   while (!Body.empty()) {
966     // Scan for the next substitution.
967     std::size_t End = Body.size(), Pos = 0;
968     for (; Pos != End; ++Pos) {
969       // Check for a substitution or escape.
970       if (Body[Pos] != '$' || Pos + 1 == End)
971         continue;
972
973       char Next = Body[Pos + 1];
974       if (Next == '$' || Next == 'n' || isdigit(Next))
975         break;
976     }
977
978     // Add the prefix.
979     OS << Body.slice(0, Pos);
980
981     // Check if we reached the end.
982     if (Pos == End)
983       break;
984
985     switch (Body[Pos+1]) {
986        // $$ => $
987     case '$':
988       OS << '$';
989       break;
990
991       // $n => number of arguments
992     case 'n':
993       OS << A.size();
994       break;
995
996        // $[0-9] => argument
997     default: {
998       // Missing arguments are ignored.
999       unsigned Index = Body[Pos+1] - '0';
1000       if (Index >= A.size())
1001         break;
1002
1003       // Otherwise substitute with the token values, with spaces eliminated.
1004       for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1005              ie = A[Index].end(); it != ie; ++it)
1006         OS << it->getString();
1007       break;
1008     }
1009     }
1010
1011     // Update the scan point.
1012     Body = Body.substr(Pos + 2);
1013   }
1014
1015   // We include the .endmacro in the buffer as our queue to exit the macro
1016   // instantiation.
1017   OS << ".endmacro\n";
1018
1019   Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1020 }
1021
1022 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1023                                  const Macro *M) {
1024   // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1025   // this, although we should protect against infinite loops.
1026   if (ActiveMacros.size() == 20)
1027     return TokError("macros cannot be nested more than 20 levels deep");
1028
1029   // Parse the macro instantiation arguments.
1030   std::vector<std::vector<AsmToken> > MacroArguments;
1031   MacroArguments.push_back(std::vector<AsmToken>());
1032   unsigned ParenLevel = 0;
1033   for (;;) {
1034     if (Lexer.is(AsmToken::Eof))
1035       return TokError("unexpected token in macro instantiation");
1036     if (Lexer.is(AsmToken::EndOfStatement))
1037       break;
1038
1039     // If we aren't inside parentheses and this is a comma, start a new token
1040     // list.
1041     if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1042       MacroArguments.push_back(std::vector<AsmToken>());
1043     } else {
1044       // Adjust the current parentheses level.
1045       if (Lexer.is(AsmToken::LParen))
1046         ++ParenLevel;
1047       else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1048         --ParenLevel;
1049
1050       // Append the token to the current argument list.
1051       MacroArguments.back().push_back(getTok());
1052     }
1053     Lex();
1054   }
1055
1056   // Create the macro instantiation object and add to the current macro
1057   // instantiation stack.
1058   MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1059                                                   getTok().getLoc(),
1060                                                   MacroArguments);
1061   ActiveMacros.push_back(MI);
1062
1063   // Jump to the macro instantiation and prime the lexer.
1064   CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1065   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1066   Lex();
1067
1068   return false;
1069 }
1070
1071 void AsmParser::HandleMacroExit() {
1072   // Jump to the EndOfStatement we should return to, and consume it.
1073   JumpToLoc(ActiveMacros.back()->ExitLoc);
1074   Lex();
1075
1076   // Pop the instantiation entry.
1077   delete ActiveMacros.back();
1078   ActiveMacros.pop_back();
1079 }
1080
1081 bool AsmParser::ParseAssignment(StringRef Name) {
1082   // FIXME: Use better location, we should use proper tokens.
1083   SMLoc EqualLoc = Lexer.getLoc();
1084
1085   const MCExpr *Value;
1086   if (ParseExpression(Value))
1087     return true;
1088   
1089   if (Lexer.isNot(AsmToken::EndOfStatement))
1090     return TokError("unexpected token in assignment");
1091
1092   // Eat the end of statement marker.
1093   Lex();
1094
1095   // Validate that the LHS is allowed to be a variable (either it has not been
1096   // used as a symbol, or it is an absolute symbol).
1097   MCSymbol *Sym = getContext().LookupSymbol(Name);
1098   if (Sym) {
1099     // Diagnose assignment to a label.
1100     //
1101     // FIXME: Diagnostics. Note the location of the definition as a label.
1102     // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1103     if (Sym->isUndefined() && !Sym->isUsedInExpr())
1104       ; // Allow redefinitions of undefined symbols only used in directives.
1105     else if (!Sym->isUndefined() && !Sym->isAbsolute())
1106       return Error(EqualLoc, "redefinition of '" + Name + "'");
1107     else if (!Sym->isVariable())
1108       return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1109     else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1110       return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1111                    Name + "'");
1112   } else
1113     Sym = getContext().GetOrCreateSymbol(Name);
1114
1115   // FIXME: Handle '.'.
1116
1117   Sym->setUsedInExpr(true);
1118
1119   // Do the assignment.
1120   Out.EmitAssignment(Sym, Value);
1121
1122   return false;
1123 }
1124
1125 /// ParseIdentifier:
1126 ///   ::= identifier
1127 ///   ::= string
1128 bool AsmParser::ParseIdentifier(StringRef &Res) {
1129   // The assembler has relaxed rules for accepting identifiers, in particular we
1130   // allow things like '.globl $foo', which would normally be separate
1131   // tokens. At this level, we have already lexed so we cannot (currently)
1132   // handle this as a context dependent token, instead we detect adjacent tokens
1133   // and return the combined identifier.
1134   if (Lexer.is(AsmToken::Dollar)) {
1135     SMLoc DollarLoc = getLexer().getLoc();
1136
1137     // Consume the dollar sign, and check for a following identifier.
1138     Lex();
1139     if (Lexer.isNot(AsmToken::Identifier))
1140       return true;
1141
1142     // We have a '$' followed by an identifier, make sure they are adjacent.
1143     if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1144       return true;
1145
1146     // Construct the joined identifier and consume the token.
1147     Res = StringRef(DollarLoc.getPointer(),
1148                     getTok().getIdentifier().size() + 1);
1149     Lex();
1150     return false;
1151   }
1152
1153   if (Lexer.isNot(AsmToken::Identifier) &&
1154       Lexer.isNot(AsmToken::String))
1155     return true;
1156
1157   Res = getTok().getIdentifier();
1158
1159   Lex(); // Consume the identifier token.
1160
1161   return false;
1162 }
1163
1164 /// ParseDirectiveSet:
1165 ///   ::= .set identifier ',' expression
1166 bool AsmParser::ParseDirectiveSet() {
1167   StringRef Name;
1168
1169   if (ParseIdentifier(Name))
1170     return TokError("expected identifier after '.set' directive");
1171   
1172   if (getLexer().isNot(AsmToken::Comma))
1173     return TokError("unexpected token in '.set'");
1174   Lex();
1175
1176   return ParseAssignment(Name);
1177 }
1178
1179 bool AsmParser::ParseEscapedString(std::string &Data) {
1180   assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1181
1182   Data = "";
1183   StringRef Str = getTok().getStringContents();
1184   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1185     if (Str[i] != '\\') {
1186       Data += Str[i];
1187       continue;
1188     }
1189
1190     // Recognize escaped characters. Note that this escape semantics currently
1191     // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1192     ++i;
1193     if (i == e)
1194       return TokError("unexpected backslash at end of string");
1195
1196     // Recognize octal sequences.
1197     if ((unsigned) (Str[i] - '0') <= 7) {
1198       // Consume up to three octal characters.
1199       unsigned Value = Str[i] - '0';
1200
1201       if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1202         ++i;
1203         Value = Value * 8 + (Str[i] - '0');
1204
1205         if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1206           ++i;
1207           Value = Value * 8 + (Str[i] - '0');
1208         }
1209       }
1210
1211       if (Value > 255)
1212         return TokError("invalid octal escape sequence (out of range)");
1213
1214       Data += (unsigned char) Value;
1215       continue;
1216     }
1217
1218     // Otherwise recognize individual escapes.
1219     switch (Str[i]) {
1220     default:
1221       // Just reject invalid escape sequences for now.
1222       return TokError("invalid escape sequence (unrecognized character)");
1223
1224     case 'b': Data += '\b'; break;
1225     case 'f': Data += '\f'; break;
1226     case 'n': Data += '\n'; break;
1227     case 'r': Data += '\r'; break;
1228     case 't': Data += '\t'; break;
1229     case '"': Data += '"'; break;
1230     case '\\': Data += '\\'; break;
1231     }
1232   }
1233
1234   return false;
1235 }
1236
1237 /// ParseDirectiveAscii:
1238 ///   ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1239 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1240   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1241     for (;;) {
1242       if (getLexer().isNot(AsmToken::String))
1243         return TokError("expected string in '.ascii' or '.asciz' directive");
1244
1245       std::string Data;
1246       if (ParseEscapedString(Data))
1247         return true;
1248
1249       getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1250       if (ZeroTerminated)
1251         getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1252
1253       Lex();
1254
1255       if (getLexer().is(AsmToken::EndOfStatement))
1256         break;
1257
1258       if (getLexer().isNot(AsmToken::Comma))
1259         return TokError("unexpected token in '.ascii' or '.asciz' directive");
1260       Lex();
1261     }
1262   }
1263
1264   Lex();
1265   return false;
1266 }
1267
1268 /// ParseDirectiveValue
1269 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
1270 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1271   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1272     for (;;) {
1273       const MCExpr *Value;
1274       SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1275       if (ParseExpression(Value))
1276         return true;
1277
1278       // Special case constant expressions to match code generator.
1279       if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1280         getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1281       else
1282         getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1283
1284       if (getLexer().is(AsmToken::EndOfStatement))
1285         break;
1286       
1287       // FIXME: Improve diagnostic.
1288       if (getLexer().isNot(AsmToken::Comma))
1289         return TokError("unexpected token in directive");
1290       Lex();
1291     }
1292   }
1293
1294   Lex();
1295   return false;
1296 }
1297
1298 /// ParseDirectiveSpace
1299 ///  ::= .space expression [ , expression ]
1300 bool AsmParser::ParseDirectiveSpace() {
1301   int64_t NumBytes;
1302   if (ParseAbsoluteExpression(NumBytes))
1303     return true;
1304
1305   int64_t FillExpr = 0;
1306   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1307     if (getLexer().isNot(AsmToken::Comma))
1308       return TokError("unexpected token in '.space' directive");
1309     Lex();
1310     
1311     if (ParseAbsoluteExpression(FillExpr))
1312       return true;
1313
1314     if (getLexer().isNot(AsmToken::EndOfStatement))
1315       return TokError("unexpected token in '.space' directive");
1316   }
1317
1318   Lex();
1319
1320   if (NumBytes <= 0)
1321     return TokError("invalid number of bytes in '.space' directive");
1322
1323   // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1324   getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1325
1326   return false;
1327 }
1328
1329 /// ParseDirectiveFill
1330 ///  ::= .fill expression , expression , expression
1331 bool AsmParser::ParseDirectiveFill() {
1332   int64_t NumValues;
1333   if (ParseAbsoluteExpression(NumValues))
1334     return true;
1335
1336   if (getLexer().isNot(AsmToken::Comma))
1337     return TokError("unexpected token in '.fill' directive");
1338   Lex();
1339   
1340   int64_t FillSize;
1341   if (ParseAbsoluteExpression(FillSize))
1342     return true;
1343
1344   if (getLexer().isNot(AsmToken::Comma))
1345     return TokError("unexpected token in '.fill' directive");
1346   Lex();
1347   
1348   int64_t FillExpr;
1349   if (ParseAbsoluteExpression(FillExpr))
1350     return true;
1351
1352   if (getLexer().isNot(AsmToken::EndOfStatement))
1353     return TokError("unexpected token in '.fill' directive");
1354   
1355   Lex();
1356
1357   if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1358     return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1359
1360   for (uint64_t i = 0, e = NumValues; i != e; ++i)
1361     getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1362
1363   return false;
1364 }
1365
1366 /// ParseDirectiveOrg
1367 ///  ::= .org expression [ , expression ]
1368 bool AsmParser::ParseDirectiveOrg() {
1369   const MCExpr *Offset;
1370   if (ParseExpression(Offset))
1371     return true;
1372
1373   // Parse optional fill expression.
1374   int64_t FillExpr = 0;
1375   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1376     if (getLexer().isNot(AsmToken::Comma))
1377       return TokError("unexpected token in '.org' directive");
1378     Lex();
1379     
1380     if (ParseAbsoluteExpression(FillExpr))
1381       return true;
1382
1383     if (getLexer().isNot(AsmToken::EndOfStatement))
1384       return TokError("unexpected token in '.org' directive");
1385   }
1386
1387   Lex();
1388
1389   // FIXME: Only limited forms of relocatable expressions are accepted here, it
1390   // has to be relative to the current section.
1391   getStreamer().EmitValueToOffset(Offset, FillExpr);
1392
1393   return false;
1394 }
1395
1396 /// ParseDirectiveAlign
1397 ///  ::= {.align, ...} expression [ , expression [ , expression ]]
1398 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1399   SMLoc AlignmentLoc = getLexer().getLoc();
1400   int64_t Alignment;
1401   if (ParseAbsoluteExpression(Alignment))
1402     return true;
1403
1404   SMLoc MaxBytesLoc;
1405   bool HasFillExpr = false;
1406   int64_t FillExpr = 0;
1407   int64_t MaxBytesToFill = 0;
1408   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1409     if (getLexer().isNot(AsmToken::Comma))
1410       return TokError("unexpected token in directive");
1411     Lex();
1412
1413     // The fill expression can be omitted while specifying a maximum number of
1414     // alignment bytes, e.g:
1415     //  .align 3,,4
1416     if (getLexer().isNot(AsmToken::Comma)) {
1417       HasFillExpr = true;
1418       if (ParseAbsoluteExpression(FillExpr))
1419         return true;
1420     }
1421
1422     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1423       if (getLexer().isNot(AsmToken::Comma))
1424         return TokError("unexpected token in directive");
1425       Lex();
1426
1427       MaxBytesLoc = getLexer().getLoc();
1428       if (ParseAbsoluteExpression(MaxBytesToFill))
1429         return true;
1430       
1431       if (getLexer().isNot(AsmToken::EndOfStatement))
1432         return TokError("unexpected token in directive");
1433     }
1434   }
1435
1436   Lex();
1437
1438   if (!HasFillExpr)
1439     FillExpr = 0;
1440
1441   // Compute alignment in bytes.
1442   if (IsPow2) {
1443     // FIXME: Diagnose overflow.
1444     if (Alignment >= 32) {
1445       Error(AlignmentLoc, "invalid alignment value");
1446       Alignment = 31;
1447     }
1448
1449     Alignment = 1ULL << Alignment;
1450   }
1451
1452   // Diagnose non-sensical max bytes to align.
1453   if (MaxBytesLoc.isValid()) {
1454     if (MaxBytesToFill < 1) {
1455       Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1456             "many bytes, ignoring maximum bytes expression");
1457       MaxBytesToFill = 0;
1458     }
1459
1460     if (MaxBytesToFill >= Alignment) {
1461       Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1462               "has no effect");
1463       MaxBytesToFill = 0;
1464     }
1465   }
1466
1467   // Check whether we should use optimal code alignment for this .align
1468   // directive.
1469   //
1470   // FIXME: This should be using a target hook.
1471   bool UseCodeAlign = false;
1472   if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1473         getStreamer().getCurrentSection()))
1474     UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1475   if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1476       ValueSize == 1 && UseCodeAlign) {
1477     getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1478   } else {
1479     // FIXME: Target specific behavior about how the "extra" bytes are filled.
1480     getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1481                                        MaxBytesToFill);
1482   }
1483
1484   return false;
1485 }
1486
1487 /// ParseDirectiveSymbolAttribute
1488 ///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1489 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1490   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1491     for (;;) {
1492       StringRef Name;
1493
1494       if (ParseIdentifier(Name))
1495         return TokError("expected identifier in directive");
1496       
1497       MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1498
1499       getStreamer().EmitSymbolAttribute(Sym, Attr);
1500
1501       if (getLexer().is(AsmToken::EndOfStatement))
1502         break;
1503
1504       if (getLexer().isNot(AsmToken::Comma))
1505         return TokError("unexpected token in directive");
1506       Lex();
1507     }
1508   }
1509
1510   Lex();
1511   return false;  
1512 }
1513
1514 /// ParseDirectiveELFType
1515 ///  ::= .type identifier , @attribute
1516 bool AsmParser::ParseDirectiveELFType() {
1517   StringRef Name;
1518   if (ParseIdentifier(Name))
1519     return TokError("expected identifier in directive");
1520
1521   // Handle the identifier as the key symbol.
1522   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1523
1524   if (getLexer().isNot(AsmToken::Comma))
1525     return TokError("unexpected token in '.type' directive");
1526   Lex();
1527
1528   if (getLexer().isNot(AsmToken::At))
1529     return TokError("expected '@' before type");
1530   Lex();
1531
1532   StringRef Type;
1533   SMLoc TypeLoc;
1534
1535   TypeLoc = getLexer().getLoc();
1536   if (ParseIdentifier(Type))
1537     return TokError("expected symbol type in directive");
1538
1539   MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1540     .Case("function", MCSA_ELF_TypeFunction)
1541     .Case("object", MCSA_ELF_TypeObject)
1542     .Case("tls_object", MCSA_ELF_TypeTLS)
1543     .Case("common", MCSA_ELF_TypeCommon)
1544     .Case("notype", MCSA_ELF_TypeNoType)
1545     .Default(MCSA_Invalid);
1546
1547   if (Attr == MCSA_Invalid)
1548     return Error(TypeLoc, "unsupported attribute in '.type' directive");
1549
1550   if (getLexer().isNot(AsmToken::EndOfStatement))
1551     return TokError("unexpected token in '.type' directive");
1552
1553   Lex();
1554
1555   getStreamer().EmitSymbolAttribute(Sym, Attr);
1556
1557   return false;
1558 }
1559
1560 /// ParseDirectiveComm
1561 ///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1562 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1563   SMLoc IDLoc = getLexer().getLoc();
1564   StringRef Name;
1565   if (ParseIdentifier(Name))
1566     return TokError("expected identifier in directive");
1567   
1568   // Handle the identifier as the key symbol.
1569   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1570
1571   if (getLexer().isNot(AsmToken::Comma))
1572     return TokError("unexpected token in directive");
1573   Lex();
1574
1575   int64_t Size;
1576   SMLoc SizeLoc = getLexer().getLoc();
1577   if (ParseAbsoluteExpression(Size))
1578     return true;
1579
1580   int64_t Pow2Alignment = 0;
1581   SMLoc Pow2AlignmentLoc;
1582   if (getLexer().is(AsmToken::Comma)) {
1583     Lex();
1584     Pow2AlignmentLoc = getLexer().getLoc();
1585     if (ParseAbsoluteExpression(Pow2Alignment))
1586       return true;
1587     
1588     // If this target takes alignments in bytes (not log) validate and convert.
1589     if (Lexer.getMAI().getAlignmentIsInBytes()) {
1590       if (!isPowerOf2_64(Pow2Alignment))
1591         return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1592       Pow2Alignment = Log2_64(Pow2Alignment);
1593     }
1594   }
1595   
1596   if (getLexer().isNot(AsmToken::EndOfStatement))
1597     return TokError("unexpected token in '.comm' or '.lcomm' directive");
1598   
1599   Lex();
1600
1601   // NOTE: a size of zero for a .comm should create a undefined symbol
1602   // but a size of .lcomm creates a bss symbol of size zero.
1603   if (Size < 0)
1604     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1605                  "be less than zero");
1606
1607   // NOTE: The alignment in the directive is a power of 2 value, the assembler
1608   // may internally end up wanting an alignment in bytes.
1609   // FIXME: Diagnose overflow.
1610   if (Pow2Alignment < 0)
1611     return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1612                  "alignment, can't be less than zero");
1613
1614   if (!Sym->isUndefined())
1615     return Error(IDLoc, "invalid symbol redefinition");
1616
1617   // '.lcomm' is equivalent to '.zerofill'.
1618   // Create the Symbol as a common or local common with Size and Pow2Alignment
1619   if (IsLocal) {
1620     getStreamer().EmitZerofill(Ctx.getMachOSection(
1621                                  "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1622                                  0, SectionKind::getBSS()),
1623                                Sym, Size, 1 << Pow2Alignment);
1624     return false;
1625   }
1626
1627   getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1628   return false;
1629 }
1630
1631 /// ParseDirectiveAbort
1632 ///  ::= .abort [... message ...]
1633 bool AsmParser::ParseDirectiveAbort() {
1634   // FIXME: Use loc from directive.
1635   SMLoc Loc = getLexer().getLoc();
1636
1637   StringRef Str = ParseStringToEndOfStatement();
1638   if (getLexer().isNot(AsmToken::EndOfStatement))
1639     return TokError("unexpected token in '.abort' directive");
1640
1641   Lex();
1642
1643   if (Str.empty())
1644     Error(Loc, ".abort detected. Assembly stopping.");
1645   else
1646     Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1647   // FIXME: Actually abort assembly here.
1648
1649   return false;
1650 }
1651
1652 /// ParseDirectiveInclude
1653 ///  ::= .include "filename"
1654 bool AsmParser::ParseDirectiveInclude() {
1655   if (getLexer().isNot(AsmToken::String))
1656     return TokError("expected string in '.include' directive");
1657   
1658   std::string Filename = getTok().getString();
1659   SMLoc IncludeLoc = getLexer().getLoc();
1660   Lex();
1661
1662   if (getLexer().isNot(AsmToken::EndOfStatement))
1663     return TokError("unexpected token in '.include' directive");
1664   
1665   // Strip the quotes.
1666   Filename = Filename.substr(1, Filename.size()-2);
1667   
1668   // Attempt to switch the lexer to the included file before consuming the end
1669   // of statement to avoid losing it when we switch.
1670   if (EnterIncludeFile(Filename)) {
1671     Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1672     return true;
1673   }
1674
1675   return false;
1676 }
1677
1678 /// ParseDirectiveIf
1679 /// ::= .if expression
1680 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1681   TheCondStack.push_back(TheCondState);
1682   TheCondState.TheCond = AsmCond::IfCond;
1683   if(TheCondState.Ignore) {
1684     EatToEndOfStatement();
1685   }
1686   else {
1687     int64_t ExprValue;
1688     if (ParseAbsoluteExpression(ExprValue))
1689       return true;
1690
1691     if (getLexer().isNot(AsmToken::EndOfStatement))
1692       return TokError("unexpected token in '.if' directive");
1693     
1694     Lex();
1695
1696     TheCondState.CondMet = ExprValue;
1697     TheCondState.Ignore = !TheCondState.CondMet;
1698   }
1699
1700   return false;
1701 }
1702
1703 /// ParseDirectiveElseIf
1704 /// ::= .elseif expression
1705 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1706   if (TheCondState.TheCond != AsmCond::IfCond &&
1707       TheCondState.TheCond != AsmCond::ElseIfCond)
1708       Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1709                           " an .elseif");
1710   TheCondState.TheCond = AsmCond::ElseIfCond;
1711
1712   bool LastIgnoreState = false;
1713   if (!TheCondStack.empty())
1714       LastIgnoreState = TheCondStack.back().Ignore;
1715   if (LastIgnoreState || TheCondState.CondMet) {
1716     TheCondState.Ignore = true;
1717     EatToEndOfStatement();
1718   }
1719   else {
1720     int64_t ExprValue;
1721     if (ParseAbsoluteExpression(ExprValue))
1722       return true;
1723
1724     if (getLexer().isNot(AsmToken::EndOfStatement))
1725       return TokError("unexpected token in '.elseif' directive");
1726     
1727     Lex();
1728     TheCondState.CondMet = ExprValue;
1729     TheCondState.Ignore = !TheCondState.CondMet;
1730   }
1731
1732   return false;
1733 }
1734
1735 /// ParseDirectiveElse
1736 /// ::= .else
1737 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1738   if (getLexer().isNot(AsmToken::EndOfStatement))
1739     return TokError("unexpected token in '.else' directive");
1740   
1741   Lex();
1742
1743   if (TheCondState.TheCond != AsmCond::IfCond &&
1744       TheCondState.TheCond != AsmCond::ElseIfCond)
1745       Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1746                           ".elseif");
1747   TheCondState.TheCond = AsmCond::ElseCond;
1748   bool LastIgnoreState = false;
1749   if (!TheCondStack.empty())
1750     LastIgnoreState = TheCondStack.back().Ignore;
1751   if (LastIgnoreState || TheCondState.CondMet)
1752     TheCondState.Ignore = true;
1753   else
1754     TheCondState.Ignore = false;
1755
1756   return false;
1757 }
1758
1759 /// ParseDirectiveEndIf
1760 /// ::= .endif
1761 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1762   if (getLexer().isNot(AsmToken::EndOfStatement))
1763     return TokError("unexpected token in '.endif' directive");
1764   
1765   Lex();
1766
1767   if ((TheCondState.TheCond == AsmCond::NoCond) ||
1768       TheCondStack.empty())
1769     Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1770                         ".else");
1771   if (!TheCondStack.empty()) {
1772     TheCondState = TheCondStack.back();
1773     TheCondStack.pop_back();
1774   }
1775
1776   return false;
1777 }
1778
1779 /// ParseDirectiveFile
1780 /// ::= .file [number] string
1781 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1782   // FIXME: I'm not sure what this is.
1783   int64_t FileNumber = -1;
1784   SMLoc FileNumberLoc = getLexer().getLoc();
1785   if (getLexer().is(AsmToken::Integer)) {
1786     FileNumber = getTok().getIntVal();
1787     Lex();
1788
1789     if (FileNumber < 1)
1790       return TokError("file number less than one");
1791   }
1792
1793   if (getLexer().isNot(AsmToken::String))
1794     return TokError("unexpected token in '.file' directive");
1795
1796   StringRef Filename = getTok().getString();
1797   Filename = Filename.substr(1, Filename.size()-2);
1798   Lex();
1799
1800   if (getLexer().isNot(AsmToken::EndOfStatement))
1801     return TokError("unexpected token in '.file' directive");
1802
1803   if (FileNumber == -1)
1804     getStreamer().EmitFileDirective(Filename);
1805   else {
1806      if (getContext().GetDwarfFile(Filename, FileNumber) == 0)
1807         Error(FileNumberLoc, "file number already allocated");
1808     getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1809   }
1810
1811   return false;
1812 }
1813
1814 /// ParseDirectiveLine
1815 /// ::= .line [number]
1816 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1817   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1818     if (getLexer().isNot(AsmToken::Integer))
1819       return TokError("unexpected token in '.line' directive");
1820
1821     int64_t LineNumber = getTok().getIntVal();
1822     (void) LineNumber;
1823     Lex();
1824
1825     // FIXME: Do something with the .line.
1826   }
1827
1828   if (getLexer().isNot(AsmToken::EndOfStatement))
1829     return TokError("unexpected token in '.line' directive");
1830
1831   return false;
1832 }
1833
1834
1835 /// ParseDirectiveLoc
1836 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
1837 ///                                [epilogue_begin] [is_stmt VALUE] [isa VALUE]
1838 /// The first number is a file number, must have been previously assigned with
1839 /// a .file directive, the second number is the line number and optionally the
1840 /// third number is a column position (zero if not specified).  The remaining
1841 /// optional items are .loc sub-directives.
1842 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1843
1844   if (getLexer().isNot(AsmToken::Integer))
1845     return TokError("unexpected token in '.loc' directive");
1846   int64_t FileNumber = getTok().getIntVal();
1847   if (FileNumber < 1)
1848     return TokError("file number less than one in '.loc' directive");
1849   if (!getContext().ValidateDwarfFileNumber(FileNumber))
1850     return TokError("unassigned file number in '.loc' directive");
1851   Lex();
1852
1853   int64_t LineNumber = 0;
1854   if (getLexer().is(AsmToken::Integer)) {
1855     LineNumber = getTok().getIntVal();
1856     if (LineNumber < 1)
1857       return TokError("line number less than one in '.loc' directive");
1858     Lex();
1859   }
1860
1861   int64_t ColumnPos = 0;
1862   if (getLexer().is(AsmToken::Integer)) {
1863     ColumnPos = getTok().getIntVal();
1864     if (ColumnPos < 0)
1865       return TokError("column position less than zero in '.loc' directive");
1866     Lex();
1867   }
1868
1869   unsigned Flags = 0;
1870   unsigned Isa = 0;
1871   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1872     for (;;) {
1873       if (getLexer().is(AsmToken::EndOfStatement))
1874         break;
1875
1876       StringRef Name;
1877       SMLoc Loc = getTok().getLoc();
1878       if (getParser().ParseIdentifier(Name))
1879         return TokError("unexpected token in '.loc' directive");
1880
1881       if (Name == "basic_block")
1882         Flags |= DWARF2_FLAG_BASIC_BLOCK;
1883       else if (Name == "prologue_end")
1884         Flags |= DWARF2_FLAG_PROLOGUE_END;
1885       else if (Name == "epilogue_begin")
1886         Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
1887       else if (Name == "is_stmt") {
1888         SMLoc Loc = getTok().getLoc();
1889         const MCExpr *Value;
1890         if (getParser().ParseExpression(Value))
1891           return true;
1892         // The expression must be the constant 0 or 1.
1893         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1894           int Value = MCE->getValue();
1895           if (Value == 0)
1896             Flags &= ~DWARF2_FLAG_IS_STMT;
1897           else if (Value == 1)
1898             Flags |= DWARF2_FLAG_IS_STMT;
1899           else
1900             return Error(Loc, "is_stmt value not 0 or 1");
1901         }
1902         else {
1903           return Error(Loc, "is_stmt value not the constant value of 0 or 1");
1904         }
1905       }
1906       else if (Name == "isa") {
1907         SMLoc Loc = getTok().getLoc();
1908         const MCExpr *Value;
1909         if (getParser().ParseExpression(Value))
1910           return true;
1911         // The expression must be a constant greater or equal to 0.
1912         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1913           int Value = MCE->getValue();
1914           if (Value < 0)
1915             return Error(Loc, "isa number less than zero");
1916           Isa = Value;
1917         }
1918         else {
1919           return Error(Loc, "isa number not a constant value");
1920         }
1921       }
1922       else {
1923         return Error(Loc, "unknown sub-directive in '.loc' directive");
1924       }
1925
1926       if (getLexer().is(AsmToken::EndOfStatement))
1927         break;
1928     }
1929   }
1930
1931   getContext().setCurrentDwarfLoc(FileNumber, LineNumber, ColumnPos, Flags,Isa);
1932
1933   return false;
1934 }
1935
1936 /// ParseDirectiveMacrosOnOff
1937 /// ::= .macros_on
1938 /// ::= .macros_off
1939 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
1940                                                  SMLoc DirectiveLoc) {
1941   if (getLexer().isNot(AsmToken::EndOfStatement))
1942     return Error(getLexer().getLoc(),
1943                  "unexpected token in '" + Directive + "' directive");
1944
1945   getParser().MacrosEnabled = Directive == ".macros_on";
1946
1947   return false;
1948 }
1949
1950 /// ParseDirectiveMacro
1951 /// ::= .macro name
1952 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
1953                                            SMLoc DirectiveLoc) {
1954   StringRef Name;
1955   if (getParser().ParseIdentifier(Name))
1956     return TokError("expected identifier in directive");
1957
1958   if (getLexer().isNot(AsmToken::EndOfStatement))
1959     return TokError("unexpected token in '.macro' directive");
1960
1961   // Eat the end of statement.
1962   Lex();
1963
1964   AsmToken EndToken, StartToken = getTok();
1965
1966   // Lex the macro definition.
1967   for (;;) {
1968     // Check whether we have reached the end of the file.
1969     if (getLexer().is(AsmToken::Eof))
1970       return Error(DirectiveLoc, "no matching '.endmacro' in definition");
1971
1972     // Otherwise, check whether we have reach the .endmacro.
1973     if (getLexer().is(AsmToken::Identifier) &&
1974         (getTok().getIdentifier() == ".endm" ||
1975          getTok().getIdentifier() == ".endmacro")) {
1976       EndToken = getTok();
1977       Lex();
1978       if (getLexer().isNot(AsmToken::EndOfStatement))
1979         return TokError("unexpected token in '" + EndToken.getIdentifier() +
1980                         "' directive");
1981       break;
1982     }
1983
1984     // Otherwise, scan til the end of the statement.
1985     getParser().EatToEndOfStatement();
1986   }
1987
1988   if (getParser().MacroMap.lookup(Name)) {
1989     return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
1990   }
1991
1992   const char *BodyStart = StartToken.getLoc().getPointer();
1993   const char *BodyEnd = EndToken.getLoc().getPointer();
1994   StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
1995   getParser().MacroMap[Name] = new Macro(Name, Body);
1996   return false;
1997 }
1998
1999 /// ParseDirectiveEndMacro
2000 /// ::= .endm
2001 /// ::= .endmacro
2002 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2003                                            SMLoc DirectiveLoc) {
2004   if (getLexer().isNot(AsmToken::EndOfStatement))
2005     return TokError("unexpected token in '" + Directive + "' directive");
2006
2007   // If we are inside a macro instantiation, terminate the current
2008   // instantiation.
2009   if (!getParser().ActiveMacros.empty()) {
2010     getParser().HandleMacroExit();
2011     return false;
2012   }
2013
2014   // Otherwise, this .endmacro is a stray entry in the file; well formed
2015   // .endmacro directives are handled during the macro definition parsing.
2016   return TokError("unexpected '" + Directive + "' in file, "
2017                   "no current macro definition");
2018 }
2019
2020 /// \brief Create an MCAsmParser instance.
2021 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2022                                      MCContext &C, MCStreamer &Out,
2023                                      const MCAsmInfo &MAI) {
2024   return new AsmParser(T, SM, C, Out, MAI);
2025 }