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