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