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