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