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