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