Remove unused calls to Lexer.getLoc and the pointless variable HasFillExpr.
[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/MC/MCParser/AsmParser.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSymbol.h"
24 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Target/TargetAsmParser.h"
30 using namespace llvm;
31
32
33 enum { DEFAULT_ADDRSPACE = 0 };
34
35 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
36                      const MCAsmInfo &_MAI) 
37   : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM), TargetParser(0),
38     CurBuffer(0) {
39   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
40   
41   // Debugging directives.
42   AddDirectiveHandler(".file", &AsmParser::ParseDirectiveFile);
43   AddDirectiveHandler(".line", &AsmParser::ParseDirectiveLine);
44   AddDirectiveHandler(".loc", &AsmParser::ParseDirectiveLoc);
45 }
46
47
48
49 AsmParser::~AsmParser() {
50 }
51
52 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
53   PrintMessage(L, Msg.str(), "warning");
54 }
55
56 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
57   PrintMessage(L, Msg.str(), "error");
58   return true;
59 }
60
61 bool AsmParser::TokError(const char *Msg) {
62   PrintMessage(Lexer.getLoc(), Msg, "error");
63   return true;
64 }
65
66 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg, 
67                              const char *Type) const {
68   SrcMgr.PrintMessage(Loc, Msg, Type);
69 }
70                   
71 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
72   int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
73   if (NewBuf == -1)
74     return true;
75   
76   CurBuffer = NewBuf;
77   
78   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
79   
80   return false;
81 }
82                   
83 const AsmToken &AsmParser::Lex() {
84   const AsmToken *tok = &Lexer.Lex();
85   
86   if (tok->is(AsmToken::Eof)) {
87     // If this is the end of an included file, pop the parent file off the
88     // include stack.
89     SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
90     if (ParentIncludeLoc != SMLoc()) {
91       CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);
92       Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), 
93                       ParentIncludeLoc.getPointer());
94       tok = &Lexer.Lex();
95     }
96   }
97     
98   if (tok->is(AsmToken::Error))
99     PrintMessage(Lexer.getErrLoc(), Lexer.getErr(), "error");
100   
101   return *tok;
102 }
103
104 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
105   // Create the initial section, if requested.
106   //
107   // FIXME: Target hook & command line option for initial section.
108   if (!NoInitialTextSection)
109     Out.SwitchSection(Ctx.getMachOSection("__TEXT", "__text",
110                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
111                                       0, SectionKind::getText()));
112
113   // Prime the lexer.
114   Lex();
115   
116   bool HadError = false;
117   
118   AsmCond StartingCondState = TheCondState;
119
120   // While we have input, parse each statement.
121   while (Lexer.isNot(AsmToken::Eof)) {
122     if (!ParseStatement()) continue;
123   
124     // We had an error, remember it and recover by skipping to the next line.
125     HadError = true;
126     EatToEndOfStatement();
127   }
128
129   if (TheCondState.TheCond != StartingCondState.TheCond ||
130       TheCondState.Ignore != StartingCondState.Ignore)
131     return TokError("unmatched .ifs or .elses");
132   
133   // Finalize the output stream if there are no errors and if the client wants
134   // us to.
135   if (!HadError && !NoFinalize)  
136     Out.Finish();
137
138   return HadError;
139 }
140
141 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
142 void AsmParser::EatToEndOfStatement() {
143   while (Lexer.isNot(AsmToken::EndOfStatement) &&
144          Lexer.isNot(AsmToken::Eof))
145     Lex();
146   
147   // Eat EOL.
148   if (Lexer.is(AsmToken::EndOfStatement))
149     Lex();
150 }
151
152
153 /// ParseParenExpr - Parse a paren expression and return it.
154 /// NOTE: This assumes the leading '(' has already been consumed.
155 ///
156 /// parenexpr ::= expr)
157 ///
158 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
159   if (ParseExpression(Res)) return true;
160   if (Lexer.isNot(AsmToken::RParen))
161     return TokError("expected ')' in parentheses expression");
162   EndLoc = Lexer.getLoc();
163   Lex();
164   return false;
165 }
166
167 MCSymbol *AsmParser::CreateSymbol(StringRef Name) {
168   // FIXME: Inline into callers.
169   return Ctx.GetOrCreateSymbol(Name);
170 }
171
172 /// ParsePrimaryExpr - Parse a primary expression and return it.
173 ///  primaryexpr ::= (parenexpr
174 ///  primaryexpr ::= symbol
175 ///  primaryexpr ::= number
176 ///  primaryexpr ::= '.'
177 ///  primaryexpr ::= ~,+,- primaryexpr
178 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
179   switch (Lexer.getKind()) {
180   default:
181     return TokError("unknown token in expression");
182   case AsmToken::Exclaim:
183     Lex(); // Eat the operator.
184     if (ParsePrimaryExpr(Res, EndLoc))
185       return true;
186     Res = MCUnaryExpr::CreateLNot(Res, getContext());
187     return false;
188   case AsmToken::String:
189   case AsmToken::Identifier: {
190     // This is a symbol reference.
191     std::pair<StringRef, StringRef> Split = getTok().getIdentifier().split('@');
192     MCSymbol *Sym = CreateSymbol(Split.first);
193
194     // Mark the symbol as used in an expression.
195     Sym->setUsedInExpr(true);
196
197     // Lookup the symbol variant if used.
198     MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
199     if (Split.first.size() != getTok().getIdentifier().size())
200       Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
201
202     EndLoc = Lexer.getLoc();
203     Lex(); // Eat identifier.
204
205     // If this is an absolute variable reference, substitute it now to preserve
206     // semantics in the face of reassignment.
207     if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
208       if (Variant)
209         return Error(EndLoc, "unexpected modified on variable reference");
210
211       Res = Sym->getVariableValue();
212       return false;
213     }
214
215     // Otherwise create a symbol ref.
216     Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
217     return false;
218   }
219   case AsmToken::Integer: {
220     SMLoc Loc = getTok().getLoc();
221     int64_t IntVal = getTok().getIntVal();
222     Res = MCConstantExpr::Create(IntVal, getContext());
223     EndLoc = Lexer.getLoc();
224     Lex(); // Eat token.
225     // Look for 'b' or 'f' following an Integer as a directional label
226     if (Lexer.getKind() == AsmToken::Identifier) {
227       StringRef IDVal = getTok().getString();
228       if (IDVal == "f" || IDVal == "b"){
229         MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
230                                                       IDVal == "f" ? 1 : 0);
231         Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
232                                       getContext());
233         if(IDVal == "b" && Sym->isUndefined())
234           return Error(Loc, "invalid reference to undefined symbol");
235         EndLoc = Lexer.getLoc();
236         Lex(); // Eat identifier.
237       }
238     }
239     return false;
240   }
241   case AsmToken::Dot: {
242     // This is a '.' reference, which references the current PC.  Emit a
243     // temporary label to the streamer and refer to it.
244     MCSymbol *Sym = Ctx.CreateTempSymbol();
245     Out.EmitLabel(Sym);
246     Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
247     EndLoc = Lexer.getLoc();
248     Lex(); // Eat identifier.
249     return false;
250   }
251       
252   case AsmToken::LParen:
253     Lex(); // Eat the '('.
254     return ParseParenExpr(Res, EndLoc);
255   case AsmToken::Minus:
256     Lex(); // Eat the operator.
257     if (ParsePrimaryExpr(Res, EndLoc))
258       return true;
259     Res = MCUnaryExpr::CreateMinus(Res, getContext());
260     return false;
261   case AsmToken::Plus:
262     Lex(); // Eat the operator.
263     if (ParsePrimaryExpr(Res, EndLoc))
264       return true;
265     Res = MCUnaryExpr::CreatePlus(Res, getContext());
266     return false;
267   case AsmToken::Tilde:
268     Lex(); // Eat the operator.
269     if (ParsePrimaryExpr(Res, EndLoc))
270       return true;
271     Res = MCUnaryExpr::CreateNot(Res, getContext());
272     return false;
273   }
274 }
275
276 bool AsmParser::ParseExpression(const MCExpr *&Res) {
277   SMLoc EndLoc;
278   return ParseExpression(Res, EndLoc);
279 }
280
281 /// ParseExpression - Parse an expression and return it.
282 /// 
283 ///  expr ::= expr +,- expr          -> lowest.
284 ///  expr ::= expr |,^,&,! expr      -> middle.
285 ///  expr ::= expr *,/,%,<<,>> expr  -> highest.
286 ///  expr ::= primaryexpr
287 ///
288 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
289   // Parse the expression.
290   Res = 0;
291   if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
292     return true;
293
294   // Try to constant fold it up front, if possible.
295   int64_t Value;
296   if (Res->EvaluateAsAbsolute(Value))
297     Res = MCConstantExpr::Create(Value, getContext());
298
299   return false;
300 }
301
302 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
303   Res = 0;
304   return ParseParenExpr(Res, EndLoc) ||
305          ParseBinOpRHS(1, Res, EndLoc);
306 }
307
308 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
309   const MCExpr *Expr;
310   
311   SMLoc StartLoc = Lexer.getLoc();
312   if (ParseExpression(Expr))
313     return true;
314
315   if (!Expr->EvaluateAsAbsolute(Res))
316     return Error(StartLoc, "expected absolute expression");
317
318   return false;
319 }
320
321 static unsigned getBinOpPrecedence(AsmToken::TokenKind K, 
322                                    MCBinaryExpr::Opcode &Kind) {
323   switch (K) {
324   default:
325     return 0;    // not a binop.
326
327     // Lowest Precedence: &&, ||
328   case AsmToken::AmpAmp:
329     Kind = MCBinaryExpr::LAnd;
330     return 1;
331   case AsmToken::PipePipe:
332     Kind = MCBinaryExpr::LOr;
333     return 1;
334
335     // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
336   case AsmToken::Plus:
337     Kind = MCBinaryExpr::Add;
338     return 2;
339   case AsmToken::Minus:
340     Kind = MCBinaryExpr::Sub;
341     return 2;
342   case AsmToken::EqualEqual:
343     Kind = MCBinaryExpr::EQ;
344     return 2;
345   case AsmToken::ExclaimEqual:
346   case AsmToken::LessGreater:
347     Kind = MCBinaryExpr::NE;
348     return 2;
349   case AsmToken::Less:
350     Kind = MCBinaryExpr::LT;
351     return 2;
352   case AsmToken::LessEqual:
353     Kind = MCBinaryExpr::LTE;
354     return 2;
355   case AsmToken::Greater:
356     Kind = MCBinaryExpr::GT;
357     return 2;
358   case AsmToken::GreaterEqual:
359     Kind = MCBinaryExpr::GTE;
360     return 2;
361
362     // Intermediate Precedence: |, &, ^
363     //
364     // FIXME: gas seems to support '!' as an infix operator?
365   case AsmToken::Pipe:
366     Kind = MCBinaryExpr::Or;
367     return 3;
368   case AsmToken::Caret:
369     Kind = MCBinaryExpr::Xor;
370     return 3;
371   case AsmToken::Amp:
372     Kind = MCBinaryExpr::And;
373     return 3;
374
375     // Highest Precedence: *, /, %, <<, >>
376   case AsmToken::Star:
377     Kind = MCBinaryExpr::Mul;
378     return 4;
379   case AsmToken::Slash:
380     Kind = MCBinaryExpr::Div;
381     return 4;
382   case AsmToken::Percent:
383     Kind = MCBinaryExpr::Mod;
384     return 4;
385   case AsmToken::LessLess:
386     Kind = MCBinaryExpr::Shl;
387     return 4;
388   case AsmToken::GreaterGreater:
389     Kind = MCBinaryExpr::Shr;
390     return 4;
391   }
392 }
393
394
395 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
396 /// Res contains the LHS of the expression on input.
397 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
398                               SMLoc &EndLoc) {
399   while (1) {
400     MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
401     unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
402     
403     // If the next token is lower precedence than we are allowed to eat, return
404     // successfully with what we ate already.
405     if (TokPrec < Precedence)
406       return false;
407     
408     Lex();
409     
410     // Eat the next primary expression.
411     const MCExpr *RHS;
412     if (ParsePrimaryExpr(RHS, EndLoc)) return true;
413     
414     // If BinOp binds less tightly with RHS than the operator after RHS, let
415     // the pending operator take RHS as its LHS.
416     MCBinaryExpr::Opcode Dummy;
417     unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
418     if (TokPrec < NextTokPrec) {
419       if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
420     }
421
422     // Merge LHS and RHS according to operator.
423     Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
424   }
425 }
426
427   
428   
429   
430 /// ParseStatement:
431 ///   ::= EndOfStatement
432 ///   ::= Label* Directive ...Operands... EndOfStatement
433 ///   ::= Label* Identifier OperandList* EndOfStatement
434 bool AsmParser::ParseStatement() {
435   if (Lexer.is(AsmToken::EndOfStatement)) {
436     Out.AddBlankLine();
437     Lex();
438     return false;
439   }
440
441   // Statements always start with an identifier.
442   AsmToken ID = getTok();
443   SMLoc IDLoc = ID.getLoc();
444   StringRef IDVal;
445   int64_t LocalLabelVal = -1;
446   // GUESS allow an integer followed by a ':' as a directional local label
447   if (Lexer.is(AsmToken::Integer)) {
448     LocalLabelVal = getTok().getIntVal();
449     if (LocalLabelVal < 0) {
450       if (!TheCondState.Ignore)
451         return TokError("unexpected token at start of statement");
452       IDVal = "";
453     }
454     else {
455       IDVal = getTok().getString();
456       Lex(); // Consume the integer token to be used as an identifier token.
457       if (Lexer.getKind() != AsmToken::Colon) {
458           if (!TheCondState.Ignore)
459             return TokError("unexpected token at start of statement");
460       }
461     }
462   }
463   else if (ParseIdentifier(IDVal)) {
464     if (!TheCondState.Ignore)
465       return TokError("unexpected token at start of statement");
466     IDVal = "";
467   }
468
469   // Handle conditional assembly here before checking for skipping.  We
470   // have to do this so that .endif isn't skipped in a ".if 0" block for
471   // example.
472   if (IDVal == ".if")
473     return ParseDirectiveIf(IDLoc);
474   if (IDVal == ".elseif")
475     return ParseDirectiveElseIf(IDLoc);
476   if (IDVal == ".else")
477     return ParseDirectiveElse(IDLoc);
478   if (IDVal == ".endif")
479     return ParseDirectiveEndIf(IDLoc);
480     
481   // If we are in a ".if 0" block, ignore this statement.
482   if (TheCondState.Ignore) {
483     EatToEndOfStatement();
484     return false;
485   }
486   
487   // FIXME: Recurse on local labels?
488
489   // See what kind of statement we have.
490   switch (Lexer.getKind()) {
491   case AsmToken::Colon: {
492     // identifier ':'   -> Label.
493     Lex();
494
495     // Diagnose attempt to use a variable as a label.
496     //
497     // FIXME: Diagnostics. Note the location of the definition as a label.
498     // FIXME: This doesn't diagnose assignment to a symbol which has been
499     // implicitly marked as external.
500     MCSymbol *Sym;
501     if (LocalLabelVal == -1)
502       Sym = CreateSymbol(IDVal);
503     else
504       Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
505     if (!Sym->isUndefined() || Sym->isVariable())
506       return Error(IDLoc, "invalid symbol redefinition");
507     
508     // Emit the label.
509     Out.EmitLabel(Sym);
510    
511     // Consume any end of statement token, if present, to avoid spurious
512     // AddBlankLine calls().
513     if (Lexer.is(AsmToken::EndOfStatement)) {
514       Lex();
515       if (Lexer.is(AsmToken::Eof))
516         return false;
517     }
518
519     return ParseStatement();
520   }
521
522   case AsmToken::Equal:
523     // identifier '=' ... -> assignment statement
524     Lex();
525
526     return ParseAssignment(IDVal);
527
528   default: // Normal instruction or directive.
529     break;
530   }
531   
532   // Otherwise, we have a normal instruction or directive.  
533   if (IDVal[0] == '.') {
534     // FIXME: This should be driven based on a hash lookup and callback.
535     if (IDVal == ".section")
536       return ParseDirectiveDarwinSection();
537     if (IDVal == ".text")
538       // FIXME: This changes behavior based on the -static flag to the
539       // assembler.
540       return ParseDirectiveSectionSwitch("__TEXT", "__text",
541                                      MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
542     if (IDVal == ".const")
543       return ParseDirectiveSectionSwitch("__TEXT", "__const");
544     if (IDVal == ".static_const")
545       return ParseDirectiveSectionSwitch("__TEXT", "__static_const");
546     if (IDVal == ".cstring")
547       return ParseDirectiveSectionSwitch("__TEXT","__cstring", 
548                                          MCSectionMachO::S_CSTRING_LITERALS);
549     if (IDVal == ".literal4")
550       return ParseDirectiveSectionSwitch("__TEXT", "__literal4",
551                                          MCSectionMachO::S_4BYTE_LITERALS,
552                                          4);
553     if (IDVal == ".literal8")
554       return ParseDirectiveSectionSwitch("__TEXT", "__literal8",
555                                          MCSectionMachO::S_8BYTE_LITERALS,
556                                          8);
557     if (IDVal == ".literal16")
558       return ParseDirectiveSectionSwitch("__TEXT","__literal16",
559                                          MCSectionMachO::S_16BYTE_LITERALS,
560                                          16);
561     if (IDVal == ".constructor")
562       return ParseDirectiveSectionSwitch("__TEXT","__constructor");
563     if (IDVal == ".destructor")
564       return ParseDirectiveSectionSwitch("__TEXT","__destructor");
565     if (IDVal == ".fvmlib_init0")
566       return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init0");
567     if (IDVal == ".fvmlib_init1")
568       return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init1");
569
570     // FIXME: The assembler manual claims that this has the self modify code
571     // flag, at least on x86-32, but that does not appear to be correct.
572     if (IDVal == ".symbol_stub")
573       return ParseDirectiveSectionSwitch("__TEXT","__symbol_stub",
574                                          MCSectionMachO::S_SYMBOL_STUBS |
575                                        MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
576                                           // FIXME: Different on PPC and ARM.
577                                          0, 16);
578     // FIXME: PowerPC only?
579     if (IDVal == ".picsymbol_stub")
580       return ParseDirectiveSectionSwitch("__TEXT","__picsymbol_stub",
581                                          MCSectionMachO::S_SYMBOL_STUBS |
582                                        MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
583                                          0, 26);
584     if (IDVal == ".data")
585       return ParseDirectiveSectionSwitch("__DATA", "__data");
586     if (IDVal == ".static_data")
587       return ParseDirectiveSectionSwitch("__DATA", "__static_data");
588
589     // FIXME: The section names of these two are misspelled in the assembler
590     // manual.
591     if (IDVal == ".non_lazy_symbol_pointer")
592       return ParseDirectiveSectionSwitch("__DATA", "__nl_symbol_ptr",
593                                      MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
594                                          4);
595     if (IDVal == ".lazy_symbol_pointer")
596       return ParseDirectiveSectionSwitch("__DATA", "__la_symbol_ptr",
597                                          MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
598                                          4);
599
600     if (IDVal == ".dyld")
601       return ParseDirectiveSectionSwitch("__DATA", "__dyld");
602     if (IDVal == ".mod_init_func")
603       return ParseDirectiveSectionSwitch("__DATA", "__mod_init_func",
604                                        MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
605                                          4);
606     if (IDVal == ".mod_term_func")
607       return ParseDirectiveSectionSwitch("__DATA", "__mod_term_func",
608                                        MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
609                                          4);
610     if (IDVal == ".const_data")
611       return ParseDirectiveSectionSwitch("__DATA", "__const");
612     
613     
614     if (IDVal == ".objc_class")
615       return ParseDirectiveSectionSwitch("__OBJC", "__class", 
616                                          MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
617     if (IDVal == ".objc_meta_class")
618       return ParseDirectiveSectionSwitch("__OBJC", "__meta_class",
619                                          MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
620     if (IDVal == ".objc_cat_cls_meth")
621       return ParseDirectiveSectionSwitch("__OBJC", "__cat_cls_meth",
622                                          MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
623     if (IDVal == ".objc_cat_inst_meth")
624       return ParseDirectiveSectionSwitch("__OBJC", "__cat_inst_meth",
625                                          MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
626     if (IDVal == ".objc_protocol")
627       return ParseDirectiveSectionSwitch("__OBJC", "__protocol",
628                                          MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
629     if (IDVal == ".objc_string_object")
630       return ParseDirectiveSectionSwitch("__OBJC", "__string_object",
631                                          MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
632     if (IDVal == ".objc_cls_meth")
633       return ParseDirectiveSectionSwitch("__OBJC", "__cls_meth",
634                                          MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
635     if (IDVal == ".objc_inst_meth")
636       return ParseDirectiveSectionSwitch("__OBJC", "__inst_meth",
637                                          MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
638     if (IDVal == ".objc_cls_refs")
639       return ParseDirectiveSectionSwitch("__OBJC", "__cls_refs",
640                                          MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
641                                          MCSectionMachO::S_LITERAL_POINTERS,
642                                          4);
643     if (IDVal == ".objc_message_refs")
644       return ParseDirectiveSectionSwitch("__OBJC", "__message_refs",
645                                          MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
646                                          MCSectionMachO::S_LITERAL_POINTERS,
647                                          4);
648     if (IDVal == ".objc_symbols")
649       return ParseDirectiveSectionSwitch("__OBJC", "__symbols",
650                                          MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
651     if (IDVal == ".objc_category")
652       return ParseDirectiveSectionSwitch("__OBJC", "__category",
653                                          MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
654     if (IDVal == ".objc_class_vars")
655       return ParseDirectiveSectionSwitch("__OBJC", "__class_vars",
656                                          MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
657     if (IDVal == ".objc_instance_vars")
658       return ParseDirectiveSectionSwitch("__OBJC", "__instance_vars",
659                                          MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
660     if (IDVal == ".objc_module_info")
661       return ParseDirectiveSectionSwitch("__OBJC", "__module_info",
662                                          MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
663     if (IDVal == ".objc_class_names")
664       return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
665                                          MCSectionMachO::S_CSTRING_LITERALS);
666     if (IDVal == ".objc_meth_var_types")
667       return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
668                                          MCSectionMachO::S_CSTRING_LITERALS);
669     if (IDVal == ".objc_meth_var_names")
670       return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
671                                          MCSectionMachO::S_CSTRING_LITERALS);
672     if (IDVal == ".objc_selector_strs")
673       return ParseDirectiveSectionSwitch("__OBJC", "__selector_strs",
674                                          MCSectionMachO::S_CSTRING_LITERALS);
675     
676     if (IDVal == ".tdata")
677       return ParseDirectiveSectionSwitch("__DATA", "__thread_data",
678                                         MCSectionMachO::S_THREAD_LOCAL_REGULAR);
679     if (IDVal == ".tlv")
680       return ParseDirectiveSectionSwitch("__DATA", "__thread_vars",
681                                       MCSectionMachO::S_THREAD_LOCAL_VARIABLES);
682     if (IDVal == ".thread_init_func")
683       return ParseDirectiveSectionSwitch("__DATA", "__thread_init",
684                         MCSectionMachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS);
685     
686     // Assembler features
687     if (IDVal == ".set")
688       return ParseDirectiveSet();
689
690     // Data directives
691
692     if (IDVal == ".ascii")
693       return ParseDirectiveAscii(false);
694     if (IDVal == ".asciz")
695       return ParseDirectiveAscii(true);
696
697     if (IDVal == ".byte")
698       return ParseDirectiveValue(1);
699     if (IDVal == ".short")
700       return ParseDirectiveValue(2);
701     if (IDVal == ".long")
702       return ParseDirectiveValue(4);
703     if (IDVal == ".quad")
704       return ParseDirectiveValue(8);
705
706     // FIXME: Target hooks for IsPow2.
707     if (IDVal == ".align")
708       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
709     if (IDVal == ".align32")
710       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
711     if (IDVal == ".balign")
712       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
713     if (IDVal == ".balignw")
714       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
715     if (IDVal == ".balignl")
716       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
717     if (IDVal == ".p2align")
718       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
719     if (IDVal == ".p2alignw")
720       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
721     if (IDVal == ".p2alignl")
722       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
723
724     if (IDVal == ".org")
725       return ParseDirectiveOrg();
726
727     if (IDVal == ".fill")
728       return ParseDirectiveFill();
729     if (IDVal == ".space")
730       return ParseDirectiveSpace();
731
732     // Symbol attribute directives
733
734     if (IDVal == ".globl" || IDVal == ".global")
735       return ParseDirectiveSymbolAttribute(MCSA_Global);
736     if (IDVal == ".hidden")
737       return ParseDirectiveSymbolAttribute(MCSA_Hidden);
738     if (IDVal == ".indirect_symbol")
739       return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
740     if (IDVal == ".internal")
741       return ParseDirectiveSymbolAttribute(MCSA_Internal);
742     if (IDVal == ".lazy_reference")
743       return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
744     if (IDVal == ".no_dead_strip")
745       return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
746     if (IDVal == ".private_extern")
747       return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
748     if (IDVal == ".protected")
749       return ParseDirectiveSymbolAttribute(MCSA_Protected);
750     if (IDVal == ".reference")
751       return ParseDirectiveSymbolAttribute(MCSA_Reference);
752     if (IDVal == ".type")
753       return ParseDirectiveELFType();
754     if (IDVal == ".weak")
755       return ParseDirectiveSymbolAttribute(MCSA_Weak);
756     if (IDVal == ".weak_definition")
757       return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
758     if (IDVal == ".weak_reference")
759       return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
760
761     if (IDVal == ".comm")
762       return ParseDirectiveComm(/*IsLocal=*/false);
763     if (IDVal == ".lcomm")
764       return ParseDirectiveComm(/*IsLocal=*/true);
765     if (IDVal == ".zerofill")
766       return ParseDirectiveDarwinZerofill();
767     if (IDVal == ".desc")
768       return ParseDirectiveDarwinSymbolDesc();
769     if (IDVal == ".lsym")
770       return ParseDirectiveDarwinLsym();
771     if (IDVal == ".tbss")
772       return ParseDirectiveDarwinTBSS();
773
774     if (IDVal == ".subsections_via_symbols")
775       return ParseDirectiveDarwinSubsectionsViaSymbols();
776     if (IDVal == ".abort")
777       return ParseDirectiveAbort();
778     if (IDVal == ".include")
779       return ParseDirectiveInclude();
780     if (IDVal == ".dump")
781       return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsDump=*/true);
782     if (IDVal == ".load")
783       return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsLoad=*/false);
784     if (IDVal == ".secure_log_unique")
785       return ParseDirectiveDarwinSecureLogUnique(IDLoc);
786     if (IDVal == ".secure_log_reset")
787       return ParseDirectiveDarwinSecureLogReset(IDLoc);
788
789     // Look up the handler in the handler table, 
790     bool(AsmParser::*Handler)(StringRef, SMLoc) = DirectiveMap[IDVal];
791     if (Handler)
792       return (this->*Handler)(IDVal, IDLoc);
793     
794     // Target hook for parsing target specific directives.
795     if (!getTargetParser().ParseDirective(ID))
796       return false;
797
798     Warning(IDLoc, "ignoring directive for now");
799     EatToEndOfStatement();
800     return false;
801   }
802
803   // Canonicalize the opcode to lower case.
804   SmallString<128> Opcode;
805   for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
806     Opcode.push_back(tolower(IDVal[i]));
807   
808   SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
809   bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
810                                                      ParsedOperands);
811   if (!HadError && Lexer.isNot(AsmToken::EndOfStatement))
812     HadError = TokError("unexpected token in argument list");
813
814   // If parsing succeeded, match the instruction.
815   if (!HadError) {
816     MCInst Inst;
817     if (!getTargetParser().MatchInstruction(ParsedOperands, Inst)) {
818       // Emit the instruction on success.
819       Out.EmitInstruction(Inst);
820     } else {
821       // Otherwise emit a diagnostic about the match failure and set the error
822       // flag.
823       //
824       // FIXME: We should give nicer diagnostics about the exact failure.
825       Error(IDLoc, "unrecognized instruction");
826       HadError = true;
827     }
828   }
829
830   // If there was no error, consume the end-of-statement token. Otherwise this
831   // will be done by our caller.
832   if (!HadError)
833     Lex();
834
835   // Free any parsed operands.
836   for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
837     delete ParsedOperands[i];
838
839   return HadError;
840 }
841
842 bool AsmParser::ParseAssignment(const StringRef &Name) {
843   // FIXME: Use better location, we should use proper tokens.
844   SMLoc EqualLoc = Lexer.getLoc();
845
846   const MCExpr *Value;
847   if (ParseExpression(Value))
848     return true;
849   
850   if (Lexer.isNot(AsmToken::EndOfStatement))
851     return TokError("unexpected token in assignment");
852
853   // Eat the end of statement marker.
854   Lex();
855
856   // Validate that the LHS is allowed to be a variable (either it has not been
857   // used as a symbol, or it is an absolute symbol).
858   MCSymbol *Sym = getContext().LookupSymbol(Name);
859   if (Sym) {
860     // Diagnose assignment to a label.
861     //
862     // FIXME: Diagnostics. Note the location of the definition as a label.
863     // FIXME: Diagnose assignment to protected identifier (e.g., register name).
864     if (Sym->isUndefined() && !Sym->isUsedInExpr())
865       ; // Allow redefinitions of undefined symbols only used in directives.
866     else if (!Sym->isUndefined() && !Sym->isAbsolute())
867       return Error(EqualLoc, "redefinition of '" + Name + "'");
868     else if (!Sym->isVariable())
869       return Error(EqualLoc, "invalid assignment to '" + Name + "'");
870     else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
871       return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
872                    Name + "'");
873   } else
874     Sym = CreateSymbol(Name);
875
876   // FIXME: Handle '.'.
877
878   Sym->setUsedInExpr(true);
879
880   // Do the assignment.
881   Out.EmitAssignment(Sym, Value);
882
883   return false;
884 }
885
886 /// ParseIdentifier:
887 ///   ::= identifier
888 ///   ::= string
889 bool AsmParser::ParseIdentifier(StringRef &Res) {
890   if (Lexer.isNot(AsmToken::Identifier) &&
891       Lexer.isNot(AsmToken::String))
892     return true;
893
894   Res = getTok().getIdentifier();
895
896   Lex(); // Consume the identifier token.
897
898   return false;
899 }
900
901 /// ParseDirectiveSet:
902 ///   ::= .set identifier ',' expression
903 bool AsmParser::ParseDirectiveSet() {
904   StringRef Name;
905
906   if (ParseIdentifier(Name))
907     return TokError("expected identifier after '.set' directive");
908   
909   if (Lexer.isNot(AsmToken::Comma))
910     return TokError("unexpected token in '.set'");
911   Lex();
912
913   return ParseAssignment(Name);
914 }
915
916 /// ParseDirectiveSection:
917 ///   ::= .section identifier (',' identifier)*
918 /// FIXME: This should actually parse out the segment, section, attributes and
919 /// sizeof_stub fields.
920 bool AsmParser::ParseDirectiveDarwinSection() {
921   SMLoc Loc = Lexer.getLoc();
922
923   StringRef SectionName;
924   if (ParseIdentifier(SectionName))
925     return Error(Loc, "expected identifier after '.section' directive");
926
927   // Verify there is a following comma.
928   if (!Lexer.is(AsmToken::Comma))
929     return TokError("unexpected token in '.section' directive");
930
931   std::string SectionSpec = SectionName;
932   SectionSpec += ",";
933
934   // Add all the tokens until the end of the line, ParseSectionSpecifier will
935   // handle this.
936   StringRef EOL = Lexer.LexUntilEndOfStatement();
937   SectionSpec.append(EOL.begin(), EOL.end());
938
939   Lex();
940   if (Lexer.isNot(AsmToken::EndOfStatement))
941     return TokError("unexpected token in '.section' directive");
942   Lex();
943
944
945   StringRef Segment, Section;
946   unsigned TAA, StubSize;
947   std::string ErrorStr = 
948     MCSectionMachO::ParseSectionSpecifier(SectionSpec, Segment, Section,
949                                           TAA, StubSize);
950   
951   if (!ErrorStr.empty())
952     return Error(Loc, ErrorStr.c_str());
953   
954   // FIXME: Arch specific.
955   bool isText = Segment == "__TEXT";  // FIXME: Hack.
956   Out.SwitchSection(Ctx.getMachOSection(Segment, Section, TAA, StubSize,
957                                         isText ? SectionKind::getText()
958                                                : SectionKind::getDataRel()));
959   return false;
960 }
961
962 /// ParseDirectiveSectionSwitch - 
963 bool AsmParser::ParseDirectiveSectionSwitch(const char *Segment,
964                                             const char *Section,
965                                             unsigned TAA, unsigned Align,
966                                             unsigned StubSize) {
967   if (Lexer.isNot(AsmToken::EndOfStatement))
968     return TokError("unexpected token in section switching directive");
969   Lex();
970   
971   // FIXME: Arch specific.
972   bool isText = StringRef(Segment) == "__TEXT";  // FIXME: Hack.
973   Out.SwitchSection(Ctx.getMachOSection(Segment, Section, TAA, StubSize,
974                                         isText ? SectionKind::getText()
975                                                : SectionKind::getDataRel()));
976
977   // Set the implicit alignment, if any.
978   //
979   // FIXME: This isn't really what 'as' does; I think it just uses the implicit
980   // alignment on the section (e.g., if one manually inserts bytes into the
981   // section, then just issueing the section switch directive will not realign
982   // the section. However, this is arguably more reasonable behavior, and there
983   // is no good reason for someone to intentionally emit incorrectly sized
984   // values into the implicitly aligned sections.
985   if (Align)
986     Out.EmitValueToAlignment(Align, 0, 1, 0);
987
988   return false;
989 }
990
991 bool AsmParser::ParseEscapedString(std::string &Data) {
992   assert(Lexer.is(AsmToken::String) && "Unexpected current token!");
993
994   Data = "";
995   StringRef Str = getTok().getStringContents();
996   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
997     if (Str[i] != '\\') {
998       Data += Str[i];
999       continue;
1000     }
1001
1002     // Recognize escaped characters. Note that this escape semantics currently
1003     // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1004     ++i;
1005     if (i == e)
1006       return TokError("unexpected backslash at end of string");
1007
1008     // Recognize octal sequences.
1009     if ((unsigned) (Str[i] - '0') <= 7) {
1010       // Consume up to three octal characters.
1011       unsigned Value = Str[i] - '0';
1012
1013       if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1014         ++i;
1015         Value = Value * 8 + (Str[i] - '0');
1016
1017         if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1018           ++i;
1019           Value = Value * 8 + (Str[i] - '0');
1020         }
1021       }
1022
1023       if (Value > 255)
1024         return TokError("invalid octal escape sequence (out of range)");
1025
1026       Data += (unsigned char) Value;
1027       continue;
1028     }
1029
1030     // Otherwise recognize individual escapes.
1031     switch (Str[i]) {
1032     default:
1033       // Just reject invalid escape sequences for now.
1034       return TokError("invalid escape sequence (unrecognized character)");
1035
1036     case 'b': Data += '\b'; break;
1037     case 'f': Data += '\f'; break;
1038     case 'n': Data += '\n'; break;
1039     case 'r': Data += '\r'; break;
1040     case 't': Data += '\t'; break;
1041     case '"': Data += '"'; break;
1042     case '\\': Data += '\\'; break;
1043     }
1044   }
1045
1046   return false;
1047 }
1048
1049 /// ParseDirectiveAscii:
1050 ///   ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1051 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1052   if (Lexer.isNot(AsmToken::EndOfStatement)) {
1053     for (;;) {
1054       if (Lexer.isNot(AsmToken::String))
1055         return TokError("expected string in '.ascii' or '.asciz' directive");
1056       
1057       std::string Data;
1058       if (ParseEscapedString(Data))
1059         return true;
1060       
1061       Out.EmitBytes(Data, DEFAULT_ADDRSPACE);
1062       if (ZeroTerminated)
1063         Out.EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1064       
1065       Lex();
1066       
1067       if (Lexer.is(AsmToken::EndOfStatement))
1068         break;
1069
1070       if (Lexer.isNot(AsmToken::Comma))
1071         return TokError("unexpected token in '.ascii' or '.asciz' directive");
1072       Lex();
1073     }
1074   }
1075
1076   Lex();
1077   return false;
1078 }
1079
1080 /// ParseDirectiveValue
1081 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
1082 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1083   if (Lexer.isNot(AsmToken::EndOfStatement)) {
1084     for (;;) {
1085       const MCExpr *Value;
1086       SMLoc ATTRIBUTE_UNUSED StartLoc = Lexer.getLoc();
1087       if (ParseExpression(Value))
1088         return true;
1089
1090       // Special case constant expressions to match code generator.
1091       if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1092         Out.EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1093       else
1094         Out.EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1095
1096       if (Lexer.is(AsmToken::EndOfStatement))
1097         break;
1098       
1099       // FIXME: Improve diagnostic.
1100       if (Lexer.isNot(AsmToken::Comma))
1101         return TokError("unexpected token in directive");
1102       Lex();
1103     }
1104   }
1105
1106   Lex();
1107   return false;
1108 }
1109
1110 /// ParseDirectiveSpace
1111 ///  ::= .space expression [ , expression ]
1112 bool AsmParser::ParseDirectiveSpace() {
1113   int64_t NumBytes;
1114   if (ParseAbsoluteExpression(NumBytes))
1115     return true;
1116
1117   int64_t FillExpr = 0;
1118   if (Lexer.isNot(AsmToken::EndOfStatement)) {
1119     if (Lexer.isNot(AsmToken::Comma))
1120       return TokError("unexpected token in '.space' directive");
1121     Lex();
1122     
1123     if (ParseAbsoluteExpression(FillExpr))
1124       return true;
1125
1126     if (Lexer.isNot(AsmToken::EndOfStatement))
1127       return TokError("unexpected token in '.space' directive");
1128   }
1129
1130   Lex();
1131
1132   if (NumBytes <= 0)
1133     return TokError("invalid number of bytes in '.space' directive");
1134
1135   // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1136   Out.EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1137
1138   return false;
1139 }
1140
1141 /// ParseDirectiveFill
1142 ///  ::= .fill expression , expression , expression
1143 bool AsmParser::ParseDirectiveFill() {
1144   int64_t NumValues;
1145   if (ParseAbsoluteExpression(NumValues))
1146     return true;
1147
1148   if (Lexer.isNot(AsmToken::Comma))
1149     return TokError("unexpected token in '.fill' directive");
1150   Lex();
1151   
1152   int64_t FillSize;
1153   if (ParseAbsoluteExpression(FillSize))
1154     return true;
1155
1156   if (Lexer.isNot(AsmToken::Comma))
1157     return TokError("unexpected token in '.fill' directive");
1158   Lex();
1159   
1160   int64_t FillExpr;
1161   if (ParseAbsoluteExpression(FillExpr))
1162     return true;
1163
1164   if (Lexer.isNot(AsmToken::EndOfStatement))
1165     return TokError("unexpected token in '.fill' directive");
1166   
1167   Lex();
1168
1169   if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1170     return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1171
1172   for (uint64_t i = 0, e = NumValues; i != e; ++i)
1173     Out.EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1174
1175   return false;
1176 }
1177
1178 /// ParseDirectiveOrg
1179 ///  ::= .org expression [ , expression ]
1180 bool AsmParser::ParseDirectiveOrg() {
1181   const MCExpr *Offset;
1182   if (ParseExpression(Offset))
1183     return true;
1184
1185   // Parse optional fill expression.
1186   int64_t FillExpr = 0;
1187   if (Lexer.isNot(AsmToken::EndOfStatement)) {
1188     if (Lexer.isNot(AsmToken::Comma))
1189       return TokError("unexpected token in '.org' directive");
1190     Lex();
1191     
1192     if (ParseAbsoluteExpression(FillExpr))
1193       return true;
1194
1195     if (Lexer.isNot(AsmToken::EndOfStatement))
1196       return TokError("unexpected token in '.org' directive");
1197   }
1198
1199   Lex();
1200
1201   // FIXME: Only limited forms of relocatable expressions are accepted here, it
1202   // has to be relative to the current section.
1203   Out.EmitValueToOffset(Offset, FillExpr);
1204
1205   return false;
1206 }
1207
1208 /// ParseDirectiveAlign
1209 ///  ::= {.align, ...} expression [ , expression [ , expression ]]
1210 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1211   SMLoc AlignmentLoc = Lexer.getLoc();
1212   int64_t Alignment;
1213   if (ParseAbsoluteExpression(Alignment))
1214     return true;
1215
1216   SMLoc MaxBytesLoc;
1217   bool HasFillExpr = false;
1218   int64_t FillExpr = 0;
1219   int64_t MaxBytesToFill = 0;
1220   if (Lexer.isNot(AsmToken::EndOfStatement)) {
1221     if (Lexer.isNot(AsmToken::Comma))
1222       return TokError("unexpected token in directive");
1223     Lex();
1224
1225     // The fill expression can be omitted while specifying a maximum number of
1226     // alignment bytes, e.g:
1227     //  .align 3,,4
1228     if (Lexer.isNot(AsmToken::Comma)) {
1229       HasFillExpr = true;
1230       if (ParseAbsoluteExpression(FillExpr))
1231         return true;
1232     }
1233
1234     if (Lexer.isNot(AsmToken::EndOfStatement)) {
1235       if (Lexer.isNot(AsmToken::Comma))
1236         return TokError("unexpected token in directive");
1237       Lex();
1238
1239       MaxBytesLoc = Lexer.getLoc();
1240       if (ParseAbsoluteExpression(MaxBytesToFill))
1241         return true;
1242       
1243       if (Lexer.isNot(AsmToken::EndOfStatement))
1244         return TokError("unexpected token in directive");
1245     }
1246   }
1247
1248   Lex();
1249
1250   if (!HasFillExpr)
1251     FillExpr = 0;
1252
1253   // Compute alignment in bytes.
1254   if (IsPow2) {
1255     // FIXME: Diagnose overflow.
1256     if (Alignment >= 32) {
1257       Error(AlignmentLoc, "invalid alignment value");
1258       Alignment = 31;
1259     }
1260
1261     Alignment = 1ULL << Alignment;
1262   }
1263
1264   // Diagnose non-sensical max bytes to align.
1265   if (MaxBytesLoc.isValid()) {
1266     if (MaxBytesToFill < 1) {
1267       Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1268             "many bytes, ignoring maximum bytes expression");
1269       MaxBytesToFill = 0;
1270     }
1271
1272     if (MaxBytesToFill >= Alignment) {
1273       Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1274               "has no effect");
1275       MaxBytesToFill = 0;
1276     }
1277   }
1278
1279   // Check whether we should use optimal code alignment for this .align
1280   // directive.
1281   //
1282   // FIXME: This should be using a target hook.
1283   bool UseCodeAlign = false;
1284   if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1285         Out.getCurrentSection()))
1286       UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1287   if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1288       ValueSize == 1 && UseCodeAlign) {
1289     Out.EmitCodeAlignment(Alignment, MaxBytesToFill);
1290   } else {
1291     // FIXME: Target specific behavior about how the "extra" bytes are filled.
1292     Out.EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill);
1293   }
1294
1295   return false;
1296 }
1297
1298 /// ParseDirectiveSymbolAttribute
1299 ///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1300 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1301   if (Lexer.isNot(AsmToken::EndOfStatement)) {
1302     for (;;) {
1303       StringRef Name;
1304
1305       if (ParseIdentifier(Name))
1306         return TokError("expected identifier in directive");
1307       
1308       MCSymbol *Sym = CreateSymbol(Name);
1309
1310       Out.EmitSymbolAttribute(Sym, Attr);
1311
1312       if (Lexer.is(AsmToken::EndOfStatement))
1313         break;
1314
1315       if (Lexer.isNot(AsmToken::Comma))
1316         return TokError("unexpected token in directive");
1317       Lex();
1318     }
1319   }
1320
1321   Lex();
1322   return false;  
1323 }
1324
1325 /// ParseDirectiveELFType
1326 ///  ::= .type identifier , @attribute
1327 bool AsmParser::ParseDirectiveELFType() {
1328   StringRef Name;
1329   if (ParseIdentifier(Name))
1330     return TokError("expected identifier in directive");
1331
1332   // Handle the identifier as the key symbol.
1333   MCSymbol *Sym = CreateSymbol(Name);
1334
1335   if (Lexer.isNot(AsmToken::Comma))
1336     return TokError("unexpected token in '.type' directive");
1337   Lex();
1338
1339   if (Lexer.isNot(AsmToken::At))
1340     return TokError("expected '@' before type");
1341   Lex();
1342
1343   StringRef Type;
1344   SMLoc TypeLoc;
1345
1346   TypeLoc = Lexer.getLoc();
1347   if (ParseIdentifier(Type))
1348     return TokError("expected symbol type in directive");
1349
1350   MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1351     .Case("function", MCSA_ELF_TypeFunction)
1352     .Case("object", MCSA_ELF_TypeObject)
1353     .Case("tls_object", MCSA_ELF_TypeTLS)
1354     .Case("common", MCSA_ELF_TypeCommon)
1355     .Case("notype", MCSA_ELF_TypeNoType)
1356     .Default(MCSA_Invalid);
1357
1358   if (Attr == MCSA_Invalid)
1359     return Error(TypeLoc, "unsupported attribute in '.type' directive");
1360
1361   if (Lexer.isNot(AsmToken::EndOfStatement))
1362     return TokError("unexpected token in '.type' directive");
1363
1364   Lex();
1365
1366   Out.EmitSymbolAttribute(Sym, Attr);
1367
1368   return false;
1369 }
1370
1371 /// ParseDirectiveDarwinSymbolDesc
1372 ///  ::= .desc identifier , expression
1373 bool AsmParser::ParseDirectiveDarwinSymbolDesc() {
1374   StringRef Name;
1375   if (ParseIdentifier(Name))
1376     return TokError("expected identifier in directive");
1377   
1378   // Handle the identifier as the key symbol.
1379   MCSymbol *Sym = CreateSymbol(Name);
1380
1381   if (Lexer.isNot(AsmToken::Comma))
1382     return TokError("unexpected token in '.desc' directive");
1383   Lex();
1384
1385   int64_t DescValue;
1386   if (ParseAbsoluteExpression(DescValue))
1387     return true;
1388
1389   if (Lexer.isNot(AsmToken::EndOfStatement))
1390     return TokError("unexpected token in '.desc' directive");
1391   
1392   Lex();
1393
1394   // Set the n_desc field of this Symbol to this DescValue
1395   Out.EmitSymbolDesc(Sym, DescValue);
1396
1397   return false;
1398 }
1399
1400 /// ParseDirectiveComm
1401 ///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1402 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1403   SMLoc IDLoc = Lexer.getLoc();
1404   StringRef Name;
1405   if (ParseIdentifier(Name))
1406     return TokError("expected identifier in directive");
1407   
1408   // Handle the identifier as the key symbol.
1409   MCSymbol *Sym = CreateSymbol(Name);
1410
1411   if (Lexer.isNot(AsmToken::Comma))
1412     return TokError("unexpected token in directive");
1413   Lex();
1414
1415   int64_t Size;
1416   SMLoc SizeLoc = Lexer.getLoc();
1417   if (ParseAbsoluteExpression(Size))
1418     return true;
1419
1420   int64_t Pow2Alignment = 0;
1421   SMLoc Pow2AlignmentLoc;
1422   if (Lexer.is(AsmToken::Comma)) {
1423     Lex();
1424     Pow2AlignmentLoc = Lexer.getLoc();
1425     if (ParseAbsoluteExpression(Pow2Alignment))
1426       return true;
1427     
1428     // If this target takes alignments in bytes (not log) validate and convert.
1429     if (Lexer.getMAI().getAlignmentIsInBytes()) {
1430       if (!isPowerOf2_64(Pow2Alignment))
1431         return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1432       Pow2Alignment = Log2_64(Pow2Alignment);
1433     }
1434   }
1435   
1436   if (Lexer.isNot(AsmToken::EndOfStatement))
1437     return TokError("unexpected token in '.comm' or '.lcomm' directive");
1438   
1439   Lex();
1440
1441   // NOTE: a size of zero for a .comm should create a undefined symbol
1442   // but a size of .lcomm creates a bss symbol of size zero.
1443   if (Size < 0)
1444     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1445                  "be less than zero");
1446
1447   // NOTE: The alignment in the directive is a power of 2 value, the assembler
1448   // may internally end up wanting an alignment in bytes.
1449   // FIXME: Diagnose overflow.
1450   if (Pow2Alignment < 0)
1451     return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1452                  "alignment, can't be less than zero");
1453
1454   if (!Sym->isUndefined())
1455     return Error(IDLoc, "invalid symbol redefinition");
1456
1457   // '.lcomm' is equivalent to '.zerofill'.
1458   // Create the Symbol as a common or local common with Size and Pow2Alignment
1459   if (IsLocal) {
1460     Out.EmitZerofill(Ctx.getMachOSection("__DATA", "__bss",
1461                                          MCSectionMachO::S_ZEROFILL, 0,
1462                                          SectionKind::getBSS()),
1463                      Sym, Size, 1 << Pow2Alignment);
1464     return false;
1465   }
1466
1467   Out.EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1468   return false;
1469 }
1470
1471 /// ParseDirectiveDarwinZerofill
1472 ///  ::= .zerofill segname , sectname [, identifier , size_expression [
1473 ///      , align_expression ]]
1474 bool AsmParser::ParseDirectiveDarwinZerofill() {
1475   StringRef Segment;
1476   if (ParseIdentifier(Segment))
1477     return TokError("expected segment name after '.zerofill' directive");
1478
1479   if (Lexer.isNot(AsmToken::Comma))
1480     return TokError("unexpected token in directive");
1481   Lex();
1482
1483   StringRef Section;
1484   if (ParseIdentifier(Section))
1485     return TokError("expected section name after comma in '.zerofill' "
1486                     "directive");
1487
1488   // If this is the end of the line all that was wanted was to create the
1489   // the section but with no symbol.
1490   if (Lexer.is(AsmToken::EndOfStatement)) {
1491     // Create the zerofill section but no symbol
1492     Out.EmitZerofill(Ctx.getMachOSection(Segment, Section,
1493                                          MCSectionMachO::S_ZEROFILL, 0,
1494                                          SectionKind::getBSS()));
1495     return false;
1496   }
1497
1498   if (Lexer.isNot(AsmToken::Comma))
1499     return TokError("unexpected token in directive");
1500   Lex();
1501
1502   SMLoc IDLoc = Lexer.getLoc();
1503   StringRef IDStr;
1504   if (ParseIdentifier(IDStr))
1505     return TokError("expected identifier in directive");
1506   
1507   // handle the identifier as the key symbol.
1508   MCSymbol *Sym = CreateSymbol(IDStr);
1509
1510   if (Lexer.isNot(AsmToken::Comma))
1511     return TokError("unexpected token in directive");
1512   Lex();
1513
1514   int64_t Size;
1515   SMLoc SizeLoc = Lexer.getLoc();
1516   if (ParseAbsoluteExpression(Size))
1517     return true;
1518
1519   int64_t Pow2Alignment = 0;
1520   SMLoc Pow2AlignmentLoc;
1521   if (Lexer.is(AsmToken::Comma)) {
1522     Lex();
1523     Pow2AlignmentLoc = Lexer.getLoc();
1524     if (ParseAbsoluteExpression(Pow2Alignment))
1525       return true;
1526   }
1527   
1528   if (Lexer.isNot(AsmToken::EndOfStatement))
1529     return TokError("unexpected token in '.zerofill' directive");
1530   
1531   Lex();
1532
1533   if (Size < 0)
1534     return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less "
1535                  "than zero");
1536
1537   // NOTE: The alignment in the directive is a power of 2 value, the assembler
1538   // may internally end up wanting an alignment in bytes.
1539   // FIXME: Diagnose overflow.
1540   if (Pow2Alignment < 0)
1541     return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, "
1542                  "can't be less than zero");
1543
1544   if (!Sym->isUndefined())
1545     return Error(IDLoc, "invalid symbol redefinition");
1546
1547   // Create the zerofill Symbol with Size and Pow2Alignment
1548   //
1549   // FIXME: Arch specific.
1550   Out.EmitZerofill(Ctx.getMachOSection(Segment, Section,
1551                                        MCSectionMachO::S_ZEROFILL, 0,
1552                                        SectionKind::getBSS()),
1553                    Sym, Size, 1 << Pow2Alignment);
1554
1555   return false;
1556 }
1557
1558 /// ParseDirectiveDarwinTBSS
1559 ///  ::= .tbss identifier, size, align
1560 bool AsmParser::ParseDirectiveDarwinTBSS() {
1561   SMLoc IDLoc = Lexer.getLoc();
1562   StringRef Name;
1563   if (ParseIdentifier(Name))
1564     return TokError("expected identifier in directive");
1565     
1566   // Handle the identifier as the key symbol.
1567   MCSymbol *Sym = CreateSymbol(Name);
1568
1569   if (Lexer.isNot(AsmToken::Comma))
1570     return TokError("unexpected token in directive");
1571   Lex();
1572
1573   int64_t Size;
1574   SMLoc SizeLoc = Lexer.getLoc();
1575   if (ParseAbsoluteExpression(Size))
1576     return true;
1577
1578   int64_t Pow2Alignment = 0;
1579   SMLoc Pow2AlignmentLoc;
1580   if (Lexer.is(AsmToken::Comma)) {
1581     Lex();
1582     Pow2AlignmentLoc = Lexer.getLoc();
1583     if (ParseAbsoluteExpression(Pow2Alignment))
1584       return true;
1585   }
1586   
1587   if (Lexer.isNot(AsmToken::EndOfStatement))
1588     return TokError("unexpected token in '.tbss' directive");
1589   
1590   Lex();
1591
1592   if (Size < 0)
1593     return Error(SizeLoc, "invalid '.tbss' directive size, can't be less than"
1594                  "zero");
1595
1596   // FIXME: Diagnose overflow.
1597   if (Pow2Alignment < 0)
1598     return Error(Pow2AlignmentLoc, "invalid '.tbss' alignment, can't be less"
1599                  "than zero");
1600
1601   if (!Sym->isUndefined())
1602     return Error(IDLoc, "invalid symbol redefinition");
1603   
1604   Out.EmitTBSSSymbol(Ctx.getMachOSection("__DATA", "__thread_bss",
1605                                         MCSectionMachO::S_THREAD_LOCAL_ZEROFILL,
1606                                         0, SectionKind::getThreadBSS()),
1607                      Sym, Size, 1 << Pow2Alignment);
1608   
1609   return false;
1610 }
1611
1612 /// ParseDirectiveDarwinSubsectionsViaSymbols
1613 ///  ::= .subsections_via_symbols
1614 bool AsmParser::ParseDirectiveDarwinSubsectionsViaSymbols() {
1615   if (Lexer.isNot(AsmToken::EndOfStatement))
1616     return TokError("unexpected token in '.subsections_via_symbols' directive");
1617   
1618   Lex();
1619
1620   Out.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
1621
1622   return false;
1623 }
1624
1625 /// ParseDirectiveAbort
1626 ///  ::= .abort [ "abort_string" ]
1627 bool AsmParser::ParseDirectiveAbort() {
1628   // FIXME: Use loc from directive.
1629   SMLoc Loc = Lexer.getLoc();
1630
1631   StringRef Str = "";
1632   if (Lexer.isNot(AsmToken::EndOfStatement)) {
1633     if (Lexer.isNot(AsmToken::String))
1634       return TokError("expected string in '.abort' directive");
1635     
1636     Str = getTok().getString();
1637
1638     Lex();
1639   }
1640
1641   if (Lexer.isNot(AsmToken::EndOfStatement))
1642     return TokError("unexpected token in '.abort' directive");
1643   
1644   Lex();
1645
1646   // FIXME: Handle here.
1647   if (Str.empty())
1648     Error(Loc, ".abort detected. Assembly stopping.");
1649   else
1650     Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1651
1652   return false;
1653 }
1654
1655 /// ParseDirectiveLsym
1656 ///  ::= .lsym identifier , expression
1657 bool AsmParser::ParseDirectiveDarwinLsym() {
1658   StringRef Name;
1659   if (ParseIdentifier(Name))
1660     return TokError("expected identifier in directive");
1661   
1662   // Handle the identifier as the key symbol.
1663   MCSymbol *Sym = CreateSymbol(Name);
1664
1665   if (Lexer.isNot(AsmToken::Comma))
1666     return TokError("unexpected token in '.lsym' directive");
1667   Lex();
1668
1669   const MCExpr *Value;
1670   if (ParseExpression(Value))
1671     return true;
1672
1673   if (Lexer.isNot(AsmToken::EndOfStatement))
1674     return TokError("unexpected token in '.lsym' directive");
1675   
1676   Lex();
1677
1678   // We don't currently support this directive.
1679   //
1680   // FIXME: Diagnostic location!
1681   (void) Sym;
1682   return TokError("directive '.lsym' is unsupported");
1683 }
1684
1685 /// ParseDirectiveInclude
1686 ///  ::= .include "filename"
1687 bool AsmParser::ParseDirectiveInclude() {
1688   if (Lexer.isNot(AsmToken::String))
1689     return TokError("expected string in '.include' directive");
1690   
1691   std::string Filename = getTok().getString();
1692   SMLoc IncludeLoc = Lexer.getLoc();
1693   Lex();
1694
1695   if (Lexer.isNot(AsmToken::EndOfStatement))
1696     return TokError("unexpected token in '.include' directive");
1697   
1698   // Strip the quotes.
1699   Filename = Filename.substr(1, Filename.size()-2);
1700   
1701   // Attempt to switch the lexer to the included file before consuming the end
1702   // of statement to avoid losing it when we switch.
1703   if (EnterIncludeFile(Filename)) {
1704     PrintMessage(IncludeLoc,
1705                  "Could not find include file '" + Filename + "'",
1706                  "error");
1707     return true;
1708   }
1709
1710   return false;
1711 }
1712
1713 /// ParseDirectiveDarwinDumpOrLoad
1714 ///  ::= ( .dump | .load ) "filename"
1715 bool AsmParser::ParseDirectiveDarwinDumpOrLoad(SMLoc IDLoc, bool IsDump) {
1716   if (Lexer.isNot(AsmToken::String))
1717     return TokError("expected string in '.dump' or '.load' directive");
1718   
1719   Lex();
1720
1721   if (Lexer.isNot(AsmToken::EndOfStatement))
1722     return TokError("unexpected token in '.dump' or '.load' directive");
1723   
1724   Lex();
1725
1726   // FIXME: If/when .dump and .load are implemented they will be done in the
1727   // the assembly parser and not have any need for an MCStreamer API.
1728   if (IsDump)
1729     Warning(IDLoc, "ignoring directive .dump for now");
1730   else
1731     Warning(IDLoc, "ignoring directive .load for now");
1732
1733   return false;
1734 }
1735
1736 /// ParseDirectiveDarwinSecureLogUnique
1737 ///  ::= .secure_log_unique "log message"
1738 bool AsmParser::ParseDirectiveDarwinSecureLogUnique(SMLoc IDLoc) {
1739   std::string LogMessage;
1740
1741   if (Lexer.isNot(AsmToken::String))
1742     LogMessage = "";
1743   else{
1744     LogMessage = getTok().getString();
1745     Lex();
1746   }
1747
1748   if (Lexer.isNot(AsmToken::EndOfStatement))
1749     return TokError("unexpected token in '.secure_log_unique' directive");
1750   
1751   if (getContext().getSecureLogUsed() != false)
1752     return Error(IDLoc, ".secure_log_unique specified multiple times");
1753
1754   char *SecureLogFile = getContext().getSecureLogFile();
1755   if (SecureLogFile == NULL)
1756     return Error(IDLoc, ".secure_log_unique used but AS_SECURE_LOG_FILE "
1757                  "environment variable unset.");
1758
1759   raw_ostream *OS = getContext().getSecureLog();
1760   if (OS == NULL) {
1761     std::string Err;
1762     OS = new raw_fd_ostream(SecureLogFile, Err, raw_fd_ostream::F_Append);
1763     if (!Err.empty()) {
1764        delete OS;
1765        return Error(IDLoc, Twine("can't open secure log file: ") +
1766                     SecureLogFile + " (" + Err + ")");
1767     }
1768     getContext().setSecureLog(OS);
1769   }
1770
1771   int CurBuf = SrcMgr.FindBufferContainingLoc(IDLoc);
1772   *OS << SrcMgr.getBufferInfo(CurBuf).Buffer->getBufferIdentifier() << ":"
1773       << SrcMgr.FindLineNumber(IDLoc, CurBuf) << ":"
1774       << LogMessage + "\n";
1775
1776   getContext().setSecureLogUsed(true);
1777
1778   return false;
1779 }
1780
1781 /// ParseDirectiveDarwinSecureLogReset
1782 ///  ::= .secure_log_reset
1783 bool AsmParser::ParseDirectiveDarwinSecureLogReset(SMLoc IDLoc) {
1784   if (Lexer.isNot(AsmToken::EndOfStatement))
1785     return TokError("unexpected token in '.secure_log_reset' directive");
1786   
1787   Lex();
1788
1789   getContext().setSecureLogUsed(false);
1790
1791   return false;
1792 }
1793
1794 /// ParseDirectiveIf
1795 /// ::= .if expression
1796 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1797   TheCondStack.push_back(TheCondState);
1798   TheCondState.TheCond = AsmCond::IfCond;
1799   if(TheCondState.Ignore) {
1800     EatToEndOfStatement();
1801   }
1802   else {
1803     int64_t ExprValue;
1804     if (ParseAbsoluteExpression(ExprValue))
1805       return true;
1806
1807     if (Lexer.isNot(AsmToken::EndOfStatement))
1808       return TokError("unexpected token in '.if' directive");
1809     
1810     Lex();
1811
1812     TheCondState.CondMet = ExprValue;
1813     TheCondState.Ignore = !TheCondState.CondMet;
1814   }
1815
1816   return false;
1817 }
1818
1819 /// ParseDirectiveElseIf
1820 /// ::= .elseif expression
1821 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1822   if (TheCondState.TheCond != AsmCond::IfCond &&
1823       TheCondState.TheCond != AsmCond::ElseIfCond)
1824       Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1825                           " an .elseif");
1826   TheCondState.TheCond = AsmCond::ElseIfCond;
1827
1828   bool LastIgnoreState = false;
1829   if (!TheCondStack.empty())
1830       LastIgnoreState = TheCondStack.back().Ignore;
1831   if (LastIgnoreState || TheCondState.CondMet) {
1832     TheCondState.Ignore = true;
1833     EatToEndOfStatement();
1834   }
1835   else {
1836     int64_t ExprValue;
1837     if (ParseAbsoluteExpression(ExprValue))
1838       return true;
1839
1840     if (Lexer.isNot(AsmToken::EndOfStatement))
1841       return TokError("unexpected token in '.elseif' directive");
1842     
1843     Lex();
1844     TheCondState.CondMet = ExprValue;
1845     TheCondState.Ignore = !TheCondState.CondMet;
1846   }
1847
1848   return false;
1849 }
1850
1851 /// ParseDirectiveElse
1852 /// ::= .else
1853 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1854   if (Lexer.isNot(AsmToken::EndOfStatement))
1855     return TokError("unexpected token in '.else' directive");
1856   
1857   Lex();
1858
1859   if (TheCondState.TheCond != AsmCond::IfCond &&
1860       TheCondState.TheCond != AsmCond::ElseIfCond)
1861       Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1862                           ".elseif");
1863   TheCondState.TheCond = AsmCond::ElseCond;
1864   bool LastIgnoreState = false;
1865   if (!TheCondStack.empty())
1866     LastIgnoreState = TheCondStack.back().Ignore;
1867   if (LastIgnoreState || TheCondState.CondMet)
1868     TheCondState.Ignore = true;
1869   else
1870     TheCondState.Ignore = false;
1871
1872   return false;
1873 }
1874
1875 /// ParseDirectiveEndIf
1876 /// ::= .endif
1877 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1878   if (Lexer.isNot(AsmToken::EndOfStatement))
1879     return TokError("unexpected token in '.endif' directive");
1880   
1881   Lex();
1882
1883   if ((TheCondState.TheCond == AsmCond::NoCond) ||
1884       TheCondStack.empty())
1885     Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1886                         ".else");
1887   if (!TheCondStack.empty()) {
1888     TheCondState = TheCondStack.back();
1889     TheCondStack.pop_back();
1890   }
1891
1892   return false;
1893 }
1894
1895 /// ParseDirectiveFile
1896 /// ::= .file [number] string
1897 bool AsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1898   // FIXME: I'm not sure what this is.
1899   int64_t FileNumber = -1;
1900   if (Lexer.is(AsmToken::Integer)) {
1901     FileNumber = getTok().getIntVal();
1902     Lex();
1903     
1904     if (FileNumber < 1)
1905       return TokError("file number less than one");
1906   }
1907
1908   if (Lexer.isNot(AsmToken::String))
1909     return TokError("unexpected token in '.file' directive");
1910   
1911   StringRef Filename = getTok().getString();
1912   Filename = Filename.substr(1, Filename.size()-2);
1913   Lex();
1914
1915   if (Lexer.isNot(AsmToken::EndOfStatement))
1916     return TokError("unexpected token in '.file' directive");
1917
1918   if (FileNumber == -1)
1919     Out.EmitFileDirective(Filename);
1920   else
1921     Out.EmitDwarfFileDirective(FileNumber, Filename);
1922   
1923   return false;
1924 }
1925
1926 /// ParseDirectiveLine
1927 /// ::= .line [number]
1928 bool AsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1929   if (Lexer.isNot(AsmToken::EndOfStatement)) {
1930     if (Lexer.isNot(AsmToken::Integer))
1931       return TokError("unexpected token in '.line' directive");
1932
1933     int64_t LineNumber = getTok().getIntVal();
1934     (void) LineNumber;
1935     Lex();
1936
1937     // FIXME: Do something with the .line.
1938   }
1939
1940   if (Lexer.isNot(AsmToken::EndOfStatement))
1941     return TokError("unexpected token in '.file' directive");
1942
1943   return false;
1944 }
1945
1946
1947 /// ParseDirectiveLoc
1948 /// ::= .loc number [number [number]]
1949 bool AsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1950   if (Lexer.isNot(AsmToken::Integer))
1951     return TokError("unexpected token in '.loc' directive");
1952
1953   // FIXME: What are these fields?
1954   int64_t FileNumber = getTok().getIntVal();
1955   (void) FileNumber;
1956   // FIXME: Validate file.
1957
1958   Lex();
1959   if (Lexer.isNot(AsmToken::EndOfStatement)) {
1960     if (Lexer.isNot(AsmToken::Integer))
1961       return TokError("unexpected token in '.loc' directive");
1962
1963     int64_t Param2 = getTok().getIntVal();
1964     (void) Param2;
1965     Lex();
1966
1967     if (Lexer.isNot(AsmToken::EndOfStatement)) {
1968       if (Lexer.isNot(AsmToken::Integer))
1969         return TokError("unexpected token in '.loc' directive");
1970
1971       int64_t Param3 = getTok().getIntVal();
1972       (void) Param3;
1973       Lex();
1974
1975       // FIXME: Do something with the .loc.
1976     }
1977   }
1978
1979   if (Lexer.isNot(AsmToken::EndOfStatement))
1980     return TokError("unexpected token in '.file' directive");
1981
1982   return false;
1983 }
1984