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