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