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