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