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