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