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