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