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