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