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