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