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