SemaDecl.cpp revision 8bf515b1f6e8ecdcbd3ebcc99fe08ea22fc7fd95
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 "SemaInit.h"
16#include "Lookup.h"
17#include "clang/AST/APValue.h"
18#include "clang/AST/ASTConsumer.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/StmtCXX.h"
24#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/ParseDiagnostic.h"
26#include "clang/Parse/Template.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Lex/HeaderSearch.h"
33#include "llvm/ADT/Triple.h"
34#include <algorithm>
35#include <cstring>
36#include <functional>
37using namespace clang;
38
39/// getDeclName - Return a pretty name for the specified decl if possible, or
40/// an empty string if not.  This is used for pretty crash reporting.
41std::string Sema::getDeclName(DeclPtrTy d) {
42  Decl *D = d.getAs<Decl>();
43  if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
44    return DN->getQualifiedNameAsString();
45  return "";
46}
47
48Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
49  return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
50}
51
52/// \brief If the identifier refers to a type name within this scope,
53/// return the declaration of that type.
54///
55/// This routine performs ordinary name lookup of the identifier II
56/// within the given scope, with optional C++ scope specifier SS, to
57/// determine whether the name refers to a type. If so, returns an
58/// opaque pointer (actually a QualType) corresponding to that
59/// type. Otherwise, returns NULL.
60///
61/// If name lookup results in an ambiguity, this routine will complain
62/// and then return NULL.
63Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
64                                Scope *S, CXXScopeSpec *SS,
65                                bool isClassName,
66                                TypeTy *ObjectTypePtr) {
67  // Determine where we will perform name lookup.
68  DeclContext *LookupCtx = 0;
69  if (ObjectTypePtr) {
70    QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
71    if (ObjectType->isRecordType())
72      LookupCtx = computeDeclContext(ObjectType);
73  } else if (SS && SS->isNotEmpty()) {
74    LookupCtx = computeDeclContext(*SS, false);
75
76    if (!LookupCtx) {
77      if (isDependentScopeSpecifier(*SS)) {
78        // C++ [temp.res]p3:
79        //   A qualified-id that refers to a type and in which the
80        //   nested-name-specifier depends on a template-parameter (14.6.2)
81        //   shall be prefixed by the keyword typename to indicate that the
82        //   qualified-id denotes a type, forming an
83        //   elaborated-type-specifier (7.1.5.3).
84        //
85        // We therefore do not perform any name lookup if the result would
86        // refer to a member of an unknown specialization.
87        if (!isClassName)
88          return 0;
89
90        // We know from the grammar that this name refers to a type, so build a
91        // DependentNameType node to describe the type.
92        return CheckTypenameType(ETK_None,
93                                 (NestedNameSpecifier *)SS->getScopeRep(),
94                                 II, SS->getRange()).getAsOpaquePtr();
95      }
96
97      return 0;
98    }
99
100    if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
101      return 0;
102  }
103
104  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
105  // lookup for class-names.
106  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
107                                      LookupOrdinaryName;
108  LookupResult Result(*this, &II, NameLoc, Kind);
109  if (LookupCtx) {
110    // Perform "qualified" name lookup into the declaration context we
111    // computed, which is either the type of the base of a member access
112    // expression or the declaration context associated with a prior
113    // nested-name-specifier.
114    LookupQualifiedName(Result, LookupCtx);
115
116    if (ObjectTypePtr && Result.empty()) {
117      // C++ [basic.lookup.classref]p3:
118      //   If the unqualified-id is ~type-name, the type-name is looked up
119      //   in the context of the entire postfix-expression. If the type T of
120      //   the object expression is of a class type C, the type-name is also
121      //   looked up in the scope of class C. At least one of the lookups shall
122      //   find a name that refers to (possibly cv-qualified) T.
123      LookupName(Result, S);
124    }
125  } else {
126    // Perform unqualified name lookup.
127    LookupName(Result, S);
128  }
129
130  NamedDecl *IIDecl = 0;
131  switch (Result.getResultKind()) {
132  case LookupResult::NotFound:
133  case LookupResult::NotFoundInCurrentInstantiation:
134  case LookupResult::FoundOverloaded:
135  case LookupResult::FoundUnresolvedValue:
136    Result.suppressDiagnostics();
137    return 0;
138
139  case LookupResult::Ambiguous:
140    // Recover from type-hiding ambiguities by hiding the type.  We'll
141    // do the lookup again when looking for an object, and we can
142    // diagnose the error then.  If we don't do this, then the error
143    // about hiding the type will be immediately followed by an error
144    // that only makes sense if the identifier was treated like a type.
145    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
146      Result.suppressDiagnostics();
147      return 0;
148    }
149
150    // Look to see if we have a type anywhere in the list of results.
151    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
152         Res != ResEnd; ++Res) {
153      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
154        if (!IIDecl ||
155            (*Res)->getLocation().getRawEncoding() <
156              IIDecl->getLocation().getRawEncoding())
157          IIDecl = *Res;
158      }
159    }
160
161    if (!IIDecl) {
162      // None of the entities we found is a type, so there is no way
163      // to even assume that the result is a type. In this case, don't
164      // complain about the ambiguity. The parser will either try to
165      // perform this lookup again (e.g., as an object name), which
166      // will produce the ambiguity, or will complain that it expected
167      // a type name.
168      Result.suppressDiagnostics();
169      return 0;
170    }
171
172    // We found a type within the ambiguous lookup; diagnose the
173    // ambiguity and then return that type. This might be the right
174    // answer, or it might not be, but it suppresses any attempt to
175    // perform the name lookup again.
176    break;
177
178  case LookupResult::Found:
179    IIDecl = Result.getFoundDecl();
180    break;
181  }
182
183  assert(IIDecl && "Didn't find decl");
184
185  QualType T;
186  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
187    DiagnoseUseOfDecl(IIDecl, NameLoc);
188
189    if (T.isNull())
190      T = Context.getTypeDeclType(TD);
191
192    if (SS)
193      T = getQualifiedNameType(*SS, T);
194
195  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
196    T = Context.getObjCInterfaceType(IDecl);
197  } else if (UnresolvedUsingTypenameDecl *UUDecl =
198               dyn_cast<UnresolvedUsingTypenameDecl>(IIDecl)) {
199    // FIXME: preserve source structure information.
200    T = Context.getDependentNameType(ETK_None,
201                                     UUDecl->getTargetNestedNameSpecifier(),
202                                     &II);
203  } else {
204    // If it's not plausibly a type, suppress diagnostics.
205    Result.suppressDiagnostics();
206    return 0;
207  }
208
209  return T.getAsOpaquePtr();
210}
211
212/// isTagName() - This method is called *for error recovery purposes only*
213/// to determine if the specified name is a valid tag name ("struct foo").  If
214/// so, this returns the TST for the tag corresponding to it (TST_enum,
215/// TST_union, TST_struct, TST_class).  This is used to diagnose cases in C
216/// where the user forgot to specify the tag.
217DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
218  // Do a tag name lookup in this scope.
219  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
220  LookupName(R, S, false);
221  R.suppressDiagnostics();
222  if (R.getResultKind() == LookupResult::Found)
223    if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
224      switch (TD->getTagKind()) {
225      case TagDecl::TK_struct: return DeclSpec::TST_struct;
226      case TagDecl::TK_union:  return DeclSpec::TST_union;
227      case TagDecl::TK_class:  return DeclSpec::TST_class;
228      case TagDecl::TK_enum:   return DeclSpec::TST_enum;
229      }
230    }
231
232  return DeclSpec::TST_unspecified;
233}
234
235bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
236                                   SourceLocation IILoc,
237                                   Scope *S,
238                                   CXXScopeSpec *SS,
239                                   TypeTy *&SuggestedType) {
240  // We don't have anything to suggest (yet).
241  SuggestedType = 0;
242
243  // There may have been a typo in the name of the type. Look up typo
244  // results, in case we have something that we can suggest.
245  LookupResult Lookup(*this, &II, IILoc, LookupOrdinaryName,
246                      NotForRedeclaration);
247
248  if (DeclarationName Corrected = CorrectTypo(Lookup, S, SS, 0, 0, CTC_Type)) {
249    if (NamedDecl *Result = Lookup.getAsSingle<NamedDecl>()) {
250      if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
251          !Result->isInvalidDecl()) {
252        // We found a similarly-named type or interface; suggest that.
253        if (!SS || !SS->isSet())
254          Diag(IILoc, diag::err_unknown_typename_suggest)
255            << &II << Lookup.getLookupName()
256            << FixItHint::CreateReplacement(SourceRange(IILoc),
257                                            Result->getNameAsString());
258        else if (DeclContext *DC = computeDeclContext(*SS, false))
259          Diag(IILoc, diag::err_unknown_nested_typename_suggest)
260            << &II << DC << Lookup.getLookupName() << SS->getRange()
261            << FixItHint::CreateReplacement(SourceRange(IILoc),
262                                            Result->getNameAsString());
263        else
264          llvm_unreachable("could not have corrected a typo here");
265
266        Diag(Result->getLocation(), diag::note_previous_decl)
267          << Result->getDeclName();
268
269        SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS);
270        return true;
271      }
272    } else if (Lookup.empty()) {
273      // We corrected to a keyword.
274      // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
275      Diag(IILoc, diag::err_unknown_typename_suggest)
276        << &II << Corrected;
277      return true;
278    }
279  }
280
281  if (getLangOptions().CPlusPlus) {
282    // See if II is a class template that the user forgot to pass arguments to.
283    UnqualifiedId Name;
284    Name.setIdentifier(&II, IILoc);
285    CXXScopeSpec EmptySS;
286    TemplateTy TemplateResult;
287    if (isTemplateName(S, SS ? *SS : EmptySS, Name, 0, true, TemplateResult)
288        == TNK_Type_template) {
289      TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
290      Diag(IILoc, diag::err_template_missing_args) << TplName;
291      if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
292        Diag(TplDecl->getLocation(), diag::note_template_decl_here)
293          << TplDecl->getTemplateParameters()->getSourceRange();
294      }
295      return true;
296    }
297  }
298
299  // FIXME: Should we move the logic that tries to recover from a missing tag
300  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
301
302  if (!SS || (!SS->isSet() && !SS->isInvalid()))
303    Diag(IILoc, diag::err_unknown_typename) << &II;
304  else if (DeclContext *DC = computeDeclContext(*SS, false))
305    Diag(IILoc, diag::err_typename_nested_not_found)
306      << &II << DC << SS->getRange();
307  else if (isDependentScopeSpecifier(*SS)) {
308    Diag(SS->getRange().getBegin(), diag::err_typename_missing)
309      << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
310      << SourceRange(SS->getRange().getBegin(), IILoc)
311      << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
312    SuggestedType = ActOnTypenameType(SourceLocation(), *SS, II, IILoc).get();
313  } else {
314    assert(SS && SS->isInvalid() &&
315           "Invalid scope specifier has already been diagnosed");
316  }
317
318  return true;
319}
320
321// Determines the context to return to after temporarily entering a
322// context.  This depends in an unnecessarily complicated way on the
323// exact ordering of callbacks from the parser.
324DeclContext *Sema::getContainingDC(DeclContext *DC) {
325
326  // Functions defined inline within classes aren't parsed until we've
327  // finished parsing the top-level class, so the top-level class is
328  // the context we'll need to return to.
329  if (isa<FunctionDecl>(DC)) {
330    DC = DC->getLexicalParent();
331
332    // A function not defined within a class will always return to its
333    // lexical context.
334    if (!isa<CXXRecordDecl>(DC))
335      return DC;
336
337    // A C++ inline method/friend is parsed *after* the topmost class
338    // it was declared in is fully parsed ("complete");  the topmost
339    // class is the context we need to return to.
340    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
341      DC = RD;
342
343    // Return the declaration context of the topmost class the inline method is
344    // declared in.
345    return DC;
346  }
347
348  if (isa<ObjCMethodDecl>(DC))
349    return Context.getTranslationUnitDecl();
350
351  return DC->getLexicalParent();
352}
353
354void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
355  assert(getContainingDC(DC) == CurContext &&
356      "The next DeclContext should be lexically contained in the current one.");
357  CurContext = DC;
358  S->setEntity(DC);
359}
360
361void Sema::PopDeclContext() {
362  assert(CurContext && "DeclContext imbalance!");
363
364  CurContext = getContainingDC(CurContext);
365}
366
367/// EnterDeclaratorContext - Used when we must lookup names in the context
368/// of a declarator's nested name specifier.
369///
370void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
371  // C++0x [basic.lookup.unqual]p13:
372  //   A name used in the definition of a static data member of class
373  //   X (after the qualified-id of the static member) is looked up as
374  //   if the name was used in a member function of X.
375  // C++0x [basic.lookup.unqual]p14:
376  //   If a variable member of a namespace is defined outside of the
377  //   scope of its namespace then any name used in the definition of
378  //   the variable member (after the declarator-id) is looked up as
379  //   if the definition of the variable member occurred in its
380  //   namespace.
381  // Both of these imply that we should push a scope whose context
382  // is the semantic context of the declaration.  We can't use
383  // PushDeclContext here because that context is not necessarily
384  // lexically contained in the current context.  Fortunately,
385  // the containing scope should have the appropriate information.
386
387  assert(!S->getEntity() && "scope already has entity");
388
389#ifndef NDEBUG
390  Scope *Ancestor = S->getParent();
391  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
392  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
393#endif
394
395  CurContext = DC;
396  S->setEntity(DC);
397}
398
399void Sema::ExitDeclaratorContext(Scope *S) {
400  assert(S->getEntity() == CurContext && "Context imbalance!");
401
402  // Switch back to the lexical context.  The safety of this is
403  // enforced by an assert in EnterDeclaratorContext.
404  Scope *Ancestor = S->getParent();
405  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
406  CurContext = (DeclContext*) Ancestor->getEntity();
407
408  // We don't need to do anything with the scope, which is going to
409  // disappear.
410}
411
412/// \brief Determine whether we allow overloading of the function
413/// PrevDecl with another declaration.
414///
415/// This routine determines whether overloading is possible, not
416/// whether some new function is actually an overload. It will return
417/// true in C++ (where we can always provide overloads) or, as an
418/// extension, in C when the previous function is already an
419/// overloaded function declaration or has the "overloadable"
420/// attribute.
421static bool AllowOverloadingOfFunction(LookupResult &Previous,
422                                       ASTContext &Context) {
423  if (Context.getLangOptions().CPlusPlus)
424    return true;
425
426  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
427    return true;
428
429  return (Previous.getResultKind() == LookupResult::Found
430          && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
431}
432
433/// Add this decl to the scope shadowed decl chains.
434void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
435  // Move up the scope chain until we find the nearest enclosing
436  // non-transparent context. The declaration will be introduced into this
437  // scope.
438  while (S->getEntity() &&
439         ((DeclContext *)S->getEntity())->isTransparentContext())
440    S = S->getParent();
441
442  // Add scoped declarations into their context, so that they can be
443  // found later. Declarations without a context won't be inserted
444  // into any context.
445  if (AddToContext)
446    CurContext->addDecl(D);
447
448  // Out-of-line definitions shouldn't be pushed into scope in C++.
449  // Out-of-line variable and function definitions shouldn't even in C.
450  if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
451      D->isOutOfLine())
452    return;
453
454  // Template instantiations should also not be pushed into scope.
455  if (isa<FunctionDecl>(D) &&
456      cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
457    return;
458
459  // If this replaces anything in the current scope,
460  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
461                               IEnd = IdResolver.end();
462  for (; I != IEnd; ++I) {
463    if (S->isDeclScope(DeclPtrTy::make(*I)) && D->declarationReplaces(*I)) {
464      S->RemoveDecl(DeclPtrTy::make(*I));
465      IdResolver.RemoveDecl(*I);
466
467      // Should only need to replace one decl.
468      break;
469    }
470  }
471
472  S->AddDecl(DeclPtrTy::make(D));
473  IdResolver.AddDecl(D);
474}
475
476bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) {
477  return IdResolver.isDeclInScope(D, Ctx, Context, S);
478}
479
480static bool isOutOfScopePreviousDeclaration(NamedDecl *,
481                                            DeclContext*,
482                                            ASTContext&);
483
484/// Filters out lookup results that don't fall within the given scope
485/// as determined by isDeclInScope.
486static void FilterLookupForScope(Sema &SemaRef, LookupResult &R,
487                                 DeclContext *Ctx, Scope *S,
488                                 bool ConsiderLinkage) {
489  LookupResult::Filter F = R.makeFilter();
490  while (F.hasNext()) {
491    NamedDecl *D = F.next();
492
493    if (SemaRef.isDeclInScope(D, Ctx, S))
494      continue;
495
496    if (ConsiderLinkage &&
497        isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context))
498      continue;
499
500    F.erase();
501  }
502
503  F.done();
504}
505
506static bool isUsingDecl(NamedDecl *D) {
507  return isa<UsingShadowDecl>(D) ||
508         isa<UnresolvedUsingTypenameDecl>(D) ||
509         isa<UnresolvedUsingValueDecl>(D);
510}
511
512/// Removes using shadow declarations from the lookup results.
513static void RemoveUsingDecls(LookupResult &R) {
514  LookupResult::Filter F = R.makeFilter();
515  while (F.hasNext())
516    if (isUsingDecl(F.next()))
517      F.erase();
518
519  F.done();
520}
521
522static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
523  if (D->isInvalidDecl())
524    return false;
525
526  if (D->isUsed() || D->hasAttr<UnusedAttr>())
527    return false;
528
529  // White-list anything that isn't a local variable.
530  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
531      !D->getDeclContext()->isFunctionOrMethod())
532    return false;
533
534  // Types of valid local variables should be complete, so this should succeed.
535  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
536
537    // White-list anything with an __attribute__((unused)) type.
538    QualType Ty = VD->getType();
539
540    // Only look at the outermost level of typedef.
541    if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
542      if (TT->getDecl()->hasAttr<UnusedAttr>())
543        return false;
544    }
545
546    if (const TagType *TT = Ty->getAs<TagType>()) {
547      const TagDecl *Tag = TT->getDecl();
548      if (Tag->hasAttr<UnusedAttr>())
549        return false;
550
551      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
552        if (!RD->hasTrivialConstructor())
553          return false;
554        if (!RD->hasTrivialDestructor())
555          return false;
556      }
557    }
558
559    // TODO: __attribute__((unused)) templates?
560  }
561
562  return true;
563}
564
565void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
566  if (S->decl_empty()) return;
567  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
568         "Scope shouldn't contain decls!");
569
570  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
571       I != E; ++I) {
572    Decl *TmpD = (*I).getAs<Decl>();
573    assert(TmpD && "This decl didn't get pushed??");
574
575    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
576    NamedDecl *D = cast<NamedDecl>(TmpD);
577
578    if (!D->getDeclName()) continue;
579
580    // Diagnose unused variables in this scope.
581    if (ShouldDiagnoseUnusedDecl(D) &&
582        S->getNumErrorsAtStart() == getDiagnostics().getNumErrors())
583      Diag(D->getLocation(), diag::warn_unused_variable) << D->getDeclName();
584
585    // Remove this name from our lexical scope.
586    IdResolver.RemoveDecl(D);
587  }
588}
589
590/// \brief Look for an Objective-C class in the translation unit.
591///
592/// \param Id The name of the Objective-C class we're looking for. If
593/// typo-correction fixes this name, the Id will be updated
594/// to the fixed name.
595///
596/// \param IdLoc The location of the name in the translation unit.
597///
598/// \param TypoCorrection If true, this routine will attempt typo correction
599/// if there is no class with the given name.
600///
601/// \returns The declaration of the named Objective-C class, or NULL if the
602/// class could not be found.
603ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
604                                              SourceLocation IdLoc,
605                                              bool TypoCorrection) {
606  // The third "scope" argument is 0 since we aren't enabling lazy built-in
607  // creation from this context.
608  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
609
610  if (!IDecl && TypoCorrection) {
611    // Perform typo correction at the given location, but only if we
612    // find an Objective-C class name.
613    LookupResult R(*this, Id, IdLoc, LookupOrdinaryName);
614    if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
615        (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
616      Diag(IdLoc, diag::err_undef_interface_suggest)
617        << Id << IDecl->getDeclName()
618        << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
619      Diag(IDecl->getLocation(), diag::note_previous_decl)
620        << IDecl->getDeclName();
621
622      Id = IDecl->getIdentifier();
623    }
624  }
625
626  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
627}
628
629/// getNonFieldDeclScope - Retrieves the innermost scope, starting
630/// from S, where a non-field would be declared. This routine copes
631/// with the difference between C and C++ scoping rules in structs and
632/// unions. For example, the following code is well-formed in C but
633/// ill-formed in C++:
634/// @code
635/// struct S6 {
636///   enum { BAR } e;
637/// };
638///
639/// void test_S6() {
640///   struct S6 a;
641///   a.e = BAR;
642/// }
643/// @endcode
644/// For the declaration of BAR, this routine will return a different
645/// scope. The scope S will be the scope of the unnamed enumeration
646/// within S6. In C++, this routine will return the scope associated
647/// with S6, because the enumeration's scope is a transparent
648/// context but structures can contain non-field names. In C, this
649/// routine will return the translation unit scope, since the
650/// enumeration's scope is a transparent context and structures cannot
651/// contain non-field names.
652Scope *Sema::getNonFieldDeclScope(Scope *S) {
653  while (((S->getFlags() & Scope::DeclScope) == 0) ||
654         (S->getEntity() &&
655          ((DeclContext *)S->getEntity())->isTransparentContext()) ||
656         (S->isClassScope() && !getLangOptions().CPlusPlus))
657    S = S->getParent();
658  return S;
659}
660
661void Sema::InitBuiltinVaListType() {
662  if (!Context.getBuiltinVaListType().isNull())
663    return;
664
665  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
666  NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, SourceLocation(),
667                                       LookupOrdinaryName, ForRedeclaration);
668  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
669  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
670}
671
672/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
673/// file scope.  lazily create a decl for it. ForRedeclaration is true
674/// if we're creating this built-in in anticipation of redeclaring the
675/// built-in.
676NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
677                                     Scope *S, bool ForRedeclaration,
678                                     SourceLocation Loc) {
679  Builtin::ID BID = (Builtin::ID)bid;
680
681  if (Context.BuiltinInfo.hasVAListUse(BID))
682    InitBuiltinVaListType();
683
684  ASTContext::GetBuiltinTypeError Error;
685  QualType R = Context.GetBuiltinType(BID, Error);
686  switch (Error) {
687  case ASTContext::GE_None:
688    // Okay
689    break;
690
691  case ASTContext::GE_Missing_stdio:
692    if (ForRedeclaration)
693      Diag(Loc, diag::err_implicit_decl_requires_stdio)
694        << Context.BuiltinInfo.GetName(BID);
695    return 0;
696
697  case ASTContext::GE_Missing_setjmp:
698    if (ForRedeclaration)
699      Diag(Loc, diag::err_implicit_decl_requires_setjmp)
700        << Context.BuiltinInfo.GetName(BID);
701    return 0;
702  }
703
704  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
705    Diag(Loc, diag::ext_implicit_lib_function_decl)
706      << Context.BuiltinInfo.GetName(BID)
707      << R;
708    if (Context.BuiltinInfo.getHeaderName(BID) &&
709        Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
710          != Diagnostic::Ignored)
711      Diag(Loc, diag::note_please_include_header)
712        << Context.BuiltinInfo.getHeaderName(BID)
713        << Context.BuiltinInfo.GetName(BID);
714  }
715
716  FunctionDecl *New = FunctionDecl::Create(Context,
717                                           Context.getTranslationUnitDecl(),
718                                           Loc, II, R, /*TInfo=*/0,
719                                           FunctionDecl::Extern,
720                                           FunctionDecl::None, false,
721                                           /*hasPrototype=*/true);
722  New->setImplicit();
723
724  // Create Decl objects for each parameter, adding them to the
725  // FunctionDecl.
726  if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
727    llvm::SmallVector<ParmVarDecl*, 16> Params;
728    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
729      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
730                                           FT->getArgType(i), /*TInfo=*/0,
731                                           VarDecl::None, VarDecl::None, 0));
732    New->setParams(Params.data(), Params.size());
733  }
734
735  AddKnownFunctionAttributes(New);
736
737  // TUScope is the translation-unit scope to insert this function into.
738  // FIXME: This is hideous. We need to teach PushOnScopeChains to
739  // relate Scopes to DeclContexts, and probably eliminate CurContext
740  // entirely, but we're not there yet.
741  DeclContext *SavedContext = CurContext;
742  CurContext = Context.getTranslationUnitDecl();
743  PushOnScopeChains(New, TUScope);
744  CurContext = SavedContext;
745  return New;
746}
747
748/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
749/// same name and scope as a previous declaration 'Old'.  Figure out
750/// how to resolve this situation, merging decls or emitting
751/// diagnostics as appropriate. If there was an error, set New to be invalid.
752///
753void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) {
754  // If the new decl is known invalid already, don't bother doing any
755  // merging checks.
756  if (New->isInvalidDecl()) return;
757
758  // Allow multiple definitions for ObjC built-in typedefs.
759  // FIXME: Verify the underlying types are equivalent!
760  if (getLangOptions().ObjC1) {
761    const IdentifierInfo *TypeID = New->getIdentifier();
762    switch (TypeID->getLength()) {
763    default: break;
764    case 2:
765      if (!TypeID->isStr("id"))
766        break;
767      Context.ObjCIdRedefinitionType = New->getUnderlyingType();
768      // Install the built-in type for 'id', ignoring the current definition.
769      New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
770      return;
771    case 5:
772      if (!TypeID->isStr("Class"))
773        break;
774      Context.ObjCClassRedefinitionType = New->getUnderlyingType();
775      // Install the built-in type for 'Class', ignoring the current definition.
776      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
777      return;
778    case 3:
779      if (!TypeID->isStr("SEL"))
780        break;
781      Context.ObjCSelRedefinitionType = New->getUnderlyingType();
782      // Install the built-in type for 'SEL', ignoring the current definition.
783      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
784      return;
785    case 8:
786      if (!TypeID->isStr("Protocol"))
787        break;
788      Context.setObjCProtoType(New->getUnderlyingType());
789      return;
790    }
791    // Fall through - the typedef name was not a builtin type.
792  }
793
794  // Verify the old decl was also a type.
795  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
796  if (!Old) {
797    Diag(New->getLocation(), diag::err_redefinition_different_kind)
798      << New->getDeclName();
799
800    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
801    if (OldD->getLocation().isValid())
802      Diag(OldD->getLocation(), diag::note_previous_definition);
803
804    return New->setInvalidDecl();
805  }
806
807  // If the old declaration is invalid, just give up here.
808  if (Old->isInvalidDecl())
809    return New->setInvalidDecl();
810
811  // Determine the "old" type we'll use for checking and diagnostics.
812  QualType OldType;
813  if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
814    OldType = OldTypedef->getUnderlyingType();
815  else
816    OldType = Context.getTypeDeclType(Old);
817
818  // If the typedef types are not identical, reject them in all languages and
819  // with any extensions enabled.
820
821  if (OldType != New->getUnderlyingType() &&
822      Context.getCanonicalType(OldType) !=
823      Context.getCanonicalType(New->getUnderlyingType())) {
824    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
825      << New->getUnderlyingType() << OldType;
826    if (Old->getLocation().isValid())
827      Diag(Old->getLocation(), diag::note_previous_definition);
828    return New->setInvalidDecl();
829  }
830
831  // The types match.  Link up the redeclaration chain if the old
832  // declaration was a typedef.
833  // FIXME: this is a potential source of wierdness if the type
834  // spellings don't match exactly.
835  if (isa<TypedefDecl>(Old))
836    New->setPreviousDeclaration(cast<TypedefDecl>(Old));
837
838  if (getLangOptions().Microsoft)
839    return;
840
841  if (getLangOptions().CPlusPlus) {
842    // C++ [dcl.typedef]p2:
843    //   In a given non-class scope, a typedef specifier can be used to
844    //   redefine the name of any type declared in that scope to refer
845    //   to the type to which it already refers.
846    if (!isa<CXXRecordDecl>(CurContext))
847      return;
848
849    // C++0x [dcl.typedef]p4:
850    //   In a given class scope, a typedef specifier can be used to redefine
851    //   any class-name declared in that scope that is not also a typedef-name
852    //   to refer to the type to which it already refers.
853    //
854    // This wording came in via DR424, which was a correction to the
855    // wording in DR56, which accidentally banned code like:
856    //
857    //   struct S {
858    //     typedef struct A { } A;
859    //   };
860    //
861    // in the C++03 standard. We implement the C++0x semantics, which
862    // allow the above but disallow
863    //
864    //   struct S {
865    //     typedef int I;
866    //     typedef int I;
867    //   };
868    //
869    // since that was the intent of DR56.
870    if (!isa<TypedefDecl >(Old))
871      return;
872
873    Diag(New->getLocation(), diag::err_redefinition)
874      << New->getDeclName();
875    Diag(Old->getLocation(), diag::note_previous_definition);
876    return New->setInvalidDecl();
877  }
878
879  // If we have a redefinition of a typedef in C, emit a warning.  This warning
880  // is normally mapped to an error, but can be controlled with
881  // -Wtypedef-redefinition.  If either the original or the redefinition is
882  // in a system header, don't emit this for compatibility with GCC.
883  if (getDiagnostics().getSuppressSystemWarnings() &&
884      (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
885       Context.getSourceManager().isInSystemHeader(New->getLocation())))
886    return;
887
888  Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
889    << New->getDeclName();
890  Diag(Old->getLocation(), diag::note_previous_definition);
891  return;
892}
893
894/// DeclhasAttr - returns true if decl Declaration already has the target
895/// attribute.
896static bool
897DeclHasAttr(const Decl *decl, const Attr *target) {
898  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
899    if (attr->getKind() == target->getKind())
900      return true;
901
902  return false;
903}
904
905/// MergeAttributes - append attributes from the Old decl to the New one.
906static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
907  for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
908    if (!DeclHasAttr(New, attr) && attr->isMerged()) {
909      Attr *NewAttr = attr->clone(C);
910      NewAttr->setInherited(true);
911      New->addAttr(NewAttr);
912    }
913  }
914}
915
916/// Used in MergeFunctionDecl to keep track of function parameters in
917/// C.
918struct GNUCompatibleParamWarning {
919  ParmVarDecl *OldParm;
920  ParmVarDecl *NewParm;
921  QualType PromotedType;
922};
923
924
925/// getSpecialMember - get the special member enum for a method.
926Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
927  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
928    if (Ctor->isCopyConstructor())
929      return Sema::CXXCopyConstructor;
930
931    return Sema::CXXConstructor;
932  }
933
934  if (isa<CXXDestructorDecl>(MD))
935    return Sema::CXXDestructor;
936
937  assert(MD->isCopyAssignment() && "Must have copy assignment operator");
938  return Sema::CXXCopyAssignment;
939}
940
941/// canREdefineFunction - checks if a function can be redefined. Currently,
942/// only extern inline functions can be redefined, and even then only in
943/// GNU89 mode.
944static bool canRedefineFunction(const FunctionDecl *FD,
945                                const LangOptions& LangOpts) {
946  return (LangOpts.GNUMode && !LangOpts.C99 && !LangOpts.CPlusPlus &&
947          FD->isInlineSpecified() &&
948          FD->getStorageClass() == FunctionDecl::Extern);
949}
950
951/// MergeFunctionDecl - We just parsed a function 'New' from
952/// declarator D which has the same name and scope as a previous
953/// declaration 'Old'.  Figure out how to resolve this situation,
954/// merging decls or emitting diagnostics as appropriate.
955///
956/// In C++, New and Old must be declarations that are not
957/// overloaded. Use IsOverload to determine whether New and Old are
958/// overloaded, and to select the Old declaration that New should be
959/// merged with.
960///
961/// Returns true if there was an error, false otherwise.
962bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
963  // Verify the old decl was also a function.
964  FunctionDecl *Old = 0;
965  if (FunctionTemplateDecl *OldFunctionTemplate
966        = dyn_cast<FunctionTemplateDecl>(OldD))
967    Old = OldFunctionTemplate->getTemplatedDecl();
968  else
969    Old = dyn_cast<FunctionDecl>(OldD);
970  if (!Old) {
971    if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
972      Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
973      Diag(Shadow->getTargetDecl()->getLocation(),
974           diag::note_using_decl_target);
975      Diag(Shadow->getUsingDecl()->getLocation(),
976           diag::note_using_decl) << 0;
977      return true;
978    }
979
980    Diag(New->getLocation(), diag::err_redefinition_different_kind)
981      << New->getDeclName();
982    Diag(OldD->getLocation(), diag::note_previous_definition);
983    return true;
984  }
985
986  // Determine whether the previous declaration was a definition,
987  // implicit declaration, or a declaration.
988  diag::kind PrevDiag;
989  if (Old->isThisDeclarationADefinition())
990    PrevDiag = diag::note_previous_definition;
991  else if (Old->isImplicit())
992    PrevDiag = diag::note_previous_implicit_declaration;
993  else
994    PrevDiag = diag::note_previous_declaration;
995
996  QualType OldQType = Context.getCanonicalType(Old->getType());
997  QualType NewQType = Context.getCanonicalType(New->getType());
998
999  // Don't complain about this if we're in GNU89 mode and the old function
1000  // is an extern inline function.
1001  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
1002      New->getStorageClass() == FunctionDecl::Static &&
1003      Old->getStorageClass() != FunctionDecl::Static &&
1004      !canRedefineFunction(Old, getLangOptions())) {
1005    Diag(New->getLocation(), diag::err_static_non_static)
1006      << New;
1007    Diag(Old->getLocation(), PrevDiag);
1008    return true;
1009  }
1010
1011  // If a function is first declared with a calling convention, but is
1012  // later declared or defined without one, the second decl assumes the
1013  // calling convention of the first.
1014  //
1015  // For the new decl, we have to look at the NON-canonical type to tell the
1016  // difference between a function that really doesn't have a calling
1017  // convention and one that is declared cdecl. That's because in
1018  // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1019  // because it is the default calling convention.
1020  //
1021  // Note also that we DO NOT return at this point, because we still have
1022  // other tests to run.
1023  const FunctionType *OldType = OldQType->getAs<FunctionType>();
1024  const FunctionType *NewType = New->getType()->getAs<FunctionType>();
1025  const FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1026  const FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1027  if (OldTypeInfo.getCC() != CC_Default &&
1028      NewTypeInfo.getCC() == CC_Default) {
1029    NewQType = Context.getCallConvType(NewQType, OldTypeInfo.getCC());
1030    New->setType(NewQType);
1031    NewQType = Context.getCanonicalType(NewQType);
1032  } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1033                                     NewTypeInfo.getCC())) {
1034    // Calling conventions really aren't compatible, so complain.
1035    Diag(New->getLocation(), diag::err_cconv_change)
1036      << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1037      << (OldTypeInfo.getCC() == CC_Default)
1038      << (OldTypeInfo.getCC() == CC_Default ? "" :
1039          FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
1040    Diag(Old->getLocation(), diag::note_previous_declaration);
1041    return true;
1042  }
1043
1044  // FIXME: diagnose the other way around?
1045  if (OldType->getNoReturnAttr() &&
1046      !NewType->getNoReturnAttr()) {
1047    NewQType = Context.getNoReturnType(NewQType);
1048    New->setType(NewQType);
1049    assert(NewQType.isCanonical());
1050  }
1051
1052  if (getLangOptions().CPlusPlus) {
1053    // (C++98 13.1p2):
1054    //   Certain function declarations cannot be overloaded:
1055    //     -- Function declarations that differ only in the return type
1056    //        cannot be overloaded.
1057    QualType OldReturnType
1058      = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
1059    QualType NewReturnType
1060      = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
1061    if (OldReturnType != NewReturnType) {
1062      Diag(New->getLocation(), diag::err_ovl_diff_return_type);
1063      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1064      return true;
1065    }
1066
1067    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1068    CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1069    if (OldMethod && NewMethod) {
1070      // Preserve triviality.
1071      NewMethod->setTrivial(OldMethod->isTrivial());
1072
1073      bool isFriend = NewMethod->getFriendObjectKind();
1074
1075      if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord()) {
1076        //    -- Member function declarations with the same name and the
1077        //       same parameter types cannot be overloaded if any of them
1078        //       is a static member function declaration.
1079        if (OldMethod->isStatic() || NewMethod->isStatic()) {
1080          Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1081          Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1082          return true;
1083        }
1084
1085        // C++ [class.mem]p1:
1086        //   [...] A member shall not be declared twice in the
1087        //   member-specification, except that a nested class or member
1088        //   class template can be declared and then later defined.
1089        unsigned NewDiag;
1090        if (isa<CXXConstructorDecl>(OldMethod))
1091          NewDiag = diag::err_constructor_redeclared;
1092        else if (isa<CXXDestructorDecl>(NewMethod))
1093          NewDiag = diag::err_destructor_redeclared;
1094        else if (isa<CXXConversionDecl>(NewMethod))
1095          NewDiag = diag::err_conv_function_redeclared;
1096        else
1097          NewDiag = diag::err_member_redeclared;
1098
1099        Diag(New->getLocation(), NewDiag);
1100        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1101
1102      // Complain if this is an explicit declaration of a special
1103      // member that was initially declared implicitly.
1104      //
1105      // As an exception, it's okay to befriend such methods in order
1106      // to permit the implicit constructor/destructor/operator calls.
1107      } else if (OldMethod->isImplicit()) {
1108        if (isFriend) {
1109          NewMethod->setImplicit();
1110        } else {
1111          Diag(NewMethod->getLocation(),
1112               diag::err_definition_of_implicitly_declared_member)
1113            << New << getSpecialMember(OldMethod);
1114          return true;
1115        }
1116      }
1117    }
1118
1119    // (C++98 8.3.5p3):
1120    //   All declarations for a function shall agree exactly in both the
1121    //   return type and the parameter-type-list.
1122    // attributes should be ignored when comparing.
1123    if (Context.getNoReturnType(OldQType, false) ==
1124        Context.getNoReturnType(NewQType, false))
1125      return MergeCompatibleFunctionDecls(New, Old);
1126
1127    // Fall through for conflicting redeclarations and redefinitions.
1128  }
1129
1130  // C: Function types need to be compatible, not identical. This handles
1131  // duplicate function decls like "void f(int); void f(enum X);" properly.
1132  if (!getLangOptions().CPlusPlus &&
1133      Context.typesAreCompatible(OldQType, NewQType)) {
1134    const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1135    const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
1136    const FunctionProtoType *OldProto = 0;
1137    if (isa<FunctionNoProtoType>(NewFuncType) &&
1138        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
1139      // The old declaration provided a function prototype, but the
1140      // new declaration does not. Merge in the prototype.
1141      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
1142      llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1143                                                 OldProto->arg_type_end());
1144      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
1145                                         ParamTypes.data(), ParamTypes.size(),
1146                                         OldProto->isVariadic(),
1147                                         OldProto->getTypeQuals(),
1148                                         false, false, 0, 0,
1149                                         OldProto->getExtInfo());
1150      New->setType(NewQType);
1151      New->setHasInheritedPrototype();
1152
1153      // Synthesize a parameter for each argument type.
1154      llvm::SmallVector<ParmVarDecl*, 16> Params;
1155      for (FunctionProtoType::arg_type_iterator
1156             ParamType = OldProto->arg_type_begin(),
1157             ParamEnd = OldProto->arg_type_end();
1158           ParamType != ParamEnd; ++ParamType) {
1159        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
1160                                                 SourceLocation(), 0,
1161                                                 *ParamType, /*TInfo=*/0,
1162                                                 VarDecl::None, VarDecl::None,
1163                                                 0);
1164        Param->setImplicit();
1165        Params.push_back(Param);
1166      }
1167
1168      New->setParams(Params.data(), Params.size());
1169    }
1170
1171    return MergeCompatibleFunctionDecls(New, Old);
1172  }
1173
1174  // GNU C permits a K&R definition to follow a prototype declaration
1175  // if the declared types of the parameters in the K&R definition
1176  // match the types in the prototype declaration, even when the
1177  // promoted types of the parameters from the K&R definition differ
1178  // from the types in the prototype. GCC then keeps the types from
1179  // the prototype.
1180  //
1181  // If a variadic prototype is followed by a non-variadic K&R definition,
1182  // the K&R definition becomes variadic.  This is sort of an edge case, but
1183  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1184  // C99 6.9.1p8.
1185  if (!getLangOptions().CPlusPlus &&
1186      Old->hasPrototype() && !New->hasPrototype() &&
1187      New->getType()->getAs<FunctionProtoType>() &&
1188      Old->getNumParams() == New->getNumParams()) {
1189    llvm::SmallVector<QualType, 16> ArgTypes;
1190    llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
1191    const FunctionProtoType *OldProto
1192      = Old->getType()->getAs<FunctionProtoType>();
1193    const FunctionProtoType *NewProto
1194      = New->getType()->getAs<FunctionProtoType>();
1195
1196    // Determine whether this is the GNU C extension.
1197    QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1198                                               NewProto->getResultType());
1199    bool LooseCompatible = !MergedReturn.isNull();
1200    for (unsigned Idx = 0, End = Old->getNumParams();
1201         LooseCompatible && Idx != End; ++Idx) {
1202      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1203      ParmVarDecl *NewParm = New->getParamDecl(Idx);
1204      if (Context.typesAreCompatible(OldParm->getType(),
1205                                     NewProto->getArgType(Idx))) {
1206        ArgTypes.push_back(NewParm->getType());
1207      } else if (Context.typesAreCompatible(OldParm->getType(),
1208                                            NewParm->getType())) {
1209        GNUCompatibleParamWarning Warn
1210          = { OldParm, NewParm, NewProto->getArgType(Idx) };
1211        Warnings.push_back(Warn);
1212        ArgTypes.push_back(NewParm->getType());
1213      } else
1214        LooseCompatible = false;
1215    }
1216
1217    if (LooseCompatible) {
1218      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1219        Diag(Warnings[Warn].NewParm->getLocation(),
1220             diag::ext_param_promoted_not_compatible_with_prototype)
1221          << Warnings[Warn].PromotedType
1222          << Warnings[Warn].OldParm->getType();
1223        Diag(Warnings[Warn].OldParm->getLocation(),
1224             diag::note_previous_declaration);
1225      }
1226
1227      New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1228                                           ArgTypes.size(),
1229                                           OldProto->isVariadic(), 0,
1230                                           false, false, 0, 0,
1231                                           OldProto->getExtInfo()));
1232      return MergeCompatibleFunctionDecls(New, Old);
1233    }
1234
1235    // Fall through to diagnose conflicting types.
1236  }
1237
1238  // A function that has already been declared has been redeclared or defined
1239  // with a different type- show appropriate diagnostic
1240  if (unsigned BuiltinID = Old->getBuiltinID()) {
1241    // The user has declared a builtin function with an incompatible
1242    // signature.
1243    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1244      // The function the user is redeclaring is a library-defined
1245      // function like 'malloc' or 'printf'. Warn about the
1246      // redeclaration, then pretend that we don't know about this
1247      // library built-in.
1248      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1249      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1250        << Old << Old->getType();
1251      New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1252      Old->setInvalidDecl();
1253      return false;
1254    }
1255
1256    PrevDiag = diag::note_previous_builtin_declaration;
1257  }
1258
1259  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
1260  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1261  return true;
1262}
1263
1264/// \brief Completes the merge of two function declarations that are
1265/// known to be compatible.
1266///
1267/// This routine handles the merging of attributes and other
1268/// properties of function declarations form the old declaration to
1269/// the new declaration, once we know that New is in fact a
1270/// redeclaration of Old.
1271///
1272/// \returns false
1273bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1274  // Merge the attributes
1275  MergeAttributes(New, Old, Context);
1276
1277  // Merge the storage class.
1278  if (Old->getStorageClass() != FunctionDecl::Extern &&
1279      Old->getStorageClass() != FunctionDecl::None)
1280    New->setStorageClass(Old->getStorageClass());
1281
1282  // Merge "pure" flag.
1283  if (Old->isPure())
1284    New->setPure();
1285
1286  // Merge the "deleted" flag.
1287  if (Old->isDeleted())
1288    New->setDeleted();
1289
1290  if (getLangOptions().CPlusPlus)
1291    return MergeCXXFunctionDecl(New, Old);
1292
1293  return false;
1294}
1295
1296/// MergeVarDecl - We just parsed a variable 'New' which has the same name
1297/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
1298/// situation, merging decls or emitting diagnostics as appropriate.
1299///
1300/// Tentative definition rules (C99 6.9.2p2) are checked by
1301/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
1302/// definitions here, since the initializer hasn't been attached.
1303///
1304void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
1305  // If the new decl is already invalid, don't do any other checking.
1306  if (New->isInvalidDecl())
1307    return;
1308
1309  // Verify the old decl was also a variable.
1310  VarDecl *Old = 0;
1311  if (!Previous.isSingleResult() ||
1312      !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
1313    Diag(New->getLocation(), diag::err_redefinition_different_kind)
1314      << New->getDeclName();
1315    Diag(Previous.getRepresentativeDecl()->getLocation(),
1316         diag::note_previous_definition);
1317    return New->setInvalidDecl();
1318  }
1319
1320  MergeAttributes(New, Old, Context);
1321
1322  // Merge the types
1323  QualType MergedT;
1324  if (getLangOptions().CPlusPlus) {
1325    if (Context.hasSameType(New->getType(), Old->getType()))
1326      MergedT = New->getType();
1327    // C++ [basic.link]p10:
1328    //   [...] the types specified by all declarations referring to a given
1329    //   object or function shall be identical, except that declarations for an
1330    //   array object can specify array types that differ by the presence or
1331    //   absence of a major array bound (8.3.4).
1332    else if (Old->getType()->isIncompleteArrayType() &&
1333             New->getType()->isArrayType()) {
1334      CanQual<ArrayType> OldArray
1335        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1336      CanQual<ArrayType> NewArray
1337        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1338      if (OldArray->getElementType() == NewArray->getElementType())
1339        MergedT = New->getType();
1340    } else if (Old->getType()->isArrayType() &&
1341             New->getType()->isIncompleteArrayType()) {
1342      CanQual<ArrayType> OldArray
1343        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1344      CanQual<ArrayType> NewArray
1345        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1346      if (OldArray->getElementType() == NewArray->getElementType())
1347        MergedT = Old->getType();
1348    }
1349  } else {
1350    MergedT = Context.mergeTypes(New->getType(), Old->getType());
1351  }
1352  if (MergedT.isNull()) {
1353    Diag(New->getLocation(), diag::err_redefinition_different_type)
1354      << New->getDeclName();
1355    Diag(Old->getLocation(), diag::note_previous_definition);
1356    return New->setInvalidDecl();
1357  }
1358  New->setType(MergedT);
1359
1360  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
1361  if (New->getStorageClass() == VarDecl::Static &&
1362      (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
1363    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
1364    Diag(Old->getLocation(), diag::note_previous_definition);
1365    return New->setInvalidDecl();
1366  }
1367  // C99 6.2.2p4:
1368  //   For an identifier declared with the storage-class specifier
1369  //   extern in a scope in which a prior declaration of that
1370  //   identifier is visible,23) if the prior declaration specifies
1371  //   internal or external linkage, the linkage of the identifier at
1372  //   the later declaration is the same as the linkage specified at
1373  //   the prior declaration. If no prior declaration is visible, or
1374  //   if the prior declaration specifies no linkage, then the
1375  //   identifier has external linkage.
1376  if (New->hasExternalStorage() && Old->hasLinkage())
1377    /* Okay */;
1378  else if (New->getStorageClass() != VarDecl::Static &&
1379           Old->getStorageClass() == VarDecl::Static) {
1380    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
1381    Diag(Old->getLocation(), diag::note_previous_definition);
1382    return New->setInvalidDecl();
1383  }
1384
1385  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
1386
1387  // FIXME: The test for external storage here seems wrong? We still
1388  // need to check for mismatches.
1389  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
1390      // Don't complain about out-of-line definitions of static members.
1391      !(Old->getLexicalDeclContext()->isRecord() &&
1392        !New->getLexicalDeclContext()->isRecord())) {
1393    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
1394    Diag(Old->getLocation(), diag::note_previous_definition);
1395    return New->setInvalidDecl();
1396  }
1397
1398  if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1399    Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1400    Diag(Old->getLocation(), diag::note_previous_definition);
1401  } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1402    Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1403    Diag(Old->getLocation(), diag::note_previous_definition);
1404  }
1405
1406  // C++ doesn't have tentative definitions, so go right ahead and check here.
1407  const VarDecl *Def;
1408  if (getLangOptions().CPlusPlus &&
1409      New->isThisDeclarationADefinition() == VarDecl::Definition &&
1410      (Def = Old->getDefinition())) {
1411    Diag(New->getLocation(), diag::err_redefinition)
1412      << New->getDeclName();
1413    Diag(Def->getLocation(), diag::note_previous_definition);
1414    New->setInvalidDecl();
1415    return;
1416  }
1417
1418  // Keep a chain of previous declarations.
1419  New->setPreviousDeclaration(Old);
1420
1421  // Inherit access appropriately.
1422  New->setAccess(Old->getAccess());
1423}
1424
1425/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1426/// no declarator (e.g. "struct foo;") is parsed.
1427Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
1428  // FIXME: Error on auto/register at file scope
1429  // FIXME: Error on inline/virtual/explicit
1430  // FIXME: Warn on useless __thread
1431  // FIXME: Warn on useless const/volatile
1432  // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1433  // FIXME: Warn on useless attributes
1434  Decl *TagD = 0;
1435  TagDecl *Tag = 0;
1436  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1437      DS.getTypeSpecType() == DeclSpec::TST_struct ||
1438      DS.getTypeSpecType() == DeclSpec::TST_union ||
1439      DS.getTypeSpecType() == DeclSpec::TST_enum) {
1440    TagD = static_cast<Decl *>(DS.getTypeRep());
1441
1442    if (!TagD) // We probably had an error
1443      return DeclPtrTy();
1444
1445    // Note that the above type specs guarantee that the
1446    // type rep is a Decl, whereas in many of the others
1447    // it's a Type.
1448    Tag = dyn_cast<TagDecl>(TagD);
1449  }
1450
1451  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1452    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
1453    // or incomplete types shall not be restrict-qualified."
1454    if (TypeQuals & DeclSpec::TQ_restrict)
1455      Diag(DS.getRestrictSpecLoc(),
1456           diag::err_typecheck_invalid_restrict_not_pointer_noarg)
1457           << DS.getSourceRange();
1458  }
1459
1460  if (DS.isFriendSpecified()) {
1461    // If we're dealing with a class template decl, assume that the
1462    // template routines are handling it.
1463    if (TagD && isa<ClassTemplateDecl>(TagD))
1464      return DeclPtrTy();
1465    return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
1466  }
1467
1468  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
1469    // If there are attributes in the DeclSpec, apply them to the record.
1470    if (const AttributeList *AL = DS.getAttributes())
1471      ProcessDeclAttributeList(S, Record, AL);
1472
1473    if (!Record->getDeclName() && Record->isDefinition() &&
1474        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1475      if (getLangOptions().CPlusPlus ||
1476          Record->getDeclContext()->isRecord())
1477        return BuildAnonymousStructOrUnion(S, DS, Record);
1478
1479      Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
1480        << DS.getSourceRange();
1481    }
1482
1483    // Microsoft allows unnamed struct/union fields. Don't complain
1484    // about them.
1485    // FIXME: Should we support Microsoft's extensions in this area?
1486    if (Record->getDeclName() && getLangOptions().Microsoft)
1487      return DeclPtrTy::make(Tag);
1488  }
1489
1490  if (!DS.isMissingDeclaratorOk() &&
1491      DS.getTypeSpecType() != DeclSpec::TST_error) {
1492    // Warn about typedefs of enums without names, since this is an
1493    // extension in both Microsoft an GNU.
1494    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1495        Tag && isa<EnumDecl>(Tag)) {
1496      Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1497        << DS.getSourceRange();
1498      return DeclPtrTy::make(Tag);
1499    }
1500
1501    Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
1502      << DS.getSourceRange();
1503  }
1504
1505  return DeclPtrTy::make(Tag);
1506}
1507
1508/// We are trying to inject an anonymous member into the given scope;
1509/// check if there's an existing declaration that can't be overloaded.
1510///
1511/// \return true if this is a forbidden redeclaration
1512static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
1513                                         Scope *S,
1514                                         DeclContext *Owner,
1515                                         DeclarationName Name,
1516                                         SourceLocation NameLoc,
1517                                         unsigned diagnostic) {
1518  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
1519                 Sema::ForRedeclaration);
1520  if (!SemaRef.LookupName(R, S)) return false;
1521
1522  if (R.getAsSingle<TagDecl>())
1523    return false;
1524
1525  // Pick a representative declaration.
1526  NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
1527  if (PrevDecl && Owner->isRecord()) {
1528    RecordDecl *Record = cast<RecordDecl>(Owner);
1529    if (!SemaRef.isDeclInScope(PrevDecl, Record, S))
1530      return false;
1531  }
1532
1533  SemaRef.Diag(NameLoc, diagnostic) << Name;
1534  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
1535
1536  return true;
1537}
1538
1539/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1540/// anonymous struct or union AnonRecord into the owning context Owner
1541/// and scope S. This routine will be invoked just after we realize
1542/// that an unnamed union or struct is actually an anonymous union or
1543/// struct, e.g.,
1544///
1545/// @code
1546/// union {
1547///   int i;
1548///   float f;
1549/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1550///    // f into the surrounding scope.x
1551/// @endcode
1552///
1553/// This routine is recursive, injecting the names of nested anonymous
1554/// structs/unions into the owning context and scope as well.
1555bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
1556                                               RecordDecl *AnonRecord) {
1557  unsigned diagKind
1558    = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
1559                            : diag::err_anonymous_struct_member_redecl;
1560
1561  bool Invalid = false;
1562  for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
1563                               FEnd = AnonRecord->field_end();
1564       F != FEnd; ++F) {
1565    if ((*F)->getDeclName()) {
1566      if (CheckAnonMemberRedeclaration(*this, S, Owner, (*F)->getDeclName(),
1567                                       (*F)->getLocation(), diagKind)) {
1568        // C++ [class.union]p2:
1569        //   The names of the members of an anonymous union shall be
1570        //   distinct from the names of any other entity in the
1571        //   scope in which the anonymous union is declared.
1572        Invalid = true;
1573      } else {
1574        // C++ [class.union]p2:
1575        //   For the purpose of name lookup, after the anonymous union
1576        //   definition, the members of the anonymous union are
1577        //   considered to have been defined in the scope in which the
1578        //   anonymous union is declared.
1579        Owner->makeDeclVisibleInContext(*F);
1580        S->AddDecl(DeclPtrTy::make(*F));
1581        IdResolver.AddDecl(*F);
1582      }
1583    } else if (const RecordType *InnerRecordType
1584                 = (*F)->getType()->getAs<RecordType>()) {
1585      RecordDecl *InnerRecord = InnerRecordType->getDecl();
1586      if (InnerRecord->isAnonymousStructOrUnion())
1587        Invalid = Invalid ||
1588          InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
1589    }
1590  }
1591
1592  return Invalid;
1593}
1594
1595/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
1596/// a VarDecl::StorageClass. Any error reporting is up to the caller:
1597/// illegal input values are mapped to VarDecl::None.
1598static VarDecl::StorageClass
1599StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
1600  switch (StorageClassSpec) {
1601  case DeclSpec::SCS_unspecified:    return VarDecl::None;
1602  case DeclSpec::SCS_extern:         return VarDecl::Extern;
1603  case DeclSpec::SCS_static:         return VarDecl::Static;
1604  case DeclSpec::SCS_auto:           return VarDecl::Auto;
1605  case DeclSpec::SCS_register:       return VarDecl::Register;
1606  case DeclSpec::SCS_private_extern: return VarDecl::PrivateExtern;
1607    // Illegal SCSs map to None: error reporting is up to the caller.
1608  case DeclSpec::SCS_mutable:        // Fall through.
1609  case DeclSpec::SCS_typedef:        return VarDecl::None;
1610  }
1611  llvm_unreachable("unknown storage class specifier");
1612}
1613
1614/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
1615/// a FunctionDecl::StorageClass. Any error reporting is up to the caller:
1616/// illegal input values are mapped to FunctionDecl::None.
1617static FunctionDecl::StorageClass
1618StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
1619  switch (StorageClassSpec) {
1620  case DeclSpec::SCS_unspecified:    return FunctionDecl::None;
1621  case DeclSpec::SCS_extern:         return FunctionDecl::Extern;
1622  case DeclSpec::SCS_static:         return FunctionDecl::Static;
1623  case DeclSpec::SCS_private_extern: return FunctionDecl::PrivateExtern;
1624    // Illegal SCSs map to None: error reporting is up to the caller.
1625  case DeclSpec::SCS_auto:           // Fall through.
1626  case DeclSpec::SCS_mutable:        // Fall through.
1627  case DeclSpec::SCS_register:       // Fall through.
1628  case DeclSpec::SCS_typedef:        return FunctionDecl::None;
1629  }
1630  llvm_unreachable("unknown storage class specifier");
1631}
1632
1633/// ActOnAnonymousStructOrUnion - Handle the declaration of an
1634/// anonymous structure or union. Anonymous unions are a C++ feature
1635/// (C++ [class.union]) and a GNU C extension; anonymous structures
1636/// are a GNU C and GNU C++ extension.
1637Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1638                                                  RecordDecl *Record) {
1639  DeclContext *Owner = Record->getDeclContext();
1640
1641  // Diagnose whether this anonymous struct/union is an extension.
1642  if (Record->isUnion() && !getLangOptions().CPlusPlus)
1643    Diag(Record->getLocation(), diag::ext_anonymous_union);
1644  else if (!Record->isUnion())
1645    Diag(Record->getLocation(), diag::ext_anonymous_struct);
1646
1647  // C and C++ require different kinds of checks for anonymous
1648  // structs/unions.
1649  bool Invalid = false;
1650  if (getLangOptions().CPlusPlus) {
1651    const char* PrevSpec = 0;
1652    unsigned DiagID;
1653    // C++ [class.union]p3:
1654    //   Anonymous unions declared in a named namespace or in the
1655    //   global namespace shall be declared static.
1656    if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1657        (isa<TranslationUnitDecl>(Owner) ||
1658         (isa<NamespaceDecl>(Owner) &&
1659          cast<NamespaceDecl>(Owner)->getDeclName()))) {
1660      Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1661      Invalid = true;
1662
1663      // Recover by adding 'static'.
1664      DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1665                             PrevSpec, DiagID);
1666    }
1667    // C++ [class.union]p3:
1668    //   A storage class is not allowed in a declaration of an
1669    //   anonymous union in a class scope.
1670    else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1671             isa<RecordDecl>(Owner)) {
1672      Diag(DS.getStorageClassSpecLoc(),
1673           diag::err_anonymous_union_with_storage_spec);
1674      Invalid = true;
1675
1676      // Recover by removing the storage specifier.
1677      DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
1678                             PrevSpec, DiagID);
1679    }
1680
1681    // C++ [class.union]p2:
1682    //   The member-specification of an anonymous union shall only
1683    //   define non-static data members. [Note: nested types and
1684    //   functions cannot be declared within an anonymous union. ]
1685    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1686                                 MemEnd = Record->decls_end();
1687         Mem != MemEnd; ++Mem) {
1688      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1689        // C++ [class.union]p3:
1690        //   An anonymous union shall not have private or protected
1691        //   members (clause 11).
1692        if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
1693          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1694            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1695          Invalid = true;
1696        }
1697      } else if ((*Mem)->isImplicit()) {
1698        // Any implicit members are fine.
1699      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1700        // This is a type that showed up in an
1701        // elaborated-type-specifier inside the anonymous struct or
1702        // union, but which actually declares a type outside of the
1703        // anonymous struct or union. It's okay.
1704      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1705        if (!MemRecord->isAnonymousStructOrUnion() &&
1706            MemRecord->getDeclName()) {
1707          // This is a nested type declaration.
1708          Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1709            << (int)Record->isUnion();
1710          Invalid = true;
1711        }
1712      } else {
1713        // We have something that isn't a non-static data
1714        // member. Complain about it.
1715        unsigned DK = diag::err_anonymous_record_bad_member;
1716        if (isa<TypeDecl>(*Mem))
1717          DK = diag::err_anonymous_record_with_type;
1718        else if (isa<FunctionDecl>(*Mem))
1719          DK = diag::err_anonymous_record_with_function;
1720        else if (isa<VarDecl>(*Mem))
1721          DK = diag::err_anonymous_record_with_static;
1722        Diag((*Mem)->getLocation(), DK)
1723            << (int)Record->isUnion();
1724          Invalid = true;
1725      }
1726    }
1727  }
1728
1729  if (!Record->isUnion() && !Owner->isRecord()) {
1730    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1731      << (int)getLangOptions().CPlusPlus;
1732    Invalid = true;
1733  }
1734
1735  // Mock up a declarator.
1736  Declarator Dc(DS, Declarator::TypeNameContext);
1737  TypeSourceInfo *TInfo = 0;
1738  GetTypeForDeclarator(Dc, S, &TInfo);
1739  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
1740
1741  // Create a declaration for this anonymous struct/union.
1742  NamedDecl *Anon = 0;
1743  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1744    Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1745                             /*IdentifierInfo=*/0,
1746                             Context.getTypeDeclType(Record),
1747                             TInfo,
1748                             /*BitWidth=*/0, /*Mutable=*/false);
1749    Anon->setAccess(AS_public);
1750    if (getLangOptions().CPlusPlus)
1751      FieldCollector->Add(cast<FieldDecl>(Anon));
1752  } else {
1753    DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
1754    assert(SCSpec != DeclSpec::SCS_typedef &&
1755           "Parser allowed 'typedef' as storage class VarDecl.");
1756    VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
1757    if (SCSpec == DeclSpec::SCS_mutable) {
1758      // mutable can only appear on non-static class members, so it's always
1759      // an error here
1760      Diag(Record->getLocation(), diag::err_mutable_nonmember);
1761      Invalid = true;
1762      SC = VarDecl::None;
1763    }
1764    SCSpec = DS.getStorageClassSpecAsWritten();
1765    VarDecl::StorageClass SCAsWritten
1766      = StorageClassSpecToVarDeclStorageClass(SCSpec);
1767
1768    Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1769                           /*IdentifierInfo=*/0,
1770                           Context.getTypeDeclType(Record),
1771                           TInfo, SC, SCAsWritten);
1772  }
1773  Anon->setImplicit();
1774
1775  // Add the anonymous struct/union object to the current
1776  // context. We'll be referencing this object when we refer to one of
1777  // its members.
1778  Owner->addDecl(Anon);
1779
1780  // Inject the members of the anonymous struct/union into the owning
1781  // context and into the identifier resolver chain for name lookup
1782  // purposes.
1783  if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1784    Invalid = true;
1785
1786  // Mark this as an anonymous struct/union type. Note that we do not
1787  // do this until after we have already checked and injected the
1788  // members of this anonymous struct/union type, because otherwise
1789  // the members could be injected twice: once by DeclContext when it
1790  // builds its lookup table, and once by
1791  // InjectAnonymousStructOrUnionMembers.
1792  Record->setAnonymousStructOrUnion(true);
1793
1794  if (Invalid)
1795    Anon->setInvalidDecl();
1796
1797  return DeclPtrTy::make(Anon);
1798}
1799
1800
1801/// GetNameForDeclarator - Determine the full declaration name for the
1802/// given Declarator.
1803DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1804  return GetNameFromUnqualifiedId(D.getName());
1805}
1806
1807/// \brief Retrieves the canonicalized name from a parsed unqualified-id.
1808DeclarationName Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
1809  switch (Name.getKind()) {
1810    case UnqualifiedId::IK_Identifier:
1811      return DeclarationName(Name.Identifier);
1812
1813    case UnqualifiedId::IK_OperatorFunctionId:
1814      return Context.DeclarationNames.getCXXOperatorName(
1815                                              Name.OperatorFunctionId.Operator);
1816
1817    case UnqualifiedId::IK_LiteralOperatorId:
1818      return Context.DeclarationNames.getCXXLiteralOperatorName(
1819                                                               Name.Identifier);
1820
1821    case UnqualifiedId::IK_ConversionFunctionId: {
1822      QualType Ty = GetTypeFromParser(Name.ConversionFunctionId);
1823      if (Ty.isNull())
1824        return DeclarationName();
1825
1826      return Context.DeclarationNames.getCXXConversionFunctionName(
1827                                                  Context.getCanonicalType(Ty));
1828    }
1829
1830    case UnqualifiedId::IK_ConstructorName: {
1831      QualType Ty = GetTypeFromParser(Name.ConstructorName);
1832      if (Ty.isNull())
1833        return DeclarationName();
1834
1835      return Context.DeclarationNames.getCXXConstructorName(
1836                                                  Context.getCanonicalType(Ty));
1837    }
1838
1839    case UnqualifiedId::IK_ConstructorTemplateId: {
1840      // In well-formed code, we can only have a constructor
1841      // template-id that refers to the current context, so go there
1842      // to find the actual type being constructed.
1843      CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
1844      if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
1845        return DeclarationName();
1846
1847      // Determine the type of the class being constructed.
1848      QualType CurClassType = Context.getTypeDeclType(CurClass);
1849
1850      // FIXME: Check two things: that the template-id names the same type as
1851      // CurClassType, and that the template-id does not occur when the name
1852      // was qualified.
1853
1854      return Context.DeclarationNames.getCXXConstructorName(
1855                                       Context.getCanonicalType(CurClassType));
1856    }
1857
1858    case UnqualifiedId::IK_DestructorName: {
1859      QualType Ty = GetTypeFromParser(Name.DestructorName);
1860      if (Ty.isNull())
1861        return DeclarationName();
1862
1863      return Context.DeclarationNames.getCXXDestructorName(
1864                                                           Context.getCanonicalType(Ty));
1865    }
1866
1867    case UnqualifiedId::IK_TemplateId: {
1868      TemplateName TName
1869        = TemplateName::getFromVoidPointer(Name.TemplateId->Template);
1870      return Context.getNameForTemplate(TName);
1871    }
1872  }
1873
1874  assert(false && "Unknown name kind");
1875  return DeclarationName();
1876}
1877
1878/// isNearlyMatchingFunction - Determine whether the C++ functions
1879/// Declaration and Definition are "nearly" matching. This heuristic
1880/// is used to improve diagnostics in the case where an out-of-line
1881/// function definition doesn't match any declaration within
1882/// the class or namespace.
1883static bool isNearlyMatchingFunction(ASTContext &Context,
1884                                     FunctionDecl *Declaration,
1885                                     FunctionDecl *Definition) {
1886  if (Declaration->param_size() != Definition->param_size())
1887    return false;
1888  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1889    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1890    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1891
1892    if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
1893                                        DefParamTy.getNonReferenceType()))
1894      return false;
1895  }
1896
1897  return true;
1898}
1899
1900Sema::DeclPtrTy
1901Sema::HandleDeclarator(Scope *S, Declarator &D,
1902                       MultiTemplateParamsArg TemplateParamLists,
1903                       bool IsFunctionDefinition) {
1904  DeclarationName Name = GetNameForDeclarator(D);
1905
1906  // All of these full declarators require an identifier.  If it doesn't have
1907  // one, the ParsedFreeStandingDeclSpec action should be used.
1908  if (!Name) {
1909    if (!D.isInvalidType())  // Reject this if we think it is valid.
1910      Diag(D.getDeclSpec().getSourceRange().getBegin(),
1911           diag::err_declarator_need_ident)
1912        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
1913    return DeclPtrTy();
1914  }
1915
1916  // The scope passed in may not be a decl scope.  Zip up the scope tree until
1917  // we find one that is.
1918  while ((S->getFlags() & Scope::DeclScope) == 0 ||
1919         (S->getFlags() & Scope::TemplateParamScope) != 0)
1920    S = S->getParent();
1921
1922  // If this is an out-of-line definition of a member of a class template
1923  // or class template partial specialization, we may need to rebuild the
1924  // type specifier in the declarator. See RebuildTypeInCurrentInstantiation()
1925  // for more information.
1926  // FIXME: cope with decltype(expr) and typeof(expr) once the rebuilder can
1927  // handle expressions properly.
1928  DeclSpec &DS = const_cast<DeclSpec&>(D.getDeclSpec());
1929  if (D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid() &&
1930      isDependentScopeSpecifier(D.getCXXScopeSpec()) &&
1931      (DS.getTypeSpecType() == DeclSpec::TST_typename ||
1932       DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
1933       DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
1934       DS.getTypeSpecType() == DeclSpec::TST_decltype)) {
1935    if (DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(), true)) {
1936      // FIXME: Preserve type source info.
1937      QualType T = GetTypeFromParser(DS.getTypeRep());
1938
1939      DeclContext *SavedContext = CurContext;
1940      CurContext = DC;
1941      T = RebuildTypeInCurrentInstantiation(T, D.getIdentifierLoc(), Name);
1942      CurContext = SavedContext;
1943
1944      if (T.isNull())
1945        return DeclPtrTy();
1946      DS.UpdateTypeRep(T.getAsOpaquePtr());
1947    }
1948  }
1949
1950  DeclContext *DC;
1951  NamedDecl *New;
1952
1953  TypeSourceInfo *TInfo = 0;
1954  QualType R = GetTypeForDeclarator(D, S, &TInfo);
1955
1956  LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
1957                        ForRedeclaration);
1958
1959  // See if this is a redefinition of a variable in the same scope.
1960  if (D.getCXXScopeSpec().isInvalid()) {
1961    DC = CurContext;
1962    D.setInvalidType();
1963  } else if (!D.getCXXScopeSpec().isSet()) {
1964    bool IsLinkageLookup = false;
1965
1966    // If the declaration we're planning to build will be a function
1967    // or object with linkage, then look for another declaration with
1968    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
1969    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1970      /* Do nothing*/;
1971    else if (R->isFunctionType()) {
1972      if (CurContext->isFunctionOrMethod() ||
1973          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1974        IsLinkageLookup = true;
1975    } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
1976      IsLinkageLookup = true;
1977    else if (CurContext->getLookupContext()->isTranslationUnit() &&
1978             D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1979      IsLinkageLookup = true;
1980
1981    if (IsLinkageLookup)
1982      Previous.clear(LookupRedeclarationWithLinkage);
1983
1984    DC = CurContext;
1985    LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
1986  } else { // Something like "int foo::x;"
1987    DC = computeDeclContext(D.getCXXScopeSpec(), true);
1988
1989    if (!DC) {
1990      // If we could not compute the declaration context, it's because the
1991      // declaration context is dependent but does not refer to a class,
1992      // class template, or class template partial specialization. Complain
1993      // and return early, to avoid the coming semantic disaster.
1994      Diag(D.getIdentifierLoc(),
1995           diag::err_template_qualified_declarator_no_match)
1996        << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
1997        << D.getCXXScopeSpec().getRange();
1998      return DeclPtrTy();
1999    }
2000
2001    if (!DC->isDependentContext() &&
2002        RequireCompleteDeclContext(D.getCXXScopeSpec()))
2003      return DeclPtrTy();
2004
2005    if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
2006      Diag(D.getIdentifierLoc(),
2007           diag::err_member_def_undefined_record)
2008        << Name << DC << D.getCXXScopeSpec().getRange();
2009      D.setInvalidType();
2010    }
2011
2012    LookupQualifiedName(Previous, DC);
2013
2014    // Don't consider using declarations as previous declarations for
2015    // out-of-line members.
2016    RemoveUsingDecls(Previous);
2017
2018    // C++ 7.3.1.2p2:
2019    // Members (including explicit specializations of templates) of a named
2020    // namespace can also be defined outside that namespace by explicit
2021    // qualification of the name being defined, provided that the entity being
2022    // defined was already declared in the namespace and the definition appears
2023    // after the point of declaration in a namespace that encloses the
2024    // declarations namespace.
2025    //
2026    // Note that we only check the context at this point. We don't yet
2027    // have enough information to make sure that PrevDecl is actually
2028    // the declaration we want to match. For example, given:
2029    //
2030    //   class X {
2031    //     void f();
2032    //     void f(float);
2033    //   };
2034    //
2035    //   void X::f(int) { } // ill-formed
2036    //
2037    // In this case, PrevDecl will point to the overload set
2038    // containing the two f's declared in X, but neither of them
2039    // matches.
2040
2041    // First check whether we named the global scope.
2042    if (isa<TranslationUnitDecl>(DC)) {
2043      Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
2044        << Name << D.getCXXScopeSpec().getRange();
2045    } else {
2046      DeclContext *Cur = CurContext;
2047      while (isa<LinkageSpecDecl>(Cur))
2048        Cur = Cur->getParent();
2049      if (!Cur->Encloses(DC)) {
2050        // The qualifying scope doesn't enclose the original declaration.
2051        // Emit diagnostic based on current scope.
2052        SourceLocation L = D.getIdentifierLoc();
2053        SourceRange R = D.getCXXScopeSpec().getRange();
2054        if (isa<FunctionDecl>(Cur))
2055          Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
2056        else
2057          Diag(L, diag::err_invalid_declarator_scope)
2058            << Name << cast<NamedDecl>(DC) << R;
2059        D.setInvalidType();
2060      }
2061    }
2062  }
2063
2064  if (Previous.isSingleResult() &&
2065      Previous.getFoundDecl()->isTemplateParameter()) {
2066    // Maybe we will complain about the shadowed template parameter.
2067    if (!D.isInvalidType())
2068      if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
2069                                          Previous.getFoundDecl()))
2070        D.setInvalidType();
2071
2072    // Just pretend that we didn't see the previous declaration.
2073    Previous.clear();
2074  }
2075
2076  // In C++, the previous declaration we find might be a tag type
2077  // (class or enum). In this case, the new declaration will hide the
2078  // tag type. Note that this does does not apply if we're declaring a
2079  // typedef (C++ [dcl.typedef]p4).
2080  if (Previous.isSingleTagDecl() &&
2081      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
2082    Previous.clear();
2083
2084  bool Redeclaration = false;
2085  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
2086    if (TemplateParamLists.size()) {
2087      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
2088      return DeclPtrTy();
2089    }
2090
2091    New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
2092  } else if (R->isFunctionType()) {
2093    New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
2094                                  move(TemplateParamLists),
2095                                  IsFunctionDefinition, Redeclaration);
2096  } else {
2097    New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
2098                                  move(TemplateParamLists),
2099                                  Redeclaration);
2100  }
2101
2102  if (New == 0)
2103    return DeclPtrTy();
2104
2105  // If this has an identifier and is not an invalid redeclaration or
2106  // function template specialization, add it to the scope stack.
2107  if (Name && !(Redeclaration && New->isInvalidDecl()))
2108    PushOnScopeChains(New, S);
2109
2110  return DeclPtrTy::make(New);
2111}
2112
2113/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2114/// types into constant array types in certain situations which would otherwise
2115/// be errors (for GCC compatibility).
2116static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2117                                                    ASTContext &Context,
2118                                                    bool &SizeIsNegative) {
2119  // This method tries to turn a variable array into a constant
2120  // array even when the size isn't an ICE.  This is necessary
2121  // for compatibility with code that depends on gcc's buggy
2122  // constant expression folding, like struct {char x[(int)(char*)2];}
2123  SizeIsNegative = false;
2124
2125  QualifierCollector Qs;
2126  const Type *Ty = Qs.strip(T);
2127
2128  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
2129    QualType Pointee = PTy->getPointeeType();
2130    QualType FixedType =
2131        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
2132    if (FixedType.isNull()) return FixedType;
2133    FixedType = Context.getPointerType(FixedType);
2134    return Qs.apply(FixedType);
2135  }
2136
2137  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2138  if (!VLATy)
2139    return QualType();
2140  // FIXME: We should probably handle this case
2141  if (VLATy->getElementType()->isVariablyModifiedType())
2142    return QualType();
2143
2144  Expr::EvalResult EvalResult;
2145  if (!VLATy->getSizeExpr() ||
2146      !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
2147      !EvalResult.Val.isInt())
2148    return QualType();
2149
2150  llvm::APSInt &Res = EvalResult.Val.getInt();
2151  if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
2152    // TODO: preserve the size expression in declarator info
2153    return Context.getConstantArrayType(VLATy->getElementType(),
2154                                        Res, ArrayType::Normal, 0);
2155  }
2156
2157  SizeIsNegative = true;
2158  return QualType();
2159}
2160
2161/// \brief Register the given locally-scoped external C declaration so
2162/// that it can be found later for redeclarations
2163void
2164Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
2165                                       const LookupResult &Previous,
2166                                       Scope *S) {
2167  assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
2168         "Decl is not a locally-scoped decl!");
2169  // Note that we have a locally-scoped external with this name.
2170  LocallyScopedExternalDecls[ND->getDeclName()] = ND;
2171
2172  if (!Previous.isSingleResult())
2173    return;
2174
2175  NamedDecl *PrevDecl = Previous.getFoundDecl();
2176
2177  // If there was a previous declaration of this variable, it may be
2178  // in our identifier chain. Update the identifier chain with the new
2179  // declaration.
2180  if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
2181    // The previous declaration was found on the identifer resolver
2182    // chain, so remove it from its scope.
2183    while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
2184      S = S->getParent();
2185
2186    if (S)
2187      S->RemoveDecl(DeclPtrTy::make(PrevDecl));
2188  }
2189}
2190
2191/// \brief Diagnose function specifiers on a declaration of an identifier that
2192/// does not identify a function.
2193void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
2194  // FIXME: We should probably indicate the identifier in question to avoid
2195  // confusion for constructs like "inline int a(), b;"
2196  if (D.getDeclSpec().isInlineSpecified())
2197    Diag(D.getDeclSpec().getInlineSpecLoc(),
2198         diag::err_inline_non_function);
2199
2200  if (D.getDeclSpec().isVirtualSpecified())
2201    Diag(D.getDeclSpec().getVirtualSpecLoc(),
2202         diag::err_virtual_non_function);
2203
2204  if (D.getDeclSpec().isExplicitSpecified())
2205    Diag(D.getDeclSpec().getExplicitSpecLoc(),
2206         diag::err_explicit_non_function);
2207}
2208
2209NamedDecl*
2210Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2211                             QualType R,  TypeSourceInfo *TInfo,
2212                             LookupResult &Previous, bool &Redeclaration) {
2213  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2214  if (D.getCXXScopeSpec().isSet()) {
2215    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2216      << D.getCXXScopeSpec().getRange();
2217    D.setInvalidType();
2218    // Pretend we didn't see the scope specifier.
2219    DC = CurContext;
2220    Previous.clear();
2221  }
2222
2223  if (getLangOptions().CPlusPlus) {
2224    // Check that there are no default arguments (C++ only).
2225    CheckExtraCXXDefaultArguments(D);
2226  }
2227
2228  DiagnoseFunctionSpecifiers(D);
2229
2230  if (D.getDeclSpec().isThreadSpecified())
2231    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2232
2233  TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
2234  if (!NewTD) return 0;
2235
2236  // Handle attributes prior to checking for duplicates in MergeVarDecl
2237  ProcessDeclAttributes(S, NewTD, D);
2238
2239  // Merge the decl with the existing one if appropriate. If the decl is
2240  // in an outer scope, it isn't the same thing.
2241  FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false);
2242  if (!Previous.empty()) {
2243    Redeclaration = true;
2244    MergeTypeDefDecl(NewTD, Previous);
2245  }
2246
2247  // C99 6.7.7p2: If a typedef name specifies a variably modified type
2248  // then it shall have block scope.
2249  QualType T = NewTD->getUnderlyingType();
2250  if (T->isVariablyModifiedType()) {
2251    FunctionNeedsScopeChecking() = true;
2252
2253    if (S->getFnParent() == 0) {
2254      bool SizeIsNegative;
2255      QualType FixedTy =
2256          TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2257      if (!FixedTy.isNull()) {
2258        Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
2259        NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
2260      } else {
2261        if (SizeIsNegative)
2262          Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2263        else if (T->isVariableArrayType())
2264          Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
2265        else
2266          Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
2267        NewTD->setInvalidDecl();
2268      }
2269    }
2270  }
2271
2272  // If this is the C FILE type, notify the AST context.
2273  if (IdentifierInfo *II = NewTD->getIdentifier())
2274    if (!NewTD->isInvalidDecl() &&
2275        NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
2276      if (II->isStr("FILE"))
2277        Context.setFILEDecl(NewTD);
2278      else if (II->isStr("jmp_buf"))
2279        Context.setjmp_bufDecl(NewTD);
2280      else if (II->isStr("sigjmp_buf"))
2281        Context.setsigjmp_bufDecl(NewTD);
2282    }
2283
2284  return NewTD;
2285}
2286
2287/// \brief Determines whether the given declaration is an out-of-scope
2288/// previous declaration.
2289///
2290/// This routine should be invoked when name lookup has found a
2291/// previous declaration (PrevDecl) that is not in the scope where a
2292/// new declaration by the same name is being introduced. If the new
2293/// declaration occurs in a local scope, previous declarations with
2294/// linkage may still be considered previous declarations (C99
2295/// 6.2.2p4-5, C++ [basic.link]p6).
2296///
2297/// \param PrevDecl the previous declaration found by name
2298/// lookup
2299///
2300/// \param DC the context in which the new declaration is being
2301/// declared.
2302///
2303/// \returns true if PrevDecl is an out-of-scope previous declaration
2304/// for a new delcaration with the same name.
2305static bool
2306isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2307                                ASTContext &Context) {
2308  if (!PrevDecl)
2309    return 0;
2310
2311  if (!PrevDecl->hasLinkage())
2312    return false;
2313
2314  if (Context.getLangOptions().CPlusPlus) {
2315    // C++ [basic.link]p6:
2316    //   If there is a visible declaration of an entity with linkage
2317    //   having the same name and type, ignoring entities declared
2318    //   outside the innermost enclosing namespace scope, the block
2319    //   scope declaration declares that same entity and receives the
2320    //   linkage of the previous declaration.
2321    DeclContext *OuterContext = DC->getLookupContext();
2322    if (!OuterContext->isFunctionOrMethod())
2323      // This rule only applies to block-scope declarations.
2324      return false;
2325    else {
2326      DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2327      if (PrevOuterContext->isRecord())
2328        // We found a member function: ignore it.
2329        return false;
2330      else {
2331        // Find the innermost enclosing namespace for the new and
2332        // previous declarations.
2333        while (!OuterContext->isFileContext())
2334          OuterContext = OuterContext->getParent();
2335        while (!PrevOuterContext->isFileContext())
2336          PrevOuterContext = PrevOuterContext->getParent();
2337
2338        // The previous declaration is in a different namespace, so it
2339        // isn't the same function.
2340        if (OuterContext->getPrimaryContext() !=
2341            PrevOuterContext->getPrimaryContext())
2342          return false;
2343      }
2344    }
2345  }
2346
2347  return true;
2348}
2349
2350static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
2351  CXXScopeSpec &SS = D.getCXXScopeSpec();
2352  if (!SS.isSet()) return;
2353  DD->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2354                       SS.getRange());
2355}
2356
2357NamedDecl*
2358Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2359                              QualType R, TypeSourceInfo *TInfo,
2360                              LookupResult &Previous,
2361                              MultiTemplateParamsArg TemplateParamLists,
2362                              bool &Redeclaration) {
2363  DeclarationName Name = GetNameForDeclarator(D);
2364
2365  // Check that there are no default arguments (C++ only).
2366  if (getLangOptions().CPlusPlus)
2367    CheckExtraCXXDefaultArguments(D);
2368
2369  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
2370  assert(SCSpec != DeclSpec::SCS_typedef &&
2371         "Parser allowed 'typedef' as storage class VarDecl.");
2372  VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
2373  if (SCSpec == DeclSpec::SCS_mutable) {
2374    // mutable can only appear on non-static class members, so it's always
2375    // an error here
2376    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
2377    D.setInvalidType();
2378    SC = VarDecl::None;
2379  }
2380  SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
2381  VarDecl::StorageClass SCAsWritten
2382    = StorageClassSpecToVarDeclStorageClass(SCSpec);
2383
2384  IdentifierInfo *II = Name.getAsIdentifierInfo();
2385  if (!II) {
2386    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2387      << Name.getAsString();
2388    return 0;
2389  }
2390
2391  DiagnoseFunctionSpecifiers(D);
2392
2393  if (!DC->isRecord() && S->getFnParent() == 0) {
2394    // C99 6.9p2: The storage-class specifiers auto and register shall not
2395    // appear in the declaration specifiers in an external declaration.
2396    if (SC == VarDecl::Auto || SC == VarDecl::Register) {
2397
2398      // If this is a register variable with an asm label specified, then this
2399      // is a GNU extension.
2400      if (SC == VarDecl::Register && D.getAsmLabel())
2401        Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2402      else
2403        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
2404      D.setInvalidType();
2405    }
2406  }
2407  if (DC->isRecord() && !CurContext->isRecord()) {
2408    // This is an out-of-line definition of a static data member.
2409    if (SC == VarDecl::Static) {
2410      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2411           diag::err_static_out_of_line)
2412        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2413    } else if (SC == VarDecl::None)
2414      SC = VarDecl::Static;
2415  }
2416  if (SC == VarDecl::Static) {
2417    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2418      if (RD->isLocalClass())
2419        Diag(D.getIdentifierLoc(),
2420             diag::err_static_data_member_not_allowed_in_local_class)
2421          << Name << RD->getDeclName();
2422    }
2423  }
2424
2425  // Match up the template parameter lists with the scope specifier, then
2426  // determine whether we have a template or a template specialization.
2427  bool isExplicitSpecialization = false;
2428  if (TemplateParameterList *TemplateParams
2429        = MatchTemplateParametersToScopeSpecifier(
2430                                  D.getDeclSpec().getSourceRange().getBegin(),
2431                                                  D.getCXXScopeSpec(),
2432                        (TemplateParameterList**)TemplateParamLists.get(),
2433                                                   TemplateParamLists.size(),
2434                                                  /*never a friend*/ false,
2435                                                  isExplicitSpecialization)) {
2436    if (TemplateParams->size() > 0) {
2437      // There is no such thing as a variable template.
2438      Diag(D.getIdentifierLoc(), diag::err_template_variable)
2439        << II
2440        << SourceRange(TemplateParams->getTemplateLoc(),
2441                       TemplateParams->getRAngleLoc());
2442      return 0;
2443    } else {
2444      // There is an extraneous 'template<>' for this variable. Complain
2445      // about it, but allow the declaration of the variable.
2446      Diag(TemplateParams->getTemplateLoc(),
2447           diag::err_template_variable_noparams)
2448        << II
2449        << SourceRange(TemplateParams->getTemplateLoc(),
2450                       TemplateParams->getRAngleLoc());
2451
2452      isExplicitSpecialization = true;
2453    }
2454  }
2455
2456  VarDecl *NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2457                                   II, R, TInfo, SC, SCAsWritten);
2458
2459  if (D.isInvalidType())
2460    NewVD->setInvalidDecl();
2461
2462  SetNestedNameSpecifier(NewVD, D);
2463
2464  if (D.getDeclSpec().isThreadSpecified()) {
2465    if (NewVD->hasLocalStorage())
2466      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
2467    else if (!Context.Target.isTLSSupported())
2468      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
2469    else
2470      NewVD->setThreadSpecified(true);
2471  }
2472
2473  // Set the lexical context. If the declarator has a C++ scope specifier, the
2474  // lexical context will be different from the semantic context.
2475  NewVD->setLexicalDeclContext(CurContext);
2476
2477  // Handle attributes prior to checking for duplicates in MergeVarDecl
2478  ProcessDeclAttributes(S, NewVD, D);
2479
2480  // Handle GNU asm-label extension (encoded as an attribute).
2481  if (Expr *E = (Expr*) D.getAsmLabel()) {
2482    // The parser guarantees this is a string.
2483    StringLiteral *SE = cast<StringLiteral>(E);
2484    NewVD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString()));
2485  }
2486
2487  // Diagnose shadowed variables before filtering for scope.
2488  if (!D.getCXXScopeSpec().isSet())
2489    CheckShadow(S, NewVD, Previous);
2490
2491  // Don't consider existing declarations that are in a different
2492  // scope and are out-of-semantic-context declarations (if the new
2493  // declaration has linkage).
2494  FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage());
2495
2496  // Merge the decl with the existing one if appropriate.
2497  if (!Previous.empty()) {
2498    if (Previous.isSingleResult() &&
2499        isa<FieldDecl>(Previous.getFoundDecl()) &&
2500        D.getCXXScopeSpec().isSet()) {
2501      // The user tried to define a non-static data member
2502      // out-of-line (C++ [dcl.meaning]p1).
2503      Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
2504        << D.getCXXScopeSpec().getRange();
2505      Previous.clear();
2506      NewVD->setInvalidDecl();
2507    }
2508  } else if (D.getCXXScopeSpec().isSet()) {
2509    // No previous declaration in the qualifying scope.
2510    Diag(D.getIdentifierLoc(), diag::err_no_member)
2511      << Name << computeDeclContext(D.getCXXScopeSpec(), true)
2512      << D.getCXXScopeSpec().getRange();
2513    NewVD->setInvalidDecl();
2514  }
2515
2516  CheckVariableDeclaration(NewVD, Previous, Redeclaration);
2517
2518  // This is an explicit specialization of a static data member. Check it.
2519  if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
2520      CheckMemberSpecialization(NewVD, Previous))
2521    NewVD->setInvalidDecl();
2522
2523  // attributes declared post-definition are currently ignored
2524  if (Previous.isSingleResult()) {
2525    VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
2526    if (Def && (Def = Def->getDefinition()) &&
2527        Def != NewVD && D.hasAttributes()) {
2528      Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
2529      Diag(Def->getLocation(), diag::note_previous_definition);
2530    }
2531  }
2532
2533  // If this is a locally-scoped extern C variable, update the map of
2534  // such variables.
2535  if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
2536      !NewVD->isInvalidDecl())
2537    RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
2538
2539  return NewVD;
2540}
2541
2542/// \brief Diagnose variable or built-in function shadowing.  Implements
2543/// -Wshadow.
2544///
2545/// This method is called whenever a VarDecl is added to a "useful"
2546/// scope.
2547///
2548/// \param S the scope in which the shadowing name is being declared
2549/// \param R the lookup of the name
2550///
2551void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
2552  // Return if warning is ignored.
2553  if (Diags.getDiagnosticLevel(diag::warn_decl_shadow) == Diagnostic::Ignored)
2554    return;
2555
2556  // Don't diagnose declarations at file scope.  The scope might not
2557  // have a DeclContext if (e.g.) we're parsing a function prototype.
2558  DeclContext *NewDC = static_cast<DeclContext*>(S->getEntity());
2559  if (NewDC && NewDC->isFileContext())
2560    return;
2561
2562  // Only diagnose if we're shadowing an unambiguous field or variable.
2563  if (R.getResultKind() != LookupResult::Found)
2564    return;
2565
2566  NamedDecl* ShadowedDecl = R.getFoundDecl();
2567  if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
2568    return;
2569
2570  DeclContext *OldDC = ShadowedDecl->getDeclContext();
2571
2572  // Only warn about certain kinds of shadowing for class members.
2573  if (NewDC && NewDC->isRecord()) {
2574    // In particular, don't warn about shadowing non-class members.
2575    if (!OldDC->isRecord())
2576      return;
2577
2578    // TODO: should we warn about static data members shadowing
2579    // static data members from base classes?
2580
2581    // TODO: don't diagnose for inaccessible shadowed members.
2582    // This is hard to do perfectly because we might friend the
2583    // shadowing context, but that's just a false negative.
2584  }
2585
2586  // Determine what kind of declaration we're shadowing.
2587  unsigned Kind;
2588  if (isa<RecordDecl>(OldDC)) {
2589    if (isa<FieldDecl>(ShadowedDecl))
2590      Kind = 3; // field
2591    else
2592      Kind = 2; // static data member
2593  } else if (OldDC->isFileContext())
2594    Kind = 1; // global
2595  else
2596    Kind = 0; // local
2597
2598  DeclarationName Name = R.getLookupName();
2599
2600  // Emit warning and note.
2601  Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
2602  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
2603}
2604
2605/// \brief Check -Wshadow without the advantage of a previous lookup.
2606void Sema::CheckShadow(Scope *S, VarDecl *D) {
2607  LookupResult R(*this, D->getDeclName(), D->getLocation(),
2608                 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
2609  LookupName(R, S);
2610  CheckShadow(S, D, R);
2611}
2612
2613/// \brief Perform semantic checking on a newly-created variable
2614/// declaration.
2615///
2616/// This routine performs all of the type-checking required for a
2617/// variable declaration once it has been built. It is used both to
2618/// check variables after they have been parsed and their declarators
2619/// have been translated into a declaration, and to check variables
2620/// that have been instantiated from a template.
2621///
2622/// Sets NewVD->isInvalidDecl() if an error was encountered.
2623void Sema::CheckVariableDeclaration(VarDecl *NewVD,
2624                                    LookupResult &Previous,
2625                                    bool &Redeclaration) {
2626  // If the decl is already known invalid, don't check it.
2627  if (NewVD->isInvalidDecl())
2628    return;
2629
2630  QualType T = NewVD->getType();
2631
2632  if (T->isObjCInterfaceType()) {
2633    Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
2634    return NewVD->setInvalidDecl();
2635  }
2636
2637  // Emit an error if an address space was applied to decl with local storage.
2638  // This includes arrays of objects with address space qualifiers, but not
2639  // automatic variables that point to other address spaces.
2640  // ISO/IEC TR 18037 S5.1.2
2641  if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
2642    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
2643    return NewVD->setInvalidDecl();
2644  }
2645
2646  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
2647      && !NewVD->hasAttr<BlocksAttr>())
2648    Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
2649
2650  bool isVM = T->isVariablyModifiedType();
2651  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
2652      NewVD->hasAttr<BlocksAttr>() ||
2653      // FIXME: We need to diagnose jumps passed initialized variables in C++.
2654      // However, this turns on the scope checker for everything with a variable
2655      // which may impact compile time.  See if we can find a better solution
2656      // to this, perhaps only checking functions that contain gotos in C++?
2657      (LangOpts.CPlusPlus && NewVD->hasLocalStorage()))
2658    FunctionNeedsScopeChecking() = true;
2659
2660  if ((isVM && NewVD->hasLinkage()) ||
2661      (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
2662    bool SizeIsNegative;
2663    QualType FixedTy =
2664        TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2665
2666    if (FixedTy.isNull() && T->isVariableArrayType()) {
2667      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
2668      // FIXME: This won't give the correct result for
2669      // int a[10][n];
2670      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
2671
2672      if (NewVD->isFileVarDecl())
2673        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
2674        << SizeRange;
2675      else if (NewVD->getStorageClass() == VarDecl::Static)
2676        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
2677        << SizeRange;
2678      else
2679        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
2680        << SizeRange;
2681      return NewVD->setInvalidDecl();
2682    }
2683
2684    if (FixedTy.isNull()) {
2685      if (NewVD->isFileVarDecl())
2686        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
2687      else
2688        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
2689      return NewVD->setInvalidDecl();
2690    }
2691
2692    Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
2693    NewVD->setType(FixedTy);
2694  }
2695
2696  if (Previous.empty() && NewVD->isExternC()) {
2697    // Since we did not find anything by this name and we're declaring
2698    // an extern "C" variable, look for a non-visible extern "C"
2699    // declaration with the same name.
2700    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2701      = LocallyScopedExternalDecls.find(NewVD->getDeclName());
2702    if (Pos != LocallyScopedExternalDecls.end())
2703      Previous.addDecl(Pos->second);
2704  }
2705
2706  if (T->isVoidType() && !NewVD->hasExternalStorage()) {
2707    Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
2708      << T;
2709    return NewVD->setInvalidDecl();
2710  }
2711
2712  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
2713    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
2714    return NewVD->setInvalidDecl();
2715  }
2716
2717  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
2718    Diag(NewVD->getLocation(), diag::err_block_on_vm);
2719    return NewVD->setInvalidDecl();
2720  }
2721
2722  if (!Previous.empty()) {
2723    Redeclaration = true;
2724    MergeVarDecl(NewVD, Previous);
2725  }
2726}
2727
2728/// \brief Data used with FindOverriddenMethod
2729struct FindOverriddenMethodData {
2730  Sema *S;
2731  CXXMethodDecl *Method;
2732};
2733
2734/// \brief Member lookup function that determines whether a given C++
2735/// method overrides a method in a base class, to be used with
2736/// CXXRecordDecl::lookupInBases().
2737static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
2738                                 CXXBasePath &Path,
2739                                 void *UserData) {
2740  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2741
2742  FindOverriddenMethodData *Data
2743    = reinterpret_cast<FindOverriddenMethodData*>(UserData);
2744
2745  DeclarationName Name = Data->Method->getDeclName();
2746
2747  // FIXME: Do we care about other names here too?
2748  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2749    // We really want to find the base class constructor here.
2750    QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
2751    CanQualType CT = Data->S->Context.getCanonicalType(T);
2752
2753    Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
2754  }
2755
2756  for (Path.Decls = BaseRecord->lookup(Name);
2757       Path.Decls.first != Path.Decls.second;
2758       ++Path.Decls.first) {
2759    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*Path.Decls.first)) {
2760      if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD))
2761        return true;
2762    }
2763  }
2764
2765  return false;
2766}
2767
2768/// AddOverriddenMethods - See if a method overrides any in the base classes,
2769/// and if so, check that it's a valid override and remember it.
2770void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2771  // Look for virtual methods in base classes that this method might override.
2772  CXXBasePaths Paths;
2773  FindOverriddenMethodData Data;
2774  Data.Method = MD;
2775  Data.S = this;
2776  if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
2777    for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
2778         E = Paths.found_decls_end(); I != E; ++I) {
2779      if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
2780        if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
2781            !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
2782            !CheckOverridingFunctionAttributes(MD, OldMD))
2783          MD->addOverriddenMethod(OldMD->getCanonicalDecl());
2784      }
2785    }
2786  }
2787}
2788
2789NamedDecl*
2790Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2791                              QualType R, TypeSourceInfo *TInfo,
2792                              LookupResult &Previous,
2793                              MultiTemplateParamsArg TemplateParamLists,
2794                              bool IsFunctionDefinition, bool &Redeclaration) {
2795  assert(R.getTypePtr()->isFunctionType());
2796
2797  DeclarationName Name = GetNameForDeclarator(D);
2798  FunctionDecl::StorageClass SC = FunctionDecl::None;
2799  switch (D.getDeclSpec().getStorageClassSpec()) {
2800  default: assert(0 && "Unknown storage class!");
2801  case DeclSpec::SCS_auto:
2802  case DeclSpec::SCS_register:
2803  case DeclSpec::SCS_mutable:
2804    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2805         diag::err_typecheck_sclass_func);
2806    D.setInvalidType();
2807    break;
2808  case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
2809  case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
2810  case DeclSpec::SCS_static: {
2811    if (CurContext->getLookupContext()->isFunctionOrMethod()) {
2812      // C99 6.7.1p5:
2813      //   The declaration of an identifier for a function that has
2814      //   block scope shall have no explicit storage-class specifier
2815      //   other than extern
2816      // See also (C++ [dcl.stc]p4).
2817      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2818           diag::err_static_block_func);
2819      SC = FunctionDecl::None;
2820    } else
2821      SC = FunctionDecl::Static;
2822    break;
2823  }
2824  case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
2825  }
2826
2827  if (D.getDeclSpec().isThreadSpecified())
2828    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2829
2830  bool isFriend = D.getDeclSpec().isFriendSpecified();
2831  bool isInline = D.getDeclSpec().isInlineSpecified();
2832  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2833  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
2834
2835  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
2836  FunctionDecl::StorageClass SCAsWritten
2837    = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
2838
2839  // Check that the return type is not an abstract class type.
2840  // For record types, this is done by the AbstractClassUsageDiagnoser once
2841  // the class has been completely parsed.
2842  if (!DC->isRecord() &&
2843      RequireNonAbstractType(D.getIdentifierLoc(),
2844                             R->getAs<FunctionType>()->getResultType(),
2845                             diag::err_abstract_type_in_decl,
2846                             AbstractReturnType))
2847    D.setInvalidType();
2848
2849  // Do not allow returning a objc interface by-value.
2850  if (R->getAs<FunctionType>()->getResultType()->isObjCInterfaceType()) {
2851    Diag(D.getIdentifierLoc(),
2852         diag::err_object_cannot_be_passed_returned_by_value) << 0
2853      << R->getAs<FunctionType>()->getResultType();
2854    D.setInvalidType();
2855  }
2856
2857  bool isVirtualOkay = false;
2858  FunctionDecl *NewFD;
2859
2860  if (isFriend) {
2861    // C++ [class.friend]p5
2862    //   A function can be defined in a friend declaration of a
2863    //   class . . . . Such a function is implicitly inline.
2864    isInline |= IsFunctionDefinition;
2865  }
2866
2867  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
2868    // This is a C++ constructor declaration.
2869    assert(DC->isRecord() &&
2870           "Constructors can only be declared in a member context");
2871
2872    R = CheckConstructorDeclarator(D, R, SC);
2873
2874    // Create the new declaration
2875    NewFD = CXXConstructorDecl::Create(Context,
2876                                       cast<CXXRecordDecl>(DC),
2877                                       D.getIdentifierLoc(), Name, R, TInfo,
2878                                       isExplicit, isInline,
2879                                       /*isImplicitlyDeclared=*/false);
2880  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2881    // This is a C++ destructor declaration.
2882    if (DC->isRecord()) {
2883      R = CheckDestructorDeclarator(D, SC);
2884
2885      NewFD = CXXDestructorDecl::Create(Context,
2886                                        cast<CXXRecordDecl>(DC),
2887                                        D.getIdentifierLoc(), Name, R,
2888                                        isInline,
2889                                        /*isImplicitlyDeclared=*/false);
2890      NewFD->setTypeSourceInfo(TInfo);
2891
2892      isVirtualOkay = true;
2893    } else {
2894      Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
2895
2896      // Create a FunctionDecl to satisfy the function definition parsing
2897      // code path.
2898      NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
2899                                   Name, R, TInfo, SC, SCAsWritten, isInline,
2900                                   /*hasPrototype=*/true);
2901      D.setInvalidType();
2902    }
2903  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2904    if (!DC->isRecord()) {
2905      Diag(D.getIdentifierLoc(),
2906           diag::err_conv_function_not_member);
2907      return 0;
2908    }
2909
2910    CheckConversionDeclarator(D, R, SC);
2911    NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
2912                                      D.getIdentifierLoc(), Name, R, TInfo,
2913                                      isInline, isExplicit);
2914
2915    isVirtualOkay = true;
2916  } else if (DC->isRecord()) {
2917    // If the of the function is the same as the name of the record, then this
2918    // must be an invalid constructor that has a return type.
2919    // (The parser checks for a return type and makes the declarator a
2920    // constructor if it has no return type).
2921    // must have an invalid constructor that has a return type
2922    if (Name.getAsIdentifierInfo() &&
2923        Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
2924      Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
2925        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2926        << SourceRange(D.getIdentifierLoc());
2927      return 0;
2928    }
2929
2930    bool isStatic = SC == FunctionDecl::Static;
2931
2932    // [class.free]p1:
2933    // Any allocation function for a class T is a static member
2934    // (even if not explicitly declared static).
2935    if (Name.getCXXOverloadedOperator() == OO_New ||
2936        Name.getCXXOverloadedOperator() == OO_Array_New)
2937      isStatic = true;
2938
2939    // [class.free]p6 Any deallocation function for a class X is a static member
2940    // (even if not explicitly declared static).
2941    if (Name.getCXXOverloadedOperator() == OO_Delete ||
2942        Name.getCXXOverloadedOperator() == OO_Array_Delete)
2943      isStatic = true;
2944
2945    // This is a C++ method declaration.
2946    NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
2947                                  D.getIdentifierLoc(), Name, R, TInfo,
2948                                  isStatic, SCAsWritten, isInline);
2949
2950    isVirtualOkay = !isStatic;
2951  } else {
2952    // Determine whether the function was written with a
2953    // prototype. This true when:
2954    //   - we're in C++ (where every function has a prototype),
2955    //   - there is a prototype in the declarator, or
2956    //   - the type R of the function is some kind of typedef or other reference
2957    //     to a type name (which eventually refers to a function type).
2958    bool HasPrototype =
2959       getLangOptions().CPlusPlus ||
2960       (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
2961       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
2962
2963    NewFD = FunctionDecl::Create(Context, DC,
2964                                 D.getIdentifierLoc(),
2965                                 Name, R, TInfo, SC, SCAsWritten, isInline,
2966                                 HasPrototype);
2967  }
2968
2969  if (D.isInvalidType())
2970    NewFD->setInvalidDecl();
2971
2972  SetNestedNameSpecifier(NewFD, D);
2973
2974  // Set the lexical context. If the declarator has a C++
2975  // scope specifier, or is the object of a friend declaration, the
2976  // lexical context will be different from the semantic context.
2977  NewFD->setLexicalDeclContext(CurContext);
2978
2979  // Match up the template parameter lists with the scope specifier, then
2980  // determine whether we have a template or a template specialization.
2981  FunctionTemplateDecl *FunctionTemplate = 0;
2982  bool isExplicitSpecialization = false;
2983  bool isFunctionTemplateSpecialization = false;
2984  if (TemplateParameterList *TemplateParams
2985        = MatchTemplateParametersToScopeSpecifier(
2986                                  D.getDeclSpec().getSourceRange().getBegin(),
2987                                  D.getCXXScopeSpec(),
2988                           (TemplateParameterList**)TemplateParamLists.get(),
2989                                                  TemplateParamLists.size(),
2990                                                  isFriend,
2991                                                  isExplicitSpecialization)) {
2992    if (TemplateParams->size() > 0) {
2993      // This is a function template
2994
2995      // Check that we can declare a template here.
2996      if (CheckTemplateDeclScope(S, TemplateParams))
2997        return 0;
2998
2999      FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
3000                                                      NewFD->getLocation(),
3001                                                      Name, TemplateParams,
3002                                                      NewFD);
3003      FunctionTemplate->setLexicalDeclContext(CurContext);
3004      NewFD->setDescribedFunctionTemplate(FunctionTemplate);
3005    } else {
3006      // This is a function template specialization.
3007      isFunctionTemplateSpecialization = true;
3008
3009      // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
3010      if (isFriend && isFunctionTemplateSpecialization) {
3011        // We want to remove the "template<>", found here.
3012        SourceRange RemoveRange = TemplateParams->getSourceRange();
3013
3014        // If we remove the template<> and the name is not a
3015        // template-id, we're actually silently creating a problem:
3016        // the friend declaration will refer to an untemplated decl,
3017        // and clearly the user wants a template specialization.  So
3018        // we need to insert '<>' after the name.
3019        SourceLocation InsertLoc;
3020        if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
3021          InsertLoc = D.getName().getSourceRange().getEnd();
3022          InsertLoc = PP.getLocForEndOfToken(InsertLoc);
3023        }
3024
3025        Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
3026          << Name << RemoveRange
3027          << FixItHint::CreateRemoval(RemoveRange)
3028          << FixItHint::CreateInsertion(InsertLoc, "<>");
3029      }
3030    }
3031
3032    // FIXME: Free this memory properly.
3033    TemplateParamLists.release();
3034  }
3035
3036  // C++ [dcl.fct.spec]p5:
3037  //   The virtual specifier shall only be used in declarations of
3038  //   nonstatic class member functions that appear within a
3039  //   member-specification of a class declaration; see 10.3.
3040  //
3041  if (isVirtual && !NewFD->isInvalidDecl()) {
3042    if (!isVirtualOkay) {
3043       Diag(D.getDeclSpec().getVirtualSpecLoc(),
3044           diag::err_virtual_non_function);
3045    } else if (!CurContext->isRecord()) {
3046      // 'virtual' was specified outside of the class.
3047      Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
3048        << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
3049    } else {
3050      // Okay: Add virtual to the method.
3051      CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
3052      CurClass->setMethodAsVirtual(NewFD);
3053    }
3054  }
3055
3056  // C++ [dcl.fct.spec]p6:
3057  //  The explicit specifier shall be used only in the declaration of a
3058  //  constructor or conversion function within its class definition; see 12.3.1
3059  //  and 12.3.2.
3060  if (isExplicit && !NewFD->isInvalidDecl()) {
3061    if (!CurContext->isRecord()) {
3062      // 'explicit' was specified outside of the class.
3063      Diag(D.getDeclSpec().getExplicitSpecLoc(),
3064           diag::err_explicit_out_of_class)
3065        << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
3066    } else if (!isa<CXXConstructorDecl>(NewFD) &&
3067               !isa<CXXConversionDecl>(NewFD)) {
3068      // 'explicit' was specified on a function that wasn't a constructor
3069      // or conversion function.
3070      Diag(D.getDeclSpec().getExplicitSpecLoc(),
3071           diag::err_explicit_non_ctor_or_conv_function)
3072        << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
3073    }
3074  }
3075
3076  // Filter out previous declarations that don't match the scope.
3077  FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
3078
3079  if (isFriend) {
3080    // DC is the namespace in which the function is being declared.
3081    assert((DC->isFileContext() || !Previous.empty()) &&
3082           "previously-undeclared friend function being created "
3083           "in a non-namespace context");
3084
3085    // For now, claim that the objects have no previous declaration.
3086    if (FunctionTemplate) {
3087      FunctionTemplate->setObjectOfFriendDecl(false);
3088      FunctionTemplate->setAccess(AS_public);
3089    }
3090    NewFD->setObjectOfFriendDecl(false);
3091    NewFD->setAccess(AS_public);
3092  }
3093
3094  if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
3095      !CurContext->isRecord()) {
3096    // C++ [class.static]p1:
3097    //   A data or function member of a class may be declared static
3098    //   in a class definition, in which case it is a static member of
3099    //   the class.
3100
3101    // Complain about the 'static' specifier if it's on an out-of-line
3102    // member function definition.
3103    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3104         diag::err_static_out_of_line)
3105      << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3106  }
3107
3108  // Handle GNU asm-label extension (encoded as an attribute).
3109  if (Expr *E = (Expr*) D.getAsmLabel()) {
3110    // The parser guarantees this is a string.
3111    StringLiteral *SE = cast<StringLiteral>(E);
3112    NewFD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString()));
3113  }
3114
3115  // Copy the parameter declarations from the declarator D to the function
3116  // declaration NewFD, if they are available.  First scavenge them into Params.
3117  llvm::SmallVector<ParmVarDecl*, 16> Params;
3118  if (D.getNumTypeObjects() > 0) {
3119    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3120
3121    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
3122    // function that takes no arguments, not a function that takes a
3123    // single void argument.
3124    // We let through "const void" here because Sema::GetTypeForDeclarator
3125    // already checks for that case.
3126    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3127        FTI.ArgInfo[0].Param &&
3128        FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
3129      // Empty arg list, don't push any params.
3130      ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
3131
3132      // In C++, the empty parameter-type-list must be spelled "void"; a
3133      // typedef of void is not permitted.
3134      if (getLangOptions().CPlusPlus &&
3135          Param->getType().getUnqualifiedType() != Context.VoidTy)
3136        Diag(Param->getLocation(), diag::err_param_typedef_of_void);
3137      // FIXME: Leaks decl?
3138    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
3139      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
3140        ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
3141        assert(Param->getDeclContext() != NewFD && "Was set before ?");
3142        Param->setDeclContext(NewFD);
3143        Params.push_back(Param);
3144
3145        if (Param->isInvalidDecl())
3146          NewFD->setInvalidDecl();
3147      }
3148    }
3149
3150  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
3151    // When we're declaring a function with a typedef, typeof, etc as in the
3152    // following example, we'll need to synthesize (unnamed)
3153    // parameters for use in the declaration.
3154    //
3155    // @code
3156    // typedef void fn(int);
3157    // fn f;
3158    // @endcode
3159
3160    // Synthesize a parameter for each argument type.
3161    for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
3162         AE = FT->arg_type_end(); AI != AE; ++AI) {
3163      ParmVarDecl *Param = ParmVarDecl::Create(Context, NewFD,
3164                                               SourceLocation(), 0,
3165                                               *AI, /*TInfo=*/0,
3166                                               VarDecl::None,
3167                                               VarDecl::None, 0);
3168      Param->setImplicit();
3169      Params.push_back(Param);
3170    }
3171  } else {
3172    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
3173           "Should not need args for typedef of non-prototype fn");
3174  }
3175  // Finally, we know we have the right number of parameters, install them.
3176  NewFD->setParams(Params.data(), Params.size());
3177
3178  // If the declarator is a template-id, translate the parser's template
3179  // argument list into our AST format.
3180  bool HasExplicitTemplateArgs = false;
3181  TemplateArgumentListInfo TemplateArgs;
3182  if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
3183    TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3184    TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
3185    TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
3186    ASTTemplateArgsPtr TemplateArgsPtr(*this,
3187                                       TemplateId->getTemplateArgs(),
3188                                       TemplateId->NumArgs);
3189    translateTemplateArguments(TemplateArgsPtr,
3190                               TemplateArgs);
3191    TemplateArgsPtr.release();
3192
3193    HasExplicitTemplateArgs = true;
3194
3195    if (FunctionTemplate) {
3196      // FIXME: Diagnose function template with explicit template
3197      // arguments.
3198      HasExplicitTemplateArgs = false;
3199    } else if (!isFunctionTemplateSpecialization &&
3200               !D.getDeclSpec().isFriendSpecified()) {
3201      // We have encountered something that the user meant to be a
3202      // specialization (because it has explicitly-specified template
3203      // arguments) but that was not introduced with a "template<>" (or had
3204      // too few of them).
3205      Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
3206        << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
3207        << FixItHint::CreateInsertion(
3208                                   D.getDeclSpec().getSourceRange().getBegin(),
3209                                                 "template<> ");
3210      isFunctionTemplateSpecialization = true;
3211    } else {
3212      // "friend void foo<>(int);" is an implicit specialization decl.
3213      isFunctionTemplateSpecialization = true;
3214    }
3215  } else if (isFriend && isFunctionTemplateSpecialization) {
3216    // This combination is only possible in a recovery case;  the user
3217    // wrote something like:
3218    //   template <> friend void foo(int);
3219    // which we're recovering from as if the user had written:
3220    //   friend void foo<>(int);
3221    // Go ahead and fake up a template id.
3222    HasExplicitTemplateArgs = true;
3223    TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
3224    TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
3225  }
3226
3227  // If it's a friend (and only if it's a friend), it's possible
3228  // that either the specialized function type or the specialized
3229  // template is dependent, and therefore matching will fail.  In
3230  // this case, don't check the specialization yet.
3231  if (isFunctionTemplateSpecialization && isFriend &&
3232      (NewFD->getType()->isDependentType() || DC->isDependentContext())) {
3233    assert(HasExplicitTemplateArgs &&
3234           "friend function specialization without template args");
3235    if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
3236                                                     Previous))
3237      NewFD->setInvalidDecl();
3238  } else if (isFunctionTemplateSpecialization) {
3239    if (CheckFunctionTemplateSpecialization(NewFD,
3240                               (HasExplicitTemplateArgs ? &TemplateArgs : 0),
3241                                            Previous))
3242      NewFD->setInvalidDecl();
3243  } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
3244    if (CheckMemberSpecialization(NewFD, Previous))
3245      NewFD->setInvalidDecl();
3246  }
3247
3248  // Perform semantic checking on the function declaration.
3249  bool OverloadableAttrRequired = false; // FIXME: HACK!
3250  CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
3251                           Redeclaration, /*FIXME:*/OverloadableAttrRequired);
3252
3253  assert((NewFD->isInvalidDecl() || !Redeclaration ||
3254          Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3255         "previous declaration set still overloaded");
3256
3257  NamedDecl *PrincipalDecl = (FunctionTemplate
3258                              ? cast<NamedDecl>(FunctionTemplate)
3259                              : NewFD);
3260
3261  if (isFriend && Redeclaration) {
3262    AccessSpecifier Access = AS_public;
3263    if (!NewFD->isInvalidDecl())
3264      Access = NewFD->getPreviousDeclaration()->getAccess();
3265
3266    NewFD->setAccess(Access);
3267    if (FunctionTemplate) FunctionTemplate->setAccess(Access);
3268
3269    PrincipalDecl->setObjectOfFriendDecl(true);
3270  }
3271
3272  if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
3273      PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3274    PrincipalDecl->setNonMemberOperator();
3275
3276  // If we have a function template, check the template parameter
3277  // list. This will check and merge default template arguments.
3278  if (FunctionTemplate) {
3279    FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
3280    CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
3281                      PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
3282             D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
3283                                                : TPC_FunctionTemplate);
3284  }
3285
3286  if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
3287    // Fake up an access specifier if it's supposed to be a class member.
3288    if (!Redeclaration && isa<CXXRecordDecl>(NewFD->getDeclContext()))
3289      NewFD->setAccess(AS_public);
3290
3291    // An out-of-line member function declaration must also be a
3292    // definition (C++ [dcl.meaning]p1).
3293    // Note that this is not the case for explicit specializations of
3294    // function templates or member functions of class templates, per
3295    // C++ [temp.expl.spec]p2.
3296    if (!IsFunctionDefinition && !isFriend &&
3297        !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
3298      Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
3299        << D.getCXXScopeSpec().getRange();
3300      NewFD->setInvalidDecl();
3301    } else if (!Redeclaration &&
3302               !(isFriend && CurContext->isDependentContext())) {
3303      // The user tried to provide an out-of-line definition for a
3304      // function that is a member of a class or namespace, but there
3305      // was no such member function declared (C++ [class.mfct]p2,
3306      // C++ [namespace.memdef]p2). For example:
3307      //
3308      // class X {
3309      //   void f() const;
3310      // };
3311      //
3312      // void X::f() { } // ill-formed
3313      //
3314      // Complain about this problem, and attempt to suggest close
3315      // matches (e.g., those that differ only in cv-qualifiers and
3316      // whether the parameter types are references).
3317      Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
3318        << Name << DC << D.getCXXScopeSpec().getRange();
3319      NewFD->setInvalidDecl();
3320
3321      LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
3322                        ForRedeclaration);
3323      LookupQualifiedName(Prev, DC);
3324      assert(!Prev.isAmbiguous() &&
3325             "Cannot have an ambiguity in previous-declaration lookup");
3326      for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3327           Func != FuncEnd; ++Func) {
3328        if (isa<FunctionDecl>(*Func) &&
3329            isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
3330          Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3331      }
3332    }
3333  }
3334
3335  // Handle attributes. We need to have merged decls when handling attributes
3336  // (for example to check for conflicts, etc).
3337  // FIXME: This needs to happen before we merge declarations. Then,
3338  // let attribute merging cope with attribute conflicts.
3339  ProcessDeclAttributes(S, NewFD, D);
3340
3341  // attributes declared post-definition are currently ignored
3342  if (Redeclaration && Previous.isSingleResult()) {
3343    const FunctionDecl *Def;
3344    FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
3345    if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) {
3346      Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
3347      Diag(Def->getLocation(), diag::note_previous_definition);
3348    }
3349  }
3350
3351  AddKnownFunctionAttributes(NewFD);
3352
3353  if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
3354    // If a function name is overloadable in C, then every function
3355    // with that name must be marked "overloadable".
3356    Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
3357      << Redeclaration << NewFD;
3358    if (!Previous.empty())
3359      Diag(Previous.getRepresentativeDecl()->getLocation(),
3360           diag::note_attribute_overloadable_prev_overload);
3361    NewFD->addAttr(::new (Context) OverloadableAttr());
3362  }
3363
3364  // If this is a locally-scoped extern C function, update the
3365  // map of such names.
3366  if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
3367      && !NewFD->isInvalidDecl())
3368    RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
3369
3370  // Set this FunctionDecl's range up to the right paren.
3371  NewFD->setLocEnd(D.getSourceRange().getEnd());
3372
3373  if (FunctionTemplate && NewFD->isInvalidDecl())
3374    FunctionTemplate->setInvalidDecl();
3375
3376  if (FunctionTemplate)
3377    return FunctionTemplate;
3378
3379
3380  // Keep track of static, non-inlined function definitions that
3381  // have not been used. We will warn later.
3382  // FIXME: Also include static functions declared but not defined.
3383  if (!NewFD->isInvalidDecl() && IsFunctionDefinition
3384      && !NewFD->isInlined() && NewFD->getLinkage() == InternalLinkage
3385      && !NewFD->isUsed() && !NewFD->hasAttr<UnusedAttr>()
3386      && !NewFD->hasAttr<ConstructorAttr>()
3387      && !NewFD->hasAttr<DestructorAttr>())
3388    UnusedStaticFuncs.push_back(NewFD);
3389
3390  return NewFD;
3391}
3392
3393/// \brief Perform semantic checking of a new function declaration.
3394///
3395/// Performs semantic analysis of the new function declaration
3396/// NewFD. This routine performs all semantic checking that does not
3397/// require the actual declarator involved in the declaration, and is
3398/// used both for the declaration of functions as they are parsed
3399/// (called via ActOnDeclarator) and for the declaration of functions
3400/// that have been instantiated via C++ template instantiation (called
3401/// via InstantiateDecl).
3402///
3403/// \param IsExplicitSpecialiation whether this new function declaration is
3404/// an explicit specialization of the previous declaration.
3405///
3406/// This sets NewFD->isInvalidDecl() to true if there was an error.
3407void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
3408                                    LookupResult &Previous,
3409                                    bool IsExplicitSpecialization,
3410                                    bool &Redeclaration,
3411                                    bool &OverloadableAttrRequired) {
3412  // If NewFD is already known erroneous, don't do any of this checking.
3413  if (NewFD->isInvalidDecl())
3414    return;
3415
3416  if (NewFD->getResultType()->isVariablyModifiedType()) {
3417    // Functions returning a variably modified type violate C99 6.7.5.2p2
3418    // because all functions have linkage.
3419    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
3420    return NewFD->setInvalidDecl();
3421  }
3422
3423  if (NewFD->isMain())
3424    CheckMain(NewFD);
3425
3426  // Check for a previous declaration of this name.
3427  if (Previous.empty() && NewFD->isExternC()) {
3428    // Since we did not find anything by this name and we're declaring
3429    // an extern "C" function, look for a non-visible extern "C"
3430    // declaration with the same name.
3431    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3432      = LocallyScopedExternalDecls.find(NewFD->getDeclName());
3433    if (Pos != LocallyScopedExternalDecls.end())
3434      Previous.addDecl(Pos->second);
3435  }
3436
3437  // Merge or overload the declaration with an existing declaration of
3438  // the same name, if appropriate.
3439  if (!Previous.empty()) {
3440    // Determine whether NewFD is an overload of PrevDecl or
3441    // a declaration that requires merging. If it's an overload,
3442    // there's no more work to do here; we'll just add the new
3443    // function to the scope.
3444
3445    NamedDecl *OldDecl = 0;
3446    if (!AllowOverloadingOfFunction(Previous, Context)) {
3447      Redeclaration = true;
3448      OldDecl = Previous.getFoundDecl();
3449    } else {
3450      if (!getLangOptions().CPlusPlus) {
3451        OverloadableAttrRequired = true;
3452
3453        // Functions marked "overloadable" must have a prototype (that
3454        // we can't get through declaration merging).
3455        if (!NewFD->getType()->getAs<FunctionProtoType>()) {
3456          Diag(NewFD->getLocation(),
3457               diag::err_attribute_overloadable_no_prototype)
3458            << NewFD;
3459          Redeclaration = true;
3460
3461          // Turn this into a variadic function with no parameters.
3462          QualType R = Context.getFunctionType(
3463                     NewFD->getType()->getAs<FunctionType>()->getResultType(),
3464                     0, 0, true, 0, false, false, 0, 0,
3465                     FunctionType::ExtInfo());
3466          NewFD->setType(R);
3467          return NewFD->setInvalidDecl();
3468        }
3469      }
3470
3471      switch (CheckOverload(NewFD, Previous, OldDecl)) {
3472      case Ovl_Match:
3473        Redeclaration = true;
3474        if (isa<UsingShadowDecl>(OldDecl) && CurContext->isRecord()) {
3475          HideUsingShadowDecl(S, cast<UsingShadowDecl>(OldDecl));
3476          Redeclaration = false;
3477        }
3478        break;
3479
3480      case Ovl_NonFunction:
3481        Redeclaration = true;
3482        break;
3483
3484      case Ovl_Overload:
3485        Redeclaration = false;
3486        break;
3487      }
3488    }
3489
3490    if (Redeclaration) {
3491      // NewFD and OldDecl represent declarations that need to be
3492      // merged.
3493      if (MergeFunctionDecl(NewFD, OldDecl))
3494        return NewFD->setInvalidDecl();
3495
3496      Previous.clear();
3497      Previous.addDecl(OldDecl);
3498
3499      if (FunctionTemplateDecl *OldTemplateDecl
3500                                    = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
3501        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
3502        FunctionTemplateDecl *NewTemplateDecl
3503          = NewFD->getDescribedFunctionTemplate();
3504        assert(NewTemplateDecl && "Template/non-template mismatch");
3505        if (CXXMethodDecl *Method
3506              = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
3507          Method->setAccess(OldTemplateDecl->getAccess());
3508          NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
3509        }
3510
3511        // If this is an explicit specialization of a member that is a function
3512        // template, mark it as a member specialization.
3513        if (IsExplicitSpecialization &&
3514            NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
3515          NewTemplateDecl->setMemberSpecialization();
3516          assert(OldTemplateDecl->isMemberSpecialization());
3517        }
3518      } else {
3519        if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
3520          NewFD->setAccess(OldDecl->getAccess());
3521        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
3522      }
3523    }
3524  }
3525
3526  // Semantic checking for this function declaration (in isolation).
3527  if (getLangOptions().CPlusPlus) {
3528    // C++-specific checks.
3529    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
3530      CheckConstructor(Constructor);
3531    } else if (CXXDestructorDecl *Destructor =
3532                dyn_cast<CXXDestructorDecl>(NewFD)) {
3533      CXXRecordDecl *Record = Destructor->getParent();
3534      QualType ClassType = Context.getTypeDeclType(Record);
3535
3536      // FIXME: Shouldn't we be able to perform thisc heck even when the class
3537      // type is dependent? Both gcc and edg can handle that.
3538      if (!ClassType->isDependentType()) {
3539        DeclarationName Name
3540          = Context.DeclarationNames.getCXXDestructorName(
3541                                        Context.getCanonicalType(ClassType));
3542        if (NewFD->getDeclName() != Name) {
3543          Diag(NewFD->getLocation(), diag::err_destructor_name);
3544          return NewFD->setInvalidDecl();
3545        }
3546      }
3547
3548      Record->setUserDeclaredDestructor(true);
3549      // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
3550      // user-defined destructor.
3551      Record->setPOD(false);
3552
3553      // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
3554      // declared destructor.
3555      // FIXME: C++0x: don't do this for "= default" destructors
3556      Record->setHasTrivialDestructor(false);
3557    } else if (CXXConversionDecl *Conversion
3558               = dyn_cast<CXXConversionDecl>(NewFD)) {
3559      ActOnConversionDeclarator(Conversion);
3560    }
3561
3562    // Find any virtual functions that this function overrides.
3563    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
3564      if (!Method->isFunctionTemplateSpecialization() &&
3565          !Method->getDescribedFunctionTemplate())
3566        AddOverriddenMethods(Method->getParent(), Method);
3567    }
3568
3569    // Additional checks for the destructor; make sure we do this after we
3570    // figure out whether the destructor is virtual.
3571    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
3572      if (!Destructor->getParent()->isDependentType())
3573        CheckDestructor(Destructor);
3574
3575    // Extra checking for C++ overloaded operators (C++ [over.oper]).
3576    if (NewFD->isOverloadedOperator() &&
3577        CheckOverloadedOperatorDeclaration(NewFD))
3578      return NewFD->setInvalidDecl();
3579
3580    // Extra checking for C++0x literal operators (C++0x [over.literal]).
3581    if (NewFD->getLiteralIdentifier() &&
3582        CheckLiteralOperatorDeclaration(NewFD))
3583      return NewFD->setInvalidDecl();
3584
3585    // In C++, check default arguments now that we have merged decls. Unless
3586    // the lexical context is the class, because in this case this is done
3587    // during delayed parsing anyway.
3588    if (!CurContext->isRecord())
3589      CheckCXXDefaultArguments(NewFD);
3590  }
3591}
3592
3593void Sema::CheckMain(FunctionDecl* FD) {
3594  // C++ [basic.start.main]p3:  A program that declares main to be inline
3595  //   or static is ill-formed.
3596  // C99 6.7.4p4:  In a hosted environment, the inline function specifier
3597  //   shall not appear in a declaration of main.
3598  // static main is not an error under C99, but we should warn about it.
3599  bool isInline = FD->isInlineSpecified();
3600  bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
3601  if (isInline || isStatic) {
3602    unsigned diagID = diag::warn_unusual_main_decl;
3603    if (isInline || getLangOptions().CPlusPlus)
3604      diagID = diag::err_unusual_main_decl;
3605
3606    int which = isStatic + (isInline << 1) - 1;
3607    Diag(FD->getLocation(), diagID) << which;
3608  }
3609
3610  QualType T = FD->getType();
3611  assert(T->isFunctionType() && "function decl is not of function type");
3612  const FunctionType* FT = T->getAs<FunctionType>();
3613
3614  if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
3615    // TODO: add a replacement fixit to turn the return type into 'int'.
3616    Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
3617    FD->setInvalidDecl(true);
3618  }
3619
3620  // Treat protoless main() as nullary.
3621  if (isa<FunctionNoProtoType>(FT)) return;
3622
3623  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
3624  unsigned nparams = FTP->getNumArgs();
3625  assert(FD->getNumParams() == nparams);
3626
3627  bool HasExtraParameters = (nparams > 3);
3628
3629  // Darwin passes an undocumented fourth argument of type char**.  If
3630  // other platforms start sprouting these, the logic below will start
3631  // getting shifty.
3632  if (nparams == 4 &&
3633      Context.Target.getTriple().getOS() == llvm::Triple::Darwin)
3634    HasExtraParameters = false;
3635
3636  if (HasExtraParameters) {
3637    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
3638    FD->setInvalidDecl(true);
3639    nparams = 3;
3640  }
3641
3642  // FIXME: a lot of the following diagnostics would be improved
3643  // if we had some location information about types.
3644
3645  QualType CharPP =
3646    Context.getPointerType(Context.getPointerType(Context.CharTy));
3647  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
3648
3649  for (unsigned i = 0; i < nparams; ++i) {
3650    QualType AT = FTP->getArgType(i);
3651
3652    bool mismatch = true;
3653
3654    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
3655      mismatch = false;
3656    else if (Expected[i] == CharPP) {
3657      // As an extension, the following forms are okay:
3658      //   char const **
3659      //   char const * const *
3660      //   char * const *
3661
3662      QualifierCollector qs;
3663      const PointerType* PT;
3664      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
3665          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
3666          (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
3667        qs.removeConst();
3668        mismatch = !qs.empty();
3669      }
3670    }
3671
3672    if (mismatch) {
3673      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
3674      // TODO: suggest replacing given type with expected type
3675      FD->setInvalidDecl(true);
3676    }
3677  }
3678
3679  if (nparams == 1 && !FD->isInvalidDecl()) {
3680    Diag(FD->getLocation(), diag::warn_main_one_arg);
3681  }
3682}
3683
3684bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
3685  // FIXME: Need strict checking.  In C89, we need to check for
3686  // any assignment, increment, decrement, function-calls, or
3687  // commas outside of a sizeof.  In C99, it's the same list,
3688  // except that the aforementioned are allowed in unevaluated
3689  // expressions.  Everything else falls under the
3690  // "may accept other forms of constant expressions" exception.
3691  // (We never end up here for C++, so the constant expression
3692  // rules there don't matter.)
3693  if (Init->isConstantInitializer(Context))
3694    return false;
3695  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
3696    << Init->getSourceRange();
3697  return true;
3698}
3699
3700void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
3701  AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
3702}
3703
3704/// AddInitializerToDecl - Adds the initializer Init to the
3705/// declaration dcl. If DirectInit is true, this is C++ direct
3706/// initialization rather than copy initialization.
3707void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
3708  Decl *RealDecl = dcl.getAs<Decl>();
3709  // If there is no declaration, there was an error parsing it.  Just ignore
3710  // the initializer.
3711  if (RealDecl == 0)
3712    return;
3713
3714  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
3715    // With declarators parsed the way they are, the parser cannot
3716    // distinguish between a normal initializer and a pure-specifier.
3717    // Thus this grotesque test.
3718    IntegerLiteral *IL;
3719    Expr *Init = static_cast<Expr *>(init.get());
3720    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
3721        Context.getCanonicalType(IL->getType()) == Context.IntTy)
3722      CheckPureMethod(Method, Init->getSourceRange());
3723    else {
3724      Diag(Method->getLocation(), diag::err_member_function_initialization)
3725        << Method->getDeclName() << Init->getSourceRange();
3726      Method->setInvalidDecl();
3727    }
3728    return;
3729  }
3730
3731  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3732  if (!VDecl) {
3733    if (getLangOptions().CPlusPlus &&
3734        RealDecl->getLexicalDeclContext()->isRecord() &&
3735        isa<NamedDecl>(RealDecl))
3736      Diag(RealDecl->getLocation(), diag::err_member_initialization)
3737        << cast<NamedDecl>(RealDecl)->getDeclName();
3738    else
3739      Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3740    RealDecl->setInvalidDecl();
3741    return;
3742  }
3743
3744  // A definition must end up with a complete type, which means it must be
3745  // complete with the restriction that an array type might be completed by the
3746  // initializer; note that later code assumes this restriction.
3747  QualType BaseDeclType = VDecl->getType();
3748  if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
3749    BaseDeclType = Array->getElementType();
3750  if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
3751                          diag::err_typecheck_decl_incomplete_type)) {
3752    RealDecl->setInvalidDecl();
3753    return;
3754  }
3755
3756  // The variable can not have an abstract class type.
3757  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
3758                             diag::err_abstract_type_in_decl,
3759                             AbstractVariableType))
3760    VDecl->setInvalidDecl();
3761
3762  const VarDecl *Def;
3763  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
3764    Diag(VDecl->getLocation(), diag::err_redefinition)
3765      << VDecl->getDeclName();
3766    Diag(Def->getLocation(), diag::note_previous_definition);
3767    VDecl->setInvalidDecl();
3768    return;
3769  }
3770
3771  // Take ownership of the expression, now that we're sure we have somewhere
3772  // to put it.
3773  Expr *Init = init.takeAs<Expr>();
3774  assert(Init && "missing initializer");
3775
3776  // Capture the variable that is being initialized and the style of
3777  // initialization.
3778  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
3779
3780  // FIXME: Poor source location information.
3781  InitializationKind Kind
3782    = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
3783                                                   Init->getLocStart(),
3784                                                   Init->getLocEnd())
3785                : InitializationKind::CreateCopy(VDecl->getLocation(),
3786                                                 Init->getLocStart());
3787
3788  // Get the decls type and save a reference for later, since
3789  // CheckInitializerTypes may change it.
3790  QualType DclT = VDecl->getType(), SavT = DclT;
3791  if (VDecl->isBlockVarDecl()) {
3792    if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
3793      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
3794      VDecl->setInvalidDecl();
3795    } else if (!VDecl->isInvalidDecl()) {
3796      InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3797      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3798                                          MultiExprArg(*this, (void**)&Init, 1),
3799                                                &DclT);
3800      if (Result.isInvalid()) {
3801        VDecl->setInvalidDecl();
3802        return;
3803      }
3804
3805      Init = Result.takeAs<Expr>();
3806
3807      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3808      // Don't check invalid declarations to avoid emitting useless diagnostics.
3809      if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3810        if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
3811          CheckForConstantInitializer(Init, DclT);
3812      }
3813    }
3814  } else if (VDecl->isStaticDataMember() &&
3815             VDecl->getLexicalDeclContext()->isRecord()) {
3816    // This is an in-class initialization for a static data member, e.g.,
3817    //
3818    // struct S {
3819    //   static const int value = 17;
3820    // };
3821
3822    // Attach the initializer
3823    VDecl->setInit(Init);
3824
3825    // C++ [class.mem]p4:
3826    //   A member-declarator can contain a constant-initializer only
3827    //   if it declares a static member (9.4) of const integral or
3828    //   const enumeration type, see 9.4.2.
3829    QualType T = VDecl->getType();
3830    if (!T->isDependentType() &&
3831        (!Context.getCanonicalType(T).isConstQualified() ||
3832         !T->isIntegralType())) {
3833      Diag(VDecl->getLocation(), diag::err_member_initialization)
3834        << VDecl->getDeclName() << Init->getSourceRange();
3835      VDecl->setInvalidDecl();
3836    } else {
3837      // C++ [class.static.data]p4:
3838      //   If a static data member is of const integral or const
3839      //   enumeration type, its declaration in the class definition
3840      //   can specify a constant-initializer which shall be an
3841      //   integral constant expression (5.19).
3842      if (!Init->isTypeDependent() &&
3843          !Init->getType()->isIntegralType()) {
3844        // We have a non-dependent, non-integral or enumeration type.
3845        Diag(Init->getSourceRange().getBegin(),
3846             diag::err_in_class_initializer_non_integral_type)
3847          << Init->getType() << Init->getSourceRange();
3848        VDecl->setInvalidDecl();
3849      } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
3850        // Check whether the expression is a constant expression.
3851        llvm::APSInt Value;
3852        SourceLocation Loc;
3853        if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
3854          Diag(Loc, diag::err_in_class_initializer_non_constant)
3855            << Init->getSourceRange();
3856          VDecl->setInvalidDecl();
3857        } else if (!VDecl->getType()->isDependentType())
3858          ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
3859      }
3860    }
3861  } else if (VDecl->isFileVarDecl()) {
3862    if (VDecl->getStorageClass() == VarDecl::Extern &&
3863        (!getLangOptions().CPlusPlus ||
3864         !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
3865      Diag(VDecl->getLocation(), diag::warn_extern_init);
3866    if (!VDecl->isInvalidDecl()) {
3867      InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3868      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3869                                          MultiExprArg(*this, (void**)&Init, 1),
3870                                                &DclT);
3871      if (Result.isInvalid()) {
3872        VDecl->setInvalidDecl();
3873        return;
3874      }
3875
3876      Init = Result.takeAs<Expr>();
3877    }
3878
3879    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3880    // Don't check invalid declarations to avoid emitting useless diagnostics.
3881    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3882      // C99 6.7.8p4. All file scoped initializers need to be constant.
3883      CheckForConstantInitializer(Init, DclT);
3884    }
3885  }
3886  // If the type changed, it means we had an incomplete type that was
3887  // completed by the initializer. For example:
3888  //   int ary[] = { 1, 3, 5 };
3889  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
3890  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
3891    VDecl->setType(DclT);
3892    Init->setType(DclT);
3893  }
3894
3895  Init = MaybeCreateCXXExprWithTemporaries(Init);
3896  // Attach the initializer to the decl.
3897  VDecl->setInit(Init);
3898
3899  if (getLangOptions().CPlusPlus) {
3900    // Make sure we mark the destructor as used if necessary.
3901    QualType InitType = VDecl->getType();
3902    while (const ArrayType *Array = Context.getAsArrayType(InitType))
3903      InitType = Context.getBaseElementType(Array);
3904    if (const RecordType *Record = InitType->getAs<RecordType>())
3905      FinalizeVarWithDestructor(VDecl, Record);
3906  }
3907
3908  return;
3909}
3910
3911/// ActOnInitializerError - Given that there was an error parsing an
3912/// initializer for the given declaration, try to return to some form
3913/// of sanity.
3914void Sema::ActOnInitializerError(DeclPtrTy dcl) {
3915  // Our main concern here is re-establishing invariants like "a
3916  // variable's type is either dependent or complete".
3917  Decl *D = dcl.getAs<Decl>();
3918  if (!D || D->isInvalidDecl()) return;
3919
3920  VarDecl *VD = dyn_cast<VarDecl>(D);
3921  if (!VD) return;
3922
3923  QualType Ty = VD->getType();
3924  if (Ty->isDependentType()) return;
3925
3926  // Require a complete type.
3927  if (RequireCompleteType(VD->getLocation(),
3928                          Context.getBaseElementType(Ty),
3929                          diag::err_typecheck_decl_incomplete_type)) {
3930    VD->setInvalidDecl();
3931    return;
3932  }
3933
3934  // Require an abstract type.
3935  if (RequireNonAbstractType(VD->getLocation(), Ty,
3936                             diag::err_abstract_type_in_decl,
3937                             AbstractVariableType)) {
3938    VD->setInvalidDecl();
3939    return;
3940  }
3941
3942  // Don't bother complaining about constructors or destructors,
3943  // though.
3944}
3945
3946void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
3947                                  bool TypeContainsUndeducedAuto) {
3948  Decl *RealDecl = dcl.getAs<Decl>();
3949
3950  // If there is no declaration, there was an error parsing it. Just ignore it.
3951  if (RealDecl == 0)
3952    return;
3953
3954  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
3955    QualType Type = Var->getType();
3956
3957    // C++0x [dcl.spec.auto]p3
3958    if (TypeContainsUndeducedAuto) {
3959      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
3960        << Var->getDeclName() << Type;
3961      Var->setInvalidDecl();
3962      return;
3963    }
3964
3965    switch (Var->isThisDeclarationADefinition()) {
3966    case VarDecl::Definition:
3967      if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
3968        break;
3969
3970      // We have an out-of-line definition of a static data member
3971      // that has an in-class initializer, so we type-check this like
3972      // a declaration.
3973      //
3974      // Fall through
3975
3976    case VarDecl::DeclarationOnly:
3977      // It's only a declaration.
3978
3979      // Block scope. C99 6.7p7: If an identifier for an object is
3980      // declared with no linkage (C99 6.2.2p6), the type for the
3981      // object shall be complete.
3982      if (!Type->isDependentType() && Var->isBlockVarDecl() &&
3983          !Var->getLinkage() && !Var->isInvalidDecl() &&
3984          RequireCompleteType(Var->getLocation(), Type,
3985                              diag::err_typecheck_decl_incomplete_type))
3986        Var->setInvalidDecl();
3987
3988      // Make sure that the type is not abstract.
3989      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
3990          RequireNonAbstractType(Var->getLocation(), Type,
3991                                 diag::err_abstract_type_in_decl,
3992                                 AbstractVariableType))
3993        Var->setInvalidDecl();
3994      return;
3995
3996    case VarDecl::TentativeDefinition:
3997      // File scope. C99 6.9.2p2: A declaration of an identifier for an
3998      // object that has file scope without an initializer, and without a
3999      // storage-class specifier or with the storage-class specifier "static",
4000      // constitutes a tentative definition. Note: A tentative definition with
4001      // external linkage is valid (C99 6.2.2p5).
4002      if (!Var->isInvalidDecl()) {
4003        if (const IncompleteArrayType *ArrayT
4004                                    = Context.getAsIncompleteArrayType(Type)) {
4005          if (RequireCompleteType(Var->getLocation(),
4006                                  ArrayT->getElementType(),
4007                                  diag::err_illegal_decl_array_incomplete_type))
4008            Var->setInvalidDecl();
4009        } else if (Var->getStorageClass() == VarDecl::Static) {
4010          // C99 6.9.2p3: If the declaration of an identifier for an object is
4011          // a tentative definition and has internal linkage (C99 6.2.2p3), the
4012          // declared type shall not be an incomplete type.
4013          // NOTE: code such as the following
4014          //     static struct s;
4015          //     struct s { int a; };
4016          // is accepted by gcc. Hence here we issue a warning instead of
4017          // an error and we do not invalidate the static declaration.
4018          // NOTE: to avoid multiple warnings, only check the first declaration.
4019          if (Var->getPreviousDeclaration() == 0)
4020            RequireCompleteType(Var->getLocation(), Type,
4021                                diag::ext_typecheck_decl_incomplete_type);
4022        }
4023      }
4024
4025      // Record the tentative definition; we're done.
4026      if (!Var->isInvalidDecl())
4027        TentativeDefinitions.push_back(Var);
4028      return;
4029    }
4030
4031    // Provide a specific diagnostic for uninitialized variable
4032    // definitions with incomplete array type.
4033    if (Type->isIncompleteArrayType()) {
4034      Diag(Var->getLocation(),
4035           diag::err_typecheck_incomplete_array_needs_initializer);
4036      Var->setInvalidDecl();
4037      return;
4038    }
4039
4040   // Provide a specific diagnostic for uninitialized variable
4041   // definitions with reference type.
4042   if (Type->isReferenceType()) {
4043     Diag(Var->getLocation(), diag::err_reference_var_requires_init)
4044       << Var->getDeclName()
4045       << SourceRange(Var->getLocation(), Var->getLocation());
4046     Var->setInvalidDecl();
4047     return;
4048   }
4049
4050    // Do not attempt to type-check the default initializer for a
4051    // variable with dependent type.
4052    if (Type->isDependentType())
4053      return;
4054
4055    if (Var->isInvalidDecl())
4056      return;
4057
4058    if (RequireCompleteType(Var->getLocation(),
4059                            Context.getBaseElementType(Type),
4060                            diag::err_typecheck_decl_incomplete_type)) {
4061      Var->setInvalidDecl();
4062      return;
4063    }
4064
4065    // The variable can not have an abstract class type.
4066    if (RequireNonAbstractType(Var->getLocation(), Type,
4067                               diag::err_abstract_type_in_decl,
4068                               AbstractVariableType)) {
4069      Var->setInvalidDecl();
4070      return;
4071    }
4072
4073    const RecordType *Record
4074      = Context.getBaseElementType(Type)->getAs<RecordType>();
4075    if (Record && getLangOptions().CPlusPlus && !getLangOptions().CPlusPlus0x &&
4076        cast<CXXRecordDecl>(Record->getDecl())->isPOD()) {
4077      // C++03 [dcl.init]p9:
4078      //   If no initializer is specified for an object, and the
4079      //   object is of (possibly cv-qualified) non-POD class type (or
4080      //   array thereof), the object shall be default-initialized; if
4081      //   the object is of const-qualified type, the underlying class
4082      //   type shall have a user-declared default
4083      //   constructor. Otherwise, if no initializer is specified for
4084      //   a non- static object, the object and its subobjects, if
4085      //   any, have an indeterminate initial value); if the object
4086      //   or any of its subobjects are of const-qualified type, the
4087      //   program is ill-formed.
4088      // FIXME: DPG thinks it is very fishy that C++0x disables this.
4089    } else {
4090      InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
4091      InitializationKind Kind
4092        = InitializationKind::CreateDefault(Var->getLocation());
4093
4094      InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
4095      OwningExprResult Init = InitSeq.Perform(*this, Entity, Kind,
4096                                              MultiExprArg(*this, 0, 0));
4097      if (Init.isInvalid())
4098        Var->setInvalidDecl();
4099      else if (Init.get())
4100        Var->setInit(MaybeCreateCXXExprWithTemporaries(Init.takeAs<Expr>()));
4101    }
4102
4103    if (!Var->isInvalidDecl() && getLangOptions().CPlusPlus && Record)
4104      FinalizeVarWithDestructor(Var, Record);
4105  }
4106}
4107
4108Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4109                                                   DeclPtrTy *Group,
4110                                                   unsigned NumDecls) {
4111  llvm::SmallVector<Decl*, 8> Decls;
4112
4113  if (DS.isTypeSpecOwned())
4114    Decls.push_back((Decl*)DS.getTypeRep());
4115
4116  for (unsigned i = 0; i != NumDecls; ++i)
4117    if (Decl *D = Group[i].getAs<Decl>())
4118      Decls.push_back(D);
4119
4120  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
4121                                                   Decls.data(), Decls.size()));
4122}
4123
4124
4125/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4126/// to introduce parameters into function prototype scope.
4127Sema::DeclPtrTy
4128Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
4129  const DeclSpec &DS = D.getDeclSpec();
4130
4131  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
4132  VarDecl::StorageClass StorageClass = VarDecl::None;
4133  VarDecl::StorageClass StorageClassAsWritten = VarDecl::None;
4134  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4135    StorageClass = VarDecl::Register;
4136    StorageClassAsWritten = VarDecl::Register;
4137  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
4138    Diag(DS.getStorageClassSpecLoc(),
4139         diag::err_invalid_storage_class_in_func_decl);
4140    D.getMutableDeclSpec().ClearStorageClassSpecs();
4141  }
4142
4143  if (D.getDeclSpec().isThreadSpecified())
4144    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4145
4146  DiagnoseFunctionSpecifiers(D);
4147
4148  // Check that there are no default arguments inside the type of this
4149  // parameter (C++ only).
4150  if (getLangOptions().CPlusPlus)
4151    CheckExtraCXXDefaultArguments(D);
4152
4153  TypeSourceInfo *TInfo = 0;
4154  TagDecl *OwnedDecl = 0;
4155  QualType parmDeclType = GetTypeForDeclarator(D, S, &TInfo, &OwnedDecl);
4156
4157  if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
4158    // C++ [dcl.fct]p6:
4159    //   Types shall not be defined in return or parameter types.
4160    Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
4161      << Context.getTypeDeclType(OwnedDecl);
4162  }
4163
4164  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
4165  IdentifierInfo *II = D.getIdentifier();
4166  if (II) {
4167    LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
4168                   ForRedeclaration);
4169    LookupName(R, S);
4170    if (R.isSingleResult()) {
4171      NamedDecl *PrevDecl = R.getFoundDecl();
4172      if (PrevDecl->isTemplateParameter()) {
4173        // Maybe we will complain about the shadowed template parameter.
4174        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4175        // Just pretend that we didn't see the previous declaration.
4176        PrevDecl = 0;
4177      } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
4178        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
4179        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4180
4181        // Recover by removing the name
4182        II = 0;
4183        D.SetIdentifier(0, D.getIdentifierLoc());
4184        D.setInvalidType(true);
4185      }
4186    }
4187  }
4188
4189  // Temporarily put parameter variables in the translation unit, not
4190  // the enclosing context.  This prevents them from accidentally
4191  // looking like class members in C++.
4192  ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
4193                                    TInfo, parmDeclType, II,
4194                                    D.getIdentifierLoc(),
4195                                    StorageClass, StorageClassAsWritten);
4196
4197  if (D.isInvalidType())
4198    New->setInvalidDecl();
4199
4200  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4201  if (D.getCXXScopeSpec().isSet()) {
4202    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
4203      << D.getCXXScopeSpec().getRange();
4204    New->setInvalidDecl();
4205  }
4206
4207  // Add the parameter declaration into this scope.
4208  S->AddDecl(DeclPtrTy::make(New));
4209  if (II)
4210    IdResolver.AddDecl(New);
4211
4212  ProcessDeclAttributes(S, New, D);
4213
4214  if (New->hasAttr<BlocksAttr>()) {
4215    Diag(New->getLocation(), diag::err_block_on_nonlocal);
4216  }
4217  return DeclPtrTy::make(New);
4218}
4219
4220ParmVarDecl *Sema::CheckParameter(DeclContext *DC,
4221                                  TypeSourceInfo *TSInfo, QualType T,
4222                                  IdentifierInfo *Name,
4223                                  SourceLocation NameLoc,
4224                                  VarDecl::StorageClass StorageClass,
4225                                  VarDecl::StorageClass StorageClassAsWritten) {
4226  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, NameLoc, Name,
4227                                         adjustParameterType(T), TSInfo,
4228                                         StorageClass, StorageClassAsWritten,
4229                                         0);
4230
4231  // Parameters can not be abstract class types.
4232  // For record types, this is done by the AbstractClassUsageDiagnoser once
4233  // the class has been completely parsed.
4234  if (!CurContext->isRecord() &&
4235      RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
4236                             AbstractParamType))
4237    New->setInvalidDecl();
4238
4239  // Parameter declarators cannot be interface types. All ObjC objects are
4240  // passed by reference.
4241  if (T->isObjCInterfaceType()) {
4242    Diag(NameLoc,
4243         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
4244    New->setInvalidDecl();
4245  }
4246
4247  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4248  // duration shall not be qualified by an address-space qualifier."
4249  // Since all parameters have automatic store duration, they can not have
4250  // an address space.
4251  if (T.getAddressSpace() != 0) {
4252    Diag(NameLoc, diag::err_arg_with_address_space);
4253    New->setInvalidDecl();
4254  }
4255
4256  return New;
4257}
4258
4259void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4260                                           SourceLocation LocAfterDecls) {
4261  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4262         "Not a function declarator!");
4263  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4264
4265  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
4266  // for a K&R function.
4267  if (!FTI.hasPrototype) {
4268    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
4269      --i;
4270      if (FTI.ArgInfo[i].Param == 0) {
4271        llvm::SmallString<256> Code;
4272        llvm::raw_svector_ostream(Code) << "  int "
4273                                        << FTI.ArgInfo[i].Ident->getName()
4274                                        << ";\n";
4275        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
4276          << FTI.ArgInfo[i].Ident
4277          << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
4278
4279        // Implicitly declare the argument as type 'int' for lack of a better
4280        // type.
4281        DeclSpec DS;
4282        const char* PrevSpec; // unused
4283        unsigned DiagID; // unused
4284        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
4285                           PrevSpec, DiagID);
4286        Declarator ParamD(DS, Declarator::KNRTypeListContext);
4287        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
4288        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
4289      }
4290    }
4291  }
4292}
4293
4294Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
4295                                              Declarator &D) {
4296  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4297  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4298         "Not a function declarator!");
4299  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4300
4301  if (FTI.hasPrototype) {
4302    // FIXME: Diagnose arguments without names in C.
4303  }
4304
4305  Scope *ParentScope = FnBodyScope->getParent();
4306
4307  DeclPtrTy DP = HandleDeclarator(ParentScope, D,
4308                                  MultiTemplateParamsArg(*this),
4309                                  /*IsFunctionDefinition=*/true);
4310  return ActOnStartOfFunctionDef(FnBodyScope, DP);
4311}
4312
4313static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
4314  // Don't warn about invalid declarations.
4315  if (FD->isInvalidDecl())
4316    return false;
4317
4318  // Or declarations that aren't global.
4319  if (!FD->isGlobal())
4320    return false;
4321
4322  // Don't warn about C++ member functions.
4323  if (isa<CXXMethodDecl>(FD))
4324    return false;
4325
4326  // Don't warn about 'main'.
4327  if (FD->isMain())
4328    return false;
4329
4330  // Don't warn about inline functions.
4331  if (FD->isInlineSpecified())
4332    return false;
4333
4334  // Don't warn about function templates.
4335  if (FD->getDescribedFunctionTemplate())
4336    return false;
4337
4338  // Don't warn about function template specializations.
4339  if (FD->isFunctionTemplateSpecialization())
4340    return false;
4341
4342  bool MissingPrototype = true;
4343  for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
4344       Prev; Prev = Prev->getPreviousDeclaration()) {
4345    // Ignore any declarations that occur in function or method
4346    // scope, because they aren't visible from the header.
4347    if (Prev->getDeclContext()->isFunctionOrMethod())
4348      continue;
4349
4350    MissingPrototype = !Prev->getType()->isFunctionProtoType();
4351    break;
4352  }
4353
4354  return MissingPrototype;
4355}
4356
4357Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
4358  // Clear the last template instantiation error context.
4359  LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
4360
4361  if (!D)
4362    return D;
4363  FunctionDecl *FD = 0;
4364
4365  if (FunctionTemplateDecl *FunTmpl
4366        = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
4367    FD = FunTmpl->getTemplatedDecl();
4368  else
4369    FD = cast<FunctionDecl>(D.getAs<Decl>());
4370
4371  // Enter a new function scope
4372  PushFunctionScope();
4373
4374  // See if this is a redefinition.
4375  // But don't complain if we're in GNU89 mode and the previous definition
4376  // was an extern inline function.
4377  const FunctionDecl *Definition;
4378  if (FD->getBody(Definition) &&
4379      !canRedefineFunction(Definition, getLangOptions())) {
4380    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
4381    Diag(Definition->getLocation(), diag::note_previous_definition);
4382  }
4383
4384  // Builtin functions cannot be defined.
4385  if (unsigned BuiltinID = FD->getBuiltinID()) {
4386    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4387      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
4388      FD->setInvalidDecl();
4389    }
4390  }
4391
4392  // The return type of a function definition must be complete
4393  // (C99 6.9.1p3, C++ [dcl.fct]p6).
4394  QualType ResultType = FD->getResultType();
4395  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
4396      !FD->isInvalidDecl() &&
4397      RequireCompleteType(FD->getLocation(), ResultType,
4398                          diag::err_func_def_incomplete_result))
4399    FD->setInvalidDecl();
4400
4401  // GNU warning -Wmissing-prototypes:
4402  //   Warn if a global function is defined without a previous
4403  //   prototype declaration. This warning is issued even if the
4404  //   definition itself provides a prototype. The aim is to detect
4405  //   global functions that fail to be declared in header files.
4406  if (ShouldWarnAboutMissingPrototype(FD))
4407    Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
4408
4409  if (FnBodyScope)
4410    PushDeclContext(FnBodyScope, FD);
4411
4412  // Check the validity of our function parameters
4413  CheckParmsForFunctionDef(FD);
4414
4415  bool ShouldCheckShadow =
4416    Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
4417
4418  // Introduce our parameters into the function scope
4419  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
4420    ParmVarDecl *Param = FD->getParamDecl(p);
4421    Param->setOwningFunction(FD);
4422
4423    // If this has an identifier, add it to the scope stack.
4424    if (Param->getIdentifier() && FnBodyScope) {
4425      if (ShouldCheckShadow)
4426        CheckShadow(FnBodyScope, Param);
4427
4428      PushOnScopeChains(Param, FnBodyScope);
4429    }
4430  }
4431
4432  // Checking attributes of current function definition
4433  // dllimport attribute.
4434  if (FD->getAttr<DLLImportAttr>() &&
4435      (!FD->getAttr<DLLExportAttr>())) {
4436    // dllimport attribute cannot be applied to definition.
4437    if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
4438      Diag(FD->getLocation(),
4439           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
4440        << "dllimport";
4441      FD->setInvalidDecl();
4442      return DeclPtrTy::make(FD);
4443    }
4444
4445    // Visual C++ appears to not think this is an issue, so only issue
4446    // a warning when Microsoft extensions are disabled.
4447    if (!LangOpts.Microsoft) {
4448      // If a symbol previously declared dllimport is later defined, the
4449      // attribute is ignored in subsequent references, and a warning is
4450      // emitted.
4451      Diag(FD->getLocation(),
4452           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4453        << FD->getNameAsCString() << "dllimport";
4454    }
4455  }
4456  return DeclPtrTy::make(FD);
4457}
4458
4459Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
4460  return ActOnFinishFunctionBody(D, move(BodyArg), false);
4461}
4462
4463Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
4464                                              bool IsInstantiation) {
4465  Decl *dcl = D.getAs<Decl>();
4466  Stmt *Body = BodyArg.takeAs<Stmt>();
4467
4468  FunctionDecl *FD = 0;
4469  FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
4470  if (FunTmpl)
4471    FD = FunTmpl->getTemplatedDecl();
4472  else
4473    FD = dyn_cast_or_null<FunctionDecl>(dcl);
4474
4475  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
4476
4477  if (FD) {
4478    FD->setBody(Body);
4479    if (FD->isMain()) {
4480      // C and C++ allow for main to automagically return 0.
4481      // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
4482      FD->setHasImplicitReturnZero(true);
4483      WP.disableCheckFallThrough();
4484    }
4485
4486    if (!FD->isInvalidDecl())
4487      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
4488
4489    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
4490      MaybeMarkVirtualMembersReferenced(Method->getLocation(), Method);
4491
4492    assert(FD == getCurFunctionDecl() && "Function parsing confused");
4493  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
4494    assert(MD == getCurMethodDecl() && "Method parsing confused");
4495    MD->setBody(Body);
4496    MD->setEndLoc(Body->getLocEnd());
4497    if (!MD->isInvalidDecl())
4498      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
4499  } else {
4500    Body->Destroy(Context);
4501    return DeclPtrTy();
4502  }
4503
4504  // Verify and clean out per-function state.
4505
4506  // Check goto/label use.
4507  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
4508       I = getLabelMap().begin(), E = getLabelMap().end(); I != E; ++I) {
4509    LabelStmt *L = I->second;
4510
4511    // Verify that we have no forward references left.  If so, there was a goto
4512    // or address of a label taken, but no definition of it.  Label fwd
4513    // definitions are indicated with a null substmt.
4514    if (L->getSubStmt() != 0)
4515      continue;
4516
4517    // Emit error.
4518    Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
4519
4520    // At this point, we have gotos that use the bogus label.  Stitch it into
4521    // the function body so that they aren't leaked and that the AST is well
4522    // formed.
4523    if (Body == 0) {
4524      // The whole function wasn't parsed correctly, just delete this.
4525      L->Destroy(Context);
4526      continue;
4527    }
4528
4529    // Otherwise, the body is valid: we want to stitch the label decl into the
4530    // function somewhere so that it is properly owned and so that the goto
4531    // has a valid target.  Do this by creating a new compound stmt with the
4532    // label in it.
4533
4534    // Give the label a sub-statement.
4535    L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
4536
4537    CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
4538                               cast<CXXTryStmt>(Body)->getTryBlock() :
4539                               cast<CompoundStmt>(Body);
4540    llvm::SmallVector<Stmt*, 64> Elements(Compound->body_begin(),
4541                                          Compound->body_end());
4542    Elements.push_back(L);
4543    Compound->setStmts(Context, Elements.data(), Elements.size());
4544  }
4545
4546  if (Body) {
4547    // C++ constructors that have function-try-blocks can't have return
4548    // statements in the handlers of that block. (C++ [except.handle]p14)
4549    // Verify this.
4550    if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
4551      DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
4552
4553    // Verify that that gotos and switch cases don't jump into scopes illegally.
4554    // Verify that that gotos and switch cases don't jump into scopes illegally.
4555    if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction())
4556      DiagnoseInvalidJumps(Body);
4557
4558    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
4559      MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4560                                             Destructor->getParent());
4561
4562    // If any errors have occurred, clear out any temporaries that may have
4563    // been leftover. This ensures that these temporaries won't be picked up for
4564    // deletion in some later function.
4565    if (PP.getDiagnostics().hasErrorOccurred())
4566      ExprTemporaries.clear();
4567    else if (!isa<FunctionTemplateDecl>(dcl)) {
4568      // Since the body is valid, issue any analysis-based warnings that are
4569      // enabled.
4570      QualType ResultType;
4571      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
4572        ResultType = FD->getResultType();
4573      }
4574      else {
4575        ObjCMethodDecl *MD = cast<ObjCMethodDecl>(dcl);
4576        ResultType = MD->getResultType();
4577      }
4578      AnalysisWarnings.IssueWarnings(WP, dcl);
4579    }
4580
4581    assert(ExprTemporaries.empty() && "Leftover temporaries in function");
4582  }
4583
4584  if (!IsInstantiation)
4585    PopDeclContext();
4586
4587  PopFunctionOrBlockScope();
4588
4589  // If any errors have occurred, clear out any temporaries that may have
4590  // been leftover. This ensures that these temporaries won't be picked up for
4591  // deletion in some later function.
4592  if (getDiagnostics().hasErrorOccurred())
4593    ExprTemporaries.clear();
4594
4595  return D;
4596}
4597
4598/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4599/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4600NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
4601                                          IdentifierInfo &II, Scope *S) {
4602  // Before we produce a declaration for an implicitly defined
4603  // function, see whether there was a locally-scoped declaration of
4604  // this name as a function or variable. If so, use that
4605  // (non-visible) declaration, and complain about it.
4606  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4607    = LocallyScopedExternalDecls.find(&II);
4608  if (Pos != LocallyScopedExternalDecls.end()) {
4609    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
4610    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
4611    return Pos->second;
4612  }
4613
4614  // Extension in C99.  Legal in C90, but warn about it.
4615  if (II.getName().startswith("__builtin_"))
4616    Diag(Loc, diag::warn_builtin_unknown) << &II;
4617  else if (getLangOptions().C99)
4618    Diag(Loc, diag::ext_implicit_function_decl) << &II;
4619  else
4620    Diag(Loc, diag::warn_implicit_function_decl) << &II;
4621
4622  // Set a Declarator for the implicit definition: int foo();
4623  const char *Dummy;
4624  DeclSpec DS;
4625  unsigned DiagID;
4626  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
4627  Error = Error; // Silence warning.
4628  assert(!Error && "Error setting up implicit decl!");
4629  Declarator D(DS, Declarator::BlockContext);
4630  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
4631                                             0, 0, false, SourceLocation(),
4632                                             false, 0,0,0, Loc, Loc, D),
4633                SourceLocation());
4634  D.SetIdentifier(&II, Loc);
4635
4636  // Insert this function into translation-unit scope.
4637
4638  DeclContext *PrevDC = CurContext;
4639  CurContext = Context.getTranslationUnitDecl();
4640
4641  FunctionDecl *FD =
4642 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
4643  FD->setImplicit();
4644
4645  CurContext = PrevDC;
4646
4647  AddKnownFunctionAttributes(FD);
4648
4649  return FD;
4650}
4651
4652/// \brief Adds any function attributes that we know a priori based on
4653/// the declaration of this function.
4654///
4655/// These attributes can apply both to implicitly-declared builtins
4656/// (like __builtin___printf_chk) or to library-declared functions
4657/// like NSLog or printf.
4658void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
4659  if (FD->isInvalidDecl())
4660    return;
4661
4662  // If this is a built-in function, map its builtin attributes to
4663  // actual attributes.
4664  if (unsigned BuiltinID = FD->getBuiltinID()) {
4665    // Handle printf-formatting attributes.
4666    unsigned FormatIdx;
4667    bool HasVAListArg;
4668    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
4669      if (!FD->getAttr<FormatAttr>())
4670        FD->addAttr(::new (Context) FormatAttr(Context, "printf", FormatIdx+1,
4671                                               HasVAListArg ? 0 : FormatIdx+2));
4672    }
4673
4674    // Mark const if we don't care about errno and that is the only
4675    // thing preventing the function from being const. This allows
4676    // IRgen to use LLVM intrinsics for such functions.
4677    if (!getLangOptions().MathErrno &&
4678        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
4679      if (!FD->getAttr<ConstAttr>())
4680        FD->addAttr(::new (Context) ConstAttr());
4681    }
4682
4683    if (Context.BuiltinInfo.isNoReturn(BuiltinID))
4684      FD->setType(Context.getNoReturnType(FD->getType()));
4685    if (Context.BuiltinInfo.isNoThrow(BuiltinID))
4686      FD->addAttr(::new (Context) NoThrowAttr());
4687    if (Context.BuiltinInfo.isConst(BuiltinID))
4688      FD->addAttr(::new (Context) ConstAttr());
4689  }
4690
4691  IdentifierInfo *Name = FD->getIdentifier();
4692  if (!Name)
4693    return;
4694  if ((!getLangOptions().CPlusPlus &&
4695       FD->getDeclContext()->isTranslationUnit()) ||
4696      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
4697       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
4698       LinkageSpecDecl::lang_c)) {
4699    // Okay: this could be a libc/libm/Objective-C function we know
4700    // about.
4701  } else
4702    return;
4703
4704  if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
4705    // FIXME: NSLog and NSLogv should be target specific
4706    if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
4707      // FIXME: We known better than our headers.
4708      const_cast<FormatAttr *>(Format)->setType(Context, "printf");
4709    } else
4710      FD->addAttr(::new (Context) FormatAttr(Context, "printf", 1,
4711                                             Name->isStr("NSLogv") ? 0 : 2));
4712  } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
4713    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
4714    // target-specific builtins, perhaps?
4715    if (!FD->getAttr<FormatAttr>())
4716      FD->addAttr(::new (Context) FormatAttr(Context, "printf", 2,
4717                                             Name->isStr("vasprintf") ? 0 : 3));
4718  }
4719}
4720
4721TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4722                                    TypeSourceInfo *TInfo) {
4723  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
4724  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
4725
4726  if (!TInfo) {
4727    assert(D.isInvalidType() && "no declarator info for valid type");
4728    TInfo = Context.getTrivialTypeSourceInfo(T);
4729  }
4730
4731  // Scope manipulation handled by caller.
4732  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
4733                                           D.getIdentifierLoc(),
4734                                           D.getIdentifier(),
4735                                           TInfo);
4736
4737  if (const TagType *TT = T->getAs<TagType>()) {
4738    TagDecl *TD = TT->getDecl();
4739
4740    // If the TagDecl that the TypedefDecl points to is an anonymous decl
4741    // keep track of the TypedefDecl.
4742    if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
4743      TD->setTypedefForAnonDecl(NewTD);
4744  }
4745
4746  if (D.isInvalidType())
4747    NewTD->setInvalidDecl();
4748  return NewTD;
4749}
4750
4751
4752/// \brief Determine whether a tag with a given kind is acceptable
4753/// as a redeclaration of the given tag declaration.
4754///
4755/// \returns true if the new tag kind is acceptable, false otherwise.
4756bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
4757                                        TagDecl::TagKind NewTag,
4758                                        SourceLocation NewTagLoc,
4759                                        const IdentifierInfo &Name) {
4760  // C++ [dcl.type.elab]p3:
4761  //   The class-key or enum keyword present in the
4762  //   elaborated-type-specifier shall agree in kind with the
4763  //   declaration to which the name in theelaborated-type-specifier
4764  //   refers. This rule also applies to the form of
4765  //   elaborated-type-specifier that declares a class-name or
4766  //   friend class since it can be construed as referring to the
4767  //   definition of the class. Thus, in any
4768  //   elaborated-type-specifier, the enum keyword shall be used to
4769  //   refer to an enumeration (7.2), the union class-keyshall be
4770  //   used to refer to a union (clause 9), and either the class or
4771  //   struct class-key shall be used to refer to a class (clause 9)
4772  //   declared using the class or struct class-key.
4773  TagDecl::TagKind OldTag = Previous->getTagKind();
4774  if (OldTag == NewTag)
4775    return true;
4776
4777  if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) &&
4778      (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) {
4779    // Warn about the struct/class tag mismatch.
4780    bool isTemplate = false;
4781    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
4782      isTemplate = Record->getDescribedClassTemplate();
4783
4784    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
4785      << (NewTag == TagDecl::TK_class)
4786      << isTemplate << &Name
4787      << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
4788                              OldTag == TagDecl::TK_class? "class" : "struct");
4789    Diag(Previous->getLocation(), diag::note_previous_use);
4790    return true;
4791  }
4792  return false;
4793}
4794
4795/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
4796/// former case, Name will be non-null.  In the later case, Name will be null.
4797/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
4798/// reference/declaration/definition of a tag.
4799Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4800                               SourceLocation KWLoc, CXXScopeSpec &SS,
4801                               IdentifierInfo *Name, SourceLocation NameLoc,
4802                               AttributeList *Attr, AccessSpecifier AS,
4803                               MultiTemplateParamsArg TemplateParameterLists,
4804                               bool &OwnedDecl, bool &IsDependent) {
4805  // If this is not a definition, it must have a name.
4806  assert((Name != 0 || TUK == TUK_Definition) &&
4807         "Nameless record must be a definition!");
4808
4809  OwnedDecl = false;
4810  TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
4811
4812  // FIXME: Check explicit specializations more carefully.
4813  bool isExplicitSpecialization = false;
4814  if (TUK != TUK_Reference) {
4815    if (TemplateParameterList *TemplateParams
4816          = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
4817                        (TemplateParameterList**)TemplateParameterLists.get(),
4818                                              TemplateParameterLists.size(),
4819                                                    TUK == TUK_Friend,
4820                                                    isExplicitSpecialization)) {
4821      if (TemplateParams->size() > 0) {
4822        // This is a declaration or definition of a class template (which may
4823        // be a member of another template).
4824        OwnedDecl = false;
4825        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
4826                                               SS, Name, NameLoc, Attr,
4827                                               TemplateParams,
4828                                               AS);
4829        TemplateParameterLists.release();
4830        return Result.get();
4831      } else {
4832        // The "template<>" header is extraneous.
4833        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
4834          << ElaboratedType::getNameForTagKind(Kind) << Name;
4835        isExplicitSpecialization = true;
4836      }
4837    }
4838
4839    TemplateParameterLists.release();
4840  }
4841
4842  DeclContext *SearchDC = CurContext;
4843  DeclContext *DC = CurContext;
4844  bool isStdBadAlloc = false;
4845  bool Invalid = false;
4846
4847  RedeclarationKind Redecl = ForRedeclaration;
4848  if (TUK == TUK_Friend || TUK == TUK_Reference)
4849    Redecl = NotForRedeclaration;
4850
4851  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
4852
4853  if (Name && SS.isNotEmpty()) {
4854    // We have a nested-name tag ('struct foo::bar').
4855
4856    // Check for invalid 'foo::'.
4857    if (SS.isInvalid()) {
4858      Name = 0;
4859      goto CreateNewDecl;
4860    }
4861
4862    // If this is a friend or a reference to a class in a dependent
4863    // context, don't try to make a decl for it.
4864    if (TUK == TUK_Friend || TUK == TUK_Reference) {
4865      DC = computeDeclContext(SS, false);
4866      if (!DC) {
4867        IsDependent = true;
4868        return DeclPtrTy();
4869      }
4870    }
4871
4872    if (RequireCompleteDeclContext(SS))
4873      return DeclPtrTy::make((Decl *)0);
4874
4875    DC = computeDeclContext(SS, true);
4876    SearchDC = DC;
4877    // Look-up name inside 'foo::'.
4878    LookupQualifiedName(Previous, DC);
4879
4880    if (Previous.isAmbiguous())
4881      return DeclPtrTy();
4882
4883    if (Previous.empty()) {
4884      // Name lookup did not find anything. However, if the
4885      // nested-name-specifier refers to the current instantiation,
4886      // and that current instantiation has any dependent base
4887      // classes, we might find something at instantiation time: treat
4888      // this as a dependent elaborated-type-specifier.
4889      if (Previous.wasNotFoundInCurrentInstantiation()) {
4890        IsDependent = true;
4891        return DeclPtrTy();
4892      }
4893
4894      // A tag 'foo::bar' must already exist.
4895      Diag(NameLoc, diag::err_not_tag_in_scope)
4896        << Kind << Name << DC << SS.getRange();
4897      Name = 0;
4898      Invalid = true;
4899      goto CreateNewDecl;
4900    }
4901  } else if (Name) {
4902    // If this is a named struct, check to see if there was a previous forward
4903    // declaration or definition.
4904    // FIXME: We're looking into outer scopes here, even when we
4905    // shouldn't be. Doing so can result in ambiguities that we
4906    // shouldn't be diagnosing.
4907    LookupName(Previous, S);
4908
4909    // Note:  there used to be some attempt at recovery here.
4910    if (Previous.isAmbiguous())
4911      return DeclPtrTy();
4912
4913    if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
4914      // FIXME: This makes sure that we ignore the contexts associated
4915      // with C structs, unions, and enums when looking for a matching
4916      // tag declaration or definition. See the similar lookup tweak
4917      // in Sema::LookupName; is there a better way to deal with this?
4918      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
4919        SearchDC = SearchDC->getParent();
4920    }
4921  }
4922
4923  if (Previous.isSingleResult() &&
4924      Previous.getFoundDecl()->isTemplateParameter()) {
4925    // Maybe we will complain about the shadowed template parameter.
4926    DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
4927    // Just pretend that we didn't see the previous declaration.
4928    Previous.clear();
4929  }
4930
4931  if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
4932      DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) {
4933    // This is a declaration of or a reference to "std::bad_alloc".
4934    isStdBadAlloc = true;
4935
4936    if (Previous.empty() && StdBadAlloc) {
4937      // std::bad_alloc has been implicitly declared (but made invisible to
4938      // name lookup). Fill in this implicit declaration as the previous
4939      // declaration, so that the declarations get chained appropriately.
4940      Previous.addDecl(StdBadAlloc);
4941    }
4942  }
4943
4944  // If we didn't find a previous declaration, and this is a reference
4945  // (or friend reference), move to the correct scope.  In C++, we
4946  // also need to do a redeclaration lookup there, just in case
4947  // there's a shadow friend decl.
4948  if (Name && Previous.empty() &&
4949      (TUK == TUK_Reference || TUK == TUK_Friend)) {
4950    if (Invalid) goto CreateNewDecl;
4951    assert(SS.isEmpty());
4952
4953    if (TUK == TUK_Reference) {
4954      // C++ [basic.scope.pdecl]p5:
4955      //   -- for an elaborated-type-specifier of the form
4956      //
4957      //          class-key identifier
4958      //
4959      //      if the elaborated-type-specifier is used in the
4960      //      decl-specifier-seq or parameter-declaration-clause of a
4961      //      function defined in namespace scope, the identifier is
4962      //      declared as a class-name in the namespace that contains
4963      //      the declaration; otherwise, except as a friend
4964      //      declaration, the identifier is declared in the smallest
4965      //      non-class, non-function-prototype scope that contains the
4966      //      declaration.
4967      //
4968      // C99 6.7.2.3p8 has a similar (but not identical!) provision for
4969      // C structs and unions.
4970      //
4971      // It is an error in C++ to declare (rather than define) an enum
4972      // type, including via an elaborated type specifier.  We'll
4973      // diagnose that later; for now, declare the enum in the same
4974      // scope as we would have picked for any other tag type.
4975      //
4976      // GNU C also supports this behavior as part of its incomplete
4977      // enum types extension, while GNU C++ does not.
4978      //
4979      // Find the context where we'll be declaring the tag.
4980      // FIXME: We would like to maintain the current DeclContext as the
4981      // lexical context,
4982      while (SearchDC->isRecord())
4983        SearchDC = SearchDC->getParent();
4984
4985      // Find the scope where we'll be declaring the tag.
4986      while (S->isClassScope() ||
4987             (getLangOptions().CPlusPlus &&
4988              S->isFunctionPrototypeScope()) ||
4989             ((S->getFlags() & Scope::DeclScope) == 0) ||
4990             (S->getEntity() &&
4991              ((DeclContext *)S->getEntity())->isTransparentContext()))
4992        S = S->getParent();
4993    } else {
4994      assert(TUK == TUK_Friend);
4995      // C++ [namespace.memdef]p3:
4996      //   If a friend declaration in a non-local class first declares a
4997      //   class or function, the friend class or function is a member of
4998      //   the innermost enclosing namespace.
4999      SearchDC = SearchDC->getEnclosingNamespaceContext();
5000    }
5001
5002    // In C++, we need to do a redeclaration lookup to properly
5003    // diagnose some problems.
5004    if (getLangOptions().CPlusPlus) {
5005      Previous.setRedeclarationKind(ForRedeclaration);
5006      LookupQualifiedName(Previous, SearchDC);
5007    }
5008  }
5009
5010  if (!Previous.empty()) {
5011    NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5012
5013    // It's okay to have a tag decl in the same scope as a typedef
5014    // which hides a tag decl in the same scope.  Finding this
5015    // insanity with a redeclaration lookup can only actually happen
5016    // in C++.
5017    //
5018    // This is also okay for elaborated-type-specifiers, which is
5019    // technically forbidden by the current standard but which is
5020    // okay according to the likely resolution of an open issue;
5021    // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
5022    if (getLangOptions().CPlusPlus) {
5023      if (TypedefDecl *TD = dyn_cast<TypedefDecl>(PrevDecl)) {
5024        if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
5025          TagDecl *Tag = TT->getDecl();
5026          if (Tag->getDeclName() == Name &&
5027              Tag->getDeclContext()->Equals(TD->getDeclContext())) {
5028            PrevDecl = Tag;
5029            Previous.clear();
5030            Previous.addDecl(Tag);
5031          }
5032        }
5033      }
5034    }
5035
5036    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
5037      // If this is a use of a previous tag, or if the tag is already declared
5038      // in the same scope (so that the definition/declaration completes or
5039      // rementions the tag), reuse the decl.
5040      if (TUK == TUK_Reference || TUK == TUK_Friend ||
5041          isDeclInScope(PrevDecl, SearchDC, S)) {
5042        // Make sure that this wasn't declared as an enum and now used as a
5043        // struct or something similar.
5044        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
5045          bool SafeToContinue
5046            = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
5047               Kind != TagDecl::TK_enum);
5048          if (SafeToContinue)
5049            Diag(KWLoc, diag::err_use_with_wrong_tag)
5050              << Name
5051              << FixItHint::CreateReplacement(SourceRange(KWLoc),
5052                                              PrevTagDecl->getKindName());
5053          else
5054            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
5055          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
5056
5057          if (SafeToContinue)
5058            Kind = PrevTagDecl->getTagKind();
5059          else {
5060            // Recover by making this an anonymous redefinition.
5061            Name = 0;
5062            Previous.clear();
5063            Invalid = true;
5064          }
5065        }
5066
5067        if (!Invalid) {
5068          // If this is a use, just return the declaration we found.
5069
5070          // FIXME: In the future, return a variant or some other clue
5071          // for the consumer of this Decl to know it doesn't own it.
5072          // For our current ASTs this shouldn't be a problem, but will
5073          // need to be changed with DeclGroups.
5074          if (TUK == TUK_Reference || TUK == TUK_Friend)
5075            return DeclPtrTy::make(PrevTagDecl);
5076
5077          // Diagnose attempts to redefine a tag.
5078          if (TUK == TUK_Definition) {
5079            if (TagDecl *Def = PrevTagDecl->getDefinition()) {
5080              // If we're defining a specialization and the previous definition
5081              // is from an implicit instantiation, don't emit an error
5082              // here; we'll catch this in the general case below.
5083              if (!isExplicitSpecialization ||
5084                  !isa<CXXRecordDecl>(Def) ||
5085                  cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
5086                                               == TSK_ExplicitSpecialization) {
5087                Diag(NameLoc, diag::err_redefinition) << Name;
5088                Diag(Def->getLocation(), diag::note_previous_definition);
5089                // If this is a redefinition, recover by making this
5090                // struct be anonymous, which will make any later
5091                // references get the previous definition.
5092                Name = 0;
5093                Previous.clear();
5094                Invalid = true;
5095              }
5096            } else {
5097              // If the type is currently being defined, complain
5098              // about a nested redefinition.
5099              TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
5100              if (Tag->isBeingDefined()) {
5101                Diag(NameLoc, diag::err_nested_redefinition) << Name;
5102                Diag(PrevTagDecl->getLocation(),
5103                     diag::note_previous_definition);
5104                Name = 0;
5105                Previous.clear();
5106                Invalid = true;
5107              }
5108            }
5109
5110            // Okay, this is definition of a previously declared or referenced
5111            // tag PrevDecl. We're going to create a new Decl for it.
5112          }
5113        }
5114        // If we get here we have (another) forward declaration or we
5115        // have a definition.  Just create a new decl.
5116
5117      } else {
5118        // If we get here, this is a definition of a new tag type in a nested
5119        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
5120        // new decl/type.  We set PrevDecl to NULL so that the entities
5121        // have distinct types.
5122        Previous.clear();
5123      }
5124      // If we get here, we're going to create a new Decl. If PrevDecl
5125      // is non-NULL, it's a definition of the tag declared by
5126      // PrevDecl. If it's NULL, we have a new definition.
5127
5128
5129    // Otherwise, PrevDecl is not a tag, but was found with tag
5130    // lookup.  This is only actually possible in C++, where a few
5131    // things like templates still live in the tag namespace.
5132    } else {
5133      assert(getLangOptions().CPlusPlus);
5134
5135      // Use a better diagnostic if an elaborated-type-specifier
5136      // found the wrong kind of type on the first
5137      // (non-redeclaration) lookup.
5138      if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
5139          !Previous.isForRedeclaration()) {
5140        unsigned Kind = 0;
5141        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
5142        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
5143        Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
5144        Diag(PrevDecl->getLocation(), diag::note_declared_at);
5145        Invalid = true;
5146
5147      // Otherwise, only diagnose if the declaration is in scope.
5148      } else if (!isDeclInScope(PrevDecl, SearchDC, S)) {
5149        // do nothing
5150
5151      // Diagnose implicit declarations introduced by elaborated types.
5152      } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
5153        unsigned Kind = 0;
5154        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
5155        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
5156        Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
5157        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
5158        Invalid = true;
5159
5160      // Otherwise it's a declaration.  Call out a particularly common
5161      // case here.
5162      } else if (isa<TypedefDecl>(PrevDecl)) {
5163        Diag(NameLoc, diag::err_tag_definition_of_typedef)
5164          << Name
5165          << cast<TypedefDecl>(PrevDecl)->getUnderlyingType();
5166        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
5167        Invalid = true;
5168
5169      // Otherwise, diagnose.
5170      } else {
5171        // The tag name clashes with something else in the target scope,
5172        // issue an error and recover by making this tag be anonymous.
5173        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
5174        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5175        Name = 0;
5176        Invalid = true;
5177      }
5178
5179      // The existing declaration isn't relevant to us; we're in a
5180      // new scope, so clear out the previous declaration.
5181      Previous.clear();
5182    }
5183  }
5184
5185CreateNewDecl:
5186
5187  TagDecl *PrevDecl = 0;
5188  if (Previous.isSingleResult())
5189    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
5190
5191  // If there is an identifier, use the location of the identifier as the
5192  // location of the decl, otherwise use the location of the struct/union
5193  // keyword.
5194  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
5195
5196  // Otherwise, create a new declaration. If there is a previous
5197  // declaration of the same entity, the two will be linked via
5198  // PrevDecl.
5199  TagDecl *New;
5200
5201  if (Kind == TagDecl::TK_enum) {
5202    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
5203    // enum X { A, B, C } D;    D should chain to X.
5204    New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
5205                           cast_or_null<EnumDecl>(PrevDecl));
5206    // If this is an undefined enum, warn.
5207    if (TUK != TUK_Definition && !Invalid)  {
5208      unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
5209                                              : diag::ext_forward_ref_enum;
5210      Diag(Loc, DK);
5211    }
5212  } else {
5213    // struct/union/class
5214
5215    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
5216    // struct X { int A; } D;    D should chain to X.
5217    if (getLangOptions().CPlusPlus) {
5218      // FIXME: Look for a way to use RecordDecl for simple structs.
5219      New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
5220                                  cast_or_null<CXXRecordDecl>(PrevDecl));
5221
5222      if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit()))
5223        StdBadAlloc = cast<CXXRecordDecl>(New);
5224    } else
5225      New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
5226                               cast_or_null<RecordDecl>(PrevDecl));
5227  }
5228
5229  // Maybe add qualifier info.
5230  if (SS.isNotEmpty()) {
5231    NestedNameSpecifier *NNS
5232      = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5233    New->setQualifierInfo(NNS, SS.getRange());
5234  }
5235
5236  if (Kind != TagDecl::TK_enum) {
5237    // Handle #pragma pack: if the #pragma pack stack has non-default
5238    // alignment, make up a packed attribute for this decl. These
5239    // attributes are checked when the ASTContext lays out the
5240    // structure.
5241    //
5242    // It is important for implementing the correct semantics that this
5243    // happen here (in act on tag decl). The #pragma pack stack is
5244    // maintained as a result of parser callbacks which can occur at
5245    // many points during the parsing of a struct declaration (because
5246    // the #pragma tokens are effectively skipped over during the
5247    // parsing of the struct).
5248    if (unsigned Alignment = getPragmaPackAlignment())
5249      New->addAttr(::new (Context) PragmaPackAttr(Alignment * 8));
5250  }
5251
5252  // If this is a specialization of a member class (of a class template),
5253  // check the specialization.
5254  if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
5255    Invalid = true;
5256
5257  if (Invalid)
5258    New->setInvalidDecl();
5259
5260  if (Attr)
5261    ProcessDeclAttributeList(S, New, Attr);
5262
5263  // If we're declaring or defining a tag in function prototype scope
5264  // in C, note that this type can only be used within the function.
5265  if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
5266    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
5267
5268  // Set the lexical context. If the tag has a C++ scope specifier, the
5269  // lexical context will be different from the semantic context.
5270  New->setLexicalDeclContext(CurContext);
5271
5272  // Mark this as a friend decl if applicable.
5273  if (TUK == TUK_Friend)
5274    New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
5275
5276  // Set the access specifier.
5277  if (!Invalid && SearchDC->isRecord())
5278    SetMemberAccessSpecifier(New, PrevDecl, AS);
5279
5280  if (TUK == TUK_Definition)
5281    New->startDefinition();
5282
5283  // If this has an identifier, add it to the scope stack.
5284  if (TUK == TUK_Friend) {
5285    // We might be replacing an existing declaration in the lookup tables;
5286    // if so, borrow its access specifier.
5287    if (PrevDecl)
5288      New->setAccess(PrevDecl->getAccess());
5289
5290    DeclContext *DC = New->getDeclContext()->getLookupContext();
5291    DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
5292    if (Name) // can be null along some error paths
5293      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
5294        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
5295  } else if (Name) {
5296    S = getNonFieldDeclScope(S);
5297    PushOnScopeChains(New, S);
5298  } else {
5299    CurContext->addDecl(New);
5300  }
5301
5302  // If this is the C FILE type, notify the AST context.
5303  if (IdentifierInfo *II = New->getIdentifier())
5304    if (!New->isInvalidDecl() &&
5305        New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
5306        II->isStr("FILE"))
5307      Context.setFILEDecl(New);
5308
5309  OwnedDecl = true;
5310  return DeclPtrTy::make(New);
5311}
5312
5313void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
5314  AdjustDeclIfTemplate(TagD);
5315  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
5316
5317  // Enter the tag context.
5318  PushDeclContext(S, Tag);
5319}
5320
5321void Sema::ActOnStartCXXMemberDeclarations(Scope *S, DeclPtrTy TagD,
5322                                           SourceLocation LBraceLoc) {
5323  AdjustDeclIfTemplate(TagD);
5324  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD.getAs<Decl>());
5325
5326  FieldCollector->StartClass();
5327
5328  if (!Record->getIdentifier())
5329    return;
5330
5331  // C++ [class]p2:
5332  //   [...] The class-name is also inserted into the scope of the
5333  //   class itself; this is known as the injected-class-name. For
5334  //   purposes of access checking, the injected-class-name is treated
5335  //   as if it were a public member name.
5336  CXXRecordDecl *InjectedClassName
5337    = CXXRecordDecl::Create(Context, Record->getTagKind(),
5338                            CurContext, Record->getLocation(),
5339                            Record->getIdentifier(),
5340                            Record->getTagKeywordLoc(),
5341                            Record);
5342  InjectedClassName->setImplicit();
5343  InjectedClassName->setAccess(AS_public);
5344  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
5345      InjectedClassName->setDescribedClassTemplate(Template);
5346  PushOnScopeChains(InjectedClassName, S);
5347  assert(InjectedClassName->isInjectedClassName() &&
5348         "Broken injected-class-name");
5349}
5350
5351// Traverses the class and any nested classes, making a note of any
5352// dynamic classes that have no key function so that we can mark all of
5353// their virtual member functions as "used" at the end of the translation
5354// unit. This ensures that all functions needed by the vtable will get
5355// instantiated/synthesized.
5356static void
5357RecordDynamicClassesWithNoKeyFunction(Sema &S, CXXRecordDecl *Record,
5358                                      SourceLocation Loc) {
5359  // We don't look at dependent or undefined classes.
5360  if (Record->isDependentContext() || !Record->isDefinition())
5361    return;
5362
5363  if (Record->isDynamicClass()) {
5364    const CXXMethodDecl *KeyFunction = S.Context.getKeyFunction(Record);
5365
5366    if (!KeyFunction)
5367      S.ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(Record,
5368                                                                   Loc));
5369
5370    if ((!KeyFunction || (KeyFunction->getBody() && KeyFunction->isInlined()))
5371        && Record->getLinkage() == ExternalLinkage)
5372      S.Diag(Record->getLocation(), diag::warn_weak_vtable) << Record;
5373  }
5374  for (DeclContext::decl_iterator D = Record->decls_begin(),
5375                               DEnd = Record->decls_end();
5376       D != DEnd; ++D) {
5377    if (CXXRecordDecl *Nested = dyn_cast<CXXRecordDecl>(*D))
5378      RecordDynamicClassesWithNoKeyFunction(S, Nested, Loc);
5379  }
5380}
5381
5382void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
5383                                    SourceLocation RBraceLoc) {
5384  AdjustDeclIfTemplate(TagD);
5385  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
5386  Tag->setRBraceLoc(RBraceLoc);
5387
5388  if (isa<CXXRecordDecl>(Tag))
5389    FieldCollector->FinishClass();
5390
5391  // Exit this scope of this tag's definition.
5392  PopDeclContext();
5393
5394  if (isa<CXXRecordDecl>(Tag) && !Tag->getLexicalDeclContext()->isRecord())
5395    RecordDynamicClassesWithNoKeyFunction(*this, cast<CXXRecordDecl>(Tag),
5396                                          RBraceLoc);
5397
5398  // Notify the consumer that we've defined a tag.
5399  Consumer.HandleTagDeclDefinition(Tag);
5400}
5401
5402void Sema::ActOnTagDefinitionError(Scope *S, DeclPtrTy TagD) {
5403  AdjustDeclIfTemplate(TagD);
5404  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
5405  Tag->setInvalidDecl();
5406
5407  // We're undoing ActOnTagStartDefinition here, not
5408  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
5409  // the FieldCollector.
5410
5411  PopDeclContext();
5412}
5413
5414// Note that FieldName may be null for anonymous bitfields.
5415bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
5416                          QualType FieldTy, const Expr *BitWidth,
5417                          bool *ZeroWidth) {
5418  // Default to true; that shouldn't confuse checks for emptiness
5419  if (ZeroWidth)
5420    *ZeroWidth = true;
5421
5422  // C99 6.7.2.1p4 - verify the field type.
5423  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
5424  if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
5425    // Handle incomplete types with specific error.
5426    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
5427      return true;
5428    if (FieldName)
5429      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
5430        << FieldName << FieldTy << BitWidth->getSourceRange();
5431    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
5432      << FieldTy << BitWidth->getSourceRange();
5433  }
5434
5435  // If the bit-width is type- or value-dependent, don't try to check
5436  // it now.
5437  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
5438    return false;
5439
5440  llvm::APSInt Value;
5441  if (VerifyIntegerConstantExpression(BitWidth, &Value))
5442    return true;
5443
5444  if (Value != 0 && ZeroWidth)
5445    *ZeroWidth = false;
5446
5447  // Zero-width bitfield is ok for anonymous field.
5448  if (Value == 0 && FieldName)
5449    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
5450
5451  if (Value.isSigned() && Value.isNegative()) {
5452    if (FieldName)
5453      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
5454               << FieldName << Value.toString(10);
5455    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
5456      << Value.toString(10);
5457  }
5458
5459  if (!FieldTy->isDependentType()) {
5460    uint64_t TypeSize = Context.getTypeSize(FieldTy);
5461    if (Value.getZExtValue() > TypeSize) {
5462      if (!getLangOptions().CPlusPlus) {
5463        if (FieldName)
5464          return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
5465            << FieldName << (unsigned)Value.getZExtValue()
5466            << (unsigned)TypeSize;
5467
5468        return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
5469          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
5470      }
5471
5472      if (FieldName)
5473        Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
5474          << FieldName << (unsigned)Value.getZExtValue()
5475          << (unsigned)TypeSize;
5476      else
5477        Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
5478          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
5479    }
5480  }
5481
5482  return false;
5483}
5484
5485/// ActOnField - Each field of a struct/union/class is passed into this in order
5486/// to create a FieldDecl object for it.
5487Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
5488                                 SourceLocation DeclStart,
5489                                 Declarator &D, ExprTy *BitfieldWidth) {
5490  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
5491                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
5492                               AS_public);
5493  return DeclPtrTy::make(Res);
5494}
5495
5496/// HandleField - Analyze a field of a C struct or a C++ data member.
5497///
5498FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
5499                             SourceLocation DeclStart,
5500                             Declarator &D, Expr *BitWidth,
5501                             AccessSpecifier AS) {
5502  IdentifierInfo *II = D.getIdentifier();
5503  SourceLocation Loc = DeclStart;
5504  if (II) Loc = D.getIdentifierLoc();
5505
5506  TypeSourceInfo *TInfo = 0;
5507  QualType T = GetTypeForDeclarator(D, S, &TInfo);
5508  if (getLangOptions().CPlusPlus)
5509    CheckExtraCXXDefaultArguments(D);
5510
5511  DiagnoseFunctionSpecifiers(D);
5512
5513  if (D.getDeclSpec().isThreadSpecified())
5514    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5515
5516  NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
5517                                         ForRedeclaration);
5518
5519  if (PrevDecl && PrevDecl->isTemplateParameter()) {
5520    // Maybe we will complain about the shadowed template parameter.
5521    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5522    // Just pretend that we didn't see the previous declaration.
5523    PrevDecl = 0;
5524  }
5525
5526  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
5527    PrevDecl = 0;
5528
5529  bool Mutable
5530    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
5531  SourceLocation TSSL = D.getSourceRange().getBegin();
5532  FieldDecl *NewFD
5533    = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
5534                     AS, PrevDecl, &D);
5535
5536  if (NewFD->isInvalidDecl())
5537    Record->setInvalidDecl();
5538
5539  if (NewFD->isInvalidDecl() && PrevDecl) {
5540    // Don't introduce NewFD into scope; there's already something
5541    // with the same name in the same scope.
5542  } else if (II) {
5543    PushOnScopeChains(NewFD, S);
5544  } else
5545    Record->addDecl(NewFD);
5546
5547  return NewFD;
5548}
5549
5550/// \brief Build a new FieldDecl and check its well-formedness.
5551///
5552/// This routine builds a new FieldDecl given the fields name, type,
5553/// record, etc. \p PrevDecl should refer to any previous declaration
5554/// with the same name and in the same scope as the field to be
5555/// created.
5556///
5557/// \returns a new FieldDecl.
5558///
5559/// \todo The Declarator argument is a hack. It will be removed once
5560FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
5561                                TypeSourceInfo *TInfo,
5562                                RecordDecl *Record, SourceLocation Loc,
5563                                bool Mutable, Expr *BitWidth,
5564                                SourceLocation TSSL,
5565                                AccessSpecifier AS, NamedDecl *PrevDecl,
5566                                Declarator *D) {
5567  IdentifierInfo *II = Name.getAsIdentifierInfo();
5568  bool InvalidDecl = false;
5569  if (D) InvalidDecl = D->isInvalidType();
5570
5571  // If we receive a broken type, recover by assuming 'int' and
5572  // marking this declaration as invalid.
5573  if (T.isNull()) {
5574    InvalidDecl = true;
5575    T = Context.IntTy;
5576  }
5577
5578  QualType EltTy = Context.getBaseElementType(T);
5579  if (!EltTy->isDependentType() &&
5580      RequireCompleteType(Loc, EltTy, diag::err_field_incomplete))
5581    InvalidDecl = true;
5582
5583  // C99 6.7.2.1p8: A member of a structure or union may have any type other
5584  // than a variably modified type.
5585  if (!InvalidDecl && T->isVariablyModifiedType()) {
5586    bool SizeIsNegative;
5587    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
5588                                                           SizeIsNegative);
5589    if (!FixedTy.isNull()) {
5590      Diag(Loc, diag::warn_illegal_constant_array_size);
5591      T = FixedTy;
5592    } else {
5593      if (SizeIsNegative)
5594        Diag(Loc, diag::err_typecheck_negative_array_size);
5595      else
5596        Diag(Loc, diag::err_typecheck_field_variable_size);
5597      InvalidDecl = true;
5598    }
5599  }
5600
5601  // Fields can not have abstract class types
5602  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
5603                                             diag::err_abstract_type_in_decl,
5604                                             AbstractFieldType))
5605    InvalidDecl = true;
5606
5607  bool ZeroWidth = false;
5608  // If this is declared as a bit-field, check the bit-field.
5609  if (!InvalidDecl && BitWidth &&
5610      VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
5611    InvalidDecl = true;
5612    DeleteExpr(BitWidth);
5613    BitWidth = 0;
5614    ZeroWidth = false;
5615  }
5616
5617  FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo,
5618                                       BitWidth, Mutable);
5619  if (InvalidDecl)
5620    NewFD->setInvalidDecl();
5621
5622  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
5623    Diag(Loc, diag::err_duplicate_member) << II;
5624    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5625    NewFD->setInvalidDecl();
5626  }
5627
5628  if (!InvalidDecl && getLangOptions().CPlusPlus) {
5629    CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
5630
5631    if (!T->isPODType())
5632      CXXRecord->setPOD(false);
5633    if (!ZeroWidth)
5634      CXXRecord->setEmpty(false);
5635
5636    if (const RecordType *RT = EltTy->getAs<RecordType>()) {
5637      CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
5638
5639      if (!RDecl->hasTrivialConstructor())
5640        CXXRecord->setHasTrivialConstructor(false);
5641      if (!RDecl->hasTrivialCopyConstructor())
5642        CXXRecord->setHasTrivialCopyConstructor(false);
5643      if (!RDecl->hasTrivialCopyAssignment())
5644        CXXRecord->setHasTrivialCopyAssignment(false);
5645      if (!RDecl->hasTrivialDestructor())
5646        CXXRecord->setHasTrivialDestructor(false);
5647
5648      // C++ 9.5p1: An object of a class with a non-trivial
5649      // constructor, a non-trivial copy constructor, a non-trivial
5650      // destructor, or a non-trivial copy assignment operator
5651      // cannot be a member of a union, nor can an array of such
5652      // objects.
5653      // TODO: C++0x alters this restriction significantly.
5654      if (Record->isUnion()) {
5655        // We check for copy constructors before constructors
5656        // because otherwise we'll never get complaints about
5657        // copy constructors.
5658
5659        CXXSpecialMember member = CXXInvalid;
5660        if (!RDecl->hasTrivialCopyConstructor())
5661          member = CXXCopyConstructor;
5662        else if (!RDecl->hasTrivialConstructor())
5663          member = CXXConstructor;
5664        else if (!RDecl->hasTrivialCopyAssignment())
5665          member = CXXCopyAssignment;
5666        else if (!RDecl->hasTrivialDestructor())
5667          member = CXXDestructor;
5668
5669        if (member != CXXInvalid) {
5670          Diag(Loc, diag::err_illegal_union_member) << Name << member;
5671          DiagnoseNontrivial(RT, member);
5672          NewFD->setInvalidDecl();
5673        }
5674      }
5675    }
5676  }
5677
5678  // FIXME: We need to pass in the attributes given an AST
5679  // representation, not a parser representation.
5680  if (D)
5681    // FIXME: What to pass instead of TUScope?
5682    ProcessDeclAttributes(TUScope, NewFD, *D);
5683
5684  if (T.isObjCGCWeak())
5685    Diag(Loc, diag::warn_attribute_weak_on_field);
5686
5687  NewFD->setAccess(AS);
5688
5689  // C++ [dcl.init.aggr]p1:
5690  //   An aggregate is an array or a class (clause 9) with [...] no
5691  //   private or protected non-static data members (clause 11).
5692  // A POD must be an aggregate.
5693  if (getLangOptions().CPlusPlus &&
5694      (AS == AS_private || AS == AS_protected)) {
5695    CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
5696    CXXRecord->setAggregate(false);
5697    CXXRecord->setPOD(false);
5698  }
5699
5700  return NewFD;
5701}
5702
5703/// DiagnoseNontrivial - Given that a class has a non-trivial
5704/// special member, figure out why.
5705void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
5706  QualType QT(T, 0U);
5707  CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
5708
5709  // Check whether the member was user-declared.
5710  switch (member) {
5711  case CXXInvalid:
5712    break;
5713
5714  case CXXConstructor:
5715    if (RD->hasUserDeclaredConstructor()) {
5716      typedef CXXRecordDecl::ctor_iterator ctor_iter;
5717      for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
5718        const FunctionDecl *body = 0;
5719        ci->getBody(body);
5720        if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
5721          SourceLocation CtorLoc = ci->getLocation();
5722          Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5723          return;
5724        }
5725      }
5726
5727      assert(0 && "found no user-declared constructors");
5728      return;
5729    }
5730    break;
5731
5732  case CXXCopyConstructor:
5733    if (RD->hasUserDeclaredCopyConstructor()) {
5734      SourceLocation CtorLoc =
5735        RD->getCopyConstructor(Context, 0)->getLocation();
5736      Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5737      return;
5738    }
5739    break;
5740
5741  case CXXCopyAssignment:
5742    if (RD->hasUserDeclaredCopyAssignment()) {
5743      // FIXME: this should use the location of the copy
5744      // assignment, not the type.
5745      SourceLocation TyLoc = RD->getSourceRange().getBegin();
5746      Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
5747      return;
5748    }
5749    break;
5750
5751  case CXXDestructor:
5752    if (RD->hasUserDeclaredDestructor()) {
5753      SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation();
5754      Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5755      return;
5756    }
5757    break;
5758  }
5759
5760  typedef CXXRecordDecl::base_class_iterator base_iter;
5761
5762  // Virtual bases and members inhibit trivial copying/construction,
5763  // but not trivial destruction.
5764  if (member != CXXDestructor) {
5765    // Check for virtual bases.  vbases includes indirect virtual bases,
5766    // so we just iterate through the direct bases.
5767    for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
5768      if (bi->isVirtual()) {
5769        SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5770        Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
5771        return;
5772      }
5773
5774    // Check for virtual methods.
5775    typedef CXXRecordDecl::method_iterator meth_iter;
5776    for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
5777         ++mi) {
5778      if (mi->isVirtual()) {
5779        SourceLocation MLoc = mi->getSourceRange().getBegin();
5780        Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
5781        return;
5782      }
5783    }
5784  }
5785
5786  bool (CXXRecordDecl::*hasTrivial)() const;
5787  switch (member) {
5788  case CXXConstructor:
5789    hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
5790  case CXXCopyConstructor:
5791    hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
5792  case CXXCopyAssignment:
5793    hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
5794  case CXXDestructor:
5795    hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
5796  default:
5797    assert(0 && "unexpected special member"); return;
5798  }
5799
5800  // Check for nontrivial bases (and recurse).
5801  for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
5802    const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
5803    assert(BaseRT && "Don't know how to handle dependent bases");
5804    CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
5805    if (!(BaseRecTy->*hasTrivial)()) {
5806      SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5807      Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
5808      DiagnoseNontrivial(BaseRT, member);
5809      return;
5810    }
5811  }
5812
5813  // Check for nontrivial members (and recurse).
5814  typedef RecordDecl::field_iterator field_iter;
5815  for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
5816       ++fi) {
5817    QualType EltTy = Context.getBaseElementType((*fi)->getType());
5818    if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
5819      CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
5820
5821      if (!(EltRD->*hasTrivial)()) {
5822        SourceLocation FLoc = (*fi)->getLocation();
5823        Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
5824        DiagnoseNontrivial(EltRT, member);
5825        return;
5826      }
5827    }
5828  }
5829
5830  assert(0 && "found no explanation for non-trivial member");
5831}
5832
5833/// TranslateIvarVisibility - Translate visibility from a token ID to an
5834///  AST enum value.
5835static ObjCIvarDecl::AccessControl
5836TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
5837  switch (ivarVisibility) {
5838  default: assert(0 && "Unknown visitibility kind");
5839  case tok::objc_private: return ObjCIvarDecl::Private;
5840  case tok::objc_public: return ObjCIvarDecl::Public;
5841  case tok::objc_protected: return ObjCIvarDecl::Protected;
5842  case tok::objc_package: return ObjCIvarDecl::Package;
5843  }
5844}
5845
5846/// ActOnIvar - Each ivar field of an objective-c class is passed into this
5847/// in order to create an IvarDecl object for it.
5848Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
5849                                SourceLocation DeclStart,
5850                                DeclPtrTy IntfDecl,
5851                                Declarator &D, ExprTy *BitfieldWidth,
5852                                tok::ObjCKeywordKind Visibility) {
5853
5854  IdentifierInfo *II = D.getIdentifier();
5855  Expr *BitWidth = (Expr*)BitfieldWidth;
5856  SourceLocation Loc = DeclStart;
5857  if (II) Loc = D.getIdentifierLoc();
5858
5859  // FIXME: Unnamed fields can be handled in various different ways, for
5860  // example, unnamed unions inject all members into the struct namespace!
5861
5862  TypeSourceInfo *TInfo = 0;
5863  QualType T = GetTypeForDeclarator(D, S, &TInfo);
5864
5865  if (BitWidth) {
5866    // 6.7.2.1p3, 6.7.2.1p4
5867    if (VerifyBitField(Loc, II, T, BitWidth)) {
5868      D.setInvalidType();
5869      DeleteExpr(BitWidth);
5870      BitWidth = 0;
5871    }
5872  } else {
5873    // Not a bitfield.
5874
5875    // validate II.
5876
5877  }
5878
5879  // C99 6.7.2.1p8: A member of a structure or union may have any type other
5880  // than a variably modified type.
5881  if (T->isVariablyModifiedType()) {
5882    Diag(Loc, diag::err_typecheck_ivar_variable_size);
5883    D.setInvalidType();
5884  }
5885
5886  // Get the visibility (access control) for this ivar.
5887  ObjCIvarDecl::AccessControl ac =
5888    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
5889                                        : ObjCIvarDecl::None;
5890  // Must set ivar's DeclContext to its enclosing interface.
5891  ObjCContainerDecl *EnclosingDecl = IntfDecl.getAs<ObjCContainerDecl>();
5892  ObjCContainerDecl *EnclosingContext;
5893  if (ObjCImplementationDecl *IMPDecl =
5894      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5895    // Case of ivar declared in an implementation. Context is that of its class.
5896    EnclosingContext = IMPDecl->getClassInterface();
5897    assert(EnclosingContext && "Implementation has no class interface!");
5898  } else {
5899    if (ObjCCategoryDecl *CDecl =
5900        dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
5901      if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
5902        Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
5903        return DeclPtrTy();
5904      }
5905    }
5906    EnclosingContext = EnclosingDecl;
5907  }
5908
5909  // Construct the decl.
5910  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
5911                                             EnclosingContext, Loc, II, T,
5912                                             TInfo, ac, (Expr *)BitfieldWidth);
5913
5914  if (II) {
5915    NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
5916                                           ForRedeclaration);
5917    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
5918        && !isa<TagDecl>(PrevDecl)) {
5919      Diag(Loc, diag::err_duplicate_member) << II;
5920      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5921      NewID->setInvalidDecl();
5922    }
5923  }
5924
5925  // Process attributes attached to the ivar.
5926  ProcessDeclAttributes(S, NewID, D);
5927
5928  if (D.isInvalidType())
5929    NewID->setInvalidDecl();
5930
5931  if (II) {
5932    // FIXME: When interfaces are DeclContexts, we'll need to add
5933    // these to the interface.
5934    S->AddDecl(DeclPtrTy::make(NewID));
5935    IdResolver.AddDecl(NewID);
5936  }
5937
5938  return DeclPtrTy::make(NewID);
5939}
5940
5941void Sema::ActOnFields(Scope* S,
5942                       SourceLocation RecLoc, DeclPtrTy RecDecl,
5943                       DeclPtrTy *Fields, unsigned NumFields,
5944                       SourceLocation LBrac, SourceLocation RBrac,
5945                       AttributeList *Attr) {
5946  Decl *EnclosingDecl = RecDecl.getAs<Decl>();
5947  assert(EnclosingDecl && "missing record or interface decl");
5948
5949  // If the decl this is being inserted into is invalid, then it may be a
5950  // redeclaration or some other bogus case.  Don't try to add fields to it.
5951  if (EnclosingDecl->isInvalidDecl()) {
5952    // FIXME: Deallocate fields?
5953    return;
5954  }
5955
5956
5957  // Verify that all the fields are okay.
5958  unsigned NumNamedMembers = 0;
5959  llvm::SmallVector<FieldDecl*, 32> RecFields;
5960
5961  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
5962  for (unsigned i = 0; i != NumFields; ++i) {
5963    FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
5964
5965    // Get the type for the field.
5966    Type *FDTy = FD->getType().getTypePtr();
5967
5968    if (!FD->isAnonymousStructOrUnion()) {
5969      // Remember all fields written by the user.
5970      RecFields.push_back(FD);
5971    }
5972
5973    // If the field is already invalid for some reason, don't emit more
5974    // diagnostics about it.
5975    if (FD->isInvalidDecl()) {
5976      EnclosingDecl->setInvalidDecl();
5977      continue;
5978    }
5979
5980    // C99 6.7.2.1p2:
5981    //   A structure or union shall not contain a member with
5982    //   incomplete or function type (hence, a structure shall not
5983    //   contain an instance of itself, but may contain a pointer to
5984    //   an instance of itself), except that the last member of a
5985    //   structure with more than one named member may have incomplete
5986    //   array type; such a structure (and any union containing,
5987    //   possibly recursively, a member that is such a structure)
5988    //   shall not be a member of a structure or an element of an
5989    //   array.
5990    if (FDTy->isFunctionType()) {
5991      // Field declared as a function.
5992      Diag(FD->getLocation(), diag::err_field_declared_as_function)
5993        << FD->getDeclName();
5994      FD->setInvalidDecl();
5995      EnclosingDecl->setInvalidDecl();
5996      continue;
5997    } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
5998               Record && Record->isStruct()) {
5999      // Flexible array member.
6000      if (NumNamedMembers < 1) {
6001        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
6002          << FD->getDeclName();
6003        FD->setInvalidDecl();
6004        EnclosingDecl->setInvalidDecl();
6005        continue;
6006      }
6007      // Okay, we have a legal flexible array member at the end of the struct.
6008      if (Record)
6009        Record->setHasFlexibleArrayMember(true);
6010    } else if (!FDTy->isDependentType() &&
6011               RequireCompleteType(FD->getLocation(), FD->getType(),
6012                                   diag::err_field_incomplete)) {
6013      // Incomplete type
6014      FD->setInvalidDecl();
6015      EnclosingDecl->setInvalidDecl();
6016      continue;
6017    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
6018      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
6019        // If this is a member of a union, then entire union becomes "flexible".
6020        if (Record && Record->isUnion()) {
6021          Record->setHasFlexibleArrayMember(true);
6022        } else {
6023          // If this is a struct/class and this is not the last element, reject
6024          // it.  Note that GCC supports variable sized arrays in the middle of
6025          // structures.
6026          if (i != NumFields-1)
6027            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
6028              << FD->getDeclName() << FD->getType();
6029          else {
6030            // We support flexible arrays at the end of structs in
6031            // other structs as an extension.
6032            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
6033              << FD->getDeclName();
6034            if (Record)
6035              Record->setHasFlexibleArrayMember(true);
6036          }
6037        }
6038      }
6039      if (Record && FDTTy->getDecl()->hasObjectMember())
6040        Record->setHasObjectMember(true);
6041    } else if (FDTy->isObjCInterfaceType()) {
6042      /// A field cannot be an Objective-c object
6043      Diag(FD->getLocation(), diag::err_statically_allocated_object);
6044      FD->setInvalidDecl();
6045      EnclosingDecl->setInvalidDecl();
6046      continue;
6047    } else if (getLangOptions().ObjC1 &&
6048               getLangOptions().getGCMode() != LangOptions::NonGC &&
6049               Record &&
6050               (FD->getType()->isObjCObjectPointerType() ||
6051                FD->getType().isObjCGCStrong()))
6052      Record->setHasObjectMember(true);
6053    // Keep track of the number of named members.
6054    if (FD->getIdentifier())
6055      ++NumNamedMembers;
6056  }
6057
6058  // Okay, we successfully defined 'Record'.
6059  if (Record) {
6060    Record->completeDefinition();
6061  } else {
6062    ObjCIvarDecl **ClsFields =
6063      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
6064    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
6065      ID->setLocEnd(RBrac);
6066      // Add ivar's to class's DeclContext.
6067      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
6068        ClsFields[i]->setLexicalDeclContext(ID);
6069        ID->addDecl(ClsFields[i]);
6070      }
6071      // Must enforce the rule that ivars in the base classes may not be
6072      // duplicates.
6073      if (ID->getSuperClass())
6074        DiagnoseDuplicateIvars(ID, ID->getSuperClass());
6075    } else if (ObjCImplementationDecl *IMPDecl =
6076                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
6077      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
6078      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
6079        // Ivar declared in @implementation never belongs to the implementation.
6080        // Only it is in implementation's lexical context.
6081        ClsFields[I]->setLexicalDeclContext(IMPDecl);
6082      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
6083    } else if (ObjCCategoryDecl *CDecl =
6084                dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
6085      // case of ivars in class extension; all other cases have been
6086      // reported as errors elsewhere.
6087      // FIXME. Class extension does not have a LocEnd field.
6088      // CDecl->setLocEnd(RBrac);
6089      // Add ivar's to class extension's DeclContext.
6090      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
6091        ClsFields[i]->setLexicalDeclContext(CDecl);
6092        CDecl->addDecl(ClsFields[i]);
6093      }
6094    }
6095  }
6096
6097  if (Attr)
6098    ProcessDeclAttributeList(S, Record, Attr);
6099}
6100
6101/// \brief Determine whether the given integral value is representable within
6102/// the given type T.
6103static bool isRepresentableIntegerValue(ASTContext &Context,
6104                                        llvm::APSInt &Value,
6105                                        QualType T) {
6106  assert(T->isIntegralType() && "Integral type required!");
6107  unsigned BitWidth = Context.getIntWidth(T);
6108
6109  if (Value.isUnsigned() || Value.isNonNegative())
6110    return Value.getActiveBits() < BitWidth;
6111
6112  return Value.getMinSignedBits() <= BitWidth;
6113}
6114
6115// \brief Given an integral type, return the next larger integral type
6116// (or a NULL type of no such type exists).
6117static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
6118  // FIXME: Int128/UInt128 support, which also needs to be introduced into
6119  // enum checking below.
6120  assert(T->isIntegralType() && "Integral type required!");
6121  const unsigned NumTypes = 4;
6122  QualType SignedIntegralTypes[NumTypes] = {
6123    Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
6124  };
6125  QualType UnsignedIntegralTypes[NumTypes] = {
6126    Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
6127    Context.UnsignedLongLongTy
6128  };
6129
6130  unsigned BitWidth = Context.getTypeSize(T);
6131  QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes
6132                                            : UnsignedIntegralTypes;
6133  for (unsigned I = 0; I != NumTypes; ++I)
6134    if (Context.getTypeSize(Types[I]) > BitWidth)
6135      return Types[I];
6136
6137  return QualType();
6138}
6139
6140EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
6141                                          EnumConstantDecl *LastEnumConst,
6142                                          SourceLocation IdLoc,
6143                                          IdentifierInfo *Id,
6144                                          ExprArg val) {
6145  Expr *Val = (Expr *)val.get();
6146
6147  unsigned IntWidth = Context.Target.getIntWidth();
6148  llvm::APSInt EnumVal(IntWidth);
6149  QualType EltTy;
6150  if (Val) {
6151    if (Enum->isDependentType() || Val->isTypeDependent())
6152      EltTy = Context.DependentTy;
6153    else {
6154      // C99 6.7.2.2p2: Make sure we have an integer constant expression.
6155      SourceLocation ExpLoc;
6156      if (!Val->isValueDependent() &&
6157          VerifyIntegerConstantExpression(Val, &EnumVal)) {
6158        Val = 0;
6159      } else {
6160        if (!getLangOptions().CPlusPlus) {
6161          // C99 6.7.2.2p2:
6162          //   The expression that defines the value of an enumeration constant
6163          //   shall be an integer constant expression that has a value
6164          //   representable as an int.
6165
6166          // Complain if the value is not representable in an int.
6167          if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
6168            Diag(IdLoc, diag::ext_enum_value_not_int)
6169              << EnumVal.toString(10) << Val->getSourceRange()
6170              << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
6171          else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
6172            // Force the type of the expression to 'int'.
6173            ImpCastExprToType(Val, Context.IntTy, CastExpr::CK_IntegralCast);
6174
6175            if (Val != val.get()) {
6176              val.release();
6177              val = Val;
6178            }
6179          }
6180        }
6181
6182        // C++0x [dcl.enum]p5:
6183        //   If the underlying type is not fixed, the type of each enumerator
6184        //   is the type of its initializing value:
6185        //     - If an initializer is specified for an enumerator, the
6186        //       initializing value has the same type as the expression.
6187        EltTy = Val->getType();
6188      }
6189    }
6190  }
6191
6192  if (!Val) {
6193    if (Enum->isDependentType())
6194      EltTy = Context.DependentTy;
6195    else if (!LastEnumConst) {
6196      // C++0x [dcl.enum]p5:
6197      //   If the underlying type is not fixed, the type of each enumerator
6198      //   is the type of its initializing value:
6199      //     - If no initializer is specified for the first enumerator, the
6200      //       initializing value has an unspecified integral type.
6201      //
6202      // GCC uses 'int' for its unspecified integral type, as does
6203      // C99 6.7.2.2p3.
6204      EltTy = Context.IntTy;
6205    } else {
6206      // Assign the last value + 1.
6207      EnumVal = LastEnumConst->getInitVal();
6208      ++EnumVal;
6209      EltTy = LastEnumConst->getType();
6210
6211      // Check for overflow on increment.
6212      if (EnumVal < LastEnumConst->getInitVal()) {
6213        // C++0x [dcl.enum]p5:
6214        //   If the underlying type is not fixed, the type of each enumerator
6215        //   is the type of its initializing value:
6216        //
6217        //     - Otherwise the type of the initializing value is the same as
6218        //       the type of the initializing value of the preceding enumerator
6219        //       unless the incremented value is not representable in that type,
6220        //       in which case the type is an unspecified integral type
6221        //       sufficient to contain the incremented value. If no such type
6222        //       exists, the program is ill-formed.
6223        QualType T = getNextLargerIntegralType(Context, EltTy);
6224        if (T.isNull()) {
6225          // There is no integral type larger enough to represent this
6226          // value. Complain, then allow the value to wrap around.
6227          EnumVal = LastEnumConst->getInitVal();
6228          EnumVal.zext(EnumVal.getBitWidth() * 2);
6229          Diag(IdLoc, diag::warn_enumerator_too_large)
6230            << EnumVal.toString(10);
6231        } else {
6232          EltTy = T;
6233        }
6234
6235        // Retrieve the last enumerator's value, extent that type to the
6236        // type that is supposed to be large enough to represent the incremented
6237        // value, then increment.
6238        EnumVal = LastEnumConst->getInitVal();
6239        EnumVal.setIsSigned(EltTy->isSignedIntegerType());
6240        EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
6241        ++EnumVal;
6242
6243        // If we're not in C++, diagnose the overflow of enumerator values,
6244        // which in C99 means that the enumerator value is not representable in
6245        // an int (C99 6.7.2.2p2). However, we support GCC's extension that
6246        // permits enumerator values that are representable in some larger
6247        // integral type.
6248        if (!getLangOptions().CPlusPlus && !T.isNull())
6249          Diag(IdLoc, diag::warn_enum_value_overflow);
6250      } else if (!getLangOptions().CPlusPlus &&
6251                 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
6252        // Enforce C99 6.7.2.2p2 even when we compute the next value.
6253        Diag(IdLoc, diag::ext_enum_value_not_int)
6254          << EnumVal.toString(10) << 1;
6255      }
6256    }
6257  }
6258
6259  if (!EltTy->isDependentType()) {
6260    // Make the enumerator value match the signedness and size of the
6261    // enumerator's type.
6262    EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
6263    EnumVal.setIsSigned(EltTy->isSignedIntegerType());
6264  }
6265
6266  val.release();
6267  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
6268                                  Val, EnumVal);
6269}
6270
6271
6272Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
6273                                        DeclPtrTy lastEnumConst,
6274                                        SourceLocation IdLoc,
6275                                        IdentifierInfo *Id,
6276                                        SourceLocation EqualLoc, ExprTy *val) {
6277  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
6278  EnumConstantDecl *LastEnumConst =
6279    cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
6280  Expr *Val = static_cast<Expr*>(val);
6281
6282  // The scope passed in may not be a decl scope.  Zip up the scope tree until
6283  // we find one that is.
6284  S = getNonFieldDeclScope(S);
6285
6286  // Verify that there isn't already something declared with this name in this
6287  // scope.
6288  NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
6289                                         ForRedeclaration);
6290  if (PrevDecl && PrevDecl->isTemplateParameter()) {
6291    // Maybe we will complain about the shadowed template parameter.
6292    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
6293    // Just pretend that we didn't see the previous declaration.
6294    PrevDecl = 0;
6295  }
6296
6297  if (PrevDecl) {
6298    // When in C++, we may get a TagDecl with the same name; in this case the
6299    // enum constant will 'hide' the tag.
6300    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
6301           "Received TagDecl when not in C++!");
6302    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
6303      if (isa<EnumConstantDecl>(PrevDecl))
6304        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
6305      else
6306        Diag(IdLoc, diag::err_redefinition) << Id;
6307      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6308      if (Val) Val->Destroy(Context);
6309      return DeclPtrTy();
6310    }
6311  }
6312
6313  EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
6314                                            IdLoc, Id, Owned(Val));
6315
6316  // Register this decl in the current scope stack.
6317  if (New) {
6318    New->setAccess(TheEnumDecl->getAccess());
6319    PushOnScopeChains(New, S);
6320  }
6321
6322  return DeclPtrTy::make(New);
6323}
6324
6325void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
6326                         SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
6327                         DeclPtrTy *Elements, unsigned NumElements,
6328                         Scope *S, AttributeList *Attr) {
6329  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
6330  QualType EnumType = Context.getTypeDeclType(Enum);
6331
6332  if (Attr)
6333    ProcessDeclAttributeList(S, Enum, Attr);
6334
6335  if (Enum->isDependentType()) {
6336    for (unsigned i = 0; i != NumElements; ++i) {
6337      EnumConstantDecl *ECD =
6338        cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6339      if (!ECD) continue;
6340
6341      ECD->setType(EnumType);
6342    }
6343
6344    Enum->completeDefinition(Context.DependentTy, Context.DependentTy);
6345    return;
6346  }
6347
6348  // TODO: If the result value doesn't fit in an int, it must be a long or long
6349  // long value.  ISO C does not support this, but GCC does as an extension,
6350  // emit a warning.
6351  unsigned IntWidth = Context.Target.getIntWidth();
6352  unsigned CharWidth = Context.Target.getCharWidth();
6353  unsigned ShortWidth = Context.Target.getShortWidth();
6354
6355  // Verify that all the values are okay, compute the size of the values, and
6356  // reverse the list.
6357  unsigned NumNegativeBits = 0;
6358  unsigned NumPositiveBits = 0;
6359
6360  // Keep track of whether all elements have type int.
6361  bool AllElementsInt = true;
6362
6363  for (unsigned i = 0; i != NumElements; ++i) {
6364    EnumConstantDecl *ECD =
6365      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6366    if (!ECD) continue;  // Already issued a diagnostic.
6367
6368    const llvm::APSInt &InitVal = ECD->getInitVal();
6369
6370    // Keep track of the size of positive and negative values.
6371    if (InitVal.isUnsigned() || InitVal.isNonNegative())
6372      NumPositiveBits = std::max(NumPositiveBits,
6373                                 (unsigned)InitVal.getActiveBits());
6374    else
6375      NumNegativeBits = std::max(NumNegativeBits,
6376                                 (unsigned)InitVal.getMinSignedBits());
6377
6378    // Keep track of whether every enum element has type int (very commmon).
6379    if (AllElementsInt)
6380      AllElementsInt = ECD->getType() == Context.IntTy;
6381  }
6382
6383  // Figure out the type that should be used for this enum.
6384  // FIXME: Support -fshort-enums.
6385  QualType BestType;
6386  unsigned BestWidth;
6387
6388  // C++0x N3000 [conv.prom]p3:
6389  //   An rvalue of an unscoped enumeration type whose underlying
6390  //   type is not fixed can be converted to an rvalue of the first
6391  //   of the following types that can represent all the values of
6392  //   the enumeration: int, unsigned int, long int, unsigned long
6393  //   int, long long int, or unsigned long long int.
6394  // C99 6.4.4.3p2:
6395  //   An identifier declared as an enumeration constant has type int.
6396  // The C99 rule is modified by a gcc extension
6397  QualType BestPromotionType;
6398
6399  bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
6400
6401  if (NumNegativeBits) {
6402    // If there is a negative value, figure out the smallest integer type (of
6403    // int/long/longlong) that fits.
6404    // If it's packed, check also if it fits a char or a short.
6405    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
6406      BestType = Context.SignedCharTy;
6407      BestWidth = CharWidth;
6408    } else if (Packed && NumNegativeBits <= ShortWidth &&
6409               NumPositiveBits < ShortWidth) {
6410      BestType = Context.ShortTy;
6411      BestWidth = ShortWidth;
6412    } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
6413      BestType = Context.IntTy;
6414      BestWidth = IntWidth;
6415    } else {
6416      BestWidth = Context.Target.getLongWidth();
6417
6418      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
6419        BestType = Context.LongTy;
6420      } else {
6421        BestWidth = Context.Target.getLongLongWidth();
6422
6423        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
6424          Diag(Enum->getLocation(), diag::warn_enum_too_large);
6425        BestType = Context.LongLongTy;
6426      }
6427    }
6428    BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
6429  } else {
6430    // If there is no negative value, figure out the smallest type that fits
6431    // all of the enumerator values.
6432    // If it's packed, check also if it fits a char or a short.
6433    if (Packed && NumPositiveBits <= CharWidth) {
6434      BestType = Context.UnsignedCharTy;
6435      BestPromotionType = Context.IntTy;
6436      BestWidth = CharWidth;
6437    } else if (Packed && NumPositiveBits <= ShortWidth) {
6438      BestType = Context.UnsignedShortTy;
6439      BestPromotionType = Context.IntTy;
6440      BestWidth = ShortWidth;
6441    } else if (NumPositiveBits <= IntWidth) {
6442      BestType = Context.UnsignedIntTy;
6443      BestWidth = IntWidth;
6444      BestPromotionType
6445        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6446                           ? Context.UnsignedIntTy : Context.IntTy;
6447    } else if (NumPositiveBits <=
6448               (BestWidth = Context.Target.getLongWidth())) {
6449      BestType = Context.UnsignedLongTy;
6450      BestPromotionType
6451        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6452                           ? Context.UnsignedLongTy : Context.LongTy;
6453    } else {
6454      BestWidth = Context.Target.getLongLongWidth();
6455      assert(NumPositiveBits <= BestWidth &&
6456             "How could an initializer get larger than ULL?");
6457      BestType = Context.UnsignedLongLongTy;
6458      BestPromotionType
6459        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6460                           ? Context.UnsignedLongLongTy : Context.LongLongTy;
6461    }
6462  }
6463
6464  // Loop over all of the enumerator constants, changing their types to match
6465  // the type of the enum if needed.
6466  for (unsigned i = 0; i != NumElements; ++i) {
6467    EnumConstantDecl *ECD =
6468      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6469    if (!ECD) continue;  // Already issued a diagnostic.
6470
6471    // Standard C says the enumerators have int type, but we allow, as an
6472    // extension, the enumerators to be larger than int size.  If each
6473    // enumerator value fits in an int, type it as an int, otherwise type it the
6474    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
6475    // that X has type 'int', not 'unsigned'.
6476
6477    // Determine whether the value fits into an int.
6478    llvm::APSInt InitVal = ECD->getInitVal();
6479
6480    // If it fits into an integer type, force it.  Otherwise force it to match
6481    // the enum decl type.
6482    QualType NewTy;
6483    unsigned NewWidth;
6484    bool NewSign;
6485    if (!getLangOptions().CPlusPlus &&
6486        isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
6487      NewTy = Context.IntTy;
6488      NewWidth = IntWidth;
6489      NewSign = true;
6490    } else if (ECD->getType() == BestType) {
6491      // Already the right type!
6492      if (getLangOptions().CPlusPlus)
6493        // C++ [dcl.enum]p4: Following the closing brace of an
6494        // enum-specifier, each enumerator has the type of its
6495        // enumeration.
6496        ECD->setType(EnumType);
6497      continue;
6498    } else {
6499      NewTy = BestType;
6500      NewWidth = BestWidth;
6501      NewSign = BestType->isSignedIntegerType();
6502    }
6503
6504    // Adjust the APSInt value.
6505    InitVal.extOrTrunc(NewWidth);
6506    InitVal.setIsSigned(NewSign);
6507    ECD->setInitVal(InitVal);
6508
6509    // Adjust the Expr initializer and type.
6510    if (ECD->getInitExpr())
6511      ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
6512                                                      CastExpr::CK_IntegralCast,
6513                                                      ECD->getInitExpr(),
6514                                                      CXXBaseSpecifierArray(),
6515                                                      /*isLvalue=*/false));
6516    if (getLangOptions().CPlusPlus)
6517      // C++ [dcl.enum]p4: Following the closing brace of an
6518      // enum-specifier, each enumerator has the type of its
6519      // enumeration.
6520      ECD->setType(EnumType);
6521    else
6522      ECD->setType(NewTy);
6523  }
6524
6525  Enum->completeDefinition(BestType, BestPromotionType);
6526}
6527
6528Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
6529                                            ExprArg expr) {
6530  StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
6531
6532  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
6533                                                   Loc, AsmString);
6534  CurContext->addDecl(New);
6535  return DeclPtrTy::make(New);
6536}
6537
6538void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
6539                             SourceLocation PragmaLoc,
6540                             SourceLocation NameLoc) {
6541  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
6542
6543  if (PrevDecl) {
6544    PrevDecl->addAttr(::new (Context) WeakAttr());
6545  } else {
6546    (void)WeakUndeclaredIdentifiers.insert(
6547      std::pair<IdentifierInfo*,WeakInfo>
6548        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
6549  }
6550}
6551
6552void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
6553                                IdentifierInfo* AliasName,
6554                                SourceLocation PragmaLoc,
6555                                SourceLocation NameLoc,
6556                                SourceLocation AliasNameLoc) {
6557  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
6558                                    LookupOrdinaryName);
6559  WeakInfo W = WeakInfo(Name, NameLoc);
6560
6561  if (PrevDecl) {
6562    if (!PrevDecl->hasAttr<AliasAttr>())
6563      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
6564        DeclApplyPragmaWeak(TUScope, ND, W);
6565  } else {
6566    (void)WeakUndeclaredIdentifiers.insert(
6567      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
6568  }
6569}
6570