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