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