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