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