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