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