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