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