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