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