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