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