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