SemaDecl.cpp revision 04421087832a031c90bd58f128c7c0e741db8dd2
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
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 file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/Builtins.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/Type.h"
22#include "clang/Parse/DeclSpec.h"
23#include "clang/Parse/Scope.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
26#include "clang/Basic/SourceManager.h"
27// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Lex/HeaderSearch.h"
30#include "llvm/ADT/SmallString.h"
31#include "llvm/ADT/SmallSet.h"
32#include "llvm/ADT/DenseSet.h"
33using namespace clang;
34
35Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
36  Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
37
38  if (IIDecl && (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl)))
39    return IIDecl;
40  return 0;
41}
42
43void Sema::PushDeclContext(DeclContext *CD) {
44  assert(CD->getParent() == CurContext &&
45      "The next DeclContext should be directly contained in the current one.");
46  CurContext = CD;
47}
48
49void Sema::PopDeclContext() {
50  assert(CurContext && "DeclContext imbalance!");
51  CurContext = CurContext->getParent();
52}
53
54void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
55  if (S->decl_empty()) return;
56  assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
57
58  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
59       I != E; ++I) {
60    Decl *TmpD = static_cast<Decl*>(*I);
61    assert(TmpD && "This decl didn't get pushed??");
62    ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
63    assert(D && "This decl isn't a ScopedDecl?");
64
65    IdentifierInfo *II = D->getIdentifier();
66    if (!II) continue;
67
68    // Unlink this decl from the identifier.  Because the scope contains decls
69    // in an unordered collection, and because we have multiple identifier
70    // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
71    if (II->getFETokenInfo<Decl>() == D) {
72      // Normal case, no multiple decls in different namespaces.
73      II->setFETokenInfo(D->getNext());
74    } else {
75      // Scan ahead.  There are only three namespaces in C, so this loop can
76      // never execute more than 3 times.
77      ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
78      while (SomeDecl->getNext() != D) {
79        SomeDecl = SomeDecl->getNext();
80        assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
81      }
82      SomeDecl->setNext(D->getNext());
83    }
84
85    // This will have to be revisited for C++: there we want to nest stuff in
86    // namespace decls etc.  Even for C, we might want a top-level translation
87    // unit decl or something.
88    if (!CurFunctionDecl)
89      continue;
90
91    // Chain this decl to the containing function, it now owns the memory for
92    // the decl.
93    D->setNext(CurFunctionDecl->getDeclChain());
94    CurFunctionDecl->setDeclChain(D);
95  }
96}
97
98/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
99/// return 0 if one not found.
100ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
101  // The third "scope" argument is 0 since we aren't enabling lazy built-in
102  // creation from this context.
103  Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
104
105  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
106}
107
108/// LookupDecl - Look up the inner-most declaration in the specified
109/// namespace.
110Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
111                       Scope *S, bool enableLazyBuiltinCreation) {
112  if (II == 0) return 0;
113  Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
114
115  // Scan up the scope chain looking for a decl that matches this identifier
116  // that is in the appropriate namespace.  This search should not take long, as
117  // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
118  for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
119    if (D->getIdentifierNamespace() == NS)
120      return D;
121
122  // If we didn't find a use of this identifier, and if the identifier
123  // corresponds to a compiler builtin, create the decl object for the builtin
124  // now, injecting it into translation unit scope, and return it.
125  if (NS == Decl::IDNS_Ordinary) {
126    if (enableLazyBuiltinCreation) {
127      // If this is a builtin on this (or all) targets, create the decl.
128      if (unsigned BuiltinID = II->getBuiltinID())
129        return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
130    }
131    if (getLangOptions().ObjC1) {
132      // @interface and @compatibility_alias introduce typedef-like names.
133      // Unlike typedef's, they can only be introduced at file-scope (and are
134      // therefore not scoped decls). They can, however, be shadowed by
135      // other names in IDNS_Ordinary.
136      ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
137      if (IDI != ObjCInterfaceDecls.end())
138        return IDI->second;
139      ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
140      if (I != ObjCAliasDecls.end())
141        return I->second->getClassInterface();
142    }
143  }
144  return 0;
145}
146
147void Sema::InitBuiltinVaListType()
148{
149  if (!Context.getBuiltinVaListType().isNull())
150    return;
151
152  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
153  Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
154  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
155  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
156}
157
158/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
159/// lazily create a decl for it.
160ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
161                                      Scope *S) {
162  Builtin::ID BID = (Builtin::ID)bid;
163
164  if (BID == Builtin::BI__builtin_va_start ||
165       BID == Builtin::BI__builtin_va_copy ||
166       BID == Builtin::BI__builtin_va_end)
167    InitBuiltinVaListType();
168
169  QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
170  FunctionDecl *New = FunctionDecl::Create(Context, CurContext,
171                                           SourceLocation(), II, R,
172                                           FunctionDecl::Extern, false, 0);
173
174  // Find translation-unit scope to insert this function into.
175  if (Scope *FnS = S->getFnParent())
176    S = FnS->getParent();   // Skip all scopes in a function at once.
177  while (S->getParent())
178    S = S->getParent();
179  S->AddDecl(New);
180
181  // Add this decl to the end of the identifier info.
182  if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
183    // Scan until we find the last (outermost) decl in the id chain.
184    while (LastDecl->getNext())
185      LastDecl = LastDecl->getNext();
186    // Insert before (outside) it.
187    LastDecl->setNext(New);
188  } else {
189    II->setFETokenInfo(New);
190  }
191  return New;
192}
193
194/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
195/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
196/// situation, merging decls or emitting diagnostics as appropriate.
197///
198TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
199  // Verify the old decl was also a typedef.
200  TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
201  if (!Old) {
202    Diag(New->getLocation(), diag::err_redefinition_different_kind,
203         New->getName());
204    Diag(OldD->getLocation(), diag::err_previous_definition);
205    return New;
206  }
207
208  // Allow multiple definitions for ObjC built-in typedefs.
209  // FIXME: Verify the underlying types are equivalent!
210  if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
211    return Old;
212
213  // Redeclaration of a type is a constraint violation (6.7.2.3p1).
214  // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
215  // *either* declaration is in a system header. The code below implements
216  // this adhoc compatibility rule. FIXME: The following code will not
217  // work properly when compiling ".i" files (containing preprocessed output).
218  SourceManager &SrcMgr = Context.getSourceManager();
219  const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
220  const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
221  HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
222  DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
223  DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
224
225  // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
226  if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
227       NewDirType != DirectoryLookup::NormalHeaderDir) ||
228      getLangOptions().Microsoft)
229    return New;
230
231  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
232  // TODO: This is totally simplistic.  It should handle merging functions
233  // together etc, merging extern int X; int X; ...
234  Diag(New->getLocation(), diag::err_redefinition, New->getName());
235  Diag(Old->getLocation(), diag::err_previous_definition);
236  return New;
237}
238
239/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
240static bool DeclHasAttr(const Decl *decl, const Attr *target) {
241  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
242    if (attr->getKind() == target->getKind())
243      return true;
244
245  return false;
246}
247
248/// MergeAttributes - append attributes from the Old decl to the New one.
249static void MergeAttributes(Decl *New, Decl *Old) {
250  Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
251
252// FIXME: fix this code to cleanup the Old attrs correctly
253  while (attr) {
254     tmp = attr;
255     attr = attr->getNext();
256
257    if (!DeclHasAttr(New, tmp)) {
258       New->addAttr(tmp);
259    } else {
260       tmp->setNext(0);
261       delete(tmp);
262    }
263  }
264}
265
266/// MergeFunctionDecl - We just parsed a function 'New' from
267/// declarator D which has the same name and scope as a previous
268/// declaration 'Old'.  Figure out how to resolve this situation,
269/// merging decls or emitting diagnostics as appropriate.
270///
271FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
272  // Verify the old decl was also a function.
273  FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
274  if (!Old) {
275    Diag(New->getLocation(), diag::err_redefinition_different_kind,
276         New->getName());
277    Diag(OldD->getLocation(), diag::err_previous_definition);
278    return New;
279  }
280
281  MergeAttributes(New, Old);
282
283  QualType OldQType = Context.getCanonicalType(Old->getType());
284  QualType NewQType = Context.getCanonicalType(New->getType());
285
286  // C++ [dcl.fct]p3:
287  //   All declarations for a function shall agree exactly in both the
288  //   return type and the parameter-type-list.
289  if (getLangOptions().CPlusPlus && OldQType == NewQType)
290    return MergeCXXFunctionDecl(New, Old);
291
292  // C: Function types need to be compatible, not identical. This handles
293  // duplicate function decls like "void f(int); void f(enum X);" properly.
294  if (!getLangOptions().CPlusPlus &&
295      Context.functionTypesAreCompatible(OldQType, NewQType)) {
296    return New;
297  }
298
299  // A function that has already been declared has been redeclared or defined
300  // with a different type- show appropriate diagnostic
301  diag::kind PrevDiag;
302  if (Old->getBody())
303    PrevDiag = diag::err_previous_definition;
304  else if (Old->isImplicit())
305    PrevDiag = diag::err_previous_implicit_declaration;
306  else
307    PrevDiag = diag::err_previous_declaration;
308
309  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
310  // TODO: This is totally simplistic.  It should handle merging functions
311  // together etc, merging extern int X; int X; ...
312  Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
313  Diag(Old->getLocation(), PrevDiag);
314  return New;
315}
316
317/// equivalentArrayTypes - Used to determine whether two array types are
318/// equivalent.
319/// We need to check this explicitly as an incomplete array definition is
320/// considered a VariableArrayType, so will not match a complete array
321/// definition that would be otherwise equivalent.
322static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
323  const ArrayType *NewAT = NewQType->getAsArrayType();
324  const ArrayType *OldAT = OldQType->getAsArrayType();
325
326  if (!NewAT || !OldAT)
327    return false;
328
329  // If either (or both) array types in incomplete we need to strip off the
330  // outer VariableArrayType.  Once the outer VAT is removed the remaining
331  // types must be identical if the array types are to be considered
332  // equivalent.
333  // eg. int[][1] and int[1][1] become
334  //     VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
335  // removing the outermost VAT gives
336  //     CAT(1, int) and CAT(1, int)
337  // which are equal, therefore the array types are equivalent.
338  if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
339    if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
340      return false;
341    NewQType = NewAT->getElementType().getCanonicalType();
342    OldQType = OldAT->getElementType().getCanonicalType();
343  }
344
345  return NewQType == OldQType;
346}
347
348/// MergeVarDecl - We just parsed a variable 'New' which has the same name
349/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
350/// situation, merging decls or emitting diagnostics as appropriate.
351///
352/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
353/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
354///
355VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
356  // Verify the old decl was also a variable.
357  VarDecl *Old = dyn_cast<VarDecl>(OldD);
358  if (!Old) {
359    Diag(New->getLocation(), diag::err_redefinition_different_kind,
360         New->getName());
361    Diag(OldD->getLocation(), diag::err_previous_definition);
362    return New;
363  }
364
365  MergeAttributes(New, Old);
366
367  // Verify the types match.
368  QualType OldCType = Context.getCanonicalType(Old->getType());
369  QualType NewCType = Context.getCanonicalType(New->getType());
370  if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
371    Diag(New->getLocation(), diag::err_redefinition, New->getName());
372    Diag(Old->getLocation(), diag::err_previous_definition);
373    return New;
374  }
375  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
376  if (New->getStorageClass() == VarDecl::Static &&
377      (Old->getStorageClass() == VarDecl::None ||
378       Old->getStorageClass() == VarDecl::Extern)) {
379    Diag(New->getLocation(), diag::err_static_non_static, New->getName());
380    Diag(Old->getLocation(), diag::err_previous_definition);
381    return New;
382  }
383  // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
384  if (New->getStorageClass() != VarDecl::Static &&
385      Old->getStorageClass() == VarDecl::Static) {
386    Diag(New->getLocation(), diag::err_non_static_static, New->getName());
387    Diag(Old->getLocation(), diag::err_previous_definition);
388    return New;
389  }
390  // We've verified the types match, now handle "tentative" definitions.
391  FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
392  FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
393
394  if (OldFSDecl && NewFSDecl) {
395    // Handle C "tentative" external object definitions (C99 6.9.2).
396    bool OldIsTentative = false;
397    bool NewIsTentative = false;
398
399    if (!OldFSDecl->getInit() &&
400        (OldFSDecl->getStorageClass() == VarDecl::None ||
401         OldFSDecl->getStorageClass() == VarDecl::Static))
402      OldIsTentative = true;
403
404    // FIXME: this check doesn't work (since the initializer hasn't been
405    // attached yet). This check should be moved to FinalizeDeclaratorGroup.
406    // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
407    // thrown out the old decl.
408    if (!NewFSDecl->getInit() &&
409        (NewFSDecl->getStorageClass() == VarDecl::None ||
410         NewFSDecl->getStorageClass() == VarDecl::Static))
411      ; // change to NewIsTentative = true; once the code is moved.
412
413    if (NewIsTentative || OldIsTentative)
414      return New;
415  }
416  if (Old->getStorageClass() != VarDecl::Extern &&
417      New->getStorageClass() != VarDecl::Extern) {
418    Diag(New->getLocation(), diag::err_redefinition, New->getName());
419    Diag(Old->getLocation(), diag::err_previous_definition);
420  }
421  return New;
422}
423
424/// CheckParmsForFunctionDef - Check that the parameters of the given
425/// function are appropriate for the definition of a function. This
426/// takes care of any checks that cannot be performed on the
427/// declaration itself, e.g., that the types of each of the function
428/// parameters are complete.
429bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
430  bool HasInvalidParm = false;
431  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
432    ParmVarDecl *Param = FD->getParamDecl(p);
433
434    // C99 6.7.5.3p4: the parameters in a parameter type list in a
435    // function declarator that is part of a function definition of
436    // that function shall not have incomplete type.
437    if (Param->getType()->isIncompleteType() &&
438        !Param->isInvalidDecl()) {
439      Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
440           Param->getType().getAsString());
441      Param->setInvalidDecl();
442      HasInvalidParm = true;
443    }
444  }
445
446  return HasInvalidParm;
447}
448
449/// CreateImplicitParameter - Creates an implicit function parameter
450/// in the scope S and with the given type. This routine is used, for
451/// example, to create the implicit "self" parameter in an Objective-C
452/// method.
453ParmVarDecl *
454Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
455                              SourceLocation IdLoc, QualType Type) {
456  ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
457                                         VarDecl::None, 0, 0);
458  if (Id) {
459    New->setNext(Id->getFETokenInfo<ScopedDecl>());
460    Id->setFETokenInfo(New);
461    S->AddDecl(New);
462  }
463
464  return New;
465}
466
467/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
468/// no declarator (e.g. "struct foo;") is parsed.
469Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
470  // TODO: emit error on 'int;' or 'const enum foo;'.
471  // TODO: emit error on 'typedef int;'
472  // if (!DS.isMissingDeclaratorOk()) Diag(...);
473
474  return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
475}
476
477bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
478  // Get the type before calling CheckSingleAssignmentConstraints(), since
479  // it can promote the expression.
480  QualType InitType = Init->getType();
481
482  AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
483  return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
484                                  InitType, Init, "initializing");
485}
486
487bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
488                         QualType ElementType) {
489  Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
490  if (CheckSingleInitializer(expr, ElementType))
491    return true; // types weren't compatible.
492
493  if (savExpr != expr) // The type was promoted, update initializer list.
494    IList->setInit(slot, expr);
495  return false;
496}
497
498bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
499  if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
500    // C99 6.7.8p14. We have an array of character type with unknown size
501    // being initialized to a string literal.
502    llvm::APSInt ConstVal(32);
503    ConstVal = strLiteral->getByteLength() + 1;
504    // Return a new array type (C99 6.7.8p22).
505    DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
506                                         ArrayType::Normal, 0);
507  } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
508    // C99 6.7.8p14. We have an array of character type with known size.
509    if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
510      Diag(strLiteral->getSourceRange().getBegin(),
511           diag::warn_initializer_string_for_char_array_too_long,
512           strLiteral->getSourceRange());
513  } else {
514    assert(0 && "HandleStringLiteralInit(): Invalid array type");
515  }
516  // Set type from "char *" to "constant array of char".
517  strLiteral->setType(DeclT);
518  // For now, we always return false (meaning success).
519  return false;
520}
521
522StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
523  const ArrayType *AT = DeclType->getAsArrayType();
524  if (AT && AT->getElementType()->isCharType()) {
525    return dyn_cast<StringLiteral>(Init);
526  }
527  return 0;
528}
529
530// CheckInitializerListTypes - Checks the types of elements of an initializer
531// list. This function is recursive: it calls itself to initialize subelements
532// of aggregate types.  Note that the topLevel parameter essentially refers to
533// whether this expression "owns" the initializer list passed in, or if this
534// initialization is taking elements out of a parent initializer.  Each
535// call to this function adds zero or more to startIndex, reports any errors,
536// and returns true if it found any inconsistent types.
537bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
538                                     bool topLevel, unsigned& startIndex) {
539  bool hadError = false;
540
541  if (DeclType->isScalarType()) {
542    // The simplest case: initializing a single scalar
543    if (topLevel) {
544      Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
545           IList->getSourceRange());
546    }
547    if (startIndex < IList->getNumInits()) {
548      Expr* expr = IList->getInit(startIndex);
549      if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
550        // FIXME: Should an error be reported here instead?
551        unsigned newIndex = 0;
552        CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
553      } else {
554        hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
555      }
556      ++startIndex;
557    }
558    // FIXME: Should an error be reported for empty initializer list + scalar?
559  } else if (DeclType->isVectorType()) {
560    if (startIndex < IList->getNumInits()) {
561      const VectorType *VT = DeclType->getAsVectorType();
562      int maxElements = VT->getNumElements();
563      QualType elementType = VT->getElementType();
564
565      for (int i = 0; i < maxElements; ++i) {
566        // Don't attempt to go past the end of the init list
567        if (startIndex >= IList->getNumInits())
568          break;
569        Expr* expr = IList->getInit(startIndex);
570        if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
571          unsigned newIndex = 0;
572          hadError |= CheckInitializerListTypes(SubInitList, elementType,
573                                                true, newIndex);
574          ++startIndex;
575        } else {
576          hadError |= CheckInitializerListTypes(IList, elementType,
577                                                false, startIndex);
578        }
579      }
580    }
581  } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
582    if (DeclType->isStructureType() || DeclType->isUnionType()) {
583      if (startIndex < IList->getNumInits() && !topLevel &&
584          Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
585                                     DeclType)) {
586        // We found a compatible struct; per the standard, this initializes the
587        // struct.  (The C standard technically says that this only applies for
588        // initializers for declarations with automatic scope; however, this
589        // construct is unambiguous anyway because a struct cannot contain
590        // a type compatible with itself. We'll output an error when we check
591        // if the initializer is constant.)
592        // FIXME: Is a call to CheckSingleInitializer required here?
593        ++startIndex;
594      } else {
595        RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
596
597        // If the record is invalid, some of it's members are invalid. To avoid
598        // confusion, we forgo checking the intializer for the entire record.
599        if (structDecl->isInvalidDecl())
600          return true;
601
602        // If structDecl is a forward declaration, this loop won't do anything;
603        // That's okay, because an error should get printed out elsewhere. It
604        // might be worthwhile to skip over the rest of the initializer, though.
605        int numMembers = structDecl->getNumMembers() -
606                         structDecl->hasFlexibleArrayMember();
607        for (int i = 0; i < numMembers; i++) {
608          // Don't attempt to go past the end of the init list
609          if (startIndex >= IList->getNumInits())
610            break;
611          FieldDecl * curField = structDecl->getMember(i);
612          if (!curField->getIdentifier()) {
613            // Don't initialize unnamed fields, e.g. "int : 20;"
614            continue;
615          }
616          QualType fieldType = curField->getType();
617          Expr* expr = IList->getInit(startIndex);
618          if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
619            unsigned newStart = 0;
620            hadError |= CheckInitializerListTypes(SubInitList, fieldType,
621                                                  true, newStart);
622            ++startIndex;
623          } else {
624            hadError |= CheckInitializerListTypes(IList, fieldType,
625                                                  false, startIndex);
626          }
627          if (DeclType->isUnionType())
628            break;
629        }
630        // FIXME: Implement flexible array initialization GCC extension (it's a
631        // really messy extension to implement, unfortunately...the necessary
632        // information isn't actually even here!)
633      }
634    } else if (DeclType->isArrayType()) {
635      // Check for the special-case of initializing an array with a string.
636      if (startIndex < IList->getNumInits()) {
637        if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
638                                                     DeclType)) {
639          CheckStringLiteralInit(lit, DeclType);
640          ++startIndex;
641          if (topLevel && startIndex < IList->getNumInits()) {
642            // We have leftover initializers; warn
643            Diag(IList->getInit(startIndex)->getLocStart(),
644                 diag::err_excess_initializers_in_char_array_initializer,
645                 IList->getInit(startIndex)->getSourceRange());
646          }
647          return false;
648        }
649      }
650      int maxElements;
651      if (DeclType->isIncompleteArrayType()) {
652        // FIXME: use a proper constant
653        maxElements = 0x7FFFFFFF;
654      } else if (const VariableArrayType *VAT =
655                                DeclType->getAsVariableArrayType()) {
656        // Check for VLAs; in standard C it would be possible to check this
657        // earlier, but I don't know where clang accepts VLAs (gcc accepts
658        // them in all sorts of strange places).
659        Diag(VAT->getSizeExpr()->getLocStart(),
660             diag::err_variable_object_no_init,
661             VAT->getSizeExpr()->getSourceRange());
662        hadError = true;
663        maxElements = 0x7FFFFFFF;
664      } else {
665        const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
666        maxElements = static_cast<int>(CAT->getSize().getZExtValue());
667      }
668      QualType elementType = DeclType->getAsArrayType()->getElementType();
669      int numElements = 0;
670      for (int i = 0; i < maxElements; ++i, ++numElements) {
671        // Don't attempt to go past the end of the init list
672        if (startIndex >= IList->getNumInits())
673          break;
674        Expr* expr = IList->getInit(startIndex);
675        if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
676          unsigned newIndex = 0;
677          hadError |= CheckInitializerListTypes(SubInitList, elementType,
678                                                true, newIndex);
679          ++startIndex;
680        } else {
681          hadError |= CheckInitializerListTypes(IList, elementType,
682                                                false, startIndex);
683        }
684      }
685      if (DeclType->isIncompleteArrayType()) {
686        // If this is an incomplete array type, the actual type needs to
687        // be calculated here
688        if (numElements == 0) {
689          // Sizing an array implicitly to zero is not allowed
690          // (It could in theory be allowed, but it doesn't really matter.)
691          Diag(IList->getLocStart(),
692               diag::err_at_least_one_initializer_needed_to_size_array);
693          hadError = true;
694        } else {
695          llvm::APSInt ConstVal(32);
696          ConstVal = numElements;
697          DeclType = Context.getConstantArrayType(elementType, ConstVal,
698                                                  ArrayType::Normal, 0);
699        }
700      }
701    } else {
702      assert(0 && "Aggregate that isn't a function or array?!");
703    }
704  } else {
705    // In C, all types are either scalars or aggregates, but
706    // additional handling is needed here for C++ (and possibly others?).
707    assert(0 && "Unsupported initializer type");
708  }
709
710  // If this init list is a base list, we set the type; an initializer doesn't
711  // fundamentally have a type, but this makes the ASTs a bit easier to read
712  if (topLevel)
713    IList->setType(DeclType);
714
715  if (topLevel && startIndex < IList->getNumInits()) {
716    // We have leftover initializers; warn
717    Diag(IList->getInit(startIndex)->getLocStart(),
718         diag::warn_excess_initializers,
719         IList->getInit(startIndex)->getSourceRange());
720  }
721  return hadError;
722}
723
724bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
725  // C99 6.7.8p3: The type of the entity to be initialized shall be an array
726  // of unknown size ("[]") or an object type that is not a variable array type.
727  if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
728    return Diag(VAT->getSizeExpr()->getLocStart(),
729                diag::err_variable_object_no_init,
730                VAT->getSizeExpr()->getSourceRange());
731
732  InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
733  if (!InitList) {
734    // FIXME: Handle wide strings
735    if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
736      return CheckStringLiteralInit(strLiteral, DeclType);
737
738    if (DeclType->isArrayType())
739      return Diag(Init->getLocStart(),
740                  diag::err_array_init_list_required,
741                  Init->getSourceRange());
742
743    return CheckSingleInitializer(Init, DeclType);
744  }
745  unsigned newIndex = 0;
746  return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
747}
748
749Sema::DeclTy *
750Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
751  ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
752  IdentifierInfo *II = D.getIdentifier();
753
754  // All of these full declarators require an identifier.  If it doesn't have
755  // one, the ParsedFreeStandingDeclSpec action should be used.
756  if (II == 0) {
757    Diag(D.getDeclSpec().getSourceRange().getBegin(),
758         diag::err_declarator_need_ident,
759         D.getDeclSpec().getSourceRange(), D.getSourceRange());
760    return 0;
761  }
762
763  // The scope passed in may not be a decl scope.  Zip up the scope tree until
764  // we find one that is.
765  while ((S->getFlags() & Scope::DeclScope) == 0)
766    S = S->getParent();
767
768  // See if this is a redefinition of a variable in the same scope.
769  Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
770  ScopedDecl *New;
771  bool InvalidDecl = false;
772
773  QualType R = GetTypeForDeclarator(D, S);
774  assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
775
776  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
777    TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
778    if (!NewTD) return 0;
779
780    // Handle attributes prior to checking for duplicates in MergeVarDecl
781    HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
782                         D.getAttributes());
783    // Merge the decl with the existing one if appropriate. If the decl is
784    // in an outer scope, it isn't the same thing.
785    if (PrevDecl && S->isDeclScope(PrevDecl)) {
786      NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
787      if (NewTD == 0) return 0;
788    }
789    New = NewTD;
790    if (S->getParent() == 0) {
791      // C99 6.7.7p2: If a typedef name specifies a variably modified type
792      // then it shall have block scope.
793      if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
794        // FIXME: Diagnostic needs to be fixed.
795        Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
796        InvalidDecl = true;
797      }
798    }
799  } else if (R.getTypePtr()->isFunctionType()) {
800    FunctionDecl::StorageClass SC = FunctionDecl::None;
801    switch (D.getDeclSpec().getStorageClassSpec()) {
802      default: assert(0 && "Unknown storage class!");
803      case DeclSpec::SCS_auto:
804      case DeclSpec::SCS_register:
805        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
806             R.getAsString());
807        InvalidDecl = true;
808        break;
809      case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
810      case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
811      case DeclSpec::SCS_static:      SC = FunctionDecl::Static; break;
812      case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
813    }
814
815    bool isInline = D.getDeclSpec().isInlineSpecified();
816    FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
817                                               D.getIdentifierLoc(),
818                                               II, R, SC, isInline,
819                                               LastDeclarator);
820    // Handle attributes.
821    HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
822                         D.getAttributes());
823
824    // Copy the parameter declarations from the declarator D to
825    // the function declaration NewFD, if they are available.
826    if (D.getNumTypeObjects() > 0 &&
827        D.getTypeObject(0).Fun.hasPrototype) {
828      DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
829
830      // Create Decl objects for each parameter, adding them to the
831      // FunctionDecl.
832      llvm::SmallVector<ParmVarDecl*, 16> Params;
833
834      // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
835      // function that takes no arguments, not a function that takes a
836      // single void argument.  FIXME: Is this really the right place
837      // to check for this? C++ says that the parameter list (void) is
838      // the same as an empty parameter list, whereas the parameter
839      // list (T) (with T typedef'd to void) is not. For C++, this
840      // should be handled in the parser. Check C89 and C99 standards
841      // to see what the correct behavior is.
842      if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
843          FTI.ArgInfo[0].Param &&
844          !((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
845          ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
846        // empty arg list, don't push any params.
847      } else {
848        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
849          Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
850      }
851
852      NewFD->setParams(&Params[0], Params.size());
853    }
854
855    // Merge the decl with the existing one if appropriate. Since C functions
856    // are in a flat namespace, make sure we consider decls in outer scopes.
857    if (PrevDecl) {
858      NewFD = MergeFunctionDecl(NewFD, PrevDecl);
859      if (NewFD == 0) return 0;
860    }
861    New = NewFD;
862
863    // In C++, check default arguments now that we have merged decls.
864    if (getLangOptions().CPlusPlus)
865      CheckCXXDefaultArguments(NewFD);
866  } else {
867    if (R.getTypePtr()->isObjCInterfaceType()) {
868      Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
869           D.getIdentifier()->getName());
870      InvalidDecl = true;
871    }
872
873    VarDecl *NewVD;
874    VarDecl::StorageClass SC;
875    switch (D.getDeclSpec().getStorageClassSpec()) {
876    default: assert(0 && "Unknown storage class!");
877    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
878    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
879    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
880    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
881    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
882    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
883    }
884    if (S->getParent() == 0) {
885      // C99 6.9p2: The storage-class specifiers auto and register shall not
886      // appear in the declaration specifiers in an external declaration.
887      if (SC == VarDecl::Auto || SC == VarDecl::Register) {
888        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
889             R.getAsString());
890        InvalidDecl = true;
891      }
892      NewVD = FileVarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
893                                  II, R, SC,
894                                  LastDeclarator);
895    } else {
896      NewVD = BlockVarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
897                                   II, R, SC,
898                                   LastDeclarator);
899    }
900    // Handle attributes prior to checking for duplicates in MergeVarDecl
901    HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
902                         D.getAttributes());
903
904    // Emit an error if an address space was applied to decl with local storage.
905    // This includes arrays of objects with address space qualifiers, but not
906    // automatic variables that point to other address spaces.
907    // ISO/IEC TR 18037 S5.1.2
908    if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
909      Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
910      InvalidDecl = true;
911    }
912    // Merge the decl with the existing one if appropriate. If the decl is
913    // in an outer scope, it isn't the same thing.
914    if (PrevDecl && S->isDeclScope(PrevDecl)) {
915      NewVD = MergeVarDecl(NewVD, PrevDecl);
916      if (NewVD == 0) return 0;
917    }
918    New = NewVD;
919  }
920
921  // If this has an identifier, add it to the scope stack.
922  if (II) {
923    New->setNext(II->getFETokenInfo<ScopedDecl>());
924    II->setFETokenInfo(New);
925    S->AddDecl(New);
926  }
927  // If any semantic error occurred, mark the decl as invalid.
928  if (D.getInvalidType() || InvalidDecl)
929    New->setInvalidDecl();
930
931  return New;
932}
933
934bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
935  SourceLocation loc;
936  // FIXME: Remove the isReference check and handle assignment to a reference.
937  if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
938    assert(loc.isValid() && "isConstantExpr didn't return a loc!");
939    Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
940    return true;
941  }
942  return false;
943}
944
945void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
946  Decl *RealDecl = static_cast<Decl *>(dcl);
947  Expr *Init = static_cast<Expr *>(init);
948  assert(Init && "missing initializer");
949
950  // If there is no declaration, there was an error parsing it.  Just ignore
951  // the initializer.
952  if (RealDecl == 0) {
953    delete Init;
954    return;
955  }
956
957  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
958  if (!VDecl) {
959    Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
960         diag::err_illegal_initializer);
961    RealDecl->setInvalidDecl();
962    return;
963  }
964  // Get the decls type and save a reference for later, since
965  // CheckInitializerTypes may change it.
966  QualType DclT = VDecl->getType(), SavT = DclT;
967  if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
968    VarDecl::StorageClass SC = BVD->getStorageClass();
969    if (SC == VarDecl::Extern) { // C99 6.7.8p5
970      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
971      BVD->setInvalidDecl();
972    } else if (!BVD->isInvalidDecl()) {
973      if (CheckInitializerTypes(Init, DclT))
974        BVD->setInvalidDecl();
975      if (SC == VarDecl::Static) // C99 6.7.8p4.
976        CheckForConstantInitializer(Init, DclT);
977    }
978  } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
979    if (FVD->getStorageClass() == VarDecl::Extern)
980      Diag(VDecl->getLocation(), diag::warn_extern_init);
981    if (!FVD->isInvalidDecl())
982      if (CheckInitializerTypes(Init, DclT))
983        FVD->setInvalidDecl();
984
985    // C99 6.7.8p4. All file scoped initializers need to be constant.
986    CheckForConstantInitializer(Init, DclT);
987  }
988  // If the type changed, it means we had an incomplete type that was
989  // completed by the initializer. For example:
990  //   int ary[] = { 1, 3, 5 };
991  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
992  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
993    VDecl->setType(DclT);
994    Init->setType(DclT);
995  }
996
997  // Attach the initializer to the decl.
998  VDecl->setInit(Init);
999  return;
1000}
1001
1002/// The declarators are chained together backwards, reverse the list.
1003Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1004  // Often we have single declarators, handle them quickly.
1005  Decl *GroupDecl = static_cast<Decl*>(group);
1006  if (GroupDecl == 0)
1007    return 0;
1008
1009  ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1010  ScopedDecl *NewGroup = 0;
1011  if (Group->getNextDeclarator() == 0)
1012    NewGroup = Group;
1013  else { // reverse the list.
1014    while (Group) {
1015      ScopedDecl *Next = Group->getNextDeclarator();
1016      Group->setNextDeclarator(NewGroup);
1017      NewGroup = Group;
1018      Group = Next;
1019    }
1020  }
1021  // Perform semantic analysis that depends on having fully processed both
1022  // the declarator and initializer.
1023  for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
1024    VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1025    if (!IDecl)
1026      continue;
1027    FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
1028    BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
1029    QualType T = IDecl->getType();
1030
1031    // C99 6.7.5.2p2: If an identifier is declared to be an object with
1032    // static storage duration, it shall not have a variable length array.
1033    if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
1034      if (T->getAsVariableArrayType()) {
1035        Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1036        IDecl->setInvalidDecl();
1037      }
1038    }
1039    // Block scope. C99 6.7p7: If an identifier for an object is declared with
1040    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
1041    if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
1042      if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
1043        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1044             T.getAsString());
1045        IDecl->setInvalidDecl();
1046      }
1047    }
1048    // File scope. C99 6.9.2p2: A declaration of an identifier for and
1049    // object that has file scope without an initializer, and without a
1050    // storage-class specifier or with the storage-class specifier "static",
1051    // constitutes a tentative definition. Note: A tentative definition with
1052    // external linkage is valid (C99 6.2.2p5).
1053    if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
1054                                   FVD->getStorageClass() == VarDecl::None)) {
1055      if (T->isIncompleteArrayType()) {
1056        // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1057        // array to be completed. Don't issue a diagnostic.
1058      } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
1059        // C99 6.9.2p3: If the declaration of an identifier for an object is
1060        // a tentative definition and has internal linkage (C99 6.2.2p3), the
1061        // declared type shall not be an incomplete type.
1062        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1063             T.getAsString());
1064        IDecl->setInvalidDecl();
1065      }
1066    }
1067  }
1068  return NewGroup;
1069}
1070
1071/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1072/// to introduce parameters into function prototype scope.
1073Sema::DeclTy *
1074Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1075  DeclSpec &DS = D.getDeclSpec();
1076
1077  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1078  if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1079      DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1080    Diag(DS.getStorageClassSpecLoc(),
1081         diag::err_invalid_storage_class_in_func_decl);
1082    DS.ClearStorageClassSpecs();
1083  }
1084  if (DS.isThreadSpecified()) {
1085    Diag(DS.getThreadSpecLoc(),
1086         diag::err_invalid_storage_class_in_func_decl);
1087    DS.ClearStorageClassSpecs();
1088  }
1089
1090
1091  // In this context, we *do not* check D.getInvalidType(). If the declarator
1092  // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1093  // though it will not reflect the user specified type.
1094  QualType parmDeclType = GetTypeForDeclarator(D, S);
1095
1096  assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1097
1098  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1099  // Can this happen for params?  We already checked that they don't conflict
1100  // among each other.  Here they can only shadow globals, which is ok.
1101  IdentifierInfo *II = D.getIdentifier();
1102  if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1103    if (S->isDeclScope(PrevDecl)) {
1104      Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1105           dyn_cast<NamedDecl>(PrevDecl)->getName());
1106
1107      // Recover by removing the name
1108      II = 0;
1109      D.SetIdentifier(0, D.getIdentifierLoc());
1110    }
1111  }
1112
1113  // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1114  // Doing the promotion here has a win and a loss. The win is the type for
1115  // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1116  // code generator). The loss is the orginal type isn't preserved. For example:
1117  //
1118  // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1119  //    int blockvardecl[5];
1120  //    sizeof(parmvardecl);  // size == 4
1121  //    sizeof(blockvardecl); // size == 20
1122  // }
1123  //
1124  // For expressions, all implicit conversions are captured using the
1125  // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1126  //
1127  // FIXME: If a source translation tool needs to see the original type, then
1128  // we need to consider storing both types (in ParmVarDecl)...
1129  //
1130  if (parmDeclType->isArrayType()) {
1131    // int x[restrict 4] ->  int *restrict
1132    parmDeclType = Context.getArrayDecayedType(parmDeclType);
1133  } else if (parmDeclType->isFunctionType())
1134    parmDeclType = Context.getPointerType(parmDeclType);
1135
1136  ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1137                                         D.getIdentifierLoc(), II,
1138                                         parmDeclType, VarDecl::None,
1139                                         0, 0);
1140
1141  if (D.getInvalidType())
1142    New->setInvalidDecl();
1143
1144  if (II) {
1145    New->setNext(II->getFETokenInfo<ScopedDecl>());
1146    II->setFETokenInfo(New);
1147    S->AddDecl(New);
1148  }
1149
1150  HandleDeclAttributes(New, D.getAttributes(), 0);
1151  return New;
1152
1153}
1154
1155Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
1156  assert(CurFunctionDecl == 0 && "Function parsing confused");
1157  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1158         "Not a function declarator!");
1159  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1160
1161  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1162  // for a K&R function.
1163  if (!FTI.hasPrototype) {
1164    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1165      if (FTI.ArgInfo[i].Param == 0) {
1166        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1167             FTI.ArgInfo[i].Ident->getName());
1168        // Implicitly declare the argument as type 'int' for lack of a better
1169        // type.
1170        DeclSpec DS;
1171        const char* PrevSpec; // unused
1172        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1173                           PrevSpec);
1174        Declarator ParamD(DS, Declarator::KNRTypeListContext);
1175        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1176        FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
1177      }
1178    }
1179
1180    // Since this is a function definition, act as though we have information
1181    // about the arguments.
1182    if (FTI.NumArgs)
1183      FTI.hasPrototype = true;
1184  } else {
1185    // FIXME: Diagnose arguments without names in C.
1186  }
1187
1188  Scope *GlobalScope = FnBodyScope->getParent();
1189
1190  // See if this is a redefinition.
1191  Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
1192                             GlobalScope);
1193  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1194    if (FD->getBody()) {
1195      Diag(D.getIdentifierLoc(), diag::err_redefinition,
1196           D.getIdentifier()->getName());
1197      Diag(FD->getLocation(), diag::err_previous_definition);
1198    }
1199  }
1200  Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
1201  FunctionDecl *FD = cast<FunctionDecl>(decl);
1202  CurFunctionDecl = FD;
1203  PushDeclContext(FD);
1204
1205  // Check the validity of our function parameters
1206  CheckParmsForFunctionDef(FD);
1207
1208  // Introduce our parameters into the function scope
1209  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1210    ParmVarDecl *Param = FD->getParamDecl(p);
1211    // If this has an identifier, add it to the scope stack.
1212    if (IdentifierInfo *II = Param->getIdentifier()) {
1213      Param->setNext(II->getFETokenInfo<ScopedDecl>());
1214      II->setFETokenInfo(Param);
1215      FnBodyScope->AddDecl(Param);
1216    }
1217  }
1218
1219  return FD;
1220}
1221
1222Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1223  Decl *dcl = static_cast<Decl *>(D);
1224  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1225    FD->setBody((Stmt*)Body);
1226    assert(FD == CurFunctionDecl && "Function parsing confused");
1227    CurFunctionDecl = 0;
1228  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
1229    MD->setBody((Stmt*)Body);
1230    CurMethodDecl = 0;
1231  }
1232  PopDeclContext();
1233  // Verify and clean out per-function state.
1234
1235  // Check goto/label use.
1236  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1237       I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1238    // Verify that we have no forward references left.  If so, there was a goto
1239    // or address of a label taken, but no definition of it.  Label fwd
1240    // definitions are indicated with a null substmt.
1241    if (I->second->getSubStmt() == 0) {
1242      LabelStmt *L = I->second;
1243      // Emit error.
1244      Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1245
1246      // At this point, we have gotos that use the bogus label.  Stitch it into
1247      // the function body so that they aren't leaked and that the AST is well
1248      // formed.
1249      if (Body) {
1250        L->setSubStmt(new NullStmt(L->getIdentLoc()));
1251        cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1252      } else {
1253        // The whole function wasn't parsed correctly, just delete this.
1254        delete L;
1255      }
1256    }
1257  }
1258  LabelMap.clear();
1259
1260  return D;
1261}
1262
1263/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1264/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
1265ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1266                                           IdentifierInfo &II, Scope *S) {
1267  if (getLangOptions().C99)  // Extension in C99.
1268    Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1269  else  // Legal in C90, but warn about it.
1270    Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1271
1272  // FIXME: handle stuff like:
1273  // void foo() { extern float X(); }
1274  // void bar() { X(); }  <-- implicit decl for X in another scope.
1275
1276  // Set a Declarator for the implicit definition: int foo();
1277  const char *Dummy;
1278  DeclSpec DS;
1279  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1280  Error = Error; // Silence warning.
1281  assert(!Error && "Error setting up implicit decl!");
1282  Declarator D(DS, Declarator::BlockContext);
1283  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1284  D.SetIdentifier(&II, Loc);
1285
1286  // Find translation-unit scope to insert this function into.
1287  if (Scope *FnS = S->getFnParent())
1288    S = FnS->getParent();   // Skip all scopes in a function at once.
1289  while (S->getParent())
1290    S = S->getParent();
1291
1292  FunctionDecl *FD =
1293    dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
1294  FD->setImplicit();
1295  return FD;
1296}
1297
1298
1299TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
1300                                    ScopedDecl *LastDeclarator) {
1301  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
1302  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1303
1304  // Scope manipulation handled by caller.
1305  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1306                                           D.getIdentifierLoc(),
1307                                           D.getIdentifier(),
1308                                           T, LastDeclarator);
1309  if (D.getInvalidType())
1310    NewTD->setInvalidDecl();
1311  return NewTD;
1312}
1313
1314/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
1315/// former case, Name will be non-null.  In the later case, Name will be null.
1316/// TagType indicates what kind of tag this is. TK indicates whether this is a
1317/// reference/declaration/definition of a tag.
1318Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
1319                             SourceLocation KWLoc, IdentifierInfo *Name,
1320                             SourceLocation NameLoc, AttributeList *Attr) {
1321  // If this is a use of an existing tag, it must have a name.
1322  assert((Name != 0 || TK == TK_Definition) &&
1323         "Nameless record must be a definition!");
1324
1325  Decl::Kind Kind;
1326  switch (TagType) {
1327  default: assert(0 && "Unknown tag type!");
1328  case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1329  case DeclSpec::TST_union:  Kind = Decl::Union; break;
1330//case DeclSpec::TST_class:  Kind = Decl::Class; break;
1331  case DeclSpec::TST_enum:   Kind = Decl::Enum; break;
1332  }
1333
1334  // If this is a named struct, check to see if there was a previous forward
1335  // declaration or definition.
1336  if (TagDecl *PrevDecl =
1337          dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
1338
1339    // If this is a use of a previous tag, or if the tag is already declared in
1340    // the same scope (so that the definition/declaration completes or
1341    // rementions the tag), reuse the decl.
1342    if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1343      // Make sure that this wasn't declared as an enum and now used as a struct
1344      // or something similar.
1345      if (PrevDecl->getKind() != Kind) {
1346        Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1347        Diag(PrevDecl->getLocation(), diag::err_previous_use);
1348      }
1349
1350      // If this is a use or a forward declaration, we're good.
1351      if (TK != TK_Definition)
1352        return PrevDecl;
1353
1354      // Diagnose attempts to redefine a tag.
1355      if (PrevDecl->isDefinition()) {
1356        Diag(NameLoc, diag::err_redefinition, Name->getName());
1357        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1358        // If this is a redefinition, recover by making this struct be
1359        // anonymous, which will make any later references get the previous
1360        // definition.
1361        Name = 0;
1362      } else {
1363        // Okay, this is definition of a previously declared or referenced tag.
1364        // Move the location of the decl to be the definition site.
1365        PrevDecl->setLocation(NameLoc);
1366        return PrevDecl;
1367      }
1368    }
1369    // If we get here, this is a definition of a new struct type in a nested
1370    // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1371    // type.
1372  }
1373
1374  // If there is an identifier, use the location of the identifier as the
1375  // location of the decl, otherwise use the location of the struct/union
1376  // keyword.
1377  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1378
1379  // Otherwise, if this is the first time we've seen this tag, create the decl.
1380  TagDecl *New;
1381  switch (Kind) {
1382  default: assert(0 && "Unknown tag kind!");
1383  case Decl::Enum:
1384    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1385    // enum X { A, B, C } D;    D should chain to X.
1386    New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
1387    // If this is an undefined enum, warn.
1388    if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1389    break;
1390  case Decl::Union:
1391  case Decl::Struct:
1392  case Decl::Class:
1393    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1394    // struct X { int A; } D;    D should chain to X.
1395    New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1396    break;
1397  }
1398
1399  // If this has an identifier, add it to the scope stack.
1400  if (Name) {
1401    // The scope passed in may not be a decl scope.  Zip up the scope tree until
1402    // we find one that is.
1403    while ((S->getFlags() & Scope::DeclScope) == 0)
1404      S = S->getParent();
1405
1406    // Add it to the decl chain.
1407    New->setNext(Name->getFETokenInfo<ScopedDecl>());
1408    Name->setFETokenInfo(New);
1409    S->AddDecl(New);
1410  }
1411
1412  HandleDeclAttributes(New, Attr, 0);
1413  return New;
1414}
1415
1416/// ActOnField - Each field of a struct/union/class is passed into this in order
1417/// to create a FieldDecl object for it.
1418Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *tagDecl,
1419                               SourceLocation DeclStart,
1420                               Declarator &D, ExprTy *BitfieldWidth) {
1421  IdentifierInfo *II = D.getIdentifier();
1422  Expr *BitWidth = (Expr*)BitfieldWidth;
1423  Decl *TagDecl = static_cast<Decl *>(tagDecl);
1424  SourceLocation Loc = DeclStart;
1425  if (II) Loc = D.getIdentifierLoc();
1426
1427  // FIXME: Unnamed fields can be handled in various different ways, for
1428  // example, unnamed unions inject all members into the struct namespace!
1429
1430
1431  if (BitWidth) {
1432    // TODO: Validate.
1433    //printf("WARNING: BITFIELDS IGNORED!\n");
1434
1435    // 6.7.2.1p3
1436    // 6.7.2.1p4
1437
1438  } else {
1439    // Not a bitfield.
1440
1441    // validate II.
1442
1443  }
1444
1445  QualType T = GetTypeForDeclarator(D, S);
1446  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1447  bool InvalidDecl = false;
1448
1449  // C99 6.7.2.1p8: A member of a structure or union may have any type other
1450  // than a variably modified type.
1451  if (T->isVariablyModifiedType()) {
1452    // FIXME: This diagnostic needs work
1453    Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1454    InvalidDecl = true;
1455  }
1456  // FIXME: Chain fielddecls together.
1457  FieldDecl *NewFD;
1458
1459  if (isa<RecordDecl>(TagDecl))
1460    NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
1461  else if (isa<ObjCInterfaceDecl>(TagDecl) ||
1462           isa<ObjCImplementationDecl>(TagDecl) ||
1463           isa<ObjCCategoryDecl>(TagDecl) ||
1464           // FIXME: ivars are currently used to model properties, and
1465           // properties can appear within a protocol.
1466           // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1467           isa<ObjCProtocolDecl>(TagDecl))
1468    NewFD = ObjCIvarDecl::Create(Context, Loc, II, T);
1469  else
1470    assert(0 && "Sema::ActOnField(): Unknown TagDecl");
1471
1472  HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1473                       D.getAttributes());
1474
1475  if (D.getInvalidType() || InvalidDecl)
1476    NewFD->setInvalidDecl();
1477  return NewFD;
1478}
1479
1480/// TranslateIvarVisibility - Translate visibility from a token ID to an
1481///  AST enum value.
1482static ObjCIvarDecl::AccessControl
1483TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
1484  switch (ivarVisibility) {
1485    case tok::objc_private: return ObjCIvarDecl::Private;
1486    case tok::objc_public: return ObjCIvarDecl::Public;
1487    case tok::objc_protected: return ObjCIvarDecl::Protected;
1488    case tok::objc_package: return ObjCIvarDecl::Package;
1489    default: assert(false && "Unknown visitibility kind");
1490  }
1491}
1492
1493void Sema::ActOnFields(Scope* S,
1494                       SourceLocation RecLoc, DeclTy *RecDecl,
1495                       DeclTy **Fields, unsigned NumFields,
1496                       SourceLocation LBrac, SourceLocation RBrac,
1497                       tok::ObjCKeywordKind *visibility) {
1498  Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1499  assert(EnclosingDecl && "missing record or interface decl");
1500  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1501
1502  if (Record && Record->isDefinition()) {
1503    // Diagnose code like:
1504    //     struct S { struct S {} X; };
1505    // We discover this when we complete the outer S.  Reject and ignore the
1506    // outer S.
1507    Diag(Record->getLocation(), diag::err_nested_redefinition,
1508         Record->getKindName());
1509    Diag(RecLoc, diag::err_previous_definition);
1510    Record->setInvalidDecl();
1511    return;
1512  }
1513  // Verify that all the fields are okay.
1514  unsigned NumNamedMembers = 0;
1515  llvm::SmallVector<FieldDecl*, 32> RecFields;
1516  llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
1517
1518  for (unsigned i = 0; i != NumFields; ++i) {
1519
1520    FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1521    assert(FD && "missing field decl");
1522
1523    // Remember all fields.
1524    RecFields.push_back(FD);
1525
1526    // Get the type for the field.
1527    Type *FDTy = FD->getType().getTypePtr();
1528
1529    // If we have visibility info, make sure the AST is set accordingly.
1530    if (visibility)
1531      cast<ObjCIvarDecl>(FD)->setAccessControl(
1532                                TranslateIvarVisibility(visibility[i]));
1533
1534    // C99 6.7.2.1p2 - A field may not be a function type.
1535    if (FDTy->isFunctionType()) {
1536      Diag(FD->getLocation(), diag::err_field_declared_as_function,
1537           FD->getName());
1538      FD->setInvalidDecl();
1539      EnclosingDecl->setInvalidDecl();
1540      continue;
1541    }
1542    // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1543    if (FDTy->isIncompleteType()) {
1544      if (!Record) {  // Incomplete ivar type is always an error.
1545        Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1546        FD->setInvalidDecl();
1547        EnclosingDecl->setInvalidDecl();
1548        continue;
1549      }
1550      if (i != NumFields-1 ||                   // ... that the last member ...
1551          Record->getKind() != Decl::Struct ||  // ... of a structure ...
1552          !FDTy->isArrayType()) {         //... may have incomplete array type.
1553        Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1554        FD->setInvalidDecl();
1555        EnclosingDecl->setInvalidDecl();
1556        continue;
1557      }
1558      if (NumNamedMembers < 1) {  //... must have more than named member ...
1559        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1560             FD->getName());
1561        FD->setInvalidDecl();
1562        EnclosingDecl->setInvalidDecl();
1563        continue;
1564      }
1565      // Okay, we have a legal flexible array member at the end of the struct.
1566      if (Record)
1567        Record->setHasFlexibleArrayMember(true);
1568    }
1569    /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1570    /// field of another structure or the element of an array.
1571    if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
1572      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1573        // If this is a member of a union, then entire union becomes "flexible".
1574        if (Record && Record->getKind() == Decl::Union) {
1575          Record->setHasFlexibleArrayMember(true);
1576        } else {
1577          // If this is a struct/class and this is not the last element, reject
1578          // it.  Note that GCC supports variable sized arrays in the middle of
1579          // structures.
1580          if (i != NumFields-1) {
1581            Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1582                 FD->getName());
1583            FD->setInvalidDecl();
1584            EnclosingDecl->setInvalidDecl();
1585            continue;
1586          }
1587          // We support flexible arrays at the end of structs in other structs
1588          // as an extension.
1589          Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1590               FD->getName());
1591          if (Record)
1592            Record->setHasFlexibleArrayMember(true);
1593        }
1594      }
1595    }
1596    /// A field cannot be an Objective-c object
1597    if (FDTy->isObjCInterfaceType()) {
1598      Diag(FD->getLocation(), diag::err_statically_allocated_object,
1599           FD->getName());
1600      FD->setInvalidDecl();
1601      EnclosingDecl->setInvalidDecl();
1602      continue;
1603    }
1604    // Keep track of the number of named members.
1605    if (IdentifierInfo *II = FD->getIdentifier()) {
1606      // Detect duplicate member names.
1607      if (!FieldIDs.insert(II)) {
1608        Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1609        // Find the previous decl.
1610        SourceLocation PrevLoc;
1611        for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1612          assert(i != e && "Didn't find previous def!");
1613          if (RecFields[i]->getIdentifier() == II) {
1614            PrevLoc = RecFields[i]->getLocation();
1615            break;
1616          }
1617        }
1618        Diag(PrevLoc, diag::err_previous_definition);
1619        FD->setInvalidDecl();
1620        EnclosingDecl->setInvalidDecl();
1621        continue;
1622      }
1623      ++NumNamedMembers;
1624    }
1625  }
1626
1627  // Okay, we successfully defined 'Record'.
1628  if (Record) {
1629    Record->defineBody(&RecFields[0], RecFields.size());
1630    Consumer.HandleTagDeclDefinition(Record);
1631  } else {
1632    ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1633    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1634      ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1635    else if (ObjCImplementationDecl *IMPDecl =
1636               dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
1637      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1638      IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
1639      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
1640    }
1641  }
1642}
1643
1644Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
1645                                      DeclTy *lastEnumConst,
1646                                      SourceLocation IdLoc, IdentifierInfo *Id,
1647                                      SourceLocation EqualLoc, ExprTy *val) {
1648  EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
1649  EnumConstantDecl *LastEnumConst =
1650    cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1651  Expr *Val = static_cast<Expr*>(val);
1652
1653  // The scope passed in may not be a decl scope.  Zip up the scope tree until
1654  // we find one that is.
1655  while ((S->getFlags() & Scope::DeclScope) == 0)
1656    S = S->getParent();
1657
1658  // Verify that there isn't already something declared with this name in this
1659  // scope.
1660  if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
1661    if (S->isDeclScope(PrevDecl)) {
1662      if (isa<EnumConstantDecl>(PrevDecl))
1663        Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1664      else
1665        Diag(IdLoc, diag::err_redefinition, Id->getName());
1666      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1667      delete Val;
1668      return 0;
1669    }
1670  }
1671
1672  llvm::APSInt EnumVal(32);
1673  QualType EltTy;
1674  if (Val) {
1675    // Make sure to promote the operand type to int.
1676    UsualUnaryConversions(Val);
1677
1678    // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1679    SourceLocation ExpLoc;
1680    if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1681      Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1682           Id->getName());
1683      delete Val;
1684      Val = 0;  // Just forget about it.
1685    } else {
1686      EltTy = Val->getType();
1687    }
1688  }
1689
1690  if (!Val) {
1691    if (LastEnumConst) {
1692      // Assign the last value + 1.
1693      EnumVal = LastEnumConst->getInitVal();
1694      ++EnumVal;
1695
1696      // Check for overflow on increment.
1697      if (EnumVal < LastEnumConst->getInitVal())
1698        Diag(IdLoc, diag::warn_enum_value_overflow);
1699
1700      EltTy = LastEnumConst->getType();
1701    } else {
1702      // First value, set to zero.
1703      EltTy = Context.IntTy;
1704      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
1705    }
1706  }
1707
1708  EnumConstantDecl *New =
1709    EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
1710                             Val, EnumVal,
1711                             LastEnumConst);
1712
1713  // Register this decl in the current scope stack.
1714  New->setNext(Id->getFETokenInfo<ScopedDecl>());
1715  Id->setFETokenInfo(New);
1716  S->AddDecl(New);
1717  return New;
1718}
1719
1720void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1721                         DeclTy **Elements, unsigned NumElements) {
1722  EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1723  assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1724
1725  // TODO: If the result value doesn't fit in an int, it must be a long or long
1726  // long value.  ISO C does not support this, but GCC does as an extension,
1727  // emit a warning.
1728  unsigned IntWidth = Context.Target.getIntWidth();
1729
1730  // Verify that all the values are okay, compute the size of the values, and
1731  // reverse the list.
1732  unsigned NumNegativeBits = 0;
1733  unsigned NumPositiveBits = 0;
1734
1735  // Keep track of whether all elements have type int.
1736  bool AllElementsInt = true;
1737
1738  EnumConstantDecl *EltList = 0;
1739  for (unsigned i = 0; i != NumElements; ++i) {
1740    EnumConstantDecl *ECD =
1741      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1742    if (!ECD) continue;  // Already issued a diagnostic.
1743
1744    // If the enum value doesn't fit in an int, emit an extension warning.
1745    const llvm::APSInt &InitVal = ECD->getInitVal();
1746    assert(InitVal.getBitWidth() >= IntWidth &&
1747           "Should have promoted value to int");
1748    if (InitVal.getBitWidth() > IntWidth) {
1749      llvm::APSInt V(InitVal);
1750      V.trunc(IntWidth);
1751      V.extend(InitVal.getBitWidth());
1752      if (V != InitVal)
1753        Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1754             InitVal.toString());
1755    }
1756
1757    // Keep track of the size of positive and negative values.
1758    if (InitVal.isUnsigned() || InitVal.isNonNegative())
1759      NumPositiveBits = std::max(NumPositiveBits,
1760                                 (unsigned)InitVal.getActiveBits());
1761    else
1762      NumNegativeBits = std::max(NumNegativeBits,
1763                                 (unsigned)InitVal.getMinSignedBits());
1764
1765    // Keep track of whether every enum element has type int (very commmon).
1766    if (AllElementsInt)
1767      AllElementsInt = ECD->getType() == Context.IntTy;
1768
1769    ECD->setNextDeclarator(EltList);
1770    EltList = ECD;
1771  }
1772
1773  // Figure out the type that should be used for this enum.
1774  // FIXME: Support attribute(packed) on enums and -fshort-enums.
1775  QualType BestType;
1776  unsigned BestWidth;
1777
1778  if (NumNegativeBits) {
1779    // If there is a negative value, figure out the smallest integer type (of
1780    // int/long/longlong) that fits.
1781    if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
1782      BestType = Context.IntTy;
1783      BestWidth = IntWidth;
1784    } else {
1785      BestWidth = Context.Target.getLongWidth();
1786
1787      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
1788        BestType = Context.LongTy;
1789      else {
1790        BestWidth = Context.Target.getLongLongWidth();
1791
1792        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
1793          Diag(Enum->getLocation(), diag::warn_enum_too_large);
1794        BestType = Context.LongLongTy;
1795      }
1796    }
1797  } else {
1798    // If there is no negative value, figure out which of uint, ulong, ulonglong
1799    // fits.
1800    if (NumPositiveBits <= IntWidth) {
1801      BestType = Context.UnsignedIntTy;
1802      BestWidth = IntWidth;
1803    } else if (NumPositiveBits <=
1804               (BestWidth = Context.Target.getLongWidth())) {
1805      BestType = Context.UnsignedLongTy;
1806    } else {
1807      BestWidth = Context.Target.getLongLongWidth();
1808      assert(NumPositiveBits <= BestWidth &&
1809             "How could an initializer get larger than ULL?");
1810      BestType = Context.UnsignedLongLongTy;
1811    }
1812  }
1813
1814  // Loop over all of the enumerator constants, changing their types to match
1815  // the type of the enum if needed.
1816  for (unsigned i = 0; i != NumElements; ++i) {
1817    EnumConstantDecl *ECD =
1818      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1819    if (!ECD) continue;  // Already issued a diagnostic.
1820
1821    // Standard C says the enumerators have int type, but we allow, as an
1822    // extension, the enumerators to be larger than int size.  If each
1823    // enumerator value fits in an int, type it as an int, otherwise type it the
1824    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
1825    // that X has type 'int', not 'unsigned'.
1826    if (ECD->getType() == Context.IntTy) {
1827      // Make sure the init value is signed.
1828      llvm::APSInt IV = ECD->getInitVal();
1829      IV.setIsSigned(true);
1830      ECD->setInitVal(IV);
1831      continue;  // Already int type.
1832    }
1833
1834    // Determine whether the value fits into an int.
1835    llvm::APSInt InitVal = ECD->getInitVal();
1836    bool FitsInInt;
1837    if (InitVal.isUnsigned() || !InitVal.isNegative())
1838      FitsInInt = InitVal.getActiveBits() < IntWidth;
1839    else
1840      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1841
1842    // If it fits into an integer type, force it.  Otherwise force it to match
1843    // the enum decl type.
1844    QualType NewTy;
1845    unsigned NewWidth;
1846    bool NewSign;
1847    if (FitsInInt) {
1848      NewTy = Context.IntTy;
1849      NewWidth = IntWidth;
1850      NewSign = true;
1851    } else if (ECD->getType() == BestType) {
1852      // Already the right type!
1853      continue;
1854    } else {
1855      NewTy = BestType;
1856      NewWidth = BestWidth;
1857      NewSign = BestType->isSignedIntegerType();
1858    }
1859
1860    // Adjust the APSInt value.
1861    InitVal.extOrTrunc(NewWidth);
1862    InitVal.setIsSigned(NewSign);
1863    ECD->setInitVal(InitVal);
1864
1865    // Adjust the Expr initializer and type.
1866    ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1867    ECD->setType(NewTy);
1868  }
1869
1870  Enum->defineElements(EltList, BestType);
1871  Consumer.HandleTagDeclDefinition(Enum);
1872}
1873
1874Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1875                                          ExprTy *expr) {
1876  StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1877
1878  return FileScopeAsmDecl::Create(Context, Loc, AsmString);
1879}
1880
1881Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
1882                                     SourceLocation LBrace,
1883                                     SourceLocation RBrace,
1884                                     const char *Lang,
1885                                     unsigned StrSize,
1886                                     DeclTy *D) {
1887  LinkageSpecDecl::LanguageIDs Language;
1888  Decl *dcl = static_cast<Decl *>(D);
1889  if (strncmp(Lang, "\"C\"", StrSize) == 0)
1890    Language = LinkageSpecDecl::lang_c;
1891  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1892    Language = LinkageSpecDecl::lang_cxx;
1893  else {
1894    Diag(Loc, diag::err_bad_language);
1895    return 0;
1896  }
1897
1898  // FIXME: Add all the various semantics of linkage specifications
1899  return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
1900}
1901
1902void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
1903
1904  switch (Attr->getKind()) {
1905  case AttributeList::AT_vector_size:
1906    if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1907      QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
1908      if (!newType.isNull()) // install the new vector type into the decl
1909        vDecl->setType(newType);
1910    }
1911    if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1912      QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1913                                                   Attr);
1914      if (!newType.isNull()) // install the new vector type into the decl
1915        tDecl->setUnderlyingType(newType);
1916    }
1917    break;
1918  case AttributeList::AT_ocu_vector_type:
1919    if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1920      HandleOCUVectorTypeAttribute(tDecl, Attr);
1921    else
1922      Diag(Attr->getLoc(),
1923           diag::err_typecheck_ocu_vector_not_typedef);
1924    break;
1925  case AttributeList::AT_address_space:
1926    if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1927      QualType newType = HandleAddressSpaceTypeAttribute(
1928                                                  tDecl->getUnderlyingType(),
1929                                                  Attr);
1930      tDecl->setUnderlyingType(newType);
1931    } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1932      QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
1933                                                         Attr);
1934      // install the new addr spaced type into the decl
1935      vDecl->setType(newType);
1936    }
1937    break;
1938  case AttributeList::AT_deprecated:
1939    HandleDeprecatedAttribute(New, Attr);
1940    break;
1941  case AttributeList::AT_visibility:
1942    HandleVisibilityAttribute(New, Attr);
1943    break;
1944  case AttributeList::AT_weak:
1945    HandleWeakAttribute(New, Attr);
1946    break;
1947  case AttributeList::AT_dllimport:
1948    HandleDLLImportAttribute(New, Attr);
1949    break;
1950  case AttributeList::AT_dllexport:
1951    HandleDLLExportAttribute(New, Attr);
1952    break;
1953  case AttributeList::AT_nothrow:
1954    HandleNothrowAttribute(New, Attr);
1955    break;
1956  case AttributeList::AT_stdcall:
1957    HandleStdCallAttribute(New, Attr);
1958    break;
1959  case AttributeList::AT_fastcall:
1960    HandleFastCallAttribute(New, Attr);
1961    break;
1962  case AttributeList::AT_aligned:
1963    HandleAlignedAttribute(New, Attr);
1964    break;
1965  case AttributeList::AT_packed:
1966    HandlePackedAttribute(New, Attr);
1967    break;
1968  case AttributeList::AT_annotate:
1969    HandleAnnotateAttribute(New, Attr);
1970    break;
1971  case AttributeList::AT_noreturn:
1972    HandleNoReturnAttribute(New, Attr);
1973    break;
1974  case AttributeList::AT_format:
1975    HandleFormatAttribute(New, Attr);
1976    break;
1977  default:
1978#if 0
1979    // TODO: when we have the full set of attributes, warn about unknown ones.
1980    Diag(Attr->getLoc(), diag::warn_attribute_ignored,
1981         Attr->getName()->getName());
1982#endif
1983    break;
1984  }
1985}
1986
1987void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1988                                AttributeList *declarator_postfix) {
1989  while (declspec_prefix) {
1990    HandleDeclAttribute(New, declspec_prefix);
1991    declspec_prefix = declspec_prefix->getNext();
1992  }
1993  while (declarator_postfix) {
1994    HandleDeclAttribute(New, declarator_postfix);
1995    declarator_postfix = declarator_postfix->getNext();
1996  }
1997}
1998
1999void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
2000                                        AttributeList *rawAttr) {
2001  QualType curType = tDecl->getUnderlyingType();
2002  // check the attribute arguments.
2003  if (rawAttr->getNumArgs() != 1) {
2004    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2005         std::string("1"));
2006    return;
2007  }
2008  Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2009  llvm::APSInt vecSize(32);
2010  if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
2011    Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
2012         "ocu_vector_type", sizeExpr->getSourceRange());
2013    return;
2014  }
2015  // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2016  // in conjunction with complex types (pointers, arrays, functions, etc.).
2017  Type *canonType = curType.getCanonicalType().getTypePtr();
2018  if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2019    Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
2020         curType.getCanonicalType().getAsString());
2021    return;
2022  }
2023  // unlike gcc's vector_size attribute, the size is specified as the
2024  // number of elements, not the number of bytes.
2025  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2026
2027  if (vectorSize == 0) {
2028    Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
2029         sizeExpr->getSourceRange());
2030    return;
2031  }
2032  // Instantiate/Install the vector type, the number of elements is > 0.
2033  tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
2034  // Remember this typedef decl, we will need it later for diagnostics.
2035  OCUVectorDecls.push_back(tDecl);
2036}
2037
2038QualType Sema::HandleVectorTypeAttribute(QualType curType,
2039                                         AttributeList *rawAttr) {
2040  // check the attribute arugments.
2041  if (rawAttr->getNumArgs() != 1) {
2042    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2043         std::string("1"));
2044    return QualType();
2045  }
2046  Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2047  llvm::APSInt vecSize(32);
2048  if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
2049    Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
2050         "vector_size", sizeExpr->getSourceRange());
2051    return QualType();
2052  }
2053  // navigate to the base type - we need to provide for vector pointers,
2054  // vector arrays, and functions returning vectors.
2055  Type *canonType = curType.getCanonicalType().getTypePtr();
2056
2057  if (canonType->isPointerType() || canonType->isArrayType() ||
2058      canonType->isFunctionType()) {
2059    assert(0 && "HandleVector(): Complex type construction unimplemented");
2060    /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2061        do {
2062          if (PointerType *PT = dyn_cast<PointerType>(canonType))
2063            canonType = PT->getPointeeType().getTypePtr();
2064          else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2065            canonType = AT->getElementType().getTypePtr();
2066          else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2067            canonType = FT->getResultType().getTypePtr();
2068        } while (canonType->isPointerType() || canonType->isArrayType() ||
2069                 canonType->isFunctionType());
2070    */
2071  }
2072  // the base type must be integer or float.
2073  if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2074    Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
2075         curType.getCanonicalType().getAsString());
2076    return QualType();
2077  }
2078  unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
2079  // vecSize is specified in bytes - convert to bits.
2080  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
2081
2082  // the vector size needs to be an integral multiple of the type size.
2083  if (vectorSize % typeSize) {
2084    Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
2085         sizeExpr->getSourceRange());
2086    return QualType();
2087  }
2088  if (vectorSize == 0) {
2089    Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
2090         sizeExpr->getSourceRange());
2091    return QualType();
2092  }
2093  // Instantiate the vector type, the number of elements is > 0, and not
2094  // required to be a power of 2, unlike GCC.
2095  return Context.getVectorType(curType, vectorSize/typeSize);
2096}
2097
2098void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
2099  // check the attribute arguments.
2100  if (rawAttr->getNumArgs() > 0) {
2101    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2102         std::string("0"));
2103    return;
2104  }
2105
2106  if (TagDecl *TD = dyn_cast<TagDecl>(d))
2107    TD->addAttr(new PackedAttr);
2108  else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2109    // If the alignment is less than or equal to 8 bits, the packed attribute
2110    // has no effect.
2111    if (Context.getTypeAlign(FD->getType()) <= 8)
2112      Diag(rawAttr->getLoc(),
2113           diag::warn_attribute_ignored_for_field_of_type,
2114           rawAttr->getName()->getName(), FD->getType().getAsString());
2115    else
2116      FD->addAttr(new PackedAttr);
2117  } else
2118    Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2119         rawAttr->getName()->getName());
2120}
2121
2122void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2123  // check the attribute arguments.
2124  if (rawAttr->getNumArgs() != 0) {
2125    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2126         std::string("0"));
2127    return;
2128  }
2129
2130  FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2131
2132  if (!Fn) {
2133    Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2134         "noreturn", "function");
2135    return;
2136  }
2137
2138  d->addAttr(new NoReturnAttr());
2139}
2140
2141void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2142  // check the attribute arguments.
2143  if (rawAttr->getNumArgs() != 0) {
2144    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2145         std::string("0"));
2146    return;
2147  }
2148
2149  d->addAttr(new DeprecatedAttr());
2150}
2151
2152void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2153  // check the attribute arguments.
2154  if (rawAttr->getNumArgs() != 1) {
2155    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2156         std::string("1"));
2157    return;
2158  }
2159
2160  Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2161  Arg = Arg->IgnoreParenCasts();
2162  StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2163
2164  if (Str == 0 || Str->isWide()) {
2165    Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2166         "visibility", std::string("1"));
2167    return;
2168  }
2169
2170  const char *TypeStr = Str->getStrData();
2171  unsigned TypeLen = Str->getByteLength();
2172  llvm::GlobalValue::VisibilityTypes type;
2173
2174  if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
2175    type = llvm::GlobalValue::DefaultVisibility;
2176  else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
2177    type = llvm::GlobalValue::HiddenVisibility;
2178  else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
2179    type = llvm::GlobalValue::HiddenVisibility; // FIXME
2180  else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
2181    type = llvm::GlobalValue::ProtectedVisibility;
2182  else {
2183    Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2184           "visibility", TypeStr);
2185    return;
2186  }
2187
2188  d->addAttr(new VisibilityAttr(type));
2189}
2190
2191void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2192  // check the attribute arguments.
2193  if (rawAttr->getNumArgs() != 0) {
2194    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2195         std::string("0"));
2196    return;
2197  }
2198
2199  d->addAttr(new WeakAttr());
2200}
2201
2202void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2203  // check the attribute arguments.
2204  if (rawAttr->getNumArgs() != 0) {
2205    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2206         std::string("0"));
2207    return;
2208  }
2209
2210  d->addAttr(new DLLImportAttr());
2211}
2212
2213void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2214  // check the attribute arguments.
2215  if (rawAttr->getNumArgs() != 0) {
2216    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2217         std::string("0"));
2218    return;
2219  }
2220
2221  d->addAttr(new DLLExportAttr());
2222}
2223
2224void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2225  // check the attribute arguments.
2226  if (rawAttr->getNumArgs() != 0) {
2227    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2228         std::string("0"));
2229    return;
2230  }
2231
2232  d->addAttr(new StdCallAttr());
2233}
2234
2235void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2236  // check the attribute arguments.
2237  if (rawAttr->getNumArgs() != 0) {
2238    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2239         std::string("0"));
2240    return;
2241  }
2242
2243  d->addAttr(new FastCallAttr());
2244}
2245
2246void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2247  // check the attribute arguments.
2248  if (rawAttr->getNumArgs() != 0) {
2249    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2250         std::string("0"));
2251    return;
2252  }
2253
2254  d->addAttr(new NoThrowAttr());
2255}
2256
2257static const FunctionTypeProto *getFunctionProto(Decl *d) {
2258  ValueDecl *decl = dyn_cast<ValueDecl>(d);
2259  if (!decl) return 0;
2260
2261  QualType Ty = decl->getType();
2262
2263  if (Ty->isFunctionPointerType()) {
2264    const PointerType *PtrTy = Ty->getAsPointerType();
2265    Ty = PtrTy->getPointeeType();
2266  }
2267
2268  if (const FunctionType *FnTy = Ty->getAsFunctionType())
2269    return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2270
2271  return 0;
2272}
2273
2274
2275/// Handle __attribute__((format(type,idx,firstarg))) attributes
2276/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2277void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2278
2279  if (!rawAttr->getParameterName()) {
2280    Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2281           "format", std::string("1"));
2282    return;
2283  }
2284
2285  if (rawAttr->getNumArgs() != 2) {
2286    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2287         std::string("3"));
2288    return;
2289  }
2290
2291  // GCC ignores the format attribute on K&R style function
2292  // prototypes, so we ignore it as well
2293  const FunctionTypeProto *proto = getFunctionProto(d);
2294
2295  if (!proto) {
2296    Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2297           "format", "function");
2298    return;
2299  }
2300
2301  // FIXME: in C++ the implicit 'this' function parameter also counts.
2302  // this is needed in order to be compatible with GCC
2303  // the index must start in 1 and the limit is numargs+1
2304  unsigned NumArgs  = proto->getNumArgs();
2305  unsigned FirstIdx = 1;
2306
2307  const char *Format = rawAttr->getParameterName()->getName();
2308  unsigned FormatLen = rawAttr->getParameterName()->getLength();
2309
2310  // Normalize the argument, __foo__ becomes foo.
2311  if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2312      Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2313    Format += 2;
2314    FormatLen -= 4;
2315  }
2316
2317  if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2318     || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2319     || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2320     || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2321    Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2322           "format", rawAttr->getParameterName()->getName());
2323    return;
2324  }
2325
2326  // checks for the 2nd argument
2327  Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
2328  llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
2329  if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2330    Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2331           "format", std::string("2"), IdxExpr->getSourceRange());
2332    return;
2333  }
2334
2335  if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
2336    Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2337           "format", std::string("2"), IdxExpr->getSourceRange());
2338    return;
2339  }
2340
2341  // make sure the format string is really a string
2342  QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2343  if (!Ty->isPointerType() ||
2344      !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2345    Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2346         IdxExpr->getSourceRange());
2347    return;
2348  }
2349
2350
2351  // check the 3rd argument
2352  Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
2353  llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
2354  if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2355    Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2356           "format", std::string("3"), FirstArgExpr->getSourceRange());
2357    return;
2358  }
2359
2360  // check if the function is variadic if the 3rd argument non-zero
2361  if (FirstArg != 0) {
2362    if (proto->isVariadic()) {
2363      ++NumArgs; // +1 for ...
2364    } else {
2365      Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2366      return;
2367    }
2368  }
2369
2370  // strftime requires FirstArg to be 0 because it doesn't read from any variable
2371  // the input is just the current time + the format string
2372  if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
2373    if (FirstArg != 0) {
2374      Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2375             FirstArgExpr->getSourceRange());
2376      return;
2377    }
2378  // if 0 it disables parameter checking (to use with e.g. va_list)
2379  } else if (FirstArg != 0 && FirstArg != NumArgs) {
2380    Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2381           "format", std::string("3"), FirstArgExpr->getSourceRange());
2382    return;
2383  }
2384
2385  d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2386                            Idx.getZExtValue(), FirstArg.getZExtValue()));
2387}
2388
2389void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2390  // check the attribute arguments.
2391  if (rawAttr->getNumArgs() != 1) {
2392    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2393         std::string("1"));
2394    return;
2395  }
2396  Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2397  StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
2398
2399  // Make sure that there is a string literal as the annotation's single
2400  // argument.
2401  if (!SE) {
2402    Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2403    return;
2404  }
2405  d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2406                                          SE->getByteLength())));
2407}
2408
2409void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2410{
2411  // check the attribute arguments.
2412  if (rawAttr->getNumArgs() > 1) {
2413    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2414         std::string("1"));
2415    return;
2416  }
2417
2418  unsigned Align = 0;
2419
2420  if (rawAttr->getNumArgs() == 0) {
2421    // FIXME: This should be the target specific maximum alignment.
2422    // (For now we just use 128 bits which is the maximum on X86.
2423    Align = 128;
2424    return;
2425  } else {
2426    Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2427    llvm::APSInt alignment(32);
2428    if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
2429      Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
2430           "aligned", alignmentExpr->getSourceRange());
2431      return;
2432    }
2433
2434    Align = alignment.getZExtValue() * 8;
2435  }
2436
2437  d->addAttr(new AlignedAttr(Align));
2438}
2439