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