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