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