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