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