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