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