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