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