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