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