Fix the case of a .cfi_rel_offset before any .cfi_def_cfa_offset.
[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/StringSwitch.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCParser/AsmCond.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
26 #include "llvm/MC/MCSectionMachO.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCDwarf.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetAsmInfo.h"
34 #include "llvm/Target/TargetAsmParser.h"
35 #include <cctype>
36 #include <vector>
37 using namespace llvm;
38
39 namespace {
40
41 /// \brief Helper class for tracking macro definitions.
42 struct Macro {
43   StringRef Name;
44   StringRef Body;
45
46 public:
47   Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
48 };
49
50 /// \brief Helper class for storing information about an active macro
51 /// instantiation.
52 struct MacroInstantiation {
53   /// The macro being instantiated.
54   const Macro *TheMacro;
55
56   /// The macro instantiation with substitutions.
57   MemoryBuffer *Instantiation;
58
59   /// The location of the instantiation.
60   SMLoc InstantiationLoc;
61
62   /// The location where parsing should resume upon instantiation completion.
63   SMLoc ExitLoc;
64
65 public:
66   MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
67                      const std::vector<std::vector<AsmToken> > &A);
68 };
69
70 /// \brief The concrete assembly parser instance.
71 class AsmParser : public MCAsmParser {
72   friend class GenericAsmParser;
73
74   AsmParser(const AsmParser &);   // DO NOT IMPLEMENT
75   void operator=(const AsmParser &);  // DO NOT IMPLEMENT
76 private:
77   AsmLexer Lexer;
78   MCContext &Ctx;
79   MCStreamer &Out;
80   SourceMgr &SrcMgr;
81   MCAsmParserExtension *GenericParser;
82   MCAsmParserExtension *PlatformParser;
83
84   // FIXME: This is not the best place to store this. To handle a (for example)
85   // .cfi_rel_offset before a .cfi_def_cfa_offset we need to know the initial
86   // frame state.
87   int64_t LastOffset;
88
89   /// This is the current buffer index we're lexing from as managed by the
90   /// SourceMgr object.
91   int CurBuffer;
92
93   AsmCond TheCondState;
94   std::vector<AsmCond> TheCondStack;
95
96   /// DirectiveMap - This is a table handlers for directives.  Each handler is
97   /// invoked after the directive identifier is read and is responsible for
98   /// parsing and validating the rest of the directive.  The handler is passed
99   /// in the directive name and the location of the directive keyword.
100   StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
101
102   /// MacroMap - Map of currently defined macros.
103   StringMap<Macro*> MacroMap;
104
105   /// ActiveMacros - Stack of active macro instantiations.
106   std::vector<MacroInstantiation*> ActiveMacros;
107
108   /// Boolean tracking whether macro substitution is enabled.
109   unsigned MacrosEnabled : 1;
110
111   /// Flag tracking whether any errors have been encountered.
112   unsigned HadError : 1;
113
114 public:
115   AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
116             const MCAsmInfo &MAI);
117   ~AsmParser();
118
119   virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
120
121   void AddDirectiveHandler(MCAsmParserExtension *Object,
122                            StringRef Directive,
123                            DirectiveHandler Handler) {
124     DirectiveMap[Directive] = std::make_pair(Object, Handler);
125   }
126
127 public:
128   /// @name MCAsmParser Interface
129   /// {
130
131   virtual SourceMgr &getSourceManager() { return SrcMgr; }
132   virtual MCAsmLexer &getLexer() { return Lexer; }
133   virtual MCContext &getContext() { return Ctx; }
134   virtual MCStreamer &getStreamer() { return Out; }
135
136   virtual void Warning(SMLoc L, const Twine &Meg);
137   virtual bool Error(SMLoc L, const Twine &Msg);
138
139   const AsmToken &Lex();
140
141   bool ParseExpression(const MCExpr *&Res);
142   virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
143   virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
144   virtual bool ParseAbsoluteExpression(int64_t &Res);
145
146   /// }
147
148   int64_t adjustLastOffset(int64_t Adjustment) {
149     LastOffset += Adjustment;
150     return LastOffset;
151   }
152   void setLastOffset(int64_t Offset) {
153     LastOffset = Offset;
154   }
155
156 private:
157   void CheckForValidSection();
158
159   bool ParseStatement();
160
161   bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
162   void HandleMacroExit();
163
164   void PrintMacroInstantiations();
165   void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type) const {
166     SrcMgr.PrintMessage(Loc, Msg, Type);
167   }
168
169   /// EnterIncludeFile - Enter the specified file. This returns true on failure.
170   bool EnterIncludeFile(const std::string &Filename);
171
172   /// \brief Reset the current lexer position to that given by \arg Loc. The
173   /// current token is not set; clients should ensure Lex() is called
174   /// subsequently.
175   void JumpToLoc(SMLoc Loc);
176
177   void EatToEndOfStatement();
178
179   /// \brief Parse up to the end of statement and a return the contents from the
180   /// current token until the end of the statement; the current token on exit
181   /// will be either the EndOfStatement or EOF.
182   StringRef ParseStringToEndOfStatement();
183
184   bool ParseAssignment(StringRef Name, bool allow_redef);
185
186   bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
187   bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
188   bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
189   bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
190
191   /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
192   /// and set \arg Res to the identifier contents.
193   bool ParseIdentifier(StringRef &Res);
194
195   // Directive Parsing.
196
197  // ".ascii", ".asciiz", ".string"
198   bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
199   bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
200   bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
201   bool ParseDirectiveFill(); // ".fill"
202   bool ParseDirectiveSpace(); // ".space"
203   bool ParseDirectiveZero(); // ".zero"
204   bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
205   bool ParseDirectiveOrg(); // ".org"
206   // ".align{,32}", ".p2align{,w,l}"
207   bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
208
209   /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
210   /// accepts a single symbol (which should be a label or an external).
211   bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
212
213   bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
214
215   bool ParseDirectiveAbort(); // ".abort"
216   bool ParseDirectiveInclude(); // ".include"
217
218   bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
219   // ".ifdef" or ".ifndef", depending on expect_defined
220   bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
221   bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
222   bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
223   bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
224
225   /// ParseEscapedString - Parse the current token as a string which may include
226   /// escaped characters and return the string contents.
227   bool ParseEscapedString(std::string &Data);
228
229   const MCExpr *ApplyModifierToExpr(const MCExpr *E,
230                                     MCSymbolRefExpr::VariantKind Variant);
231 };
232
233 /// \brief Generic implementations of directive handling, etc. which is shared
234 /// (or the default, at least) for all assembler parser.
235 class GenericAsmParser : public MCAsmParserExtension {
236   template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
237   void AddDirectiveHandler(StringRef Directive) {
238     getParser().AddDirectiveHandler(this, Directive,
239                                     HandleDirective<GenericAsmParser, Handler>);
240   }
241 public:
242   GenericAsmParser() {}
243
244   AsmParser &getParser() {
245     return (AsmParser&) this->MCAsmParserExtension::getParser();
246   }
247
248   virtual void Initialize(MCAsmParser &Parser) {
249     // Call the base implementation.
250     this->MCAsmParserExtension::Initialize(Parser);
251
252     // Debugging directives.
253     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
254     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
255     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
256     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
257
258     // CFI directives.
259     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
260                                                               ".cfi_startproc");
261     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
262                                                                 ".cfi_endproc");
263     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
264                                                          ".cfi_def_cfa");
265     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
266                                                          ".cfi_def_cfa_offset");
267     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
268                                                       ".cfi_adjust_cfa_offset");
269     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
270                                                        ".cfi_def_cfa_register");
271     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
272                                                                  ".cfi_offset");
273     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
274                                                              ".cfi_rel_offset");
275     AddDirectiveHandler<
276      &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
277     AddDirectiveHandler<
278             &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
279     AddDirectiveHandler<
280       &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
281     AddDirectiveHandler<
282       &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
283     AddDirectiveHandler<
284       &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
285
286     // Macro directives.
287     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
288       ".macros_on");
289     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
290       ".macros_off");
291     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
292     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
293     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
294
295     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
296     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
297   }
298
299   bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
300
301   bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
302   bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
303   bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
304   bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
305   bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
306   bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
307   bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
308   bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
309   bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
310   bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
311   bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
312   bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
313   bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
314   bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
315   bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
316   bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
317
318   bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
319   bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
320   bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
321
322   bool ParseDirectiveLEB128(StringRef, SMLoc);
323 };
324
325 }
326
327 namespace llvm {
328
329 extern MCAsmParserExtension *createDarwinAsmParser();
330 extern MCAsmParserExtension *createELFAsmParser();
331 extern MCAsmParserExtension *createCOFFAsmParser();
332
333 }
334
335 enum { DEFAULT_ADDRSPACE = 0 };
336
337 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
338                      MCStreamer &_Out, const MCAsmInfo &_MAI)
339   : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
340     GenericParser(new GenericAsmParser), PlatformParser(0), LastOffset(0),
341     CurBuffer(0), MacrosEnabled(true) {
342   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
343
344   // Initialize the generic parser.
345   GenericParser->Initialize(*this);
346
347   // Initialize the platform / file format parser.
348   //
349   // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
350   // created.
351   if (_MAI.hasMicrosoftFastStdCallMangling()) {
352     PlatformParser = createCOFFAsmParser();
353     PlatformParser->Initialize(*this);
354   } else if (_MAI.hasSubsectionsViaSymbols()) {
355     PlatformParser = createDarwinAsmParser();
356     PlatformParser->Initialize(*this);
357   } else {
358     PlatformParser = createELFAsmParser();
359     PlatformParser->Initialize(*this);
360   }
361 }
362
363 AsmParser::~AsmParser() {
364   assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
365
366   // Destroy any macros.
367   for (StringMap<Macro*>::iterator it = MacroMap.begin(),
368          ie = MacroMap.end(); it != ie; ++it)
369     delete it->getValue();
370
371   delete PlatformParser;
372   delete GenericParser;
373 }
374
375 void AsmParser::PrintMacroInstantiations() {
376   // Print the active macro instantiation stack.
377   for (std::vector<MacroInstantiation*>::const_reverse_iterator
378          it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
379     PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
380                  "note");
381 }
382
383 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
384   PrintMessage(L, Msg, "warning");
385   PrintMacroInstantiations();
386 }
387
388 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
389   HadError = true;
390   PrintMessage(L, Msg, "error");
391   PrintMacroInstantiations();
392   return true;
393 }
394
395 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
396   int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
397   if (NewBuf == -1)
398     return true;
399
400   CurBuffer = NewBuf;
401
402   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
403
404   return false;
405 }
406
407 void AsmParser::JumpToLoc(SMLoc Loc) {
408   CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
409   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
410 }
411
412 const AsmToken &AsmParser::Lex() {
413   const AsmToken *tok = &Lexer.Lex();
414
415   if (tok->is(AsmToken::Eof)) {
416     // If this is the end of an included file, pop the parent file off the
417     // include stack.
418     SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
419     if (ParentIncludeLoc != SMLoc()) {
420       JumpToLoc(ParentIncludeLoc);
421       tok = &Lexer.Lex();
422     }
423   }
424
425   if (tok->is(AsmToken::Error))
426     Error(Lexer.getErrLoc(), Lexer.getErr());
427
428   return *tok;
429 }
430
431 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
432   // Create the initial section, if requested.
433   if (!NoInitialTextSection)
434     Out.InitSections();
435
436   // Prime the lexer.
437   Lex();
438
439   HadError = false;
440   AsmCond StartingCondState = TheCondState;
441
442   // While we have input, parse each statement.
443   while (Lexer.isNot(AsmToken::Eof)) {
444     if (!ParseStatement()) continue;
445
446     // We had an error, validate that one was emitted and recover by skipping to
447     // the next line.
448     assert(HadError && "Parse statement returned an error, but none emitted!");
449     EatToEndOfStatement();
450   }
451
452   if (TheCondState.TheCond != StartingCondState.TheCond ||
453       TheCondState.Ignore != StartingCondState.Ignore)
454     return TokError("unmatched .ifs or .elses");
455
456   // Check to see there are no empty DwarfFile slots.
457   const std::vector<MCDwarfFile *> &MCDwarfFiles =
458     getContext().getMCDwarfFiles();
459   for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
460     if (!MCDwarfFiles[i])
461       TokError("unassigned file number: " + Twine(i) + " for .file directives");
462   }
463
464   // Finalize the output stream if there are no errors and if the client wants
465   // us to.
466   if (!HadError && !NoFinalize)
467     Out.Finish();
468
469   return HadError;
470 }
471
472 void AsmParser::CheckForValidSection() {
473   if (!getStreamer().getCurrentSection()) {
474     TokError("expected section directive before assembly directive");
475     Out.SwitchSection(Ctx.getMachOSection(
476                         "__TEXT", "__text",
477                         MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
478                         0, SectionKind::getText()));
479   }
480 }
481
482 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
483 void AsmParser::EatToEndOfStatement() {
484   while (Lexer.isNot(AsmToken::EndOfStatement) &&
485          Lexer.isNot(AsmToken::Eof))
486     Lex();
487
488   // Eat EOL.
489   if (Lexer.is(AsmToken::EndOfStatement))
490     Lex();
491 }
492
493 StringRef AsmParser::ParseStringToEndOfStatement() {
494   const char *Start = getTok().getLoc().getPointer();
495
496   while (Lexer.isNot(AsmToken::EndOfStatement) &&
497          Lexer.isNot(AsmToken::Eof))
498     Lex();
499
500   const char *End = getTok().getLoc().getPointer();
501   return StringRef(Start, End - Start);
502 }
503
504 /// ParseParenExpr - Parse a paren expression and return it.
505 /// NOTE: This assumes the leading '(' has already been consumed.
506 ///
507 /// parenexpr ::= expr)
508 ///
509 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
510   if (ParseExpression(Res)) return true;
511   if (Lexer.isNot(AsmToken::RParen))
512     return TokError("expected ')' in parentheses expression");
513   EndLoc = Lexer.getLoc();
514   Lex();
515   return false;
516 }
517
518 /// ParseBracketExpr - Parse a bracket expression and return it.
519 /// NOTE: This assumes the leading '[' has already been consumed.
520 ///
521 /// bracketexpr ::= expr]
522 ///
523 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
524   if (ParseExpression(Res)) return true;
525   if (Lexer.isNot(AsmToken::RBrac))
526     return TokError("expected ']' in brackets expression");
527   EndLoc = Lexer.getLoc();
528   Lex();
529   return false;
530 }
531
532 /// ParsePrimaryExpr - Parse a primary expression and return it.
533 ///  primaryexpr ::= (parenexpr
534 ///  primaryexpr ::= symbol
535 ///  primaryexpr ::= number
536 ///  primaryexpr ::= '.'
537 ///  primaryexpr ::= ~,+,- primaryexpr
538 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
539   switch (Lexer.getKind()) {
540   default:
541     return TokError("unknown token in expression");
542   // If we have an error assume that we've already handled it.
543   case AsmToken::Error:
544     return true;
545   case AsmToken::Exclaim:
546     Lex(); // Eat the operator.
547     if (ParsePrimaryExpr(Res, EndLoc))
548       return true;
549     Res = MCUnaryExpr::CreateLNot(Res, getContext());
550     return false;
551   case AsmToken::Dollar:
552   case AsmToken::String:
553   case AsmToken::Identifier: {
554     EndLoc = Lexer.getLoc();
555
556     StringRef Identifier;
557     if (ParseIdentifier(Identifier))
558       return false;
559
560     // This is a symbol reference.
561     std::pair<StringRef, StringRef> Split = Identifier.split('@');
562     MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
563
564     // Lookup the symbol variant if used.
565     MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
566     if (Split.first.size() != Identifier.size()) {
567       Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
568       if (Variant == MCSymbolRefExpr::VK_Invalid) {
569         Variant = MCSymbolRefExpr::VK_None;
570         return TokError("invalid variant '" + Split.second + "'");
571       }
572     }
573
574     // If this is an absolute variable reference, substitute it now to preserve
575     // semantics in the face of reassignment.
576     if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
577       if (Variant)
578         return Error(EndLoc, "unexpected modifier on variable reference");
579
580       Res = Sym->getVariableValue();
581       return false;
582     }
583
584     // Otherwise create a symbol ref.
585     Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
586     return false;
587   }
588   case AsmToken::Integer: {
589     SMLoc Loc = getTok().getLoc();
590     int64_t IntVal = getTok().getIntVal();
591     Res = MCConstantExpr::Create(IntVal, getContext());
592     EndLoc = Lexer.getLoc();
593     Lex(); // Eat token.
594     // Look for 'b' or 'f' following an Integer as a directional label
595     if (Lexer.getKind() == AsmToken::Identifier) {
596       StringRef IDVal = getTok().getString();
597       if (IDVal == "f" || IDVal == "b"){
598         MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
599                                                       IDVal == "f" ? 1 : 0);
600         Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
601                                       getContext());
602         if(IDVal == "b" && Sym->isUndefined())
603           return Error(Loc, "invalid reference to undefined symbol");
604         EndLoc = Lexer.getLoc();
605         Lex(); // Eat identifier.
606       }
607     }
608     return false;
609   }
610   case AsmToken::Real: {
611     APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
612     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
613     Res = MCConstantExpr::Create(IntVal, getContext());
614     Lex(); // Eat token.
615     return false;
616   }
617   case AsmToken::Dot: {
618     // This is a '.' reference, which references the current PC.  Emit a
619     // temporary label to the streamer and refer to it.
620     MCSymbol *Sym = Ctx.CreateTempSymbol();
621     Out.EmitLabel(Sym);
622     Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
623     EndLoc = Lexer.getLoc();
624     Lex(); // Eat identifier.
625     return false;
626   }
627   case AsmToken::LParen:
628     Lex(); // Eat the '('.
629     return ParseParenExpr(Res, EndLoc);
630   case AsmToken::LBrac:
631     if (!PlatformParser->HasBracketExpressions())
632       return TokError("brackets expression not supported on this target");
633     Lex(); // Eat the '['.
634     return ParseBracketExpr(Res, EndLoc);
635   case AsmToken::Minus:
636     Lex(); // Eat the operator.
637     if (ParsePrimaryExpr(Res, EndLoc))
638       return true;
639     Res = MCUnaryExpr::CreateMinus(Res, getContext());
640     return false;
641   case AsmToken::Plus:
642     Lex(); // Eat the operator.
643     if (ParsePrimaryExpr(Res, EndLoc))
644       return true;
645     Res = MCUnaryExpr::CreatePlus(Res, getContext());
646     return false;
647   case AsmToken::Tilde:
648     Lex(); // Eat the operator.
649     if (ParsePrimaryExpr(Res, EndLoc))
650       return true;
651     Res = MCUnaryExpr::CreateNot(Res, getContext());
652     return false;
653   }
654 }
655
656 bool AsmParser::ParseExpression(const MCExpr *&Res) {
657   SMLoc EndLoc;
658   return ParseExpression(Res, EndLoc);
659 }
660
661 const MCExpr *
662 AsmParser::ApplyModifierToExpr(const MCExpr *E,
663                                MCSymbolRefExpr::VariantKind Variant) {
664   // Recurse over the given expression, rebuilding it to apply the given variant
665   // if there is exactly one symbol.
666   switch (E->getKind()) {
667   case MCExpr::Target:
668   case MCExpr::Constant:
669     return 0;
670
671   case MCExpr::SymbolRef: {
672     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
673
674     if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
675       TokError("invalid variant on expression '" +
676                getTok().getIdentifier() + "' (already modified)");
677       return E;
678     }
679
680     return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
681   }
682
683   case MCExpr::Unary: {
684     const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
685     const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
686     if (!Sub)
687       return 0;
688     return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
689   }
690
691   case MCExpr::Binary: {
692     const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
693     const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
694     const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
695
696     if (!LHS && !RHS)
697       return 0;
698
699     if (!LHS) LHS = BE->getLHS();
700     if (!RHS) RHS = BE->getRHS();
701
702     return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
703   }
704   }
705
706   assert(0 && "Invalid expression kind!");
707   return 0;
708 }
709
710 /// ParseExpression - Parse an expression and return it.
711 ///
712 ///  expr ::= expr +,- expr          -> lowest.
713 ///  expr ::= expr |,^,&,! expr      -> middle.
714 ///  expr ::= expr *,/,%,<<,>> expr  -> highest.
715 ///  expr ::= primaryexpr
716 ///
717 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
718   // Parse the expression.
719   Res = 0;
720   if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
721     return true;
722
723   // As a special case, we support 'a op b @ modifier' by rewriting the
724   // expression to include the modifier. This is inefficient, but in general we
725   // expect users to use 'a@modifier op b'.
726   if (Lexer.getKind() == AsmToken::At) {
727     Lex();
728
729     if (Lexer.isNot(AsmToken::Identifier))
730       return TokError("unexpected symbol modifier following '@'");
731
732     MCSymbolRefExpr::VariantKind Variant =
733       MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
734     if (Variant == MCSymbolRefExpr::VK_Invalid)
735       return TokError("invalid variant '" + getTok().getIdentifier() + "'");
736
737     const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
738     if (!ModifiedRes) {
739       return TokError("invalid modifier '" + getTok().getIdentifier() +
740                       "' (no symbols present)");
741       return true;
742     }
743
744     Res = ModifiedRes;
745     Lex();
746   }
747
748   // Try to constant fold it up front, if possible.
749   int64_t Value;
750   if (Res->EvaluateAsAbsolute(Value))
751     Res = MCConstantExpr::Create(Value, getContext());
752
753   return false;
754 }
755
756 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
757   Res = 0;
758   return ParseParenExpr(Res, EndLoc) ||
759          ParseBinOpRHS(1, Res, EndLoc);
760 }
761
762 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
763   const MCExpr *Expr;
764
765   SMLoc StartLoc = Lexer.getLoc();
766   if (ParseExpression(Expr))
767     return true;
768
769   if (!Expr->EvaluateAsAbsolute(Res))
770     return Error(StartLoc, "expected absolute expression");
771
772   return false;
773 }
774
775 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
776                                    MCBinaryExpr::Opcode &Kind) {
777   switch (K) {
778   default:
779     return 0;    // not a binop.
780
781     // Lowest Precedence: &&, ||, @
782   case AsmToken::AmpAmp:
783     Kind = MCBinaryExpr::LAnd;
784     return 1;
785   case AsmToken::PipePipe:
786     Kind = MCBinaryExpr::LOr;
787     return 1;
788
789
790     // Low Precedence: |, &, ^
791     //
792     // FIXME: gas seems to support '!' as an infix operator?
793   case AsmToken::Pipe:
794     Kind = MCBinaryExpr::Or;
795     return 2;
796   case AsmToken::Caret:
797     Kind = MCBinaryExpr::Xor;
798     return 2;
799   case AsmToken::Amp:
800     Kind = MCBinaryExpr::And;
801     return 2;
802
803     // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
804   case AsmToken::EqualEqual:
805     Kind = MCBinaryExpr::EQ;
806     return 3;
807   case AsmToken::ExclaimEqual:
808   case AsmToken::LessGreater:
809     Kind = MCBinaryExpr::NE;
810     return 3;
811   case AsmToken::Less:
812     Kind = MCBinaryExpr::LT;
813     return 3;
814   case AsmToken::LessEqual:
815     Kind = MCBinaryExpr::LTE;
816     return 3;
817   case AsmToken::Greater:
818     Kind = MCBinaryExpr::GT;
819     return 3;
820   case AsmToken::GreaterEqual:
821     Kind = MCBinaryExpr::GTE;
822     return 3;
823
824     // High Intermediate Precedence: +, -
825   case AsmToken::Plus:
826     Kind = MCBinaryExpr::Add;
827     return 4;
828   case AsmToken::Minus:
829     Kind = MCBinaryExpr::Sub;
830     return 4;
831
832     // Highest Precedence: *, /, %, <<, >>
833   case AsmToken::Star:
834     Kind = MCBinaryExpr::Mul;
835     return 5;
836   case AsmToken::Slash:
837     Kind = MCBinaryExpr::Div;
838     return 5;
839   case AsmToken::Percent:
840     Kind = MCBinaryExpr::Mod;
841     return 5;
842   case AsmToken::LessLess:
843     Kind = MCBinaryExpr::Shl;
844     return 5;
845   case AsmToken::GreaterGreater:
846     Kind = MCBinaryExpr::Shr;
847     return 5;
848   }
849 }
850
851
852 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
853 /// Res contains the LHS of the expression on input.
854 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
855                               SMLoc &EndLoc) {
856   while (1) {
857     MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
858     unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
859
860     // If the next token is lower precedence than we are allowed to eat, return
861     // successfully with what we ate already.
862     if (TokPrec < Precedence)
863       return false;
864
865     Lex();
866
867     // Eat the next primary expression.
868     const MCExpr *RHS;
869     if (ParsePrimaryExpr(RHS, EndLoc)) return true;
870
871     // If BinOp binds less tightly with RHS than the operator after RHS, let
872     // the pending operator take RHS as its LHS.
873     MCBinaryExpr::Opcode Dummy;
874     unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
875     if (TokPrec < NextTokPrec) {
876       if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
877     }
878
879     // Merge LHS and RHS according to operator.
880     Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
881   }
882 }
883
884
885
886
887 /// ParseStatement:
888 ///   ::= EndOfStatement
889 ///   ::= Label* Directive ...Operands... EndOfStatement
890 ///   ::= Label* Identifier OperandList* EndOfStatement
891 bool AsmParser::ParseStatement() {
892   if (Lexer.is(AsmToken::EndOfStatement)) {
893     Out.AddBlankLine();
894     Lex();
895     return false;
896   }
897
898   // Statements always start with an identifier or are a full line comment.
899   AsmToken ID = getTok();
900   SMLoc IDLoc = ID.getLoc();
901   StringRef IDVal;
902   int64_t LocalLabelVal = -1;
903   // A full line comment is a '#' as the first token.
904   if (Lexer.is(AsmToken::Hash)) {
905     EatToEndOfStatement();
906     return false;
907   }
908
909   // Allow an integer followed by a ':' as a directional local label.
910   if (Lexer.is(AsmToken::Integer)) {
911     LocalLabelVal = getTok().getIntVal();
912     if (LocalLabelVal < 0) {
913       if (!TheCondState.Ignore)
914         return TokError("unexpected token at start of statement");
915       IDVal = "";
916     }
917     else {
918       IDVal = getTok().getString();
919       Lex(); // Consume the integer token to be used as an identifier token.
920       if (Lexer.getKind() != AsmToken::Colon) {
921         if (!TheCondState.Ignore)
922           return TokError("unexpected token at start of statement");
923       }
924     }
925
926   } else if (Lexer.is(AsmToken::Dot)) {
927     // Treat '.' as a valid identifier in this context.
928     Lex();
929     IDVal = ".";
930
931   } else if (ParseIdentifier(IDVal)) {
932     if (!TheCondState.Ignore)
933       return TokError("unexpected token at start of statement");
934     IDVal = "";
935   }
936
937
938   // Handle conditional assembly here before checking for skipping.  We
939   // have to do this so that .endif isn't skipped in a ".if 0" block for
940   // example.
941   if (IDVal == ".if")
942     return ParseDirectiveIf(IDLoc);
943   if (IDVal == ".ifdef")
944     return ParseDirectiveIfdef(IDLoc, true);
945   if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
946     return ParseDirectiveIfdef(IDLoc, false);
947   if (IDVal == ".elseif")
948     return ParseDirectiveElseIf(IDLoc);
949   if (IDVal == ".else")
950     return ParseDirectiveElse(IDLoc);
951   if (IDVal == ".endif")
952     return ParseDirectiveEndIf(IDLoc);
953
954   // If we are in a ".if 0" block, ignore this statement.
955   if (TheCondState.Ignore) {
956     EatToEndOfStatement();
957     return false;
958   }
959
960   // FIXME: Recurse on local labels?
961
962   // See what kind of statement we have.
963   switch (Lexer.getKind()) {
964   case AsmToken::Colon: {
965     CheckForValidSection();
966
967     // identifier ':'   -> Label.
968     Lex();
969
970     // Diagnose attempt to use '.' as a label.
971     if (IDVal == ".")
972       return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
973
974     // Diagnose attempt to use a variable as a label.
975     //
976     // FIXME: Diagnostics. Note the location of the definition as a label.
977     // FIXME: This doesn't diagnose assignment to a symbol which has been
978     // implicitly marked as external.
979     MCSymbol *Sym;
980     if (LocalLabelVal == -1)
981       Sym = getContext().GetOrCreateSymbol(IDVal);
982     else
983       Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
984     if (!Sym->isUndefined() || Sym->isVariable())
985       return Error(IDLoc, "invalid symbol redefinition");
986
987     // Emit the label.
988     Out.EmitLabel(Sym);
989
990     // Consume any end of statement token, if present, to avoid spurious
991     // AddBlankLine calls().
992     if (Lexer.is(AsmToken::EndOfStatement)) {
993       Lex();
994       if (Lexer.is(AsmToken::Eof))
995         return false;
996     }
997
998     return ParseStatement();
999   }
1000
1001   case AsmToken::Equal:
1002     // identifier '=' ... -> assignment statement
1003     Lex();
1004
1005     return ParseAssignment(IDVal, true);
1006
1007   default: // Normal instruction or directive.
1008     break;
1009   }
1010
1011   // If macros are enabled, check to see if this is a macro instantiation.
1012   if (MacrosEnabled)
1013     if (const Macro *M = MacroMap.lookup(IDVal))
1014       return HandleMacroEntry(IDVal, IDLoc, M);
1015
1016   // Otherwise, we have a normal instruction or directive.
1017   if (IDVal[0] == '.' && IDVal != ".") {
1018     // Assembler features
1019     if (IDVal == ".set" || IDVal == ".equ")
1020       return ParseDirectiveSet(IDVal, true);
1021     if (IDVal == ".equiv")
1022       return ParseDirectiveSet(IDVal, false);
1023
1024     // Data directives
1025
1026     if (IDVal == ".ascii")
1027       return ParseDirectiveAscii(IDVal, false);
1028     if (IDVal == ".asciz" || IDVal == ".string")
1029       return ParseDirectiveAscii(IDVal, true);
1030
1031     if (IDVal == ".byte")
1032       return ParseDirectiveValue(1);
1033     if (IDVal == ".short")
1034       return ParseDirectiveValue(2);
1035     if (IDVal == ".value")
1036       return ParseDirectiveValue(2);
1037     if (IDVal == ".2byte")
1038       return ParseDirectiveValue(2);
1039     if (IDVal == ".long")
1040       return ParseDirectiveValue(4);
1041     if (IDVal == ".int")
1042       return ParseDirectiveValue(4);
1043     if (IDVal == ".4byte")
1044       return ParseDirectiveValue(4);
1045     if (IDVal == ".quad")
1046       return ParseDirectiveValue(8);
1047     if (IDVal == ".8byte")
1048       return ParseDirectiveValue(8);
1049     if (IDVal == ".single" || IDVal == ".float")
1050       return ParseDirectiveRealValue(APFloat::IEEEsingle);
1051     if (IDVal == ".double")
1052       return ParseDirectiveRealValue(APFloat::IEEEdouble);
1053
1054     if (IDVal == ".align") {
1055       bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1056       return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1057     }
1058     if (IDVal == ".align32") {
1059       bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1060       return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1061     }
1062     if (IDVal == ".balign")
1063       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1064     if (IDVal == ".balignw")
1065       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1066     if (IDVal == ".balignl")
1067       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1068     if (IDVal == ".p2align")
1069       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1070     if (IDVal == ".p2alignw")
1071       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1072     if (IDVal == ".p2alignl")
1073       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1074
1075     if (IDVal == ".org")
1076       return ParseDirectiveOrg();
1077
1078     if (IDVal == ".fill")
1079       return ParseDirectiveFill();
1080     if (IDVal == ".space" || IDVal == ".skip")
1081       return ParseDirectiveSpace();
1082     if (IDVal == ".zero")
1083       return ParseDirectiveZero();
1084
1085     // Symbol attribute directives
1086
1087     if (IDVal == ".globl" || IDVal == ".global")
1088       return ParseDirectiveSymbolAttribute(MCSA_Global);
1089     // ELF only? Should it be here?
1090     if (IDVal == ".local")
1091       return ParseDirectiveSymbolAttribute(MCSA_Local);
1092     if (IDVal == ".hidden")
1093       return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1094     if (IDVal == ".indirect_symbol")
1095       return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1096     if (IDVal == ".internal")
1097       return ParseDirectiveSymbolAttribute(MCSA_Internal);
1098     if (IDVal == ".lazy_reference")
1099       return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1100     if (IDVal == ".no_dead_strip")
1101       return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1102     if (IDVal == ".symbol_resolver")
1103       return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1104     if (IDVal == ".private_extern")
1105       return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1106     if (IDVal == ".protected")
1107       return ParseDirectiveSymbolAttribute(MCSA_Protected);
1108     if (IDVal == ".reference")
1109       return ParseDirectiveSymbolAttribute(MCSA_Reference);
1110     if (IDVal == ".weak")
1111       return ParseDirectiveSymbolAttribute(MCSA_Weak);
1112     if (IDVal == ".weak_definition")
1113       return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1114     if (IDVal == ".weak_reference")
1115       return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1116     if (IDVal == ".weak_def_can_be_hidden")
1117       return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1118
1119     if (IDVal == ".comm")
1120       return ParseDirectiveComm(/*IsLocal=*/false);
1121     if (IDVal == ".lcomm")
1122       return ParseDirectiveComm(/*IsLocal=*/true);
1123
1124     if (IDVal == ".abort")
1125       return ParseDirectiveAbort();
1126     if (IDVal == ".include")
1127       return ParseDirectiveInclude();
1128
1129     if (IDVal == ".code16" || IDVal == ".code32" || IDVal == ".code64")
1130       return TokError(Twine(IDVal) + " not supported yet");
1131
1132     // Look up the handler in the handler table.
1133     std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1134       DirectiveMap.lookup(IDVal);
1135     if (Handler.first)
1136       return (*Handler.second)(Handler.first, IDVal, IDLoc);
1137
1138     // Target hook for parsing target specific directives.
1139     if (!getTargetParser().ParseDirective(ID))
1140       return false;
1141
1142     Warning(IDLoc, "ignoring directive for now");
1143     EatToEndOfStatement();
1144     return false;
1145   }
1146
1147   CheckForValidSection();
1148
1149   // Canonicalize the opcode to lower case.
1150   SmallString<128> Opcode;
1151   for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1152     Opcode.push_back(tolower(IDVal[i]));
1153
1154   SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1155   bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1156                                                      ParsedOperands);
1157
1158   // Dump the parsed representation, if requested.
1159   if (getShowParsedOperands()) {
1160     SmallString<256> Str;
1161     raw_svector_ostream OS(Str);
1162     OS << "parsed instruction: [";
1163     for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1164       if (i != 0)
1165         OS << ", ";
1166       ParsedOperands[i]->dump(OS);
1167     }
1168     OS << "]";
1169
1170     PrintMessage(IDLoc, OS.str(), "note");
1171   }
1172
1173   // If parsing succeeded, match the instruction.
1174   if (!HadError)
1175     HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1176                                                          Out);
1177
1178   // Free any parsed operands.
1179   for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1180     delete ParsedOperands[i];
1181
1182   // Don't skip the rest of the line, the instruction parser is responsible for
1183   // that.
1184   return false;
1185 }
1186
1187 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1188                                    const std::vector<std::vector<AsmToken> > &A)
1189   : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1190 {
1191   // Macro instantiation is lexical, unfortunately. We construct a new buffer
1192   // to hold the macro body with substitutions.
1193   SmallString<256> Buf;
1194   raw_svector_ostream OS(Buf);
1195
1196   StringRef Body = M->Body;
1197   while (!Body.empty()) {
1198     // Scan for the next substitution.
1199     std::size_t End = Body.size(), Pos = 0;
1200     for (; Pos != End; ++Pos) {
1201       // Check for a substitution or escape.
1202       if (Body[Pos] != '$' || Pos + 1 == End)
1203         continue;
1204
1205       char Next = Body[Pos + 1];
1206       if (Next == '$' || Next == 'n' || isdigit(Next))
1207         break;
1208     }
1209
1210     // Add the prefix.
1211     OS << Body.slice(0, Pos);
1212
1213     // Check if we reached the end.
1214     if (Pos == End)
1215       break;
1216
1217     switch (Body[Pos+1]) {
1218        // $$ => $
1219     case '$':
1220       OS << '$';
1221       break;
1222
1223       // $n => number of arguments
1224     case 'n':
1225       OS << A.size();
1226       break;
1227
1228        // $[0-9] => argument
1229     default: {
1230       // Missing arguments are ignored.
1231       unsigned Index = Body[Pos+1] - '0';
1232       if (Index >= A.size())
1233         break;
1234
1235       // Otherwise substitute with the token values, with spaces eliminated.
1236       for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1237              ie = A[Index].end(); it != ie; ++it)
1238         OS << it->getString();
1239       break;
1240     }
1241     }
1242
1243     // Update the scan point.
1244     Body = Body.substr(Pos + 2);
1245   }
1246
1247   // We include the .endmacro in the buffer as our queue to exit the macro
1248   // instantiation.
1249   OS << ".endmacro\n";
1250
1251   Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1252 }
1253
1254 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1255                                  const Macro *M) {
1256   // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1257   // this, although we should protect against infinite loops.
1258   if (ActiveMacros.size() == 20)
1259     return TokError("macros cannot be nested more than 20 levels deep");
1260
1261   // Parse the macro instantiation arguments.
1262   std::vector<std::vector<AsmToken> > MacroArguments;
1263   MacroArguments.push_back(std::vector<AsmToken>());
1264   unsigned ParenLevel = 0;
1265   for (;;) {
1266     if (Lexer.is(AsmToken::Eof))
1267       return TokError("unexpected token in macro instantiation");
1268     if (Lexer.is(AsmToken::EndOfStatement))
1269       break;
1270
1271     // If we aren't inside parentheses and this is a comma, start a new token
1272     // list.
1273     if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1274       MacroArguments.push_back(std::vector<AsmToken>());
1275     } else {
1276       // Adjust the current parentheses level.
1277       if (Lexer.is(AsmToken::LParen))
1278         ++ParenLevel;
1279       else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1280         --ParenLevel;
1281
1282       // Append the token to the current argument list.
1283       MacroArguments.back().push_back(getTok());
1284     }
1285     Lex();
1286   }
1287
1288   // Create the macro instantiation object and add to the current macro
1289   // instantiation stack.
1290   MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1291                                                   getTok().getLoc(),
1292                                                   MacroArguments);
1293   ActiveMacros.push_back(MI);
1294
1295   // Jump to the macro instantiation and prime the lexer.
1296   CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1297   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1298   Lex();
1299
1300   return false;
1301 }
1302
1303 void AsmParser::HandleMacroExit() {
1304   // Jump to the EndOfStatement we should return to, and consume it.
1305   JumpToLoc(ActiveMacros.back()->ExitLoc);
1306   Lex();
1307
1308   // Pop the instantiation entry.
1309   delete ActiveMacros.back();
1310   ActiveMacros.pop_back();
1311 }
1312
1313 static void MarkUsed(const MCExpr *Value) {
1314   switch (Value->getKind()) {
1315   case MCExpr::Binary:
1316     MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1317     MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1318     break;
1319   case MCExpr::Target:
1320   case MCExpr::Constant:
1321     break;
1322   case MCExpr::SymbolRef: {
1323     static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1324     break;
1325   }
1326   case MCExpr::Unary:
1327     MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1328     break;
1329   }
1330 }
1331
1332 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1333   // FIXME: Use better location, we should use proper tokens.
1334   SMLoc EqualLoc = Lexer.getLoc();
1335
1336   const MCExpr *Value;
1337   if (ParseExpression(Value))
1338     return true;
1339
1340   MarkUsed(Value);
1341
1342   if (Lexer.isNot(AsmToken::EndOfStatement))
1343     return TokError("unexpected token in assignment");
1344
1345   // Error on assignment to '.'.
1346   if (Name == ".") {
1347     return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1348                             "(use '.space' or '.org').)"));
1349   }
1350
1351   // Eat the end of statement marker.
1352   Lex();
1353
1354   // Validate that the LHS is allowed to be a variable (either it has not been
1355   // used as a symbol, or it is an absolute symbol).
1356   MCSymbol *Sym = getContext().LookupSymbol(Name);
1357   if (Sym) {
1358     // Diagnose assignment to a label.
1359     //
1360     // FIXME: Diagnostics. Note the location of the definition as a label.
1361     // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1362     if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1363       ; // Allow redefinitions of undefined symbols only used in directives.
1364     else if (!Sym->isUndefined() && (!Sym->isAbsolute() || !allow_redef))
1365       return Error(EqualLoc, "redefinition of '" + Name + "'");
1366     else if (!Sym->isVariable())
1367       return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1368     else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1369       return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1370                    Name + "'");
1371
1372     // Don't count these checks as uses.
1373     Sym->setUsed(false);
1374   } else
1375     Sym = getContext().GetOrCreateSymbol(Name);
1376
1377   // FIXME: Handle '.'.
1378
1379   // Do the assignment.
1380   Out.EmitAssignment(Sym, Value);
1381
1382   return false;
1383 }
1384
1385 /// ParseIdentifier:
1386 ///   ::= identifier
1387 ///   ::= string
1388 bool AsmParser::ParseIdentifier(StringRef &Res) {
1389   // The assembler has relaxed rules for accepting identifiers, in particular we
1390   // allow things like '.globl $foo', which would normally be separate
1391   // tokens. At this level, we have already lexed so we cannot (currently)
1392   // handle this as a context dependent token, instead we detect adjacent tokens
1393   // and return the combined identifier.
1394   if (Lexer.is(AsmToken::Dollar)) {
1395     SMLoc DollarLoc = getLexer().getLoc();
1396
1397     // Consume the dollar sign, and check for a following identifier.
1398     Lex();
1399     if (Lexer.isNot(AsmToken::Identifier))
1400       return true;
1401
1402     // We have a '$' followed by an identifier, make sure they are adjacent.
1403     if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1404       return true;
1405
1406     // Construct the joined identifier and consume the token.
1407     Res = StringRef(DollarLoc.getPointer(),
1408                     getTok().getIdentifier().size() + 1);
1409     Lex();
1410     return false;
1411   }
1412
1413   if (Lexer.isNot(AsmToken::Identifier) &&
1414       Lexer.isNot(AsmToken::String))
1415     return true;
1416
1417   Res = getTok().getIdentifier();
1418
1419   Lex(); // Consume the identifier token.
1420
1421   return false;
1422 }
1423
1424 /// ParseDirectiveSet:
1425 ///   ::= .equ identifier ',' expression
1426 ///   ::= .equiv identifier ',' expression
1427 ///   ::= .set identifier ',' expression
1428 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1429   StringRef Name;
1430
1431   if (ParseIdentifier(Name))
1432     return TokError("expected identifier after '" + Twine(IDVal) + "'");
1433
1434   if (getLexer().isNot(AsmToken::Comma))
1435     return TokError("unexpected token in '" + Twine(IDVal) + "'");
1436   Lex();
1437
1438   return ParseAssignment(Name, allow_redef);
1439 }
1440
1441 bool AsmParser::ParseEscapedString(std::string &Data) {
1442   assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1443
1444   Data = "";
1445   StringRef Str = getTok().getStringContents();
1446   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1447     if (Str[i] != '\\') {
1448       Data += Str[i];
1449       continue;
1450     }
1451
1452     // Recognize escaped characters. Note that this escape semantics currently
1453     // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1454     ++i;
1455     if (i == e)
1456       return TokError("unexpected backslash at end of string");
1457
1458     // Recognize octal sequences.
1459     if ((unsigned) (Str[i] - '0') <= 7) {
1460       // Consume up to three octal characters.
1461       unsigned Value = Str[i] - '0';
1462
1463       if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1464         ++i;
1465         Value = Value * 8 + (Str[i] - '0');
1466
1467         if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1468           ++i;
1469           Value = Value * 8 + (Str[i] - '0');
1470         }
1471       }
1472
1473       if (Value > 255)
1474         return TokError("invalid octal escape sequence (out of range)");
1475
1476       Data += (unsigned char) Value;
1477       continue;
1478     }
1479
1480     // Otherwise recognize individual escapes.
1481     switch (Str[i]) {
1482     default:
1483       // Just reject invalid escape sequences for now.
1484       return TokError("invalid escape sequence (unrecognized character)");
1485
1486     case 'b': Data += '\b'; break;
1487     case 'f': Data += '\f'; break;
1488     case 'n': Data += '\n'; break;
1489     case 'r': Data += '\r'; break;
1490     case 't': Data += '\t'; break;
1491     case '"': Data += '"'; break;
1492     case '\\': Data += '\\'; break;
1493     }
1494   }
1495
1496   return false;
1497 }
1498
1499 /// ParseDirectiveAscii:
1500 ///   ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1501 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1502   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1503     CheckForValidSection();
1504
1505     for (;;) {
1506       if (getLexer().isNot(AsmToken::String))
1507         return TokError("expected string in '" + Twine(IDVal) + "' directive");
1508
1509       std::string Data;
1510       if (ParseEscapedString(Data))
1511         return true;
1512
1513       getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1514       if (ZeroTerminated)
1515         getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1516
1517       Lex();
1518
1519       if (getLexer().is(AsmToken::EndOfStatement))
1520         break;
1521
1522       if (getLexer().isNot(AsmToken::Comma))
1523         return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1524       Lex();
1525     }
1526   }
1527
1528   Lex();
1529   return false;
1530 }
1531
1532 /// ParseDirectiveValue
1533 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
1534 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1535   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1536     CheckForValidSection();
1537
1538     for (;;) {
1539       const MCExpr *Value;
1540       if (ParseExpression(Value))
1541         return true;
1542
1543       // Special case constant expressions to match code generator.
1544       if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1545         getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1546       else
1547         getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1548
1549       if (getLexer().is(AsmToken::EndOfStatement))
1550         break;
1551
1552       // FIXME: Improve diagnostic.
1553       if (getLexer().isNot(AsmToken::Comma))
1554         return TokError("unexpected token in directive");
1555       Lex();
1556     }
1557   }
1558
1559   Lex();
1560   return false;
1561 }
1562
1563 /// ParseDirectiveRealValue
1564 ///  ::= (.single | .double) [ expression (, expression)* ]
1565 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1566   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1567     CheckForValidSection();
1568
1569     for (;;) {
1570       // We don't truly support arithmetic on floating point expressions, so we
1571       // have to manually parse unary prefixes.
1572       bool IsNeg = false;
1573       if (getLexer().is(AsmToken::Minus)) {
1574         Lex();
1575         IsNeg = true;
1576       } else if (getLexer().is(AsmToken::Plus))
1577         Lex();
1578
1579       if (getLexer().isNot(AsmToken::Integer) &&
1580           getLexer().isNot(AsmToken::Real) &&
1581           getLexer().isNot(AsmToken::Identifier))
1582         return TokError("unexpected token in directive");
1583
1584       // Convert to an APFloat.
1585       APFloat Value(Semantics);
1586       StringRef IDVal = getTok().getString();
1587       if (getLexer().is(AsmToken::Identifier)) {
1588         if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1589           Value = APFloat::getInf(Semantics);
1590         else if (!IDVal.compare_lower("nan"))
1591           Value = APFloat::getNaN(Semantics, false, ~0);
1592         else
1593           return TokError("invalid floating point literal");
1594       } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1595           APFloat::opInvalidOp)
1596         return TokError("invalid floating point literal");
1597       if (IsNeg)
1598         Value.changeSign();
1599
1600       // Consume the numeric token.
1601       Lex();
1602
1603       // Emit the value as an integer.
1604       APInt AsInt = Value.bitcastToAPInt();
1605       getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1606                                  AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1607
1608       if (getLexer().is(AsmToken::EndOfStatement))
1609         break;
1610
1611       if (getLexer().isNot(AsmToken::Comma))
1612         return TokError("unexpected token in directive");
1613       Lex();
1614     }
1615   }
1616
1617   Lex();
1618   return false;
1619 }
1620
1621 /// ParseDirectiveSpace
1622 ///  ::= .space expression [ , expression ]
1623 bool AsmParser::ParseDirectiveSpace() {
1624   CheckForValidSection();
1625
1626   int64_t NumBytes;
1627   if (ParseAbsoluteExpression(NumBytes))
1628     return true;
1629
1630   int64_t FillExpr = 0;
1631   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1632     if (getLexer().isNot(AsmToken::Comma))
1633       return TokError("unexpected token in '.space' directive");
1634     Lex();
1635
1636     if (ParseAbsoluteExpression(FillExpr))
1637       return true;
1638
1639     if (getLexer().isNot(AsmToken::EndOfStatement))
1640       return TokError("unexpected token in '.space' directive");
1641   }
1642
1643   Lex();
1644
1645   if (NumBytes <= 0)
1646     return TokError("invalid number of bytes in '.space' directive");
1647
1648   // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1649   getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1650
1651   return false;
1652 }
1653
1654 /// ParseDirectiveZero
1655 ///  ::= .zero expression
1656 bool AsmParser::ParseDirectiveZero() {
1657   CheckForValidSection();
1658
1659   int64_t NumBytes;
1660   if (ParseAbsoluteExpression(NumBytes))
1661     return true;
1662
1663   int64_t Val = 0;
1664   if (getLexer().is(AsmToken::Comma)) {
1665     Lex();
1666     if (ParseAbsoluteExpression(Val))
1667       return true;
1668   }
1669
1670   if (getLexer().isNot(AsmToken::EndOfStatement))
1671     return TokError("unexpected token in '.zero' directive");
1672
1673   Lex();
1674
1675   getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1676
1677   return false;
1678 }
1679
1680 /// ParseDirectiveFill
1681 ///  ::= .fill expression , expression , expression
1682 bool AsmParser::ParseDirectiveFill() {
1683   CheckForValidSection();
1684
1685   int64_t NumValues;
1686   if (ParseAbsoluteExpression(NumValues))
1687     return true;
1688
1689   if (getLexer().isNot(AsmToken::Comma))
1690     return TokError("unexpected token in '.fill' directive");
1691   Lex();
1692
1693   int64_t FillSize;
1694   if (ParseAbsoluteExpression(FillSize))
1695     return true;
1696
1697   if (getLexer().isNot(AsmToken::Comma))
1698     return TokError("unexpected token in '.fill' directive");
1699   Lex();
1700
1701   int64_t FillExpr;
1702   if (ParseAbsoluteExpression(FillExpr))
1703     return true;
1704
1705   if (getLexer().isNot(AsmToken::EndOfStatement))
1706     return TokError("unexpected token in '.fill' directive");
1707
1708   Lex();
1709
1710   if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1711     return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1712
1713   for (uint64_t i = 0, e = NumValues; i != e; ++i)
1714     getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1715
1716   return false;
1717 }
1718
1719 /// ParseDirectiveOrg
1720 ///  ::= .org expression [ , expression ]
1721 bool AsmParser::ParseDirectiveOrg() {
1722   CheckForValidSection();
1723
1724   const MCExpr *Offset;
1725   if (ParseExpression(Offset))
1726     return true;
1727
1728   // Parse optional fill expression.
1729   int64_t FillExpr = 0;
1730   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1731     if (getLexer().isNot(AsmToken::Comma))
1732       return TokError("unexpected token in '.org' directive");
1733     Lex();
1734
1735     if (ParseAbsoluteExpression(FillExpr))
1736       return true;
1737
1738     if (getLexer().isNot(AsmToken::EndOfStatement))
1739       return TokError("unexpected token in '.org' directive");
1740   }
1741
1742   Lex();
1743
1744   // FIXME: Only limited forms of relocatable expressions are accepted here, it
1745   // has to be relative to the current section.
1746   getStreamer().EmitValueToOffset(Offset, FillExpr);
1747
1748   return false;
1749 }
1750
1751 /// ParseDirectiveAlign
1752 ///  ::= {.align, ...} expression [ , expression [ , expression ]]
1753 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1754   CheckForValidSection();
1755
1756   SMLoc AlignmentLoc = getLexer().getLoc();
1757   int64_t Alignment;
1758   if (ParseAbsoluteExpression(Alignment))
1759     return true;
1760
1761   SMLoc MaxBytesLoc;
1762   bool HasFillExpr = false;
1763   int64_t FillExpr = 0;
1764   int64_t MaxBytesToFill = 0;
1765   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1766     if (getLexer().isNot(AsmToken::Comma))
1767       return TokError("unexpected token in directive");
1768     Lex();
1769
1770     // The fill expression can be omitted while specifying a maximum number of
1771     // alignment bytes, e.g:
1772     //  .align 3,,4
1773     if (getLexer().isNot(AsmToken::Comma)) {
1774       HasFillExpr = true;
1775       if (ParseAbsoluteExpression(FillExpr))
1776         return true;
1777     }
1778
1779     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1780       if (getLexer().isNot(AsmToken::Comma))
1781         return TokError("unexpected token in directive");
1782       Lex();
1783
1784       MaxBytesLoc = getLexer().getLoc();
1785       if (ParseAbsoluteExpression(MaxBytesToFill))
1786         return true;
1787
1788       if (getLexer().isNot(AsmToken::EndOfStatement))
1789         return TokError("unexpected token in directive");
1790     }
1791   }
1792
1793   Lex();
1794
1795   if (!HasFillExpr)
1796     FillExpr = 0;
1797
1798   // Compute alignment in bytes.
1799   if (IsPow2) {
1800     // FIXME: Diagnose overflow.
1801     if (Alignment >= 32) {
1802       Error(AlignmentLoc, "invalid alignment value");
1803       Alignment = 31;
1804     }
1805
1806     Alignment = 1ULL << Alignment;
1807   }
1808
1809   // Diagnose non-sensical max bytes to align.
1810   if (MaxBytesLoc.isValid()) {
1811     if (MaxBytesToFill < 1) {
1812       Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1813             "many bytes, ignoring maximum bytes expression");
1814       MaxBytesToFill = 0;
1815     }
1816
1817     if (MaxBytesToFill >= Alignment) {
1818       Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1819               "has no effect");
1820       MaxBytesToFill = 0;
1821     }
1822   }
1823
1824   // Check whether we should use optimal code alignment for this .align
1825   // directive.
1826   bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1827   if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1828       ValueSize == 1 && UseCodeAlign) {
1829     getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1830   } else {
1831     // FIXME: Target specific behavior about how the "extra" bytes are filled.
1832     getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1833                                        MaxBytesToFill);
1834   }
1835
1836   return false;
1837 }
1838
1839 /// ParseDirectiveSymbolAttribute
1840 ///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1841 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1842   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1843     for (;;) {
1844       StringRef Name;
1845
1846       if (ParseIdentifier(Name))
1847         return TokError("expected identifier in directive");
1848
1849       MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1850
1851       getStreamer().EmitSymbolAttribute(Sym, Attr);
1852
1853       if (getLexer().is(AsmToken::EndOfStatement))
1854         break;
1855
1856       if (getLexer().isNot(AsmToken::Comma))
1857         return TokError("unexpected token in directive");
1858       Lex();
1859     }
1860   }
1861
1862   Lex();
1863   return false;
1864 }
1865
1866 /// ParseDirectiveComm
1867 ///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1868 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1869   CheckForValidSection();
1870
1871   SMLoc IDLoc = getLexer().getLoc();
1872   StringRef Name;
1873   if (ParseIdentifier(Name))
1874     return TokError("expected identifier in directive");
1875
1876   // Handle the identifier as the key symbol.
1877   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1878
1879   if (getLexer().isNot(AsmToken::Comma))
1880     return TokError("unexpected token in directive");
1881   Lex();
1882
1883   int64_t Size;
1884   SMLoc SizeLoc = getLexer().getLoc();
1885   if (ParseAbsoluteExpression(Size))
1886     return true;
1887
1888   int64_t Pow2Alignment = 0;
1889   SMLoc Pow2AlignmentLoc;
1890   if (getLexer().is(AsmToken::Comma)) {
1891     Lex();
1892     Pow2AlignmentLoc = getLexer().getLoc();
1893     if (ParseAbsoluteExpression(Pow2Alignment))
1894       return true;
1895
1896     // If this target takes alignments in bytes (not log) validate and convert.
1897     if (Lexer.getMAI().getAlignmentIsInBytes()) {
1898       if (!isPowerOf2_64(Pow2Alignment))
1899         return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1900       Pow2Alignment = Log2_64(Pow2Alignment);
1901     }
1902   }
1903
1904   if (getLexer().isNot(AsmToken::EndOfStatement))
1905     return TokError("unexpected token in '.comm' or '.lcomm' directive");
1906
1907   Lex();
1908
1909   // NOTE: a size of zero for a .comm should create a undefined symbol
1910   // but a size of .lcomm creates a bss symbol of size zero.
1911   if (Size < 0)
1912     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1913                  "be less than zero");
1914
1915   // NOTE: The alignment in the directive is a power of 2 value, the assembler
1916   // may internally end up wanting an alignment in bytes.
1917   // FIXME: Diagnose overflow.
1918   if (Pow2Alignment < 0)
1919     return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1920                  "alignment, can't be less than zero");
1921
1922   if (!Sym->isUndefined())
1923     return Error(IDLoc, "invalid symbol redefinition");
1924
1925   // '.lcomm' is equivalent to '.zerofill'.
1926   // Create the Symbol as a common or local common with Size and Pow2Alignment
1927   if (IsLocal) {
1928     getStreamer().EmitZerofill(Ctx.getMachOSection(
1929                                  "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1930                                  0, SectionKind::getBSS()),
1931                                Sym, Size, 1 << Pow2Alignment);
1932     return false;
1933   }
1934
1935   getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1936   return false;
1937 }
1938
1939 /// ParseDirectiveAbort
1940 ///  ::= .abort [... message ...]
1941 bool AsmParser::ParseDirectiveAbort() {
1942   // FIXME: Use loc from directive.
1943   SMLoc Loc = getLexer().getLoc();
1944
1945   StringRef Str = ParseStringToEndOfStatement();
1946   if (getLexer().isNot(AsmToken::EndOfStatement))
1947     return TokError("unexpected token in '.abort' directive");
1948
1949   Lex();
1950
1951   if (Str.empty())
1952     Error(Loc, ".abort detected. Assembly stopping.");
1953   else
1954     Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1955   // FIXME: Actually abort assembly here.
1956
1957   return false;
1958 }
1959
1960 /// ParseDirectiveInclude
1961 ///  ::= .include "filename"
1962 bool AsmParser::ParseDirectiveInclude() {
1963   if (getLexer().isNot(AsmToken::String))
1964     return TokError("expected string in '.include' directive");
1965
1966   std::string Filename = getTok().getString();
1967   SMLoc IncludeLoc = getLexer().getLoc();
1968   Lex();
1969
1970   if (getLexer().isNot(AsmToken::EndOfStatement))
1971     return TokError("unexpected token in '.include' directive");
1972
1973   // Strip the quotes.
1974   Filename = Filename.substr(1, Filename.size()-2);
1975
1976   // Attempt to switch the lexer to the included file before consuming the end
1977   // of statement to avoid losing it when we switch.
1978   if (EnterIncludeFile(Filename)) {
1979     Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1980     return true;
1981   }
1982
1983   return false;
1984 }
1985
1986 /// ParseDirectiveIf
1987 /// ::= .if expression
1988 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1989   TheCondStack.push_back(TheCondState);
1990   TheCondState.TheCond = AsmCond::IfCond;
1991   if(TheCondState.Ignore) {
1992     EatToEndOfStatement();
1993   }
1994   else {
1995     int64_t ExprValue;
1996     if (ParseAbsoluteExpression(ExprValue))
1997       return true;
1998
1999     if (getLexer().isNot(AsmToken::EndOfStatement))
2000       return TokError("unexpected token in '.if' directive");
2001
2002     Lex();
2003
2004     TheCondState.CondMet = ExprValue;
2005     TheCondState.Ignore = !TheCondState.CondMet;
2006   }
2007
2008   return false;
2009 }
2010
2011 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2012   StringRef Name;
2013   TheCondStack.push_back(TheCondState);
2014   TheCondState.TheCond = AsmCond::IfCond;
2015
2016   if (TheCondState.Ignore) {
2017     EatToEndOfStatement();
2018   } else {
2019     if (ParseIdentifier(Name))
2020       return TokError("expected identifier after '.ifdef'");
2021
2022     Lex();
2023
2024     MCSymbol *Sym = getContext().LookupSymbol(Name);
2025
2026     if (expect_defined)
2027       TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2028     else
2029       TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2030     TheCondState.Ignore = !TheCondState.CondMet;
2031   }
2032
2033   return false;
2034 }
2035
2036 /// ParseDirectiveElseIf
2037 /// ::= .elseif expression
2038 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2039   if (TheCondState.TheCond != AsmCond::IfCond &&
2040       TheCondState.TheCond != AsmCond::ElseIfCond)
2041       Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2042                           " an .elseif");
2043   TheCondState.TheCond = AsmCond::ElseIfCond;
2044
2045   bool LastIgnoreState = false;
2046   if (!TheCondStack.empty())
2047       LastIgnoreState = TheCondStack.back().Ignore;
2048   if (LastIgnoreState || TheCondState.CondMet) {
2049     TheCondState.Ignore = true;
2050     EatToEndOfStatement();
2051   }
2052   else {
2053     int64_t ExprValue;
2054     if (ParseAbsoluteExpression(ExprValue))
2055       return true;
2056
2057     if (getLexer().isNot(AsmToken::EndOfStatement))
2058       return TokError("unexpected token in '.elseif' directive");
2059
2060     Lex();
2061     TheCondState.CondMet = ExprValue;
2062     TheCondState.Ignore = !TheCondState.CondMet;
2063   }
2064
2065   return false;
2066 }
2067
2068 /// ParseDirectiveElse
2069 /// ::= .else
2070 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2071   if (getLexer().isNot(AsmToken::EndOfStatement))
2072     return TokError("unexpected token in '.else' directive");
2073
2074   Lex();
2075
2076   if (TheCondState.TheCond != AsmCond::IfCond &&
2077       TheCondState.TheCond != AsmCond::ElseIfCond)
2078       Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2079                           ".elseif");
2080   TheCondState.TheCond = AsmCond::ElseCond;
2081   bool LastIgnoreState = false;
2082   if (!TheCondStack.empty())
2083     LastIgnoreState = TheCondStack.back().Ignore;
2084   if (LastIgnoreState || TheCondState.CondMet)
2085     TheCondState.Ignore = true;
2086   else
2087     TheCondState.Ignore = false;
2088
2089   return false;
2090 }
2091
2092 /// ParseDirectiveEndIf
2093 /// ::= .endif
2094 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2095   if (getLexer().isNot(AsmToken::EndOfStatement))
2096     return TokError("unexpected token in '.endif' directive");
2097
2098   Lex();
2099
2100   if ((TheCondState.TheCond == AsmCond::NoCond) ||
2101       TheCondStack.empty())
2102     Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2103                         ".else");
2104   if (!TheCondStack.empty()) {
2105     TheCondState = TheCondStack.back();
2106     TheCondStack.pop_back();
2107   }
2108
2109   return false;
2110 }
2111
2112 /// ParseDirectiveFile
2113 /// ::= .file [number] string
2114 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2115   // FIXME: I'm not sure what this is.
2116   int64_t FileNumber = -1;
2117   SMLoc FileNumberLoc = getLexer().getLoc();
2118   if (getLexer().is(AsmToken::Integer)) {
2119     FileNumber = getTok().getIntVal();
2120     Lex();
2121
2122     if (FileNumber < 1)
2123       return TokError("file number less than one");
2124   }
2125
2126   if (getLexer().isNot(AsmToken::String))
2127     return TokError("unexpected token in '.file' directive");
2128
2129   StringRef Filename = getTok().getString();
2130   Filename = Filename.substr(1, Filename.size()-2);
2131   Lex();
2132
2133   if (getLexer().isNot(AsmToken::EndOfStatement))
2134     return TokError("unexpected token in '.file' directive");
2135
2136   if (FileNumber == -1)
2137     getStreamer().EmitFileDirective(Filename);
2138   else {
2139     if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2140       Error(FileNumberLoc, "file number already allocated");
2141   }
2142
2143   return false;
2144 }
2145
2146 /// ParseDirectiveLine
2147 /// ::= .line [number]
2148 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2149   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2150     if (getLexer().isNot(AsmToken::Integer))
2151       return TokError("unexpected token in '.line' directive");
2152
2153     int64_t LineNumber = getTok().getIntVal();
2154     (void) LineNumber;
2155     Lex();
2156
2157     // FIXME: Do something with the .line.
2158   }
2159
2160   if (getLexer().isNot(AsmToken::EndOfStatement))
2161     return TokError("unexpected token in '.line' directive");
2162
2163   return false;
2164 }
2165
2166
2167 /// ParseDirectiveLoc
2168 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2169 ///                                [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2170 /// The first number is a file number, must have been previously assigned with
2171 /// a .file directive, the second number is the line number and optionally the
2172 /// third number is a column position (zero if not specified).  The remaining
2173 /// optional items are .loc sub-directives.
2174 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2175
2176   if (getLexer().isNot(AsmToken::Integer))
2177     return TokError("unexpected token in '.loc' directive");
2178   int64_t FileNumber = getTok().getIntVal();
2179   if (FileNumber < 1)
2180     return TokError("file number less than one in '.loc' directive");
2181   if (!getContext().isValidDwarfFileNumber(FileNumber))
2182     return TokError("unassigned file number in '.loc' directive");
2183   Lex();
2184
2185   int64_t LineNumber = 0;
2186   if (getLexer().is(AsmToken::Integer)) {
2187     LineNumber = getTok().getIntVal();
2188     if (LineNumber < 1)
2189       return TokError("line number less than one in '.loc' directive");
2190     Lex();
2191   }
2192
2193   int64_t ColumnPos = 0;
2194   if (getLexer().is(AsmToken::Integer)) {
2195     ColumnPos = getTok().getIntVal();
2196     if (ColumnPos < 0)
2197       return TokError("column position less than zero in '.loc' directive");
2198     Lex();
2199   }
2200
2201   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2202   unsigned Isa = 0;
2203   int64_t Discriminator = 0;
2204   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2205     for (;;) {
2206       if (getLexer().is(AsmToken::EndOfStatement))
2207         break;
2208
2209       StringRef Name;
2210       SMLoc Loc = getTok().getLoc();
2211       if (getParser().ParseIdentifier(Name))
2212         return TokError("unexpected token in '.loc' directive");
2213
2214       if (Name == "basic_block")
2215         Flags |= DWARF2_FLAG_BASIC_BLOCK;
2216       else if (Name == "prologue_end")
2217         Flags |= DWARF2_FLAG_PROLOGUE_END;
2218       else if (Name == "epilogue_begin")
2219         Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2220       else if (Name == "is_stmt") {
2221         SMLoc Loc = getTok().getLoc();
2222         const MCExpr *Value;
2223         if (getParser().ParseExpression(Value))
2224           return true;
2225         // The expression must be the constant 0 or 1.
2226         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2227           int Value = MCE->getValue();
2228           if (Value == 0)
2229             Flags &= ~DWARF2_FLAG_IS_STMT;
2230           else if (Value == 1)
2231             Flags |= DWARF2_FLAG_IS_STMT;
2232           else
2233             return Error(Loc, "is_stmt value not 0 or 1");
2234         }
2235         else {
2236           return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2237         }
2238       }
2239       else if (Name == "isa") {
2240         SMLoc Loc = getTok().getLoc();
2241         const MCExpr *Value;
2242         if (getParser().ParseExpression(Value))
2243           return true;
2244         // The expression must be a constant greater or equal to 0.
2245         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2246           int Value = MCE->getValue();
2247           if (Value < 0)
2248             return Error(Loc, "isa number less than zero");
2249           Isa = Value;
2250         }
2251         else {
2252           return Error(Loc, "isa number not a constant value");
2253         }
2254       }
2255       else if (Name == "discriminator") {
2256         if (getParser().ParseAbsoluteExpression(Discriminator))
2257           return true;
2258       }
2259       else {
2260         return Error(Loc, "unknown sub-directive in '.loc' directive");
2261       }
2262
2263       if (getLexer().is(AsmToken::EndOfStatement))
2264         break;
2265     }
2266   }
2267
2268   getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2269                                       Isa, Discriminator);
2270
2271   return false;
2272 }
2273
2274 /// ParseDirectiveStabs
2275 /// ::= .stabs string, number, number, number
2276 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2277                                            SMLoc DirectiveLoc) {
2278   return TokError("unsupported directive '" + Directive + "'");
2279 }
2280
2281 /// ParseDirectiveCFIStartProc
2282 /// ::= .cfi_startproc
2283 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2284                                                   SMLoc DirectiveLoc) {
2285   return getStreamer().EmitCFIStartProc();
2286 }
2287
2288 /// ParseDirectiveCFIEndProc
2289 /// ::= .cfi_endproc
2290 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2291   return getStreamer().EmitCFIEndProc();
2292 }
2293
2294 /// ParseRegisterOrRegisterNumber - parse register name or number.
2295 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2296                                                      SMLoc DirectiveLoc) {
2297   unsigned RegNo;
2298
2299   if (getLexer().is(AsmToken::Percent)) {
2300     if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2301       DirectiveLoc))
2302       return true;
2303     Register = getContext().getTargetAsmInfo().getDwarfRegNum(RegNo, true);
2304   } else
2305     return getParser().ParseAbsoluteExpression(Register);
2306
2307   return false;
2308 }
2309
2310 /// ParseDirectiveCFIDefCfa
2311 /// ::= .cfi_def_cfa register,  offset
2312 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2313                                                SMLoc DirectiveLoc) {
2314   int64_t Register = 0;
2315   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2316     return true;
2317
2318   if (getLexer().isNot(AsmToken::Comma))
2319     return TokError("unexpected token in directive");
2320   Lex();
2321
2322   int64_t Offset = 0;
2323   if (getParser().ParseAbsoluteExpression(Offset))
2324     return true;
2325
2326   return getStreamer().EmitCFIDefCfa(Register, Offset);
2327 }
2328
2329 /// ParseDirectiveCFIDefCfaOffset
2330 /// ::= .cfi_def_cfa_offset offset
2331 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2332                                                      SMLoc DirectiveLoc) {
2333   int64_t Offset = 0;
2334   if (getParser().ParseAbsoluteExpression(Offset))
2335     return true;
2336
2337   getParser().setLastOffset(Offset);
2338
2339   return getStreamer().EmitCFIDefCfaOffset(Offset);
2340 }
2341
2342 /// ParseDirectiveCFIAdjustCfaOffset
2343 /// ::= .cfi_adjust_cfa_offset adjustment
2344 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2345                                                         SMLoc DirectiveLoc) {
2346   int64_t Adjustment = 0;
2347   if (getParser().ParseAbsoluteExpression(Adjustment))
2348     return true;
2349
2350   int64_t Offset = getParser().adjustLastOffset(Adjustment);
2351
2352   return getStreamer().EmitCFIDefCfaOffset(Offset);
2353 }
2354
2355 /// ParseDirectiveCFIDefCfaRegister
2356 /// ::= .cfi_def_cfa_register register
2357 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2358                                                        SMLoc DirectiveLoc) {
2359   int64_t Register = 0;
2360   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2361     return true;
2362
2363   return getStreamer().EmitCFIDefCfaRegister(Register);
2364 }
2365
2366 /// ParseDirectiveCFIOffset
2367 /// ::= .cfi_offset register, offset
2368 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2369   int64_t Register = 0;
2370   int64_t Offset = 0;
2371
2372   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2373     return true;
2374
2375   if (getLexer().isNot(AsmToken::Comma))
2376     return TokError("unexpected token in directive");
2377   Lex();
2378
2379   if (getParser().ParseAbsoluteExpression(Offset))
2380     return true;
2381
2382   return getStreamer().EmitCFIOffset(Register, Offset);
2383 }
2384
2385 /// ParseDirectiveCFIRelOffset
2386 /// ::= .cfi_rel_offset register, offset
2387 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2388                                                   SMLoc DirectiveLoc) {
2389   int64_t Register = 0;
2390
2391   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2392     return true;
2393
2394   if (getLexer().isNot(AsmToken::Comma))
2395     return TokError("unexpected token in directive");
2396   Lex();
2397
2398   int64_t Offset = 0;
2399   if (getParser().ParseAbsoluteExpression(Offset))
2400     return true;
2401
2402   getStreamer().EmitCFIRelOffset(Register, Offset);
2403   return false;
2404 }
2405
2406 static bool isValidEncoding(int64_t Encoding) {
2407   if (Encoding & ~0xff)
2408     return false;
2409
2410   if (Encoding == dwarf::DW_EH_PE_omit)
2411     return true;
2412
2413   const unsigned Format = Encoding & 0xf;
2414   if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2415       Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2416       Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2417       Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2418     return false;
2419
2420   const unsigned Application = Encoding & 0x70;
2421   if (Application != dwarf::DW_EH_PE_absptr &&
2422       Application != dwarf::DW_EH_PE_pcrel)
2423     return false;
2424
2425   return true;
2426 }
2427
2428 /// ParseDirectiveCFIPersonalityOrLsda
2429 /// ::= .cfi_personality encoding, [symbol_name]
2430 /// ::= .cfi_lsda encoding, [symbol_name]
2431 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2432                                                     SMLoc DirectiveLoc) {
2433   int64_t Encoding = 0;
2434   if (getParser().ParseAbsoluteExpression(Encoding))
2435     return true;
2436   if (Encoding == dwarf::DW_EH_PE_omit)
2437     return false;
2438
2439   if (!isValidEncoding(Encoding))
2440     return TokError("unsupported encoding.");
2441
2442   if (getLexer().isNot(AsmToken::Comma))
2443     return TokError("unexpected token in directive");
2444   Lex();
2445
2446   StringRef Name;
2447   if (getParser().ParseIdentifier(Name))
2448     return TokError("expected identifier in directive");
2449
2450   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2451
2452   if (IDVal == ".cfi_personality")
2453     return getStreamer().EmitCFIPersonality(Sym, Encoding);
2454   else {
2455     assert(IDVal == ".cfi_lsda");
2456     return getStreamer().EmitCFILsda(Sym, Encoding);
2457   }
2458 }
2459
2460 /// ParseDirectiveCFIRememberState
2461 /// ::= .cfi_remember_state
2462 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2463                                                       SMLoc DirectiveLoc) {
2464   return getStreamer().EmitCFIRememberState();
2465 }
2466
2467 /// ParseDirectiveCFIRestoreState
2468 /// ::= .cfi_remember_state
2469 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2470                                                      SMLoc DirectiveLoc) {
2471   return getStreamer().EmitCFIRestoreState();
2472 }
2473
2474 /// ParseDirectiveCFISameValue
2475 /// ::= .cfi_same_value register
2476 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2477                                                   SMLoc DirectiveLoc) {
2478   int64_t Register = 0;
2479
2480   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2481     return true;
2482
2483   getStreamer().EmitCFISameValue(Register);
2484
2485   return false;
2486 }
2487
2488 /// ParseDirectiveMacrosOnOff
2489 /// ::= .macros_on
2490 /// ::= .macros_off
2491 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2492                                                  SMLoc DirectiveLoc) {
2493   if (getLexer().isNot(AsmToken::EndOfStatement))
2494     return Error(getLexer().getLoc(),
2495                  "unexpected token in '" + Directive + "' directive");
2496
2497   getParser().MacrosEnabled = Directive == ".macros_on";
2498
2499   return false;
2500 }
2501
2502 /// ParseDirectiveMacro
2503 /// ::= .macro name
2504 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2505                                            SMLoc DirectiveLoc) {
2506   StringRef Name;
2507   if (getParser().ParseIdentifier(Name))
2508     return TokError("expected identifier in directive");
2509
2510   if (getLexer().isNot(AsmToken::EndOfStatement))
2511     return TokError("unexpected token in '.macro' directive");
2512
2513   // Eat the end of statement.
2514   Lex();
2515
2516   AsmToken EndToken, StartToken = getTok();
2517
2518   // Lex the macro definition.
2519   for (;;) {
2520     // Check whether we have reached the end of the file.
2521     if (getLexer().is(AsmToken::Eof))
2522       return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2523
2524     // Otherwise, check whether we have reach the .endmacro.
2525     if (getLexer().is(AsmToken::Identifier) &&
2526         (getTok().getIdentifier() == ".endm" ||
2527          getTok().getIdentifier() == ".endmacro")) {
2528       EndToken = getTok();
2529       Lex();
2530       if (getLexer().isNot(AsmToken::EndOfStatement))
2531         return TokError("unexpected token in '" + EndToken.getIdentifier() +
2532                         "' directive");
2533       break;
2534     }
2535
2536     // Otherwise, scan til the end of the statement.
2537     getParser().EatToEndOfStatement();
2538   }
2539
2540   if (getParser().MacroMap.lookup(Name)) {
2541     return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2542   }
2543
2544   const char *BodyStart = StartToken.getLoc().getPointer();
2545   const char *BodyEnd = EndToken.getLoc().getPointer();
2546   StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2547   getParser().MacroMap[Name] = new Macro(Name, Body);
2548   return false;
2549 }
2550
2551 /// ParseDirectiveEndMacro
2552 /// ::= .endm
2553 /// ::= .endmacro
2554 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2555                                            SMLoc DirectiveLoc) {
2556   if (getLexer().isNot(AsmToken::EndOfStatement))
2557     return TokError("unexpected token in '" + Directive + "' directive");
2558
2559   // If we are inside a macro instantiation, terminate the current
2560   // instantiation.
2561   if (!getParser().ActiveMacros.empty()) {
2562     getParser().HandleMacroExit();
2563     return false;
2564   }
2565
2566   // Otherwise, this .endmacro is a stray entry in the file; well formed
2567   // .endmacro directives are handled during the macro definition parsing.
2568   return TokError("unexpected '" + Directive + "' in file, "
2569                   "no current macro definition");
2570 }
2571
2572 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2573   getParser().CheckForValidSection();
2574
2575   const MCExpr *Value;
2576
2577   if (getParser().ParseExpression(Value))
2578     return true;
2579
2580   if (getLexer().isNot(AsmToken::EndOfStatement))
2581     return TokError("unexpected token in directive");
2582
2583   if (DirName[1] == 's')
2584     getStreamer().EmitSLEB128Value(Value);
2585   else
2586     getStreamer().EmitULEB128Value(Value);
2587
2588   return false;
2589 }
2590
2591
2592 /// \brief Create an MCAsmParser instance.
2593 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2594                                      MCContext &C, MCStreamer &Out,
2595                                      const MCAsmInfo &MAI) {
2596   return new AsmParser(T, SM, C, Out, MAI);
2597 }