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