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