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