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