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