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