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