]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Sema/SemaDeclCXX.cpp
Vendor import of clang trunk r132879:
[FreeBSD/FreeBSD.git] / lib / Sema / SemaDeclCXX.cpp
1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ 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 C++ declarations.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/CXXFieldCollector.h"
16 #include "clang/Sema/Scope.h"
17 #include "clang/Sema/Initialization.h"
18 #include "clang/Sema/Lookup.h"
19 #include "clang/AST/ASTConsumer.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/ASTMutationListener.h"
22 #include "clang/AST/CharUnits.h"
23 #include "clang/AST/CXXInheritance.h"
24 #include "clang/AST/DeclVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/RecordLayout.h"
27 #include "clang/AST/StmtVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/AST/TypeOrdering.h"
30 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/ParsedTemplate.h"
32 #include "clang/Basic/PartialDiagnostic.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "llvm/ADT/DenseSet.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include <map>
37 #include <set>
38
39 using namespace clang;
40
41 //===----------------------------------------------------------------------===//
42 // CheckDefaultArgumentVisitor
43 //===----------------------------------------------------------------------===//
44
45 namespace {
46   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47   /// the default argument of a parameter to determine whether it
48   /// contains any ill-formed subexpressions. For example, this will
49   /// diagnose the use of local variables or parameters within the
50   /// default argument expression.
51   class CheckDefaultArgumentVisitor
52     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
53     Expr *DefaultArg;
54     Sema *S;
55
56   public:
57     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
58       : DefaultArg(defarg), S(s) {}
59
60     bool VisitExpr(Expr *Node);
61     bool VisitDeclRefExpr(DeclRefExpr *DRE);
62     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
63   };
64
65   /// VisitExpr - Visit all of the children of this expression.
66   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67     bool IsInvalid = false;
68     for (Stmt::child_range I = Node->children(); I; ++I)
69       IsInvalid |= Visit(*I);
70     return IsInvalid;
71   }
72
73   /// VisitDeclRefExpr - Visit a reference to a declaration, to
74   /// determine whether this declaration can be used in the default
75   /// argument expression.
76   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
77     NamedDecl *Decl = DRE->getDecl();
78     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79       // C++ [dcl.fct.default]p9
80       //   Default arguments are evaluated each time the function is
81       //   called. The order of evaluation of function arguments is
82       //   unspecified. Consequently, parameters of a function shall not
83       //   be used in default argument expressions, even if they are not
84       //   evaluated. Parameters of a function declared before a default
85       //   argument expression are in scope and can hide namespace and
86       //   class member names.
87       return S->Diag(DRE->getSourceRange().getBegin(),
88                      diag::err_param_default_argument_references_param)
89          << Param->getDeclName() << DefaultArg->getSourceRange();
90     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
91       // C++ [dcl.fct.default]p7
92       //   Local variables shall not be used in default argument
93       //   expressions.
94       if (VDecl->isLocalVarDecl())
95         return S->Diag(DRE->getSourceRange().getBegin(),
96                        diag::err_param_default_argument_references_local)
97           << VDecl->getDeclName() << DefaultArg->getSourceRange();
98     }
99
100     return false;
101   }
102
103   /// VisitCXXThisExpr - Visit a C++ "this" expression.
104   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105     // C++ [dcl.fct.default]p8:
106     //   The keyword this shall not be used in a default argument of a
107     //   member function.
108     return S->Diag(ThisE->getSourceRange().getBegin(),
109                    diag::err_param_default_argument_references_this)
110                << ThisE->getSourceRange();
111   }
112 }
113
114 void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
115   assert(Context && "ImplicitExceptionSpecification without an ASTContext");
116   // If we have an MSAny or unknown spec already, don't bother.
117   if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
118     return;
119
120   const FunctionProtoType *Proto
121     = Method->getType()->getAs<FunctionProtoType>();
122
123   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
124
125   // If this function can throw any exceptions, make a note of that.
126   if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
127     ClearExceptions();
128     ComputedEST = EST;
129     return;
130   }
131
132   // FIXME: If the call to this decl is using any of its default arguments, we
133   // need to search them for potentially-throwing calls.
134
135   // If this function has a basic noexcept, it doesn't affect the outcome.
136   if (EST == EST_BasicNoexcept)
137     return;
138
139   // If we have a throw-all spec at this point, ignore the function.
140   if (ComputedEST == EST_None)
141     return;
142
143   // If we're still at noexcept(true) and there's a nothrow() callee,
144   // change to that specification.
145   if (EST == EST_DynamicNone) {
146     if (ComputedEST == EST_BasicNoexcept)
147       ComputedEST = EST_DynamicNone;
148     return;
149   }
150
151   // Check out noexcept specs.
152   if (EST == EST_ComputedNoexcept) {
153     FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
154     assert(NR != FunctionProtoType::NR_NoNoexcept &&
155            "Must have noexcept result for EST_ComputedNoexcept.");
156     assert(NR != FunctionProtoType::NR_Dependent &&
157            "Should not generate implicit declarations for dependent cases, "
158            "and don't know how to handle them anyway.");
159
160     // noexcept(false) -> no spec on the new function
161     if (NR == FunctionProtoType::NR_Throw) {
162       ClearExceptions();
163       ComputedEST = EST_None;
164     }
165     // noexcept(true) won't change anything either.
166     return;
167   }
168
169   assert(EST == EST_Dynamic && "EST case not considered earlier.");
170   assert(ComputedEST != EST_None &&
171          "Shouldn't collect exceptions when throw-all is guaranteed.");
172   ComputedEST = EST_Dynamic;
173   // Record the exceptions in this function's exception specification.
174   for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
175                                           EEnd = Proto->exception_end();
176        E != EEnd; ++E)
177     if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
178       Exceptions.push_back(*E);
179 }
180
181 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
182   if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
183     return;
184
185   // FIXME:
186   //
187   // C++0x [except.spec]p14:
188   //   [An] implicit exception-specification specifies the type-id T if and
189   // only if T is allowed by the exception-specification of a function directly
190   // invoked by f’s implicit definition; f shall allow all exceptions if any
191   // function it directly invokes allows all exceptions, and f shall allow no
192   // exceptions if every function it directly invokes allows no exceptions.
193   //
194   // Note in particular that if an implicit exception-specification is generated
195   // for a function containing a throw-expression, that specification can still
196   // be noexcept(true).
197   //
198   // Note also that 'directly invoked' is not defined in the standard, and there
199   // is no indication that we should only consider potentially-evaluated calls.
200   //
201   // Ultimately we should implement the intent of the standard: the exception
202   // specification should be the set of exceptions which can be thrown by the
203   // implicit definition. For now, we assume that any non-nothrow expression can
204   // throw any exception.
205
206   if (E->CanThrow(*Context))
207     ComputedEST = EST_None;
208 }
209
210 bool
211 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
212                               SourceLocation EqualLoc) {
213   if (RequireCompleteType(Param->getLocation(), Param->getType(),
214                           diag::err_typecheck_decl_incomplete_type)) {
215     Param->setInvalidDecl();
216     return true;
217   }
218
219   // C++ [dcl.fct.default]p5
220   //   A default argument expression is implicitly converted (clause
221   //   4) to the parameter type. The default argument expression has
222   //   the same semantic constraints as the initializer expression in
223   //   a declaration of a variable of the parameter type, using the
224   //   copy-initialization semantics (8.5).
225   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
226                                                                     Param);
227   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
228                                                            EqualLoc);
229   InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
230   ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
231                                       MultiExprArg(*this, &Arg, 1));
232   if (Result.isInvalid())
233     return true;
234   Arg = Result.takeAs<Expr>();
235
236   CheckImplicitConversions(Arg, EqualLoc);
237   Arg = MaybeCreateExprWithCleanups(Arg);
238
239   // Okay: add the default argument to the parameter
240   Param->setDefaultArg(Arg);
241
242   // We have already instantiated this parameter; provide each of the 
243   // instantiations with the uninstantiated default argument.
244   UnparsedDefaultArgInstantiationsMap::iterator InstPos
245     = UnparsedDefaultArgInstantiations.find(Param);
246   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
247     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
248       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
249     
250     // We're done tracking this parameter's instantiations.
251     UnparsedDefaultArgInstantiations.erase(InstPos);
252   }
253   
254   return false;
255 }
256
257 /// ActOnParamDefaultArgument - Check whether the default argument
258 /// provided for a function parameter is well-formed. If so, attach it
259 /// to the parameter declaration.
260 void
261 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
262                                 Expr *DefaultArg) {
263   if (!param || !DefaultArg)
264     return;
265
266   ParmVarDecl *Param = cast<ParmVarDecl>(param);
267   UnparsedDefaultArgLocs.erase(Param);
268
269   // Default arguments are only permitted in C++
270   if (!getLangOptions().CPlusPlus) {
271     Diag(EqualLoc, diag::err_param_default_argument)
272       << DefaultArg->getSourceRange();
273     Param->setInvalidDecl();
274     return;
275   }
276
277   // Check for unexpanded parameter packs.
278   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
279     Param->setInvalidDecl();
280     return;
281   }    
282       
283   // Check that the default argument is well-formed
284   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285   if (DefaultArgChecker.Visit(DefaultArg)) {
286     Param->setInvalidDecl();
287     return;
288   }
289
290   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
291 }
292
293 /// ActOnParamUnparsedDefaultArgument - We've seen a default
294 /// argument for a function parameter, but we can't parse it yet
295 /// because we're inside a class definition. Note that this default
296 /// argument will be parsed later.
297 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
298                                              SourceLocation EqualLoc,
299                                              SourceLocation ArgLoc) {
300   if (!param)
301     return;
302
303   ParmVarDecl *Param = cast<ParmVarDecl>(param);
304   if (Param)
305     Param->setUnparsedDefaultArg();
306
307   UnparsedDefaultArgLocs[Param] = ArgLoc;
308 }
309
310 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311 /// the default argument for the parameter param failed.
312 void Sema::ActOnParamDefaultArgumentError(Decl *param) {
313   if (!param)
314     return;
315
316   ParmVarDecl *Param = cast<ParmVarDecl>(param);
317
318   Param->setInvalidDecl();
319
320   UnparsedDefaultArgLocs.erase(Param);
321 }
322
323 /// CheckExtraCXXDefaultArguments - Check for any extra default
324 /// arguments in the declarator, which is not a function declaration
325 /// or definition and therefore is not permitted to have default
326 /// arguments. This routine should be invoked for every declarator
327 /// that is not a function declaration or definition.
328 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
329   // C++ [dcl.fct.default]p3
330   //   A default argument expression shall be specified only in the
331   //   parameter-declaration-clause of a function declaration or in a
332   //   template-parameter (14.1). It shall not be specified for a
333   //   parameter pack. If it is specified in a
334   //   parameter-declaration-clause, it shall not occur within a
335   //   declarator or abstract-declarator of a parameter-declaration.
336   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
337     DeclaratorChunk &chunk = D.getTypeObject(i);
338     if (chunk.Kind == DeclaratorChunk::Function) {
339       for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
340         ParmVarDecl *Param =
341           cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
342         if (Param->hasUnparsedDefaultArg()) {
343           CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
344           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
345             << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
346           delete Toks;
347           chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
348         } else if (Param->getDefaultArg()) {
349           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
350             << Param->getDefaultArg()->getSourceRange();
351           Param->setDefaultArg(0);
352         }
353       }
354     }
355   }
356 }
357
358 // MergeCXXFunctionDecl - Merge two declarations of the same C++
359 // function, once we already know that they have the same
360 // type. Subroutine of MergeFunctionDecl. Returns true if there was an
361 // error, false otherwise.
362 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
363   bool Invalid = false;
364
365   // C++ [dcl.fct.default]p4:
366   //   For non-template functions, default arguments can be added in
367   //   later declarations of a function in the same
368   //   scope. Declarations in different scopes have completely
369   //   distinct sets of default arguments. That is, declarations in
370   //   inner scopes do not acquire default arguments from
371   //   declarations in outer scopes, and vice versa. In a given
372   //   function declaration, all parameters subsequent to a
373   //   parameter with a default argument shall have default
374   //   arguments supplied in this or previous declarations. A
375   //   default argument shall not be redefined by a later
376   //   declaration (not even to the same value).
377   //
378   // C++ [dcl.fct.default]p6:
379   //   Except for member functions of class templates, the default arguments 
380   //   in a member function definition that appears outside of the class 
381   //   definition are added to the set of default arguments provided by the 
382   //   member function declaration in the class definition.
383   for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
384     ParmVarDecl *OldParam = Old->getParamDecl(p);
385     ParmVarDecl *NewParam = New->getParamDecl(p);
386
387     if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
388
389       unsigned DiagDefaultParamID =
390         diag::err_param_default_argument_redefinition;
391
392       // MSVC accepts that default parameters be redefined for member functions
393       // of template class. The new default parameter's value is ignored.
394       Invalid = true;
395       if (getLangOptions().Microsoft) {
396         CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
397         if (MD && MD->getParent()->getDescribedClassTemplate()) {
398           // Merge the old default argument into the new parameter.
399           NewParam->setHasInheritedDefaultArg();
400           if (OldParam->hasUninstantiatedDefaultArg())
401             NewParam->setUninstantiatedDefaultArg(
402                                       OldParam->getUninstantiatedDefaultArg());
403           else
404             NewParam->setDefaultArg(OldParam->getInit());
405           DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
406           Invalid = false;
407         }
408       }
409       
410       // FIXME: If we knew where the '=' was, we could easily provide a fix-it 
411       // hint here. Alternatively, we could walk the type-source information
412       // for NewParam to find the last source location in the type... but it
413       // isn't worth the effort right now. This is the kind of test case that
414       // is hard to get right:
415       //   int f(int);
416       //   void g(int (*fp)(int) = f);
417       //   void g(int (*fp)(int) = &f);
418       Diag(NewParam->getLocation(), DiagDefaultParamID)
419         << NewParam->getDefaultArgRange();
420       
421       // Look for the function declaration where the default argument was
422       // actually written, which may be a declaration prior to Old.
423       for (FunctionDecl *Older = Old->getPreviousDeclaration();
424            Older; Older = Older->getPreviousDeclaration()) {
425         if (!Older->getParamDecl(p)->hasDefaultArg())
426           break;
427         
428         OldParam = Older->getParamDecl(p);
429       }        
430       
431       Diag(OldParam->getLocation(), diag::note_previous_definition)
432         << OldParam->getDefaultArgRange();
433     } else if (OldParam->hasDefaultArg()) {
434       // Merge the old default argument into the new parameter.
435       // It's important to use getInit() here;  getDefaultArg()
436       // strips off any top-level ExprWithCleanups.
437       NewParam->setHasInheritedDefaultArg();
438       if (OldParam->hasUninstantiatedDefaultArg())
439         NewParam->setUninstantiatedDefaultArg(
440                                       OldParam->getUninstantiatedDefaultArg());
441       else
442         NewParam->setDefaultArg(OldParam->getInit());
443     } else if (NewParam->hasDefaultArg()) {
444       if (New->getDescribedFunctionTemplate()) {
445         // Paragraph 4, quoted above, only applies to non-template functions.
446         Diag(NewParam->getLocation(),
447              diag::err_param_default_argument_template_redecl)
448           << NewParam->getDefaultArgRange();
449         Diag(Old->getLocation(), diag::note_template_prev_declaration)
450           << false;
451       } else if (New->getTemplateSpecializationKind()
452                    != TSK_ImplicitInstantiation &&
453                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
454         // C++ [temp.expr.spec]p21:
455         //   Default function arguments shall not be specified in a declaration
456         //   or a definition for one of the following explicit specializations:
457         //     - the explicit specialization of a function template;
458         //     - the explicit specialization of a member function template;
459         //     - the explicit specialization of a member function of a class 
460         //       template where the class template specialization to which the
461         //       member function specialization belongs is implicitly 
462         //       instantiated.
463         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
464           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
465           << New->getDeclName()
466           << NewParam->getDefaultArgRange();
467       } else if (New->getDeclContext()->isDependentContext()) {
468         // C++ [dcl.fct.default]p6 (DR217):
469         //   Default arguments for a member function of a class template shall 
470         //   be specified on the initial declaration of the member function 
471         //   within the class template.
472         //
473         // Reading the tea leaves a bit in DR217 and its reference to DR205 
474         // leads me to the conclusion that one cannot add default function 
475         // arguments for an out-of-line definition of a member function of a 
476         // dependent type.
477         int WhichKind = 2;
478         if (CXXRecordDecl *Record 
479               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
480           if (Record->getDescribedClassTemplate())
481             WhichKind = 0;
482           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
483             WhichKind = 1;
484           else
485             WhichKind = 2;
486         }
487         
488         Diag(NewParam->getLocation(), 
489              diag::err_param_default_argument_member_template_redecl)
490           << WhichKind
491           << NewParam->getDefaultArgRange();
492       } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
493         CXXSpecialMember NewSM = getSpecialMember(Ctor),
494                          OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
495         if (NewSM != OldSM) {
496           Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
497             << NewParam->getDefaultArgRange() << NewSM;
498           Diag(Old->getLocation(), diag::note_previous_declaration_special)
499             << OldSM;
500         }
501       }
502     }
503   }
504
505   if (CheckEquivalentExceptionSpec(Old, New))
506     Invalid = true;
507
508   return Invalid;
509 }
510
511 /// \brief Merge the exception specifications of two variable declarations.
512 ///
513 /// This is called when there's a redeclaration of a VarDecl. The function
514 /// checks if the redeclaration might have an exception specification and
515 /// validates compatibility and merges the specs if necessary.
516 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
517   // Shortcut if exceptions are disabled.
518   if (!getLangOptions().CXXExceptions)
519     return;
520
521   assert(Context.hasSameType(New->getType(), Old->getType()) &&
522          "Should only be called if types are otherwise the same.");
523
524   QualType NewType = New->getType();
525   QualType OldType = Old->getType();
526
527   // We're only interested in pointers and references to functions, as well
528   // as pointers to member functions.
529   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
530     NewType = R->getPointeeType();
531     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
532   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
533     NewType = P->getPointeeType();
534     OldType = OldType->getAs<PointerType>()->getPointeeType();
535   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
536     NewType = M->getPointeeType();
537     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
538   }
539
540   if (!NewType->isFunctionProtoType())
541     return;
542
543   // There's lots of special cases for functions. For function pointers, system
544   // libraries are hopefully not as broken so that we don't need these
545   // workarounds.
546   if (CheckEquivalentExceptionSpec(
547         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
548         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
549     New->setInvalidDecl();
550   }
551 }
552
553 /// CheckCXXDefaultArguments - Verify that the default arguments for a
554 /// function declaration are well-formed according to C++
555 /// [dcl.fct.default].
556 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
557   unsigned NumParams = FD->getNumParams();
558   unsigned p;
559
560   // Find first parameter with a default argument
561   for (p = 0; p < NumParams; ++p) {
562     ParmVarDecl *Param = FD->getParamDecl(p);
563     if (Param->hasDefaultArg())
564       break;
565   }
566
567   // C++ [dcl.fct.default]p4:
568   //   In a given function declaration, all parameters
569   //   subsequent to a parameter with a default argument shall
570   //   have default arguments supplied in this or previous
571   //   declarations. A default argument shall not be redefined
572   //   by a later declaration (not even to the same value).
573   unsigned LastMissingDefaultArg = 0;
574   for (; p < NumParams; ++p) {
575     ParmVarDecl *Param = FD->getParamDecl(p);
576     if (!Param->hasDefaultArg()) {
577       if (Param->isInvalidDecl())
578         /* We already complained about this parameter. */;
579       else if (Param->getIdentifier())
580         Diag(Param->getLocation(),
581              diag::err_param_default_argument_missing_name)
582           << Param->getIdentifier();
583       else
584         Diag(Param->getLocation(),
585              diag::err_param_default_argument_missing);
586
587       LastMissingDefaultArg = p;
588     }
589   }
590
591   if (LastMissingDefaultArg > 0) {
592     // Some default arguments were missing. Clear out all of the
593     // default arguments up to (and including) the last missing
594     // default argument, so that we leave the function parameters
595     // in a semantically valid state.
596     for (p = 0; p <= LastMissingDefaultArg; ++p) {
597       ParmVarDecl *Param = FD->getParamDecl(p);
598       if (Param->hasDefaultArg()) {
599         Param->setDefaultArg(0);
600       }
601     }
602   }
603 }
604
605 /// isCurrentClassName - Determine whether the identifier II is the
606 /// name of the class type currently being defined. In the case of
607 /// nested classes, this will only return true if II is the name of
608 /// the innermost class.
609 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
610                               const CXXScopeSpec *SS) {
611   assert(getLangOptions().CPlusPlus && "No class names in C!");
612
613   CXXRecordDecl *CurDecl;
614   if (SS && SS->isSet() && !SS->isInvalid()) {
615     DeclContext *DC = computeDeclContext(*SS, true);
616     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
617   } else
618     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
619
620   if (CurDecl && CurDecl->getIdentifier())
621     return &II == CurDecl->getIdentifier();
622   else
623     return false;
624 }
625
626 /// \brief Check the validity of a C++ base class specifier.
627 ///
628 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
629 /// and returns NULL otherwise.
630 CXXBaseSpecifier *
631 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
632                          SourceRange SpecifierRange,
633                          bool Virtual, AccessSpecifier Access,
634                          TypeSourceInfo *TInfo,
635                          SourceLocation EllipsisLoc) {
636   QualType BaseType = TInfo->getType();
637
638   // C++ [class.union]p1:
639   //   A union shall not have base classes.
640   if (Class->isUnion()) {
641     Diag(Class->getLocation(), diag::err_base_clause_on_union)
642       << SpecifierRange;
643     return 0;
644   }
645
646   if (EllipsisLoc.isValid() && 
647       !TInfo->getType()->containsUnexpandedParameterPack()) {
648     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
649       << TInfo->getTypeLoc().getSourceRange();
650     EllipsisLoc = SourceLocation();
651   }
652   
653   if (BaseType->isDependentType())
654     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
655                                           Class->getTagKind() == TTK_Class,
656                                           Access, TInfo, EllipsisLoc);
657
658   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
659
660   // Base specifiers must be record types.
661   if (!BaseType->isRecordType()) {
662     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
663     return 0;
664   }
665
666   // C++ [class.union]p1:
667   //   A union shall not be used as a base class.
668   if (BaseType->isUnionType()) {
669     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
670     return 0;
671   }
672
673   // C++ [class.derived]p2:
674   //   The class-name in a base-specifier shall not be an incompletely
675   //   defined class.
676   if (RequireCompleteType(BaseLoc, BaseType,
677                           PDiag(diag::err_incomplete_base_class)
678                             << SpecifierRange)) {
679     Class->setInvalidDecl();
680     return 0;
681   }
682
683   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
684   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
685   assert(BaseDecl && "Record type has no declaration");
686   BaseDecl = BaseDecl->getDefinition();
687   assert(BaseDecl && "Base type is not incomplete, but has no definition");
688   CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
689   assert(CXXBaseDecl && "Base type is not a C++ type");
690
691   // C++ [class]p3:
692   //   If a class is marked final and it appears as a base-type-specifier in 
693   //   base-clause, the program is ill-formed.
694   if (CXXBaseDecl->hasAttr<FinalAttr>()) {
695     Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 
696       << CXXBaseDecl->getDeclName();
697     Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
698       << CXXBaseDecl->getDeclName();
699     return 0;
700   }
701
702   if (BaseDecl->isInvalidDecl())
703     Class->setInvalidDecl();
704   
705   // Create the base specifier.
706   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
707                                         Class->getTagKind() == TTK_Class,
708                                         Access, TInfo, EllipsisLoc);
709 }
710
711 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
712 /// one entry in the base class list of a class specifier, for
713 /// example:
714 ///    class foo : public bar, virtual private baz {
715 /// 'public bar' and 'virtual private baz' are each base-specifiers.
716 BaseResult
717 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
718                          bool Virtual, AccessSpecifier Access,
719                          ParsedType basetype, SourceLocation BaseLoc,
720                          SourceLocation EllipsisLoc) {
721   if (!classdecl)
722     return true;
723
724   AdjustDeclIfTemplate(classdecl);
725   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
726   if (!Class)
727     return true;
728
729   TypeSourceInfo *TInfo = 0;
730   GetTypeFromParser(basetype, &TInfo);
731
732   if (EllipsisLoc.isInvalid() &&
733       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 
734                                       UPPC_BaseType))
735     return true;
736   
737   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
738                                                       Virtual, Access, TInfo,
739                                                       EllipsisLoc))
740     return BaseSpec;
741
742   return true;
743 }
744
745 /// \brief Performs the actual work of attaching the given base class
746 /// specifiers to a C++ class.
747 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
748                                 unsigned NumBases) {
749  if (NumBases == 0)
750     return false;
751
752   // Used to keep track of which base types we have already seen, so
753   // that we can properly diagnose redundant direct base types. Note
754   // that the key is always the unqualified canonical type of the base
755   // class.
756   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
757
758   // Copy non-redundant base specifiers into permanent storage.
759   unsigned NumGoodBases = 0;
760   bool Invalid = false;
761   for (unsigned idx = 0; idx < NumBases; ++idx) {
762     QualType NewBaseType
763       = Context.getCanonicalType(Bases[idx]->getType());
764     NewBaseType = NewBaseType.getLocalUnqualifiedType();
765     if (!Class->hasObjectMember()) {
766       if (const RecordType *FDTTy = 
767             NewBaseType.getTypePtr()->getAs<RecordType>())
768         if (FDTTy->getDecl()->hasObjectMember())
769           Class->setHasObjectMember(true);
770     }
771     
772     if (KnownBaseTypes[NewBaseType]) {
773       // C++ [class.mi]p3:
774       //   A class shall not be specified as a direct base class of a
775       //   derived class more than once.
776       Diag(Bases[idx]->getSourceRange().getBegin(),
777            diag::err_duplicate_base_class)
778         << KnownBaseTypes[NewBaseType]->getType()
779         << Bases[idx]->getSourceRange();
780
781       // Delete the duplicate base class specifier; we're going to
782       // overwrite its pointer later.
783       Context.Deallocate(Bases[idx]);
784
785       Invalid = true;
786     } else {
787       // Okay, add this new base class.
788       KnownBaseTypes[NewBaseType] = Bases[idx];
789       Bases[NumGoodBases++] = Bases[idx];
790     }
791   }
792
793   // Attach the remaining base class specifiers to the derived class.
794   Class->setBases(Bases, NumGoodBases);
795
796   // Delete the remaining (good) base class specifiers, since their
797   // data has been copied into the CXXRecordDecl.
798   for (unsigned idx = 0; idx < NumGoodBases; ++idx)
799     Context.Deallocate(Bases[idx]);
800
801   return Invalid;
802 }
803
804 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
805 /// class, after checking whether there are any duplicate base
806 /// classes.
807 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
808                                unsigned NumBases) {
809   if (!ClassDecl || !Bases || !NumBases)
810     return;
811
812   AdjustDeclIfTemplate(ClassDecl);
813   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
814                        (CXXBaseSpecifier**)(Bases), NumBases);
815 }
816
817 static CXXRecordDecl *GetClassForType(QualType T) {
818   if (const RecordType *RT = T->getAs<RecordType>())
819     return cast<CXXRecordDecl>(RT->getDecl());
820   else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
821     return ICT->getDecl();
822   else
823     return 0;
824 }
825
826 /// \brief Determine whether the type \p Derived is a C++ class that is
827 /// derived from the type \p Base.
828 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
829   if (!getLangOptions().CPlusPlus)
830     return false;
831   
832   CXXRecordDecl *DerivedRD = GetClassForType(Derived);
833   if (!DerivedRD)
834     return false;
835   
836   CXXRecordDecl *BaseRD = GetClassForType(Base);
837   if (!BaseRD)
838     return false;
839   
840   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
841   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
842 }
843
844 /// \brief Determine whether the type \p Derived is a C++ class that is
845 /// derived from the type \p Base.
846 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
847   if (!getLangOptions().CPlusPlus)
848     return false;
849   
850   CXXRecordDecl *DerivedRD = GetClassForType(Derived);
851   if (!DerivedRD)
852     return false;
853   
854   CXXRecordDecl *BaseRD = GetClassForType(Base);
855   if (!BaseRD)
856     return false;
857   
858   return DerivedRD->isDerivedFrom(BaseRD, Paths);
859 }
860
861 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 
862                               CXXCastPath &BasePathArray) {
863   assert(BasePathArray.empty() && "Base path array must be empty!");
864   assert(Paths.isRecordingPaths() && "Must record paths!");
865   
866   const CXXBasePath &Path = Paths.front();
867        
868   // We first go backward and check if we have a virtual base.
869   // FIXME: It would be better if CXXBasePath had the base specifier for
870   // the nearest virtual base.
871   unsigned Start = 0;
872   for (unsigned I = Path.size(); I != 0; --I) {
873     if (Path[I - 1].Base->isVirtual()) {
874       Start = I - 1;
875       break;
876     }
877   }
878
879   // Now add all bases.
880   for (unsigned I = Start, E = Path.size(); I != E; ++I)
881     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
882 }
883
884 /// \brief Determine whether the given base path includes a virtual
885 /// base class.
886 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
887   for (CXXCastPath::const_iterator B = BasePath.begin(), 
888                                 BEnd = BasePath.end();
889        B != BEnd; ++B)
890     if ((*B)->isVirtual())
891       return true;
892
893   return false;
894 }
895
896 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
897 /// conversion (where Derived and Base are class types) is
898 /// well-formed, meaning that the conversion is unambiguous (and
899 /// that all of the base classes are accessible). Returns true
900 /// and emits a diagnostic if the code is ill-formed, returns false
901 /// otherwise. Loc is the location where this routine should point to
902 /// if there is an error, and Range is the source range to highlight
903 /// if there is an error.
904 bool
905 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
906                                    unsigned InaccessibleBaseID,
907                                    unsigned AmbigiousBaseConvID,
908                                    SourceLocation Loc, SourceRange Range,
909                                    DeclarationName Name,
910                                    CXXCastPath *BasePath) {
911   // First, determine whether the path from Derived to Base is
912   // ambiguous. This is slightly more expensive than checking whether
913   // the Derived to Base conversion exists, because here we need to
914   // explore multiple paths to determine if there is an ambiguity.
915   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
916                      /*DetectVirtual=*/false);
917   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
918   assert(DerivationOkay &&
919          "Can only be used with a derived-to-base conversion");
920   (void)DerivationOkay;
921   
922   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
923     if (InaccessibleBaseID) {
924       // Check that the base class can be accessed.
925       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
926                                    InaccessibleBaseID)) {
927         case AR_inaccessible: 
928           return true;
929         case AR_accessible: 
930         case AR_dependent:
931         case AR_delayed:
932           break;
933       }
934     }
935     
936     // Build a base path if necessary.
937     if (BasePath)
938       BuildBasePathArray(Paths, *BasePath);
939     return false;
940   }
941   
942   // We know that the derived-to-base conversion is ambiguous, and
943   // we're going to produce a diagnostic. Perform the derived-to-base
944   // search just one more time to compute all of the possible paths so
945   // that we can print them out. This is more expensive than any of
946   // the previous derived-to-base checks we've done, but at this point
947   // performance isn't as much of an issue.
948   Paths.clear();
949   Paths.setRecordingPaths(true);
950   bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
951   assert(StillOkay && "Can only be used with a derived-to-base conversion");
952   (void)StillOkay;
953   
954   // Build up a textual representation of the ambiguous paths, e.g.,
955   // D -> B -> A, that will be used to illustrate the ambiguous
956   // conversions in the diagnostic. We only print one of the paths
957   // to each base class subobject.
958   std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
959   
960   Diag(Loc, AmbigiousBaseConvID)
961   << Derived << Base << PathDisplayStr << Range << Name;
962   return true;
963 }
964
965 bool
966 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
967                                    SourceLocation Loc, SourceRange Range,
968                                    CXXCastPath *BasePath,
969                                    bool IgnoreAccess) {
970   return CheckDerivedToBaseConversion(Derived, Base,
971                                       IgnoreAccess ? 0
972                                        : diag::err_upcast_to_inaccessible_base,
973                                       diag::err_ambiguous_derived_to_base_conv,
974                                       Loc, Range, DeclarationName(), 
975                                       BasePath);
976 }
977
978
979 /// @brief Builds a string representing ambiguous paths from a
980 /// specific derived class to different subobjects of the same base
981 /// class.
982 ///
983 /// This function builds a string that can be used in error messages
984 /// to show the different paths that one can take through the
985 /// inheritance hierarchy to go from the derived class to different
986 /// subobjects of a base class. The result looks something like this:
987 /// @code
988 /// struct D -> struct B -> struct A
989 /// struct D -> struct C -> struct A
990 /// @endcode
991 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
992   std::string PathDisplayStr;
993   std::set<unsigned> DisplayedPaths;
994   for (CXXBasePaths::paths_iterator Path = Paths.begin();
995        Path != Paths.end(); ++Path) {
996     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
997       // We haven't displayed a path to this particular base
998       // class subobject yet.
999       PathDisplayStr += "\n    ";
1000       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1001       for (CXXBasePath::const_iterator Element = Path->begin();
1002            Element != Path->end(); ++Element)
1003         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1004     }
1005   }
1006   
1007   return PathDisplayStr;
1008 }
1009
1010 //===----------------------------------------------------------------------===//
1011 // C++ class member Handling
1012 //===----------------------------------------------------------------------===//
1013
1014 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1015 Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1016                                  SourceLocation ASLoc,
1017                                  SourceLocation ColonLoc) {
1018   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1019   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1020                                                   ASLoc, ColonLoc);
1021   CurContext->addHiddenDecl(ASDecl);
1022   return ASDecl;
1023 }
1024
1025 /// CheckOverrideControl - Check C++0x override control semantics.
1026 void Sema::CheckOverrideControl(const Decl *D) {
1027   const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
1028   if (!MD || !MD->isVirtual())
1029     return;
1030
1031   if (MD->isDependentContext())
1032     return;
1033
1034   // C++0x [class.virtual]p3:
1035   //   If a virtual function is marked with the virt-specifier override and does
1036   //   not override a member function of a base class, 
1037   //   the program is ill-formed.
1038   bool HasOverriddenMethods = 
1039     MD->begin_overridden_methods() != MD->end_overridden_methods();
1040   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
1041     Diag(MD->getLocation(), 
1042                  diag::err_function_marked_override_not_overriding)
1043       << MD->getDeclName();
1044     return;
1045   }
1046 }
1047
1048 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 
1049 /// function overrides a virtual member function marked 'final', according to
1050 /// C++0x [class.virtual]p3.
1051 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1052                                                   const CXXMethodDecl *Old) {
1053   if (!Old->hasAttr<FinalAttr>())
1054     return false;
1055
1056   Diag(New->getLocation(), diag::err_final_function_overridden)
1057     << New->getDeclName();
1058   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1059   return true;
1060 }
1061
1062 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1063 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1064 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1065 /// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1066 /// present but parsing it has been deferred.
1067 Decl *
1068 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1069                                MultiTemplateParamsArg TemplateParameterLists,
1070                                ExprTy *BW, const VirtSpecifiers &VS,
1071                                ExprTy *InitExpr, bool HasDeferredInit,
1072                                bool IsDefinition) {
1073   const DeclSpec &DS = D.getDeclSpec();
1074   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1075   DeclarationName Name = NameInfo.getName();
1076   SourceLocation Loc = NameInfo.getLoc();
1077
1078   // For anonymous bitfields, the location should point to the type.
1079   if (Loc.isInvalid())
1080     Loc = D.getSourceRange().getBegin();
1081
1082   Expr *BitWidth = static_cast<Expr*>(BW);
1083   Expr *Init = static_cast<Expr*>(InitExpr);
1084
1085   assert(isa<CXXRecordDecl>(CurContext));
1086   assert(!DS.isFriendSpecified());
1087   assert(!Init || !HasDeferredInit);
1088
1089   bool isFunc = false;
1090   if (D.isFunctionDeclarator())
1091     isFunc = true;
1092   else if (D.getNumTypeObjects() == 0 &&
1093            D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
1094     QualType TDType = GetTypeFromParser(DS.getRepAsType());
1095     isFunc = TDType->isFunctionType();
1096   }
1097
1098   // C++ 9.2p6: A member shall not be declared to have automatic storage
1099   // duration (auto, register) or with the extern storage-class-specifier.
1100   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1101   // data members and cannot be applied to names declared const or static,
1102   // and cannot be applied to reference members.
1103   switch (DS.getStorageClassSpec()) {
1104     case DeclSpec::SCS_unspecified:
1105     case DeclSpec::SCS_typedef:
1106     case DeclSpec::SCS_static:
1107       // FALL THROUGH.
1108       break;
1109     case DeclSpec::SCS_mutable:
1110       if (isFunc) {
1111         if (DS.getStorageClassSpecLoc().isValid())
1112           Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1113         else
1114           Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1115
1116         // FIXME: It would be nicer if the keyword was ignored only for this
1117         // declarator. Otherwise we could get follow-up errors.
1118         D.getMutableDeclSpec().ClearStorageClassSpecs();
1119       }
1120       break;
1121     default:
1122       if (DS.getStorageClassSpecLoc().isValid())
1123         Diag(DS.getStorageClassSpecLoc(),
1124              diag::err_storageclass_invalid_for_member);
1125       else
1126         Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1127       D.getMutableDeclSpec().ClearStorageClassSpecs();
1128   }
1129
1130   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1131                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1132                       !isFunc);
1133
1134   Decl *Member;
1135   if (isInstField) {
1136     CXXScopeSpec &SS = D.getCXXScopeSpec();
1137     
1138     if (SS.isSet() && !SS.isInvalid()) {
1139       // The user provided a superfluous scope specifier inside a class
1140       // definition:
1141       //
1142       // class X {
1143       //   int X::member;
1144       // };
1145       DeclContext *DC = 0;
1146       if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1147         Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1148         << Name << FixItHint::CreateRemoval(SS.getRange());
1149       else
1150         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1151           << Name << SS.getRange();
1152        
1153       SS.clear();
1154     }
1155     
1156     // FIXME: Check for template parameters!
1157     // FIXME: Check that the name is an identifier!
1158     Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1159                          HasDeferredInit, AS);
1160     assert(Member && "HandleField never returns null");
1161   } else {
1162     assert(!HasDeferredInit);
1163
1164     Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
1165     if (!Member) {
1166       return 0;
1167     }
1168
1169     // Non-instance-fields can't have a bitfield.
1170     if (BitWidth) {
1171       if (Member->isInvalidDecl()) {
1172         // don't emit another diagnostic.
1173       } else if (isa<VarDecl>(Member)) {
1174         // C++ 9.6p3: A bit-field shall not be a static member.
1175         // "static member 'A' cannot be a bit-field"
1176         Diag(Loc, diag::err_static_not_bitfield)
1177           << Name << BitWidth->getSourceRange();
1178       } else if (isa<TypedefDecl>(Member)) {
1179         // "typedef member 'x' cannot be a bit-field"
1180         Diag(Loc, diag::err_typedef_not_bitfield)
1181           << Name << BitWidth->getSourceRange();
1182       } else {
1183         // A function typedef ("typedef int f(); f a;").
1184         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1185         Diag(Loc, diag::err_not_integral_type_bitfield)
1186           << Name << cast<ValueDecl>(Member)->getType()
1187           << BitWidth->getSourceRange();
1188       }
1189
1190       BitWidth = 0;
1191       Member->setInvalidDecl();
1192     }
1193
1194     Member->setAccess(AS);
1195
1196     // If we have declared a member function template, set the access of the
1197     // templated declaration as well.
1198     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1199       FunTmpl->getTemplatedDecl()->setAccess(AS);
1200   }
1201
1202   if (VS.isOverrideSpecified()) {
1203     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1204     if (!MD || !MD->isVirtual()) {
1205       Diag(Member->getLocStart(), 
1206            diag::override_keyword_only_allowed_on_virtual_member_functions)
1207         << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
1208     } else
1209       MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1210   }
1211   if (VS.isFinalSpecified()) {
1212     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1213     if (!MD || !MD->isVirtual()) {
1214       Diag(Member->getLocStart(), 
1215            diag::override_keyword_only_allowed_on_virtual_member_functions)
1216       << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
1217     } else
1218       MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1219   }
1220
1221   if (VS.getLastLocation().isValid()) {
1222     // Update the end location of a method that has a virt-specifiers.
1223     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1224       MD->setRangeEnd(VS.getLastLocation());
1225   }
1226       
1227   CheckOverrideControl(Member);
1228
1229   assert((Name || isInstField) && "No identifier for non-field ?");
1230
1231   if (Init)
1232     AddInitializerToDecl(Member, Init, false,
1233                          DS.getTypeSpecType() == DeclSpec::TST_auto);
1234   else if (DS.getTypeSpecType() == DeclSpec::TST_auto &&
1235            DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1236     // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static
1237     // data member if a brace-or-equal-initializer is provided.
1238     Diag(Loc, diag::err_auto_var_requires_init)
1239       << Name << cast<ValueDecl>(Member)->getType();
1240     Member->setInvalidDecl();
1241   }
1242
1243   FinalizeDeclaration(Member);
1244
1245   if (isInstField)
1246     FieldCollector->Add(cast<FieldDecl>(Member));
1247   return Member;
1248 }
1249
1250 /// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1251 /// in-class initializer for a non-static C++ class member. Such parsing
1252 /// is deferred until the class is complete.
1253 void
1254 Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1255                                        Expr *InitExpr) {
1256   FieldDecl *FD = cast<FieldDecl>(D);
1257
1258   if (!InitExpr) {
1259     FD->setInvalidDecl();
1260     FD->removeInClassInitializer();
1261     return;
1262   }
1263
1264   ExprResult Init = InitExpr;
1265   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1266     // FIXME: if there is no EqualLoc, this is list-initialization.
1267     Init = PerformCopyInitialization(
1268       InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1269     if (Init.isInvalid()) {
1270       FD->setInvalidDecl();
1271       return;
1272     }
1273
1274     CheckImplicitConversions(Init.get(), EqualLoc);
1275   }
1276
1277   // C++0x [class.base.init]p7:
1278   //   The initialization of each base and member constitutes a
1279   //   full-expression.
1280   Init = MaybeCreateExprWithCleanups(Init);
1281   if (Init.isInvalid()) {
1282     FD->setInvalidDecl();
1283     return;
1284   }
1285
1286   InitExpr = Init.release();
1287
1288   FD->setInClassInitializer(InitExpr);
1289 }
1290
1291 /// \brief Find the direct and/or virtual base specifiers that
1292 /// correspond to the given base type, for use in base initialization
1293 /// within a constructor.
1294 static bool FindBaseInitializer(Sema &SemaRef, 
1295                                 CXXRecordDecl *ClassDecl,
1296                                 QualType BaseType,
1297                                 const CXXBaseSpecifier *&DirectBaseSpec,
1298                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
1299   // First, check for a direct base class.
1300   DirectBaseSpec = 0;
1301   for (CXXRecordDecl::base_class_const_iterator Base
1302          = ClassDecl->bases_begin(); 
1303        Base != ClassDecl->bases_end(); ++Base) {
1304     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1305       // We found a direct base of this type. That's what we're
1306       // initializing.
1307       DirectBaseSpec = &*Base;
1308       break;
1309     }
1310   }
1311
1312   // Check for a virtual base class.
1313   // FIXME: We might be able to short-circuit this if we know in advance that
1314   // there are no virtual bases.
1315   VirtualBaseSpec = 0;
1316   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1317     // We haven't found a base yet; search the class hierarchy for a
1318     // virtual base class.
1319     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1320                        /*DetectVirtual=*/false);
1321     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 
1322                               BaseType, Paths)) {
1323       for (CXXBasePaths::paths_iterator Path = Paths.begin();
1324            Path != Paths.end(); ++Path) {
1325         if (Path->back().Base->isVirtual()) {
1326           VirtualBaseSpec = Path->back().Base;
1327           break;
1328         }
1329       }
1330     }
1331   }
1332
1333   return DirectBaseSpec || VirtualBaseSpec;
1334 }
1335
1336 /// ActOnMemInitializer - Handle a C++ member initializer.
1337 MemInitResult
1338 Sema::ActOnMemInitializer(Decl *ConstructorD,
1339                           Scope *S,
1340                           CXXScopeSpec &SS,
1341                           IdentifierInfo *MemberOrBase,
1342                           ParsedType TemplateTypeTy,
1343                           SourceLocation IdLoc,
1344                           SourceLocation LParenLoc,
1345                           ExprTy **Args, unsigned NumArgs,
1346                           SourceLocation RParenLoc,
1347                           SourceLocation EllipsisLoc) {
1348   if (!ConstructorD)
1349     return true;
1350
1351   AdjustDeclIfTemplate(ConstructorD);
1352
1353   CXXConstructorDecl *Constructor
1354     = dyn_cast<CXXConstructorDecl>(ConstructorD);
1355   if (!Constructor) {
1356     // The user wrote a constructor initializer on a function that is
1357     // not a C++ constructor. Ignore the error for now, because we may
1358     // have more member initializers coming; we'll diagnose it just
1359     // once in ActOnMemInitializers.
1360     return true;
1361   }
1362
1363   CXXRecordDecl *ClassDecl = Constructor->getParent();
1364
1365   // C++ [class.base.init]p2:
1366   //   Names in a mem-initializer-id are looked up in the scope of the
1367   //   constructor's class and, if not found in that scope, are looked
1368   //   up in the scope containing the constructor's definition.
1369   //   [Note: if the constructor's class contains a member with the
1370   //   same name as a direct or virtual base class of the class, a
1371   //   mem-initializer-id naming the member or base class and composed
1372   //   of a single identifier refers to the class member. A
1373   //   mem-initializer-id for the hidden base class may be specified
1374   //   using a qualified name. ]
1375   if (!SS.getScopeRep() && !TemplateTypeTy) {
1376     // Look for a member, first.
1377     FieldDecl *Member = 0;
1378     DeclContext::lookup_result Result
1379       = ClassDecl->lookup(MemberOrBase);
1380     if (Result.first != Result.second) {
1381       Member = dyn_cast<FieldDecl>(*Result.first);
1382     
1383       if (Member) {
1384         if (EllipsisLoc.isValid())
1385           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1386             << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1387         
1388         return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1389                                     LParenLoc, RParenLoc);
1390       }
1391       
1392       // Handle anonymous union case.
1393       if (IndirectFieldDecl* IndirectField
1394             = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1395         if (EllipsisLoc.isValid())
1396           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1397             << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1398
1399          return BuildMemberInitializer(IndirectField, (Expr**)Args,
1400                                        NumArgs, IdLoc,
1401                                        LParenLoc, RParenLoc);
1402       }
1403     }
1404   }
1405   // It didn't name a member, so see if it names a class.
1406   QualType BaseType;
1407   TypeSourceInfo *TInfo = 0;
1408
1409   if (TemplateTypeTy) {
1410     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1411   } else {
1412     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1413     LookupParsedName(R, S, &SS);
1414
1415     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1416     if (!TyD) {
1417       if (R.isAmbiguous()) return true;
1418
1419       // We don't want access-control diagnostics here.
1420       R.suppressDiagnostics();
1421
1422       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1423         bool NotUnknownSpecialization = false;
1424         DeclContext *DC = computeDeclContext(SS, false);
1425         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 
1426           NotUnknownSpecialization = !Record->hasAnyDependentBases();
1427
1428         if (!NotUnknownSpecialization) {
1429           // When the scope specifier can refer to a member of an unknown
1430           // specialization, we take it as a type name.
1431           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1432                                        SS.getWithLocInContext(Context),
1433                                        *MemberOrBase, IdLoc);
1434           if (BaseType.isNull())
1435             return true;
1436
1437           R.clear();
1438           R.setLookupName(MemberOrBase);
1439         }
1440       }
1441
1442       // If no results were found, try to correct typos.
1443       if (R.empty() && BaseType.isNull() &&
1444           CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) && 
1445           R.isSingleResult()) {
1446         if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1447           if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
1448             // We have found a non-static data member with a similar
1449             // name to what was typed; complain and initialize that
1450             // member.
1451             Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1452               << MemberOrBase << true << R.getLookupName()
1453               << FixItHint::CreateReplacement(R.getNameLoc(),
1454                                               R.getLookupName().getAsString());
1455             Diag(Member->getLocation(), diag::note_previous_decl)
1456               << Member->getDeclName();
1457
1458             return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1459                                           LParenLoc, RParenLoc);
1460           }
1461         } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1462           const CXXBaseSpecifier *DirectBaseSpec;
1463           const CXXBaseSpecifier *VirtualBaseSpec;
1464           if (FindBaseInitializer(*this, ClassDecl, 
1465                                   Context.getTypeDeclType(Type),
1466                                   DirectBaseSpec, VirtualBaseSpec)) {
1467             // We have found a direct or virtual base class with a
1468             // similar name to what was typed; complain and initialize
1469             // that base class.
1470             Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1471               << MemberOrBase << false << R.getLookupName()
1472               << FixItHint::CreateReplacement(R.getNameLoc(),
1473                                               R.getLookupName().getAsString());
1474
1475             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 
1476                                                              : VirtualBaseSpec;
1477             Diag(BaseSpec->getSourceRange().getBegin(),
1478                  diag::note_base_class_specified_here)
1479               << BaseSpec->getType()
1480               << BaseSpec->getSourceRange();
1481
1482             TyD = Type;
1483           }
1484         }
1485       }
1486
1487       if (!TyD && BaseType.isNull()) {
1488         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1489           << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1490         return true;
1491       }
1492     }
1493
1494     if (BaseType.isNull()) {
1495       BaseType = Context.getTypeDeclType(TyD);
1496       if (SS.isSet()) {
1497         NestedNameSpecifier *Qualifier =
1498           static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1499
1500         // FIXME: preserve source range information
1501         BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
1502       }
1503     }
1504   }
1505
1506   if (!TInfo)
1507     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1508
1509   return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs, 
1510                               LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
1511 }
1512
1513 /// Checks an initializer expression for use of uninitialized fields, such as
1514 /// containing the field that is being initialized. Returns true if there is an
1515 /// uninitialized field was used an updates the SourceLocation parameter; false
1516 /// otherwise.
1517 static bool InitExprContainsUninitializedFields(const Stmt *S,
1518                                                 const ValueDecl *LhsField,
1519                                                 SourceLocation *L) {
1520   assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1521
1522   if (isa<CallExpr>(S)) {
1523     // Do not descend into function calls or constructors, as the use
1524     // of an uninitialized field may be valid. One would have to inspect
1525     // the contents of the function/ctor to determine if it is safe or not.
1526     // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1527     // may be safe, depending on what the function/ctor does.
1528     return false;
1529   }
1530   if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1531     const NamedDecl *RhsField = ME->getMemberDecl();
1532
1533     if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1534       // The member expression points to a static data member.
1535       assert(VD->isStaticDataMember() && 
1536              "Member points to non-static data member!");
1537       (void)VD;
1538       return false;
1539     }
1540     
1541     if (isa<EnumConstantDecl>(RhsField)) {
1542       // The member expression points to an enum.
1543       return false;
1544     }
1545
1546     if (RhsField == LhsField) {
1547       // Initializing a field with itself. Throw a warning.
1548       // But wait; there are exceptions!
1549       // Exception #1:  The field may not belong to this record.
1550       // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1551       const Expr *base = ME->getBase();
1552       if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1553         // Even though the field matches, it does not belong to this record.
1554         return false;
1555       }
1556       // None of the exceptions triggered; return true to indicate an
1557       // uninitialized field was used.
1558       *L = ME->getMemberLoc();
1559       return true;
1560     }
1561   } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
1562     // sizeof/alignof doesn't reference contents, do not warn.
1563     return false;
1564   } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1565     // address-of doesn't reference contents (the pointer may be dereferenced
1566     // in the same expression but it would be rare; and weird).
1567     if (UOE->getOpcode() == UO_AddrOf)
1568       return false;
1569   }
1570   for (Stmt::const_child_range it = S->children(); it; ++it) {
1571     if (!*it) {
1572       // An expression such as 'member(arg ?: "")' may trigger this.
1573       continue;
1574     }
1575     if (InitExprContainsUninitializedFields(*it, LhsField, L))
1576       return true;
1577   }
1578   return false;
1579 }
1580
1581 MemInitResult
1582 Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
1583                              unsigned NumArgs, SourceLocation IdLoc,
1584                              SourceLocation LParenLoc,
1585                              SourceLocation RParenLoc) {
1586   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1587   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1588   assert((DirectMember || IndirectMember) &&
1589          "Member must be a FieldDecl or IndirectFieldDecl");
1590
1591   if (Member->isInvalidDecl())
1592     return true;
1593
1594   // Diagnose value-uses of fields to initialize themselves, e.g.
1595   //   foo(foo)
1596   // where foo is not also a parameter to the constructor.
1597   // TODO: implement -Wuninitialized and fold this into that framework.
1598   for (unsigned i = 0; i < NumArgs; ++i) {
1599     SourceLocation L;
1600     if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1601       // FIXME: Return true in the case when other fields are used before being
1602       // uninitialized. For example, let this field be the i'th field. When
1603       // initializing the i'th field, throw a warning if any of the >= i'th
1604       // fields are used, as they are not yet initialized.
1605       // Right now we are only handling the case where the i'th field uses
1606       // itself in its initializer.
1607       Diag(L, diag::warn_field_is_uninit);
1608     }
1609   }
1610
1611   bool HasDependentArg = false;
1612   for (unsigned i = 0; i < NumArgs; i++)
1613     HasDependentArg |= Args[i]->isTypeDependent();
1614
1615   Expr *Init;
1616   if (Member->getType()->isDependentType() || HasDependentArg) {
1617     // Can't check initialization for a member of dependent type or when
1618     // any of the arguments are type-dependent expressions.
1619     Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1620                                        RParenLoc);
1621
1622     // Erase any temporaries within this evaluation context; we're not
1623     // going to track them in the AST, since we'll be rebuilding the
1624     // ASTs during template instantiation.
1625     ExprTemporaries.erase(
1626               ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1627                           ExprTemporaries.end());
1628   } else {
1629     // Initialize the member.
1630     InitializedEntity MemberEntity =
1631       DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1632                    : InitializedEntity::InitializeMember(IndirectMember, 0);
1633     InitializationKind Kind =
1634       InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1635
1636     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1637
1638     ExprResult MemberInit =
1639       InitSeq.Perform(*this, MemberEntity, Kind,
1640                       MultiExprArg(*this, Args, NumArgs), 0);
1641     if (MemberInit.isInvalid())
1642       return true;
1643
1644     CheckImplicitConversions(MemberInit.get(), LParenLoc);
1645
1646     // C++0x [class.base.init]p7:
1647     //   The initialization of each base and member constitutes a
1648     //   full-expression.
1649     MemberInit = MaybeCreateExprWithCleanups(MemberInit);
1650     if (MemberInit.isInvalid())
1651       return true;
1652
1653     // If we are in a dependent context, template instantiation will
1654     // perform this type-checking again. Just save the arguments that we
1655     // received in a ParenListExpr.
1656     // FIXME: This isn't quite ideal, since our ASTs don't capture all
1657     // of the information that we have about the member
1658     // initializer. However, deconstructing the ASTs is a dicey process,
1659     // and this approach is far more likely to get the corner cases right.
1660     if (CurContext->isDependentContext())
1661       Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1662                                                RParenLoc);
1663     else
1664       Init = MemberInit.get();
1665   }
1666
1667   if (DirectMember) {
1668     return new (Context) CXXCtorInitializer(Context, DirectMember,
1669                                                     IdLoc, LParenLoc, Init,
1670                                                     RParenLoc);
1671   } else {
1672     return new (Context) CXXCtorInitializer(Context, IndirectMember,
1673                                                     IdLoc, LParenLoc, Init,
1674                                                     RParenLoc);
1675   }
1676 }
1677
1678 MemInitResult
1679 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1680                                  Expr **Args, unsigned NumArgs,
1681                                  SourceLocation NameLoc,
1682                                  SourceLocation LParenLoc,
1683                                  SourceLocation RParenLoc,
1684                                  CXXRecordDecl *ClassDecl) {
1685   SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1686   if (!LangOpts.CPlusPlus0x)
1687     return Diag(Loc, diag::err_delegation_0x_only)
1688       << TInfo->getTypeLoc().getLocalSourceRange();
1689
1690   // Initialize the object.
1691   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1692                                      QualType(ClassDecl->getTypeForDecl(), 0));
1693   InitializationKind Kind =
1694     InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1695
1696   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1697
1698   ExprResult DelegationInit =
1699     InitSeq.Perform(*this, DelegationEntity, Kind,
1700                     MultiExprArg(*this, Args, NumArgs), 0);
1701   if (DelegationInit.isInvalid())
1702     return true;
1703
1704   CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
1705   CXXConstructorDecl *Constructor
1706     = ConExpr->getConstructor();
1707   assert(Constructor && "Delegating constructor with no target?");
1708
1709   CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1710
1711   // C++0x [class.base.init]p7:
1712   //   The initialization of each base and member constitutes a
1713   //   full-expression.
1714   DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1715   if (DelegationInit.isInvalid())
1716     return true;
1717
1718   // If we are in a dependent context, template instantiation will
1719   // perform this type-checking again. Just save the arguments that we
1720   // received in a ParenListExpr.
1721   // FIXME: This isn't quite ideal, since our ASTs don't capture all
1722   // of the information that we have about the base
1723   // initializer. However, deconstructing the ASTs is a dicey process,
1724   // and this approach is far more likely to get the corner cases right.
1725   if (CurContext->isDependentContext()) {
1726     ExprResult Init
1727       = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1728                                           NumArgs, RParenLoc));
1729     return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1730                                             Constructor, Init.takeAs<Expr>(),
1731                                             RParenLoc);
1732   }
1733
1734   return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1735                                           DelegationInit.takeAs<Expr>(),
1736                                           RParenLoc);
1737 }
1738
1739 MemInitResult
1740 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
1741                            Expr **Args, unsigned NumArgs, 
1742                            SourceLocation LParenLoc, SourceLocation RParenLoc, 
1743                            CXXRecordDecl *ClassDecl,
1744                            SourceLocation EllipsisLoc) {
1745   bool HasDependentArg = false;
1746   for (unsigned i = 0; i < NumArgs; i++)
1747     HasDependentArg |= Args[i]->isTypeDependent();
1748
1749   SourceLocation BaseLoc
1750     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1751   
1752   if (!BaseType->isDependentType() && !BaseType->isRecordType())
1753     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1754              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1755
1756   // C++ [class.base.init]p2:
1757   //   [...] Unless the mem-initializer-id names a nonstatic data
1758   //   member of the constructor's class or a direct or virtual base
1759   //   of that class, the mem-initializer is ill-formed. A
1760   //   mem-initializer-list can initialize a base class using any
1761   //   name that denotes that base class type.
1762   bool Dependent = BaseType->isDependentType() || HasDependentArg;
1763
1764   if (EllipsisLoc.isValid()) {
1765     // This is a pack expansion.
1766     if (!BaseType->containsUnexpandedParameterPack())  {
1767       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1768         << SourceRange(BaseLoc, RParenLoc);
1769       
1770       EllipsisLoc = SourceLocation();
1771     }
1772   } else {
1773     // Check for any unexpanded parameter packs.
1774     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1775       return true;
1776     
1777     for (unsigned I = 0; I != NumArgs; ++I)
1778       if (DiagnoseUnexpandedParameterPack(Args[I]))
1779         return true;
1780   }
1781   
1782   // Check for direct and virtual base classes.
1783   const CXXBaseSpecifier *DirectBaseSpec = 0;
1784   const CXXBaseSpecifier *VirtualBaseSpec = 0;
1785   if (!Dependent) { 
1786     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1787                                        BaseType))
1788       return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1789                                         LParenLoc, RParenLoc, ClassDecl);
1790
1791     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 
1792                         VirtualBaseSpec);
1793
1794     // C++ [base.class.init]p2:
1795     // Unless the mem-initializer-id names a nonstatic data member of the
1796     // constructor's class or a direct or virtual base of that class, the
1797     // mem-initializer is ill-formed.
1798     if (!DirectBaseSpec && !VirtualBaseSpec) {
1799       // If the class has any dependent bases, then it's possible that
1800       // one of those types will resolve to the same type as
1801       // BaseType. Therefore, just treat this as a dependent base
1802       // class initialization.  FIXME: Should we try to check the
1803       // initialization anyway? It seems odd.
1804       if (ClassDecl->hasAnyDependentBases())
1805         Dependent = true;
1806       else
1807         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1808           << BaseType << Context.getTypeDeclType(ClassDecl)
1809           << BaseTInfo->getTypeLoc().getLocalSourceRange();
1810     }
1811   }
1812
1813   if (Dependent) {
1814     // Can't check initialization for a base of dependent type or when
1815     // any of the arguments are type-dependent expressions.
1816     ExprResult BaseInit
1817       = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1818                                           RParenLoc));
1819
1820     // Erase any temporaries within this evaluation context; we're not
1821     // going to track them in the AST, since we'll be rebuilding the
1822     // ASTs during template instantiation.
1823     ExprTemporaries.erase(
1824               ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1825                           ExprTemporaries.end());
1826
1827     return new (Context) CXXCtorInitializer(Context, BaseTInfo, 
1828                                                     /*IsVirtual=*/false,
1829                                                     LParenLoc, 
1830                                                     BaseInit.takeAs<Expr>(),
1831                                                     RParenLoc,
1832                                                     EllipsisLoc);
1833   }
1834
1835   // C++ [base.class.init]p2:
1836   //   If a mem-initializer-id is ambiguous because it designates both
1837   //   a direct non-virtual base class and an inherited virtual base
1838   //   class, the mem-initializer is ill-formed.
1839   if (DirectBaseSpec && VirtualBaseSpec)
1840     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1841       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1842
1843   CXXBaseSpecifier *BaseSpec
1844     = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1845   if (!BaseSpec)
1846     BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1847
1848   // Initialize the base.
1849   InitializedEntity BaseEntity =
1850     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
1851   InitializationKind Kind = 
1852     InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1853   
1854   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1855   
1856   ExprResult BaseInit =
1857     InitSeq.Perform(*this, BaseEntity, Kind, 
1858                     MultiExprArg(*this, Args, NumArgs), 0);
1859   if (BaseInit.isInvalid())
1860     return true;
1861
1862   CheckImplicitConversions(BaseInit.get(), LParenLoc);
1863   
1864   // C++0x [class.base.init]p7:
1865   //   The initialization of each base and member constitutes a 
1866   //   full-expression.
1867   BaseInit = MaybeCreateExprWithCleanups(BaseInit);
1868   if (BaseInit.isInvalid())
1869     return true;
1870
1871   // If we are in a dependent context, template instantiation will
1872   // perform this type-checking again. Just save the arguments that we
1873   // received in a ParenListExpr.
1874   // FIXME: This isn't quite ideal, since our ASTs don't capture all
1875   // of the information that we have about the base
1876   // initializer. However, deconstructing the ASTs is a dicey process,
1877   // and this approach is far more likely to get the corner cases right.
1878   if (CurContext->isDependentContext()) {
1879     ExprResult Init
1880       = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1881                                           RParenLoc));
1882     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1883                                                     BaseSpec->isVirtual(),
1884                                                     LParenLoc, 
1885                                                     Init.takeAs<Expr>(),
1886                                                     RParenLoc,
1887                                                     EllipsisLoc);
1888   }
1889
1890   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1891                                                   BaseSpec->isVirtual(),
1892                                                   LParenLoc, 
1893                                                   BaseInit.takeAs<Expr>(),
1894                                                   RParenLoc,
1895                                                   EllipsisLoc);
1896 }
1897
1898 /// ImplicitInitializerKind - How an implicit base or member initializer should
1899 /// initialize its base or member.
1900 enum ImplicitInitializerKind {
1901   IIK_Default,
1902   IIK_Copy,
1903   IIK_Move
1904 };
1905
1906 static bool
1907 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1908                              ImplicitInitializerKind ImplicitInitKind,
1909                              CXXBaseSpecifier *BaseSpec,
1910                              bool IsInheritedVirtualBase,
1911                              CXXCtorInitializer *&CXXBaseInit) {
1912   InitializedEntity InitEntity
1913     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1914                                         IsInheritedVirtualBase);
1915
1916   ExprResult BaseInit;
1917   
1918   switch (ImplicitInitKind) {
1919   case IIK_Default: {
1920     InitializationKind InitKind
1921       = InitializationKind::CreateDefault(Constructor->getLocation());
1922     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1923     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1924                                MultiExprArg(SemaRef, 0, 0));
1925     break;
1926   }
1927
1928   case IIK_Copy: {
1929     ParmVarDecl *Param = Constructor->getParamDecl(0);
1930     QualType ParamType = Param->getType().getNonReferenceType();
1931     
1932     Expr *CopyCtorArg = 
1933       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param, 
1934                           Constructor->getLocation(), ParamType,
1935                           VK_LValue, 0);
1936     
1937     // Cast to the base class to avoid ambiguities.
1938     QualType ArgTy = 
1939       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 
1940                                        ParamType.getQualifiers());
1941
1942     CXXCastPath BasePath;
1943     BasePath.push_back(BaseSpec);
1944     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1945                                             CK_UncheckedDerivedToBase,
1946                                             VK_LValue, &BasePath).take();
1947
1948     InitializationKind InitKind
1949       = InitializationKind::CreateDirect(Constructor->getLocation(),
1950                                          SourceLocation(), SourceLocation());
1951     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 
1952                                    &CopyCtorArg, 1);
1953     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1954                                MultiExprArg(&CopyCtorArg, 1));
1955     break;
1956   }
1957
1958   case IIK_Move:
1959     assert(false && "Unhandled initializer kind!");
1960   }
1961
1962   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
1963   if (BaseInit.isInvalid())
1964     return true;
1965         
1966   CXXBaseInit =
1967     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
1968                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 
1969                                                         SourceLocation()),
1970                                              BaseSpec->isVirtual(),
1971                                              SourceLocation(),
1972                                              BaseInit.takeAs<Expr>(),
1973                                              SourceLocation(),
1974                                              SourceLocation());
1975
1976   return false;
1977 }
1978
1979 static bool
1980 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1981                                ImplicitInitializerKind ImplicitInitKind,
1982                                FieldDecl *Field,
1983                                CXXCtorInitializer *&CXXMemberInit) {
1984   if (Field->isInvalidDecl())
1985     return true;
1986
1987   SourceLocation Loc = Constructor->getLocation();
1988
1989   if (ImplicitInitKind == IIK_Copy) {
1990     ParmVarDecl *Param = Constructor->getParamDecl(0);
1991     QualType ParamType = Param->getType().getNonReferenceType();
1992     
1993     Expr *MemberExprBase = 
1994       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param, 
1995                           Loc, ParamType, VK_LValue, 0);
1996
1997     // Build a reference to this field within the parameter.
1998     CXXScopeSpec SS;
1999     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2000                               Sema::LookupMemberName);
2001     MemberLookup.addDecl(Field, AS_public);
2002     MemberLookup.resolveKind();
2003     ExprResult CopyCtorArg 
2004       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2005                                          ParamType, Loc,
2006                                          /*IsArrow=*/false,
2007                                          SS,
2008                                          /*FirstQualifierInScope=*/0,
2009                                          MemberLookup,
2010                                          /*TemplateArgs=*/0);    
2011     if (CopyCtorArg.isInvalid())
2012       return true;
2013     
2014     // When the field we are copying is an array, create index variables for 
2015     // each dimension of the array. We use these index variables to subscript
2016     // the source array, and other clients (e.g., CodeGen) will perform the
2017     // necessary iteration with these index variables.
2018     llvm::SmallVector<VarDecl *, 4> IndexVariables;
2019     QualType BaseType = Field->getType();
2020     QualType SizeType = SemaRef.Context.getSizeType();
2021     while (const ConstantArrayType *Array
2022                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2023       // Create the iteration variable for this array index.
2024       IdentifierInfo *IterationVarName = 0;
2025       {
2026         llvm::SmallString<8> Str;
2027         llvm::raw_svector_ostream OS(Str);
2028         OS << "__i" << IndexVariables.size();
2029         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2030       }
2031       VarDecl *IterationVar
2032         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2033                           IterationVarName, SizeType,
2034                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2035                           SC_None, SC_None);
2036       IndexVariables.push_back(IterationVar);
2037       
2038       // Create a reference to the iteration variable.
2039       ExprResult IterationVarRef
2040         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
2041       assert(!IterationVarRef.isInvalid() &&
2042              "Reference to invented variable cannot fail!");
2043       
2044       // Subscript the array with this iteration variable.
2045       CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
2046                                                             Loc,
2047                                                         IterationVarRef.take(),
2048                                                             Loc);
2049       if (CopyCtorArg.isInvalid())
2050         return true;
2051       
2052       BaseType = Array->getElementType();
2053     }
2054     
2055     // Construct the entity that we will be initializing. For an array, this
2056     // will be first element in the array, which may require several levels
2057     // of array-subscript entities. 
2058     llvm::SmallVector<InitializedEntity, 4> Entities;
2059     Entities.reserve(1 + IndexVariables.size());
2060     Entities.push_back(InitializedEntity::InitializeMember(Field));
2061     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2062       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2063                                                               0,
2064                                                               Entities.back()));
2065     
2066     // Direct-initialize to use the copy constructor.
2067     InitializationKind InitKind =
2068       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2069     
2070     Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
2071     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2072                                    &CopyCtorArgE, 1);
2073     
2074     ExprResult MemberInit
2075       = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 
2076                         MultiExprArg(&CopyCtorArgE, 1));
2077     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2078     if (MemberInit.isInvalid())
2079       return true;
2080
2081     CXXMemberInit
2082       = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
2083                                            MemberInit.takeAs<Expr>(), Loc,
2084                                            IndexVariables.data(),
2085                                            IndexVariables.size());
2086     return false;
2087   }
2088
2089   assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2090
2091   QualType FieldBaseElementType = 
2092     SemaRef.Context.getBaseElementType(Field->getType());
2093   
2094   if (FieldBaseElementType->isRecordType()) {
2095     InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
2096     InitializationKind InitKind = 
2097       InitializationKind::CreateDefault(Loc);
2098     
2099     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2100     ExprResult MemberInit = 
2101       InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2102
2103     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2104     if (MemberInit.isInvalid())
2105       return true;
2106     
2107     CXXMemberInit =
2108       new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2109                                                        Field, Loc, Loc,
2110                                                        MemberInit.get(),
2111                                                        Loc);
2112     return false;
2113   }
2114
2115   if (!Field->getParent()->isUnion()) {
2116     if (FieldBaseElementType->isReferenceType()) {
2117       SemaRef.Diag(Constructor->getLocation(), 
2118                    diag::err_uninitialized_member_in_ctor)
2119       << (int)Constructor->isImplicit() 
2120       << SemaRef.Context.getTagDeclType(Constructor->getParent())
2121       << 0 << Field->getDeclName();
2122       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2123       return true;
2124     }
2125
2126     if (FieldBaseElementType.isConstQualified()) {
2127       SemaRef.Diag(Constructor->getLocation(), 
2128                    diag::err_uninitialized_member_in_ctor)
2129       << (int)Constructor->isImplicit() 
2130       << SemaRef.Context.getTagDeclType(Constructor->getParent())
2131       << 1 << Field->getDeclName();
2132       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2133       return true;
2134     }
2135   }
2136   
2137   // Nothing to initialize.
2138   CXXMemberInit = 0;
2139   return false;
2140 }
2141
2142 namespace {
2143 struct BaseAndFieldInfo {
2144   Sema &S;
2145   CXXConstructorDecl *Ctor;
2146   bool AnyErrorsInInits;
2147   ImplicitInitializerKind IIK;
2148   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2149   llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
2150
2151   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2152     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2153     // FIXME: Handle implicit move constructors.
2154     if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2155       IIK = IIK_Copy;
2156     else
2157       IIK = IIK_Default;
2158   }
2159 };
2160 }
2161
2162 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
2163                                     FieldDecl *Top, FieldDecl *Field) {
2164
2165   // Overwhelmingly common case: we have a direct initializer for this field.
2166   if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
2167     Info.AllToInit.push_back(Init);
2168     return false;
2169   }
2170
2171   // C++0x [class.base.init]p8: if the entity is a non-static data member that
2172   // has a brace-or-equal-initializer, the entity is initialized as specified
2173   // in [dcl.init].
2174   if (Field->hasInClassInitializer()) {
2175     Info.AllToInit.push_back(
2176       new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2177                                                SourceLocation(),
2178                                                SourceLocation(), 0,
2179                                                SourceLocation()));
2180     return false;
2181   }
2182
2183   if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2184     const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2185     assert(FieldClassType && "anonymous struct/union without record type");
2186     CXXRecordDecl *FieldClassDecl
2187       = cast<CXXRecordDecl>(FieldClassType->getDecl());
2188
2189     // Even though union members never have non-trivial default
2190     // constructions in C++03, we still build member initializers for aggregate
2191     // record types which can be union members, and C++0x allows non-trivial
2192     // default constructors for union members, so we ensure that only one
2193     // member is initialized for these.
2194     if (FieldClassDecl->isUnion()) {
2195       // First check for an explicit initializer for one field.
2196       for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2197            EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2198         if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
2199           Info.AllToInit.push_back(Init);
2200
2201           // Once we've initialized a field of an anonymous union, the union
2202           // field in the class is also initialized, so exit immediately.
2203           return false;
2204         } else if ((*FA)->isAnonymousStructOrUnion()) {
2205           if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
2206             return true;
2207         }
2208       }
2209
2210       // Fallthrough and construct a default initializer for the union as
2211       // a whole, which can call its default constructor if such a thing exists
2212       // (C++0x perhaps). FIXME: It's not clear that this is the correct
2213       // behavior going forward with C++0x, when anonymous unions there are
2214       // finalized, we should revisit this.
2215     } else {
2216       // For structs, we simply descend through to initialize all members where
2217       // necessary.
2218       for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2219            EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2220         if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
2221           return true;
2222       }
2223     }
2224   }
2225
2226   // Don't try to build an implicit initializer if there were semantic
2227   // errors in any of the initializers (and therefore we might be
2228   // missing some that the user actually wrote).
2229   if (Info.AnyErrorsInInits || Field->isInvalidDecl())
2230     return false;
2231
2232   CXXCtorInitializer *Init = 0;
2233   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2234     return true;
2235
2236   if (Init)
2237     Info.AllToInit.push_back(Init);
2238
2239   return false;
2240 }
2241
2242 bool
2243 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2244                                CXXCtorInitializer *Initializer) {
2245   assert(Initializer->isDelegatingInitializer());
2246   Constructor->setNumCtorInitializers(1);
2247   CXXCtorInitializer **initializer =
2248     new (Context) CXXCtorInitializer*[1];
2249   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2250   Constructor->setCtorInitializers(initializer);
2251
2252   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2253     MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2254     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2255   }
2256
2257   DelegatingCtorDecls.push_back(Constructor);
2258
2259   return false;
2260 }
2261                                
2262 bool
2263 Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2264                                   CXXCtorInitializer **Initializers,
2265                                   unsigned NumInitializers,
2266                                   bool AnyErrors) {
2267   if (Constructor->getDeclContext()->isDependentContext()) {
2268     // Just store the initializers as written, they will be checked during
2269     // instantiation.
2270     if (NumInitializers > 0) {
2271       Constructor->setNumCtorInitializers(NumInitializers);
2272       CXXCtorInitializer **baseOrMemberInitializers =
2273         new (Context) CXXCtorInitializer*[NumInitializers];
2274       memcpy(baseOrMemberInitializers, Initializers,
2275              NumInitializers * sizeof(CXXCtorInitializer*));
2276       Constructor->setCtorInitializers(baseOrMemberInitializers);
2277     }
2278     
2279     return false;
2280   }
2281
2282   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
2283
2284   // We need to build the initializer AST according to order of construction
2285   // and not what user specified in the Initializers list.
2286   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
2287   if (!ClassDecl)
2288     return true;
2289   
2290   bool HadError = false;
2291
2292   for (unsigned i = 0; i < NumInitializers; i++) {
2293     CXXCtorInitializer *Member = Initializers[i];
2294     
2295     if (Member->isBaseInitializer())
2296       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
2297     else
2298       Info.AllBaseFields[Member->getAnyMember()] = Member;
2299   }
2300
2301   // Keep track of the direct virtual bases.
2302   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2303   for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2304        E = ClassDecl->bases_end(); I != E; ++I) {
2305     if (I->isVirtual())
2306       DirectVBases.insert(I);
2307   }
2308
2309   // Push virtual bases before others.
2310   for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2311        E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2312
2313     if (CXXCtorInitializer *Value
2314         = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2315       Info.AllToInit.push_back(Value);
2316     } else if (!AnyErrors) {
2317       bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
2318       CXXCtorInitializer *CXXBaseInit;
2319       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2320                                        VBase, IsInheritedVirtualBase, 
2321                                        CXXBaseInit)) {
2322         HadError = true;
2323         continue;
2324       }
2325
2326       Info.AllToInit.push_back(CXXBaseInit);
2327     }
2328   }
2329
2330   // Non-virtual bases.
2331   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2332        E = ClassDecl->bases_end(); Base != E; ++Base) {
2333     // Virtuals are in the virtual base list and already constructed.
2334     if (Base->isVirtual())
2335       continue;
2336
2337     if (CXXCtorInitializer *Value
2338           = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2339       Info.AllToInit.push_back(Value);
2340     } else if (!AnyErrors) {
2341       CXXCtorInitializer *CXXBaseInit;
2342       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2343                                        Base, /*IsInheritedVirtualBase=*/false,
2344                                        CXXBaseInit)) {
2345         HadError = true;
2346         continue;
2347       }
2348
2349       Info.AllToInit.push_back(CXXBaseInit);
2350     }
2351   }
2352
2353   // Fields.
2354   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2355        E = ClassDecl->field_end(); Field != E; ++Field) {
2356     if ((*Field)->getType()->isIncompleteArrayType()) {
2357       assert(ClassDecl->hasFlexibleArrayMember() &&
2358              "Incomplete array type is not valid");
2359       continue;
2360     }
2361     if (CollectFieldInitializer(*this, Info, *Field, *Field))
2362       HadError = true;
2363   }
2364
2365   NumInitializers = Info.AllToInit.size();
2366   if (NumInitializers > 0) {
2367     Constructor->setNumCtorInitializers(NumInitializers);
2368     CXXCtorInitializer **baseOrMemberInitializers =
2369       new (Context) CXXCtorInitializer*[NumInitializers];
2370     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
2371            NumInitializers * sizeof(CXXCtorInitializer*));
2372     Constructor->setCtorInitializers(baseOrMemberInitializers);
2373
2374     // Constructors implicitly reference the base and member
2375     // destructors.
2376     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2377                                            Constructor->getParent());
2378   }
2379
2380   return HadError;
2381 }
2382
2383 static void *GetKeyForTopLevelField(FieldDecl *Field) {
2384   // For anonymous unions, use the class declaration as the key.
2385   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
2386     if (RT->getDecl()->isAnonymousStructOrUnion())
2387       return static_cast<void *>(RT->getDecl());
2388   }
2389   return static_cast<void *>(Field);
2390 }
2391
2392 static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
2393   return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
2394 }
2395
2396 static void *GetKeyForMember(ASTContext &Context,
2397                              CXXCtorInitializer *Member) {
2398   if (!Member->isAnyMemberInitializer())
2399     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
2400     
2401   // For fields injected into the class via declaration of an anonymous union,
2402   // use its anonymous union class declaration as the unique key.
2403   FieldDecl *Field = Member->getAnyMember();
2404  
2405   // If the field is a member of an anonymous struct or union, our key
2406   // is the anonymous record decl that's a direct child of the class.
2407   RecordDecl *RD = Field->getParent();
2408   if (RD->isAnonymousStructOrUnion()) {
2409     while (true) {
2410       RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2411       if (Parent->isAnonymousStructOrUnion())
2412         RD = Parent;
2413       else
2414         break;
2415     }
2416       
2417     return static_cast<void *>(RD);
2418   }
2419
2420   return static_cast<void *>(Field);
2421 }
2422
2423 static void
2424 DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
2425                                   const CXXConstructorDecl *Constructor,
2426                                   CXXCtorInitializer **Inits,
2427                                   unsigned NumInits) {
2428   if (Constructor->getDeclContext()->isDependentContext())
2429     return;
2430
2431   // Don't check initializers order unless the warning is enabled at the
2432   // location of at least one initializer. 
2433   bool ShouldCheckOrder = false;
2434   for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2435     CXXCtorInitializer *Init = Inits[InitIndex];
2436     if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2437                                          Init->getSourceLocation())
2438           != Diagnostic::Ignored) {
2439       ShouldCheckOrder = true;
2440       break;
2441     }
2442   }
2443   if (!ShouldCheckOrder)
2444     return;
2445   
2446   // Build the list of bases and members in the order that they'll
2447   // actually be initialized.  The explicit initializers should be in
2448   // this same order but may be missing things.
2449   llvm::SmallVector<const void*, 32> IdealInitKeys;
2450
2451   const CXXRecordDecl *ClassDecl = Constructor->getParent();
2452
2453   // 1. Virtual bases.
2454   for (CXXRecordDecl::base_class_const_iterator VBase =
2455        ClassDecl->vbases_begin(),
2456        E = ClassDecl->vbases_end(); VBase != E; ++VBase)
2457     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
2458
2459   // 2. Non-virtual bases.
2460   for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
2461        E = ClassDecl->bases_end(); Base != E; ++Base) {
2462     if (Base->isVirtual())
2463       continue;
2464     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
2465   }
2466
2467   // 3. Direct fields.
2468   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2469        E = ClassDecl->field_end(); Field != E; ++Field)
2470     IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
2471
2472   unsigned NumIdealInits = IdealInitKeys.size();
2473   unsigned IdealIndex = 0;
2474
2475   CXXCtorInitializer *PrevInit = 0;
2476   for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2477     CXXCtorInitializer *Init = Inits[InitIndex];
2478     void *InitKey = GetKeyForMember(SemaRef.Context, Init);
2479
2480     // Scan forward to try to find this initializer in the idealized
2481     // initializers list.
2482     for (; IdealIndex != NumIdealInits; ++IdealIndex)
2483       if (InitKey == IdealInitKeys[IdealIndex])
2484         break;
2485
2486     // If we didn't find this initializer, it must be because we
2487     // scanned past it on a previous iteration.  That can only
2488     // happen if we're out of order;  emit a warning.
2489     if (IdealIndex == NumIdealInits && PrevInit) {
2490       Sema::SemaDiagnosticBuilder D =
2491         SemaRef.Diag(PrevInit->getSourceLocation(),
2492                      diag::warn_initializer_out_of_order);
2493
2494       if (PrevInit->isAnyMemberInitializer())
2495         D << 0 << PrevInit->getAnyMember()->getDeclName();
2496       else
2497         D << 1 << PrevInit->getBaseClassInfo()->getType();
2498       
2499       if (Init->isAnyMemberInitializer())
2500         D << 0 << Init->getAnyMember()->getDeclName();
2501       else
2502         D << 1 << Init->getBaseClassInfo()->getType();
2503
2504       // Move back to the initializer's location in the ideal list.
2505       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2506         if (InitKey == IdealInitKeys[IdealIndex])
2507           break;
2508
2509       assert(IdealIndex != NumIdealInits &&
2510              "initializer not found in initializer list");
2511     }
2512
2513     PrevInit = Init;
2514   }
2515 }
2516
2517 namespace {
2518 bool CheckRedundantInit(Sema &S,
2519                         CXXCtorInitializer *Init,
2520                         CXXCtorInitializer *&PrevInit) {
2521   if (!PrevInit) {
2522     PrevInit = Init;
2523     return false;
2524   }
2525
2526   if (FieldDecl *Field = Init->getMember())
2527     S.Diag(Init->getSourceLocation(),
2528            diag::err_multiple_mem_initialization)
2529       << Field->getDeclName()
2530       << Init->getSourceRange();
2531   else {
2532     const Type *BaseClass = Init->getBaseClass();
2533     assert(BaseClass && "neither field nor base");
2534     S.Diag(Init->getSourceLocation(),
2535            diag::err_multiple_base_initialization)
2536       << QualType(BaseClass, 0)
2537       << Init->getSourceRange();
2538   }
2539   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2540     << 0 << PrevInit->getSourceRange();
2541
2542   return true;
2543 }
2544
2545 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
2546 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2547
2548 bool CheckRedundantUnionInit(Sema &S,
2549                              CXXCtorInitializer *Init,
2550                              RedundantUnionMap &Unions) {
2551   FieldDecl *Field = Init->getAnyMember();
2552   RecordDecl *Parent = Field->getParent();
2553   if (!Parent->isAnonymousStructOrUnion())
2554     return false;
2555
2556   NamedDecl *Child = Field;
2557   do {
2558     if (Parent->isUnion()) {
2559       UnionEntry &En = Unions[Parent];
2560       if (En.first && En.first != Child) {
2561         S.Diag(Init->getSourceLocation(),
2562                diag::err_multiple_mem_union_initialization)
2563           << Field->getDeclName()
2564           << Init->getSourceRange();
2565         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2566           << 0 << En.second->getSourceRange();
2567         return true;
2568       } else if (!En.first) {
2569         En.first = Child;
2570         En.second = Init;
2571       }
2572     }
2573
2574     Child = Parent;
2575     Parent = cast<RecordDecl>(Parent->getDeclContext());
2576   } while (Parent->isAnonymousStructOrUnion());
2577
2578   return false;
2579 }
2580 }
2581
2582 /// ActOnMemInitializers - Handle the member initializers for a constructor.
2583 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
2584                                 SourceLocation ColonLoc,
2585                                 MemInitTy **meminits, unsigned NumMemInits,
2586                                 bool AnyErrors) {
2587   if (!ConstructorDecl)
2588     return;
2589
2590   AdjustDeclIfTemplate(ConstructorDecl);
2591
2592   CXXConstructorDecl *Constructor
2593     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
2594
2595   if (!Constructor) {
2596     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2597     return;
2598   }
2599   
2600   CXXCtorInitializer **MemInits =
2601     reinterpret_cast<CXXCtorInitializer **>(meminits);
2602
2603   // Mapping for the duplicate initializers check.
2604   // For member initializers, this is keyed with a FieldDecl*.
2605   // For base initializers, this is keyed with a Type*.
2606   llvm::DenseMap<void*, CXXCtorInitializer *> Members;
2607
2608   // Mapping for the inconsistent anonymous-union initializers check.
2609   RedundantUnionMap MemberUnions;
2610
2611   bool HadError = false;
2612   for (unsigned i = 0; i < NumMemInits; i++) {
2613     CXXCtorInitializer *Init = MemInits[i];
2614
2615     // Set the source order index.
2616     Init->setSourceOrder(i);
2617
2618     if (Init->isAnyMemberInitializer()) {
2619       FieldDecl *Field = Init->getAnyMember();
2620       if (CheckRedundantInit(*this, Init, Members[Field]) ||
2621           CheckRedundantUnionInit(*this, Init, MemberUnions))
2622         HadError = true;
2623     } else if (Init->isBaseInitializer()) {
2624       void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2625       if (CheckRedundantInit(*this, Init, Members[Key]))
2626         HadError = true;
2627     } else {
2628       assert(Init->isDelegatingInitializer());
2629       // This must be the only initializer
2630       if (i != 0 || NumMemInits > 1) {
2631         Diag(MemInits[0]->getSourceLocation(),
2632              diag::err_delegating_initializer_alone)
2633           << MemInits[0]->getSourceRange();
2634         HadError = true;
2635         // We will treat this as being the only initializer.
2636       }
2637       SetDelegatingInitializer(Constructor, MemInits[i]);
2638       // Return immediately as the initializer is set.
2639       return;
2640     }
2641   }
2642
2643   if (HadError)
2644     return;
2645
2646   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
2647
2648   SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
2649 }
2650
2651 void
2652 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2653                                              CXXRecordDecl *ClassDecl) {
2654   // Ignore dependent contexts.
2655   if (ClassDecl->isDependentContext())
2656     return;
2657
2658   // FIXME: all the access-control diagnostics are positioned on the
2659   // field/base declaration.  That's probably good; that said, the
2660   // user might reasonably want to know why the destructor is being
2661   // emitted, and we currently don't say.
2662   
2663   // Non-static data members.
2664   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2665        E = ClassDecl->field_end(); I != E; ++I) {
2666     FieldDecl *Field = *I;
2667     if (Field->isInvalidDecl())
2668       continue;
2669     QualType FieldType = Context.getBaseElementType(Field->getType());
2670     
2671     const RecordType* RT = FieldType->getAs<RecordType>();
2672     if (!RT)
2673       continue;
2674     
2675     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2676     if (FieldClassDecl->isInvalidDecl())
2677       continue;
2678     if (FieldClassDecl->hasTrivialDestructor())
2679       continue;
2680
2681     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
2682     assert(Dtor && "No dtor found for FieldClassDecl!");
2683     CheckDestructorAccess(Field->getLocation(), Dtor,
2684                           PDiag(diag::err_access_dtor_field)
2685                             << Field->getDeclName()
2686                             << FieldType);
2687
2688     MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2689   }
2690
2691   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2692
2693   // Bases.
2694   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2695        E = ClassDecl->bases_end(); Base != E; ++Base) {
2696     // Bases are always records in a well-formed non-dependent class.
2697     const RecordType *RT = Base->getType()->getAs<RecordType>();
2698
2699     // Remember direct virtual bases.
2700     if (Base->isVirtual())
2701       DirectVirtualBases.insert(RT);
2702
2703     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2704     // If our base class is invalid, we probably can't get its dtor anyway.
2705     if (BaseClassDecl->isInvalidDecl())
2706       continue;
2707     // Ignore trivial destructors.
2708     if (BaseClassDecl->hasTrivialDestructor())
2709       continue;
2710
2711     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2712     assert(Dtor && "No dtor found for BaseClassDecl!");
2713
2714     // FIXME: caret should be on the start of the class name
2715     CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
2716                           PDiag(diag::err_access_dtor_base)
2717                             << Base->getType()
2718                             << Base->getSourceRange());
2719     
2720     MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2721   }
2722   
2723   // Virtual bases.
2724   for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2725        E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2726
2727     // Bases are always records in a well-formed non-dependent class.
2728     const RecordType *RT = VBase->getType()->getAs<RecordType>();
2729
2730     // Ignore direct virtual bases.
2731     if (DirectVirtualBases.count(RT))
2732       continue;
2733
2734     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2735     // If our base class is invalid, we probably can't get its dtor anyway.
2736     if (BaseClassDecl->isInvalidDecl())
2737       continue;
2738     // Ignore trivial destructors.
2739     if (BaseClassDecl->hasTrivialDestructor())
2740       continue;
2741
2742     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2743     assert(Dtor && "No dtor found for BaseClassDecl!");
2744     CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
2745                           PDiag(diag::err_access_dtor_vbase)
2746                             << VBase->getType());
2747
2748     MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2749   }
2750 }
2751
2752 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
2753   if (!CDtorDecl)
2754     return;
2755
2756   if (CXXConstructorDecl *Constructor
2757       = dyn_cast<CXXConstructorDecl>(CDtorDecl))
2758     SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
2759 }
2760
2761 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2762                                   unsigned DiagID, AbstractDiagSelID SelID) {
2763   if (SelID == -1)
2764     return RequireNonAbstractType(Loc, T, PDiag(DiagID));
2765   else
2766     return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
2767 }
2768
2769 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2770                                   const PartialDiagnostic &PD) {
2771   if (!getLangOptions().CPlusPlus)
2772     return false;
2773
2774   if (const ArrayType *AT = Context.getAsArrayType(T))
2775     return RequireNonAbstractType(Loc, AT->getElementType(), PD);
2776
2777   if (const PointerType *PT = T->getAs<PointerType>()) {
2778     // Find the innermost pointer type.
2779     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
2780       PT = T;
2781
2782     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
2783       return RequireNonAbstractType(Loc, AT->getElementType(), PD);
2784   }
2785
2786   const RecordType *RT = T->getAs<RecordType>();
2787   if (!RT)
2788     return false;
2789
2790   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2791
2792   // We can't answer whether something is abstract until it has a
2793   // definition.  If it's currently being defined, we'll walk back
2794   // over all the declarations when we have a full definition.
2795   const CXXRecordDecl *Def = RD->getDefinition();
2796   if (!Def || Def->isBeingDefined())
2797     return false;
2798
2799   if (!RD->isAbstract())
2800     return false;
2801
2802   Diag(Loc, PD) << RD->getDeclName();
2803   DiagnoseAbstractType(RD);
2804
2805   return true;
2806 }
2807
2808 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2809   // Check if we've already emitted the list of pure virtual functions
2810   // for this class.
2811   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2812     return;
2813
2814   CXXFinalOverriderMap FinalOverriders;
2815   RD->getFinalOverriders(FinalOverriders);
2816
2817   // Keep a set of seen pure methods so we won't diagnose the same method
2818   // more than once.
2819   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2820   
2821   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 
2822                                    MEnd = FinalOverriders.end();
2823        M != MEnd; 
2824        ++M) {
2825     for (OverridingMethods::iterator SO = M->second.begin(), 
2826                                   SOEnd = M->second.end();
2827          SO != SOEnd; ++SO) {
2828       // C++ [class.abstract]p4:
2829       //   A class is abstract if it contains or inherits at least one
2830       //   pure virtual function for which the final overrider is pure
2831       //   virtual.
2832
2833       // 
2834       if (SO->second.size() != 1)
2835         continue;
2836
2837       if (!SO->second.front().Method->isPure())
2838         continue;
2839
2840       if (!SeenPureMethods.insert(SO->second.front().Method))
2841         continue;
2842
2843       Diag(SO->second.front().Method->getLocation(), 
2844            diag::note_pure_virtual_function) 
2845         << SO->second.front().Method->getDeclName() << RD->getDeclName();
2846     }
2847   }
2848
2849   if (!PureVirtualClassDiagSet)
2850     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2851   PureVirtualClassDiagSet->insert(RD);
2852 }
2853
2854 namespace {
2855 struct AbstractUsageInfo {
2856   Sema &S;
2857   CXXRecordDecl *Record;
2858   CanQualType AbstractType;
2859   bool Invalid;
2860
2861   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2862     : S(S), Record(Record),
2863       AbstractType(S.Context.getCanonicalType(
2864                    S.Context.getTypeDeclType(Record))),
2865       Invalid(false) {}
2866
2867   void DiagnoseAbstractType() {
2868     if (Invalid) return;
2869     S.DiagnoseAbstractType(Record);
2870     Invalid = true;
2871   }
2872
2873   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2874 };
2875
2876 struct CheckAbstractUsage {
2877   AbstractUsageInfo &Info;
2878   const NamedDecl *Ctx;
2879
2880   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2881     : Info(Info), Ctx(Ctx) {}
2882
2883   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2884     switch (TL.getTypeLocClass()) {
2885 #define ABSTRACT_TYPELOC(CLASS, PARENT)
2886 #define TYPELOC(CLASS, PARENT) \
2887     case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2888 #include "clang/AST/TypeLocNodes.def"
2889     }
2890   }
2891
2892   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2893     Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2894     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2895       if (!TL.getArg(I))
2896         continue;
2897       
2898       TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2899       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
2900     }
2901   }
2902
2903   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2904     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2905   }
2906
2907   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2908     // Visit the type parameters from a permissive context.
2909     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2910       TemplateArgumentLoc TAL = TL.getArgLoc(I);
2911       if (TAL.getArgument().getKind() == TemplateArgument::Type)
2912         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2913           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2914       // TODO: other template argument types?
2915     }
2916   }
2917
2918   // Visit pointee types from a permissive context.
2919 #define CheckPolymorphic(Type) \
2920   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2921     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2922   }
2923   CheckPolymorphic(PointerTypeLoc)
2924   CheckPolymorphic(ReferenceTypeLoc)
2925   CheckPolymorphic(MemberPointerTypeLoc)
2926   CheckPolymorphic(BlockPointerTypeLoc)
2927
2928   /// Handle all the types we haven't given a more specific
2929   /// implementation for above.
2930   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2931     // Every other kind of type that we haven't called out already
2932     // that has an inner type is either (1) sugar or (2) contains that
2933     // inner type in some way as a subobject.
2934     if (TypeLoc Next = TL.getNextTypeLoc())
2935       return Visit(Next, Sel);
2936
2937     // If there's no inner type and we're in a permissive context,
2938     // don't diagnose.
2939     if (Sel == Sema::AbstractNone) return;
2940
2941     // Check whether the type matches the abstract type.
2942     QualType T = TL.getType();
2943     if (T->isArrayType()) {
2944       Sel = Sema::AbstractArrayType;
2945       T = Info.S.Context.getBaseElementType(T);
2946     }
2947     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2948     if (CT != Info.AbstractType) return;
2949
2950     // It matched; do some magic.
2951     if (Sel == Sema::AbstractArrayType) {
2952       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2953         << T << TL.getSourceRange();
2954     } else {
2955       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2956         << Sel << T << TL.getSourceRange();
2957     }
2958     Info.DiagnoseAbstractType();
2959   }
2960 };
2961
2962 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2963                                   Sema::AbstractDiagSelID Sel) {
2964   CheckAbstractUsage(*this, D).Visit(TL, Sel);
2965 }
2966
2967 }
2968
2969 /// Check for invalid uses of an abstract type in a method declaration.
2970 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2971                                     CXXMethodDecl *MD) {
2972   // No need to do the check on definitions, which require that
2973   // the return/param types be complete.
2974   if (MD->doesThisDeclarationHaveABody())
2975     return;
2976
2977   // For safety's sake, just ignore it if we don't have type source
2978   // information.  This should never happen for non-implicit methods,
2979   // but...
2980   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2981     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2982 }
2983
2984 /// Check for invalid uses of an abstract type within a class definition.
2985 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2986                                     CXXRecordDecl *RD) {
2987   for (CXXRecordDecl::decl_iterator
2988          I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2989     Decl *D = *I;
2990     if (D->isImplicit()) continue;
2991
2992     // Methods and method templates.
2993     if (isa<CXXMethodDecl>(D)) {
2994       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2995     } else if (isa<FunctionTemplateDecl>(D)) {
2996       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2997       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2998
2999     // Fields and static variables.
3000     } else if (isa<FieldDecl>(D)) {
3001       FieldDecl *FD = cast<FieldDecl>(D);
3002       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3003         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3004     } else if (isa<VarDecl>(D)) {
3005       VarDecl *VD = cast<VarDecl>(D);
3006       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3007         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3008
3009     // Nested classes and class templates.
3010     } else if (isa<CXXRecordDecl>(D)) {
3011       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3012     } else if (isa<ClassTemplateDecl>(D)) {
3013       CheckAbstractClassUsage(Info,
3014                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3015     }
3016   }
3017 }
3018
3019 /// \brief Perform semantic checks on a class definition that has been
3020 /// completing, introducing implicitly-declared members, checking for
3021 /// abstract types, etc.
3022 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3023   if (!Record)
3024     return;
3025
3026   if (Record->isAbstract() && !Record->isInvalidDecl()) {
3027     AbstractUsageInfo Info(*this, Record);
3028     CheckAbstractClassUsage(Info, Record);
3029   }
3030   
3031   // If this is not an aggregate type and has no user-declared constructor,
3032   // complain about any non-static data members of reference or const scalar
3033   // type, since they will never get initializers.
3034   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3035       !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3036     bool Complained = false;
3037     for (RecordDecl::field_iterator F = Record->field_begin(), 
3038                                  FEnd = Record->field_end();
3039          F != FEnd; ++F) {
3040       if (F->hasInClassInitializer())
3041         continue;
3042
3043       if (F->getType()->isReferenceType() ||
3044           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3045         if (!Complained) {
3046           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3047             << Record->getTagKind() << Record;
3048           Complained = true;
3049         }
3050         
3051         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3052           << F->getType()->isReferenceType()
3053           << F->getDeclName();
3054       }
3055     }
3056   }
3057
3058   if (Record->isDynamicClass() && !Record->isDependentType())
3059     DynamicClasses.push_back(Record);
3060
3061   if (Record->getIdentifier()) {
3062     // C++ [class.mem]p13:
3063     //   If T is the name of a class, then each of the following shall have a 
3064     //   name different from T:
3065     //     - every member of every anonymous union that is a member of class T.
3066     //
3067     // C++ [class.mem]p14:
3068     //   In addition, if class T has a user-declared constructor (12.1), every 
3069     //   non-static data member of class T shall have a name different from T.
3070     for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3071          R.first != R.second; ++R.first) {
3072       NamedDecl *D = *R.first;
3073       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3074           isa<IndirectFieldDecl>(D)) {
3075         Diag(D->getLocation(), diag::err_member_name_of_class)
3076           << D->getDeclName();
3077         break;
3078       }
3079     }
3080   }
3081
3082   // Warn if the class has virtual methods but non-virtual public destructor.
3083   if (Record->isPolymorphic() && !Record->isDependentType()) {
3084     CXXDestructorDecl *dtor = Record->getDestructor();
3085     if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3086       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3087            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3088   }
3089
3090   // See if a method overloads virtual methods in a base
3091   /// class without overriding any.
3092   if (!Record->isDependentType()) {
3093     for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3094                                      MEnd = Record->method_end();
3095          M != MEnd; ++M) {
3096       if (!(*M)->isStatic())
3097         DiagnoseHiddenVirtualMethods(Record, *M);
3098     }
3099   }
3100
3101   // Declare inherited constructors. We do this eagerly here because:
3102   // - The standard requires an eager diagnostic for conflicting inherited
3103   //   constructors from different classes.
3104   // - The lazy declaration of the other implicit constructors is so as to not
3105   //   waste space and performance on classes that are not meant to be
3106   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
3107   //   have inherited constructors.
3108   DeclareInheritedConstructors(Record);
3109
3110   if (!Record->isDependentType())
3111     CheckExplicitlyDefaultedMethods(Record);
3112 }
3113
3114 void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3115   for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3116                                       ME = Record->method_end();
3117        MI != ME; ++MI) {
3118     if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3119       switch (getSpecialMember(*MI)) {
3120       case CXXDefaultConstructor:
3121         CheckExplicitlyDefaultedDefaultConstructor(
3122                                                   cast<CXXConstructorDecl>(*MI));
3123         break;
3124
3125       case CXXDestructor:
3126         CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3127         break;
3128
3129       case CXXCopyConstructor:
3130         CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3131         break;
3132
3133       case CXXCopyAssignment:
3134         CheckExplicitlyDefaultedCopyAssignment(*MI);
3135         break;
3136
3137       case CXXMoveConstructor:
3138       case CXXMoveAssignment:
3139         Diag(MI->getLocation(), diag::err_defaulted_move_unsupported);
3140         break;
3141
3142       default:
3143         // FIXME: Do moves once they exist
3144         llvm_unreachable("non-special member explicitly defaulted!");
3145       }
3146     }
3147   }
3148
3149 }
3150
3151 void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3152   assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3153   
3154   // Whether this was the first-declared instance of the constructor.
3155   // This affects whether we implicitly add an exception spec (and, eventually,
3156   // constexpr). It is also ill-formed to explicitly default a constructor such
3157   // that it would be deleted. (C++0x [decl.fct.def.default])
3158   bool First = CD == CD->getCanonicalDecl();
3159
3160   bool HadError = false;
3161   if (CD->getNumParams() != 0) {
3162     Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3163       << CD->getSourceRange();
3164     HadError = true;
3165   }
3166
3167   ImplicitExceptionSpecification Spec
3168     = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3169   FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3170   if (EPI.ExceptionSpecType == EST_Delayed) {
3171     // Exception specification depends on some deferred part of the class. We'll
3172     // try again when the class's definition has been fully processed.
3173     return;
3174   }
3175   const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3176                           *ExceptionType = Context.getFunctionType(
3177                          Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3178
3179   if (CtorType->hasExceptionSpec()) {
3180     if (CheckEquivalentExceptionSpec(
3181           PDiag(diag::err_incorrect_defaulted_exception_spec)
3182             << CXXDefaultConstructor,
3183           PDiag(),
3184           ExceptionType, SourceLocation(),
3185           CtorType, CD->getLocation())) {
3186       HadError = true;
3187     }
3188   } else if (First) {
3189     // We set the declaration to have the computed exception spec here.
3190     // We know there are no parameters.
3191     EPI.ExtInfo = CtorType->getExtInfo();
3192     CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3193   }
3194
3195   if (HadError) {
3196     CD->setInvalidDecl();
3197     return;
3198   }
3199
3200   if (ShouldDeleteDefaultConstructor(CD)) {
3201     if (First) {
3202       CD->setDeletedAsWritten();
3203     } else {
3204       Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3205         << CXXDefaultConstructor;
3206       CD->setInvalidDecl();
3207     }
3208   }
3209 }
3210
3211 void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3212   assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3213
3214   // Whether this was the first-declared instance of the constructor.
3215   bool First = CD == CD->getCanonicalDecl();
3216
3217   bool HadError = false;
3218   if (CD->getNumParams() != 1) {
3219     Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3220       << CD->getSourceRange();
3221     HadError = true;
3222   }
3223
3224   ImplicitExceptionSpecification Spec(Context);
3225   bool Const;
3226   llvm::tie(Spec, Const) =
3227     ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3228   
3229   FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3230   const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3231                           *ExceptionType = Context.getFunctionType(
3232                          Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3233
3234   // Check for parameter type matching.
3235   // This is a copy ctor so we know it's a cv-qualified reference to T.
3236   QualType ArgType = CtorType->getArgType(0);
3237   if (ArgType->getPointeeType().isVolatileQualified()) {
3238     Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3239     HadError = true;
3240   }
3241   if (ArgType->getPointeeType().isConstQualified() && !Const) {
3242     Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3243     HadError = true;
3244   }
3245
3246   if (CtorType->hasExceptionSpec()) {
3247     if (CheckEquivalentExceptionSpec(
3248           PDiag(diag::err_incorrect_defaulted_exception_spec)
3249             << CXXCopyConstructor,
3250           PDiag(),
3251           ExceptionType, SourceLocation(),
3252           CtorType, CD->getLocation())) {
3253       HadError = true;
3254     }
3255   } else if (First) {
3256     // We set the declaration to have the computed exception spec here.
3257     // We duplicate the one parameter type.
3258     EPI.ExtInfo = CtorType->getExtInfo();
3259     CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3260   }
3261
3262   if (HadError) {
3263     CD->setInvalidDecl();
3264     return;
3265   }
3266
3267   if (ShouldDeleteCopyConstructor(CD)) {
3268     if (First) {
3269       CD->setDeletedAsWritten();
3270     } else {
3271       Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3272         << CXXCopyConstructor;
3273       CD->setInvalidDecl();
3274     }
3275   }
3276 }
3277
3278 void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3279   assert(MD->isExplicitlyDefaulted());
3280
3281   // Whether this was the first-declared instance of the operator
3282   bool First = MD == MD->getCanonicalDecl();
3283
3284   bool HadError = false;
3285   if (MD->getNumParams() != 1) {
3286     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3287       << MD->getSourceRange();
3288     HadError = true;
3289   }
3290
3291   QualType ReturnType =
3292     MD->getType()->getAs<FunctionType>()->getResultType();
3293   if (!ReturnType->isLValueReferenceType() ||
3294       !Context.hasSameType(
3295         Context.getCanonicalType(ReturnType->getPointeeType()),
3296         Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3297     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3298     HadError = true;
3299   }
3300
3301   ImplicitExceptionSpecification Spec(Context);
3302   bool Const;
3303   llvm::tie(Spec, Const) =
3304     ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3305   
3306   FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3307   const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3308                           *ExceptionType = Context.getFunctionType(
3309                          Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3310
3311   QualType ArgType = OperType->getArgType(0);
3312   if (!ArgType->isReferenceType()) {
3313     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
3314     HadError = true;
3315   } else {
3316     if (ArgType->getPointeeType().isVolatileQualified()) {
3317       Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3318       HadError = true;
3319     }
3320     if (ArgType->getPointeeType().isConstQualified() && !Const) {
3321       Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3322       HadError = true;
3323     }
3324   }
3325
3326   if (OperType->getTypeQuals()) {
3327     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3328     HadError = true;
3329   }
3330
3331   if (OperType->hasExceptionSpec()) {
3332     if (CheckEquivalentExceptionSpec(
3333           PDiag(diag::err_incorrect_defaulted_exception_spec)
3334             << CXXCopyAssignment,
3335           PDiag(),
3336           ExceptionType, SourceLocation(),
3337           OperType, MD->getLocation())) {
3338       HadError = true;
3339     }
3340   } else if (First) {
3341     // We set the declaration to have the computed exception spec here.
3342     // We duplicate the one parameter type.
3343     EPI.RefQualifier = OperType->getRefQualifier();
3344     EPI.ExtInfo = OperType->getExtInfo();
3345     MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3346   }
3347
3348   if (HadError) {
3349     MD->setInvalidDecl();
3350     return;
3351   }
3352
3353   if (ShouldDeleteCopyAssignmentOperator(MD)) {
3354     if (First) {
3355       MD->setDeletedAsWritten();
3356     } else {
3357       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3358         << CXXCopyAssignment;
3359       MD->setInvalidDecl();
3360     }
3361   }
3362 }
3363
3364 void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3365   assert(DD->isExplicitlyDefaulted());
3366
3367   // Whether this was the first-declared instance of the destructor.
3368   bool First = DD == DD->getCanonicalDecl();
3369
3370   ImplicitExceptionSpecification Spec
3371     = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3372   FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3373   const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3374                           *ExceptionType = Context.getFunctionType(
3375                          Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3376
3377   if (DtorType->hasExceptionSpec()) {
3378     if (CheckEquivalentExceptionSpec(
3379           PDiag(diag::err_incorrect_defaulted_exception_spec)
3380             << CXXDestructor,
3381           PDiag(),
3382           ExceptionType, SourceLocation(),
3383           DtorType, DD->getLocation())) {
3384       DD->setInvalidDecl();
3385       return;
3386     }
3387   } else if (First) {
3388     // We set the declaration to have the computed exception spec here.
3389     // There are no parameters.
3390     EPI.ExtInfo = DtorType->getExtInfo();
3391     DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3392   }
3393
3394   if (ShouldDeleteDestructor(DD)) {
3395     if (First) {
3396       DD->setDeletedAsWritten();
3397     } else {
3398       Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
3399         << CXXDestructor;
3400       DD->setInvalidDecl();
3401     }
3402   }
3403 }
3404
3405 bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3406   CXXRecordDecl *RD = CD->getParent();
3407   assert(!RD->isDependentType() && "do deletion after instantiation");
3408   if (!LangOpts.CPlusPlus0x)
3409     return false;
3410
3411   SourceLocation Loc = CD->getLocation();
3412
3413   // Do access control from the constructor
3414   ContextRAII CtorContext(*this, CD);
3415
3416   bool Union = RD->isUnion();
3417   bool AllConst = true;
3418
3419   // We do this because we should never actually use an anonymous
3420   // union's constructor.
3421   if (Union && RD->isAnonymousStructOrUnion())
3422     return false;
3423
3424   // FIXME: We should put some diagnostic logic right into this function.
3425
3426   // C++0x [class.ctor]/5
3427   //    A defaulted default constructor for class X is defined as deleted if:
3428
3429   for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3430                                           BE = RD->bases_end();
3431        BI != BE; ++BI) {
3432     // We'll handle this one later
3433     if (BI->isVirtual())
3434       continue;
3435
3436     CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3437     assert(BaseDecl && "base isn't a CXXRecordDecl");
3438
3439     // -- any [direct base class] has a type with a destructor that is
3440     //    deleted or inaccessible from the defaulted default constructor
3441     CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3442     if (BaseDtor->isDeleted())
3443       return true;
3444     if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3445         AR_accessible)
3446       return true;
3447
3448     // -- any [direct base class either] has no default constructor or
3449     //    overload resolution as applied to [its] default constructor
3450     //    results in an ambiguity or in a function that is deleted or
3451     //    inaccessible from the defaulted default constructor
3452     CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3453     if (!BaseDefault || BaseDefault->isDeleted())
3454       return true;
3455
3456     if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3457                                PDiag()) != AR_accessible)
3458       return true;
3459   }
3460
3461   for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3462                                           BE = RD->vbases_end();
3463        BI != BE; ++BI) {
3464     CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3465     assert(BaseDecl && "base isn't a CXXRecordDecl");
3466
3467     // -- any [virtual base class] has a type with a destructor that is
3468     //    delete or inaccessible from the defaulted default constructor
3469     CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3470     if (BaseDtor->isDeleted())
3471       return true;
3472     if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3473         AR_accessible)
3474       return true;
3475
3476     // -- any [virtual base class either] has no default constructor or
3477     //    overload resolution as applied to [its] default constructor
3478     //    results in an ambiguity or in a function that is deleted or
3479     //    inaccessible from the defaulted default constructor
3480     CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3481     if (!BaseDefault || BaseDefault->isDeleted())
3482       return true;
3483
3484     if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3485                                PDiag()) != AR_accessible)
3486       return true;
3487   }
3488
3489   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3490                                      FE = RD->field_end();
3491        FI != FE; ++FI) {
3492     if (FI->isInvalidDecl())
3493       continue;
3494     
3495     QualType FieldType = Context.getBaseElementType(FI->getType());
3496     CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3497
3498     // -- any non-static data member with no brace-or-equal-initializer is of
3499     //    reference type
3500     if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
3501       return true;
3502
3503     // -- X is a union and all its variant members are of const-qualified type
3504     //    (or array thereof)
3505     if (Union && !FieldType.isConstQualified())
3506       AllConst = false;
3507
3508     if (FieldRecord) {
3509       // -- X is a union-like class that has a variant member with a non-trivial
3510       //    default constructor
3511       if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3512         return true;
3513
3514       CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3515       if (FieldDtor->isDeleted())
3516         return true;
3517       if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
3518           AR_accessible)
3519         return true;
3520
3521       // -- any non-variant non-static data member of const-qualified type (or
3522       //    array thereof) with no brace-or-equal-initializer does not have a
3523       //    user-provided default constructor
3524       if (FieldType.isConstQualified() &&
3525           !FI->hasInClassInitializer() &&
3526           !FieldRecord->hasUserProvidedDefaultConstructor())
3527         return true;
3528  
3529       if (!Union && FieldRecord->isUnion() &&
3530           FieldRecord->isAnonymousStructOrUnion()) {
3531         // We're okay to reuse AllConst here since we only care about the
3532         // value otherwise if we're in a union.
3533         AllConst = true;
3534
3535         for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3536                                            UE = FieldRecord->field_end();
3537              UI != UE; ++UI) {
3538           QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3539           CXXRecordDecl *UnionFieldRecord =
3540             UnionFieldType->getAsCXXRecordDecl();
3541
3542           if (!UnionFieldType.isConstQualified())
3543             AllConst = false;
3544
3545           if (UnionFieldRecord &&
3546               !UnionFieldRecord->hasTrivialDefaultConstructor())
3547             return true;
3548         }
3549
3550         if (AllConst)
3551           return true;
3552
3553         // Don't try to initialize the anonymous union
3554         // This is technically non-conformant, but sanity demands it.
3555         continue;
3556       }
3557
3558       // -- any non-static data member with no brace-or-equal-initializer has
3559       //    class type M (or array thereof) and either M has no default
3560       //    constructor or overload resolution as applied to M's default
3561       //    constructor results in an ambiguity or in a function that is deleted
3562       //    or inaccessible from the defaulted default constructor.
3563       if (!FI->hasInClassInitializer()) {
3564         CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3565         if (!FieldDefault || FieldDefault->isDeleted())
3566           return true;
3567         if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3568                                    PDiag()) != AR_accessible)
3569           return true;
3570       }
3571     } else if (!Union && FieldType.isConstQualified() &&
3572                !FI->hasInClassInitializer()) {
3573       // -- any non-variant non-static data member of const-qualified type (or
3574       //    array thereof) with no brace-or-equal-initializer does not have a
3575       //    user-provided default constructor
3576       return true;
3577     }
3578   }
3579
3580   if (Union && AllConst)
3581     return true;
3582
3583   return false;
3584 }
3585
3586 bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
3587   CXXRecordDecl *RD = CD->getParent();
3588   assert(!RD->isDependentType() && "do deletion after instantiation");
3589   if (!LangOpts.CPlusPlus0x)
3590     return false;
3591
3592   SourceLocation Loc = CD->getLocation();
3593
3594   // Do access control from the constructor
3595   ContextRAII CtorContext(*this, CD);
3596
3597   bool Union = RD->isUnion();
3598
3599   assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3600          "copy assignment arg has no pointee type");
3601   unsigned ArgQuals =
3602     CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3603       Qualifiers::Const : 0;
3604
3605   // We do this because we should never actually use an anonymous
3606   // union's constructor.
3607   if (Union && RD->isAnonymousStructOrUnion())
3608     return false;
3609
3610   // FIXME: We should put some diagnostic logic right into this function.
3611
3612   // C++0x [class.copy]/11
3613   //    A defaulted [copy] constructor for class X is defined as delete if X has:
3614
3615   for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3616                                           BE = RD->bases_end();
3617        BI != BE; ++BI) {
3618     // We'll handle this one later
3619     if (BI->isVirtual())
3620       continue;
3621
3622     QualType BaseType = BI->getType();
3623     CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3624     assert(BaseDecl && "base isn't a CXXRecordDecl");
3625
3626     // -- any [direct base class] of a type with a destructor that is deleted or
3627     //    inaccessible from the defaulted constructor
3628     CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3629     if (BaseDtor->isDeleted())
3630       return true;
3631     if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3632         AR_accessible)
3633       return true;
3634
3635     // -- a [direct base class] B that cannot be [copied] because overload
3636     //    resolution, as applied to B's [copy] constructor, results in an
3637     //    ambiguity or a function that is deleted or inaccessible from the
3638     //    defaulted constructor
3639     CXXConstructorDecl *BaseCtor = LookupCopyConstructor(BaseDecl, ArgQuals);
3640     if (!BaseCtor || BaseCtor->isDeleted())
3641       return true;
3642     if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3643         AR_accessible)
3644       return true;
3645   }
3646
3647   for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3648                                           BE = RD->vbases_end();
3649        BI != BE; ++BI) {
3650     QualType BaseType = BI->getType();
3651     CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3652     assert(BaseDecl && "base isn't a CXXRecordDecl");
3653
3654     // -- any [virtual base class] of a type with a destructor that is deleted or
3655     //    inaccessible from the defaulted constructor
3656     CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3657     if (BaseDtor->isDeleted())
3658       return true;
3659     if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3660         AR_accessible)
3661       return true;
3662
3663     // -- a [virtual base class] B that cannot be [copied] because overload
3664     //    resolution, as applied to B's [copy] constructor, results in an
3665     //    ambiguity or a function that is deleted or inaccessible from the
3666     //    defaulted constructor
3667     CXXConstructorDecl *BaseCtor = LookupCopyConstructor(BaseDecl, ArgQuals);
3668     if (!BaseCtor || BaseCtor->isDeleted())
3669       return true;
3670     if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3671         AR_accessible)
3672       return true;
3673   }
3674
3675   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3676                                      FE = RD->field_end();
3677        FI != FE; ++FI) {
3678     QualType FieldType = Context.getBaseElementType(FI->getType());
3679     
3680     // -- for a copy constructor, a non-static data member of rvalue reference
3681     //    type
3682     if (FieldType->isRValueReferenceType())
3683       return true;
3684  
3685     CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3686
3687     if (FieldRecord) {
3688       // This is an anonymous union
3689       if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3690         // Anonymous unions inside unions do not variant members create
3691         if (!Union) {
3692           for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3693                                              UE = FieldRecord->field_end();
3694                UI != UE; ++UI) {
3695             QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3696             CXXRecordDecl *UnionFieldRecord =
3697               UnionFieldType->getAsCXXRecordDecl();
3698
3699             // -- a variant member with a non-trivial [copy] constructor and X
3700             //    is a union-like class
3701             if (UnionFieldRecord &&
3702                 !UnionFieldRecord->hasTrivialCopyConstructor())
3703               return true;
3704           }
3705         }
3706
3707         // Don't try to initalize an anonymous union
3708         continue;
3709       } else {
3710          // -- a variant member with a non-trivial [copy] constructor and X is a
3711          //    union-like class
3712         if (Union && !FieldRecord->hasTrivialCopyConstructor())
3713           return true;
3714
3715         // -- any [non-static data member] of a type with a destructor that is
3716         //    deleted or inaccessible from the defaulted constructor
3717         CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3718         if (FieldDtor->isDeleted())
3719           return true;
3720         if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
3721             AR_accessible)
3722           return true;
3723       }
3724
3725     // -- a [non-static data member of class type (or array thereof)] B that
3726     //    cannot be [copied] because overload resolution, as applied to B's
3727     //    [copy] constructor, results in an ambiguity or a function that is
3728     //    deleted or inaccessible from the defaulted constructor
3729       CXXConstructorDecl *FieldCtor = LookupCopyConstructor(FieldRecord,
3730                                                             ArgQuals);
3731       if (!FieldCtor || FieldCtor->isDeleted())
3732         return true;
3733       if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
3734                                  PDiag()) != AR_accessible)
3735         return true;
3736     }
3737   }
3738
3739   return false;
3740 }
3741
3742 bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3743   CXXRecordDecl *RD = MD->getParent();
3744   assert(!RD->isDependentType() && "do deletion after instantiation");
3745   if (!LangOpts.CPlusPlus0x)
3746     return false;
3747
3748   SourceLocation Loc = MD->getLocation();
3749
3750   // Do access control from the constructor
3751   ContextRAII MethodContext(*this, MD);
3752
3753   bool Union = RD->isUnion();
3754
3755   bool ConstArg =
3756     MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified();
3757
3758   // We do this because we should never actually use an anonymous
3759   // union's constructor.
3760   if (Union && RD->isAnonymousStructOrUnion())
3761     return false;
3762
3763   DeclarationName OperatorName =
3764     Context.DeclarationNames.getCXXOperatorName(OO_Equal);
3765   LookupResult R(*this, OperatorName, Loc, LookupOrdinaryName);
3766   R.suppressDiagnostics();
3767
3768   // FIXME: We should put some diagnostic logic right into this function.
3769
3770   // C++0x [class.copy]/11
3771   //    A defaulted [copy] assignment operator for class X is defined as deleted
3772   //    if X has:
3773
3774   for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3775                                           BE = RD->bases_end();
3776        BI != BE; ++BI) {
3777     // We'll handle this one later
3778     if (BI->isVirtual())
3779       continue;
3780
3781     QualType BaseType = BI->getType();
3782     CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3783     assert(BaseDecl && "base isn't a CXXRecordDecl");
3784
3785     // -- a [direct base class] B that cannot be [copied] because overload
3786     //    resolution, as applied to B's [copy] assignment operator, results in
3787     //    an ambiguity or a function that is deleted or inaccessible from the
3788     //    assignment operator
3789
3790     LookupQualifiedName(R, BaseDecl, false);
3791
3792     // Filter out any result that isn't a copy-assignment operator.
3793     LookupResult::Filter F = R.makeFilter();
3794     while (F.hasNext()) {
3795       NamedDecl *D = F.next();
3796       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3797         if (Method->isCopyAssignmentOperator())
3798           continue;
3799       
3800       F.erase();
3801     }
3802     F.done();
3803  
3804     // Build a fake argument expression
3805     QualType ArgType = BaseType;
3806     QualType ThisType = BaseType;
3807     if (ConstArg)
3808       ArgType.addConst();
3809     Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3810                    , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3811                    };
3812
3813     OverloadCandidateSet OCS((Loc));
3814     OverloadCandidateSet::iterator Best;
3815
3816     AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3817
3818     if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3819         OR_Success)
3820       return true;
3821   }
3822
3823   for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3824                                           BE = RD->vbases_end();
3825        BI != BE; ++BI) {
3826     QualType BaseType = BI->getType();
3827     CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3828     assert(BaseDecl && "base isn't a CXXRecordDecl");
3829
3830     // -- a [virtual base class] B that cannot be [copied] because overload
3831     //    resolution, as applied to B's [copy] assignment operator, results in
3832     //    an ambiguity or a function that is deleted or inaccessible from the
3833     //    assignment operator
3834
3835     LookupQualifiedName(R, BaseDecl, false);
3836
3837     // Filter out any result that isn't a copy-assignment operator.
3838     LookupResult::Filter F = R.makeFilter();
3839     while (F.hasNext()) {
3840       NamedDecl *D = F.next();
3841       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3842         if (Method->isCopyAssignmentOperator())
3843           continue;
3844       
3845       F.erase();
3846     }
3847     F.done();
3848  
3849     // Build a fake argument expression
3850     QualType ArgType = BaseType;
3851     QualType ThisType = BaseType;
3852     if (ConstArg)
3853       ArgType.addConst();
3854     Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3855                    , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3856                    };
3857
3858     OverloadCandidateSet OCS((Loc));
3859     OverloadCandidateSet::iterator Best;
3860
3861     AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3862
3863     if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3864         OR_Success)
3865       return true;
3866   }
3867
3868   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3869                                      FE = RD->field_end();
3870        FI != FE; ++FI) {
3871     QualType FieldType = Context.getBaseElementType(FI->getType());
3872     
3873     // -- a non-static data member of reference type
3874     if (FieldType->isReferenceType())
3875       return true;
3876
3877     // -- a non-static data member of const non-class type (or array thereof)
3878     if (FieldType.isConstQualified() && !FieldType->isRecordType())
3879       return true;
3880  
3881     CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3882
3883     if (FieldRecord) {
3884       // This is an anonymous union
3885       if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3886         // Anonymous unions inside unions do not variant members create
3887         if (!Union) {
3888           for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3889                                              UE = FieldRecord->field_end();
3890                UI != UE; ++UI) {
3891             QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3892             CXXRecordDecl *UnionFieldRecord =
3893               UnionFieldType->getAsCXXRecordDecl();
3894
3895             // -- a variant member with a non-trivial [copy] assignment operator
3896             //    and X is a union-like class
3897             if (UnionFieldRecord &&
3898                 !UnionFieldRecord->hasTrivialCopyAssignment())
3899               return true;
3900           }
3901         }
3902
3903         // Don't try to initalize an anonymous union
3904         continue;
3905       // -- a variant member with a non-trivial [copy] assignment operator
3906       //    and X is a union-like class
3907       } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
3908           return true;
3909       }
3910
3911       LookupQualifiedName(R, FieldRecord, false);
3912
3913       // Filter out any result that isn't a copy-assignment operator.
3914       LookupResult::Filter F = R.makeFilter();
3915       while (F.hasNext()) {
3916         NamedDecl *D = F.next();
3917         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3918           if (Method->isCopyAssignmentOperator())
3919             continue;
3920         
3921         F.erase();
3922       }
3923       F.done();
3924    
3925       // Build a fake argument expression
3926       QualType ArgType = FieldType;
3927       QualType ThisType = FieldType;
3928       if (ConstArg)
3929         ArgType.addConst();
3930       Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3931                      , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3932                      };
3933
3934       OverloadCandidateSet OCS((Loc));
3935       OverloadCandidateSet::iterator Best;
3936
3937       AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3938
3939       if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3940           OR_Success)
3941         return true;
3942     }
3943   }
3944
3945   return false;
3946 }
3947
3948 bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
3949   CXXRecordDecl *RD = DD->getParent();
3950   assert(!RD->isDependentType() && "do deletion after instantiation");
3951   if (!LangOpts.CPlusPlus0x)
3952     return false;
3953
3954   SourceLocation Loc = DD->getLocation();
3955
3956   // Do access control from the destructor
3957   ContextRAII CtorContext(*this, DD);
3958
3959   bool Union = RD->isUnion();
3960
3961   // We do this because we should never actually use an anonymous
3962   // union's destructor.
3963   if (Union && RD->isAnonymousStructOrUnion())
3964     return false;
3965
3966   // C++0x [class.dtor]p5
3967   //    A defaulted destructor for a class X is defined as deleted if:
3968   for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3969                                           BE = RD->bases_end();
3970        BI != BE; ++BI) {
3971     // We'll handle this one later
3972     if (BI->isVirtual())
3973       continue;
3974
3975     CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3976     CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3977     assert(BaseDtor && "base has no destructor");
3978
3979     // -- any direct or virtual base class has a deleted destructor or
3980     //    a destructor that is inaccessible from the defaulted destructor
3981     if (BaseDtor->isDeleted())
3982       return true;
3983     if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3984         AR_accessible)
3985       return true;
3986   }
3987
3988   for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3989                                           BE = RD->vbases_end();
3990        BI != BE; ++BI) {
3991     CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3992     CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3993     assert(BaseDtor && "base has no destructor");
3994
3995     // -- any direct or virtual base class has a deleted destructor or
3996     //    a destructor that is inaccessible from the defaulted destructor
3997     if (BaseDtor->isDeleted())
3998       return true;
3999     if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4000         AR_accessible)
4001       return true;
4002   }
4003
4004   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4005                                      FE = RD->field_end();
4006        FI != FE; ++FI) {
4007     QualType FieldType = Context.getBaseElementType(FI->getType());
4008     CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4009     if (FieldRecord) {
4010       if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4011          for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4012                                             UE = FieldRecord->field_end();
4013               UI != UE; ++UI) {
4014            QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4015            CXXRecordDecl *UnionFieldRecord =
4016              UnionFieldType->getAsCXXRecordDecl();
4017
4018            // -- X is a union-like class that has a variant member with a non-
4019            //    trivial destructor.
4020            if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4021              return true;
4022          }
4023       // Technically we are supposed to do this next check unconditionally.
4024       // But that makes absolutely no sense.
4025       } else {
4026         CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4027
4028         // -- any of the non-static data members has class type M (or array
4029         //    thereof) and M has a deleted destructor or a destructor that is
4030         //    inaccessible from the defaulted destructor
4031         if (FieldDtor->isDeleted())
4032           return true;
4033         if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4034           AR_accessible)
4035         return true;
4036         
4037         // -- X is a union-like class that has a variant member with a non-
4038         //    trivial destructor.
4039         if (Union && !FieldDtor->isTrivial())
4040           return true;
4041       }
4042     }
4043   }
4044
4045   if (DD->isVirtual()) {
4046     FunctionDecl *OperatorDelete = 0;
4047     DeclarationName Name =
4048       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4049     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
4050           false))
4051       return true;
4052   }
4053
4054
4055   return false;
4056 }
4057
4058 /// \brief Data used with FindHiddenVirtualMethod
4059 namespace {
4060   struct FindHiddenVirtualMethodData {
4061     Sema *S;
4062     CXXMethodDecl *Method;
4063     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4064     llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4065   };
4066 }
4067
4068 /// \brief Member lookup function that determines whether a given C++
4069 /// method overloads virtual methods in a base class without overriding any,
4070 /// to be used with CXXRecordDecl::lookupInBases().
4071 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4072                                     CXXBasePath &Path,
4073                                     void *UserData) {
4074   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4075
4076   FindHiddenVirtualMethodData &Data
4077     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4078
4079   DeclarationName Name = Data.Method->getDeclName();
4080   assert(Name.getNameKind() == DeclarationName::Identifier);
4081
4082   bool foundSameNameMethod = false;
4083   llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4084   for (Path.Decls = BaseRecord->lookup(Name);
4085        Path.Decls.first != Path.Decls.second;
4086        ++Path.Decls.first) {
4087     NamedDecl *D = *Path.Decls.first;
4088     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4089       MD = MD->getCanonicalDecl();
4090       foundSameNameMethod = true;
4091       // Interested only in hidden virtual methods.
4092       if (!MD->isVirtual())
4093         continue;
4094       // If the method we are checking overrides a method from its base
4095       // don't warn about the other overloaded methods.
4096       if (!Data.S->IsOverload(Data.Method, MD, false))
4097         return true;
4098       // Collect the overload only if its hidden.
4099       if (!Data.OverridenAndUsingBaseMethods.count(MD))
4100         overloadedMethods.push_back(MD);
4101     }
4102   }
4103
4104   if (foundSameNameMethod)
4105     Data.OverloadedMethods.append(overloadedMethods.begin(),
4106                                    overloadedMethods.end());
4107   return foundSameNameMethod;
4108 }
4109
4110 /// \brief See if a method overloads virtual methods in a base class without
4111 /// overriding any.
4112 void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4113   if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4114                                MD->getLocation()) == Diagnostic::Ignored)
4115     return;
4116   if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4117     return;
4118
4119   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4120                      /*bool RecordPaths=*/false,
4121                      /*bool DetectVirtual=*/false);
4122   FindHiddenVirtualMethodData Data;
4123   Data.Method = MD;
4124   Data.S = this;
4125
4126   // Keep the base methods that were overriden or introduced in the subclass
4127   // by 'using' in a set. A base method not in this set is hidden.
4128   for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4129        res.first != res.second; ++res.first) {
4130     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4131       for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4132                                           E = MD->end_overridden_methods();
4133            I != E; ++I)
4134         Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
4135     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4136       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
4137         Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
4138   }
4139
4140   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4141       !Data.OverloadedMethods.empty()) {
4142     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4143       << MD << (Data.OverloadedMethods.size() > 1);
4144
4145     for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4146       CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4147       Diag(overloadedMD->getLocation(),
4148            diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4149     }
4150   }
4151 }
4152
4153 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4154                                              Decl *TagDecl,
4155                                              SourceLocation LBrac,
4156                                              SourceLocation RBrac,
4157                                              AttributeList *AttrList) {
4158   if (!TagDecl)
4159     return;
4160
4161   AdjustDeclIfTemplate(TagDecl);
4162
4163   ActOnFields(S, RLoc, TagDecl,
4164               // strict aliasing violation!
4165               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
4166               FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
4167
4168   CheckCompletedCXXClass(
4169                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
4170 }
4171
4172 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4173 /// special functions, such as the default constructor, copy
4174 /// constructor, or destructor, to the given C++ class (C++
4175 /// [special]p1).  This routine can only be executed just before the
4176 /// definition of the class is complete.
4177 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
4178   if (!ClassDecl->hasUserDeclaredConstructor())
4179     ++ASTContext::NumImplicitDefaultConstructors;
4180
4181   if (!ClassDecl->hasUserDeclaredCopyConstructor())
4182     ++ASTContext::NumImplicitCopyConstructors;
4183
4184   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4185     ++ASTContext::NumImplicitCopyAssignmentOperators;
4186     
4187     // If we have a dynamic class, then the copy assignment operator may be 
4188     // virtual, so we have to declare it immediately. This ensures that, e.g.,
4189     // it shows up in the right place in the vtable and that we diagnose 
4190     // problems with the implicit exception specification.    
4191     if (ClassDecl->isDynamicClass())
4192       DeclareImplicitCopyAssignment(ClassDecl);
4193   }
4194
4195   if (!ClassDecl->hasUserDeclaredDestructor()) {
4196     ++ASTContext::NumImplicitDestructors;
4197     
4198     // If we have a dynamic class, then the destructor may be virtual, so we 
4199     // have to declare the destructor immediately. This ensures that, e.g., it
4200     // shows up in the right place in the vtable and that we diagnose problems
4201     // with the implicit exception specification.
4202     if (ClassDecl->isDynamicClass())
4203       DeclareImplicitDestructor(ClassDecl);
4204   }
4205 }
4206
4207 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4208   if (!D)
4209     return;
4210
4211   int NumParamList = D->getNumTemplateParameterLists();
4212   for (int i = 0; i < NumParamList; i++) {
4213     TemplateParameterList* Params = D->getTemplateParameterList(i);
4214     for (TemplateParameterList::iterator Param = Params->begin(),
4215                                       ParamEnd = Params->end();
4216           Param != ParamEnd; ++Param) {
4217       NamedDecl *Named = cast<NamedDecl>(*Param);
4218       if (Named->getDeclName()) {
4219         S->AddDecl(Named);
4220         IdResolver.AddDecl(Named);
4221       }
4222     }
4223   }
4224 }
4225
4226 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
4227   if (!D)
4228     return;
4229   
4230   TemplateParameterList *Params = 0;
4231   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4232     Params = Template->getTemplateParameters();
4233   else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4234            = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4235     Params = PartialSpec->getTemplateParameters();
4236   else
4237     return;
4238
4239   for (TemplateParameterList::iterator Param = Params->begin(),
4240                                     ParamEnd = Params->end();
4241        Param != ParamEnd; ++Param) {
4242     NamedDecl *Named = cast<NamedDecl>(*Param);
4243     if (Named->getDeclName()) {
4244       S->AddDecl(Named);
4245       IdResolver.AddDecl(Named);
4246     }
4247   }
4248 }
4249
4250 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4251   if (!RecordD) return;
4252   AdjustDeclIfTemplate(RecordD);
4253   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
4254   PushDeclContext(S, Record);
4255 }
4256
4257 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4258   if (!RecordD) return;
4259   PopDeclContext();
4260 }
4261
4262 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
4263 /// parsing a top-level (non-nested) C++ class, and we are now
4264 /// parsing those parts of the given Method declaration that could
4265 /// not be parsed earlier (C++ [class.mem]p2), such as default
4266 /// arguments. This action should enter the scope of the given
4267 /// Method declaration as if we had just parsed the qualified method
4268 /// name. However, it should not bring the parameters into scope;
4269 /// that will be performed by ActOnDelayedCXXMethodParameter.
4270 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4271 }
4272
4273 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
4274 /// C++ method declaration. We're (re-)introducing the given
4275 /// function parameter into scope for use in parsing later parts of
4276 /// the method declaration. For example, we could see an
4277 /// ActOnParamDefaultArgument event for this parameter.
4278 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
4279   if (!ParamD)
4280     return;
4281
4282   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
4283
4284   // If this parameter has an unparsed default argument, clear it out
4285   // to make way for the parsed default argument.
4286   if (Param->hasUnparsedDefaultArg())
4287     Param->setDefaultArg(0);
4288
4289   S->AddDecl(Param);
4290   if (Param->getDeclName())
4291     IdResolver.AddDecl(Param);
4292 }
4293
4294 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4295 /// processing the delayed method declaration for Method. The method
4296 /// declaration is now considered finished. There may be a separate
4297 /// ActOnStartOfFunctionDef action later (not necessarily
4298 /// immediately!) for this method, if it was also defined inside the
4299 /// class body.
4300 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4301   if (!MethodD)
4302     return;
4303
4304   AdjustDeclIfTemplate(MethodD);
4305
4306   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
4307
4308   // Now that we have our default arguments, check the constructor
4309   // again. It could produce additional diagnostics or affect whether
4310   // the class has implicitly-declared destructors, among other
4311   // things.
4312   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4313     CheckConstructor(Constructor);
4314
4315   // Check the default arguments, which we may have added.
4316   if (!Method->isInvalidDecl())
4317     CheckCXXDefaultArguments(Method);
4318 }
4319
4320 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
4321 /// the well-formedness of the constructor declarator @p D with type @p
4322 /// R. If there are any errors in the declarator, this routine will
4323 /// emit diagnostics and set the invalid bit to true.  In any case, the type
4324 /// will be updated to reflect a well-formed type for the constructor and
4325 /// returned.
4326 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
4327                                           StorageClass &SC) {
4328   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4329
4330   // C++ [class.ctor]p3:
4331   //   A constructor shall not be virtual (10.3) or static (9.4). A
4332   //   constructor can be invoked for a const, volatile or const
4333   //   volatile object. A constructor shall not be declared const,
4334   //   volatile, or const volatile (9.3.2).
4335   if (isVirtual) {
4336     if (!D.isInvalidType())
4337       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4338         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4339         << SourceRange(D.getIdentifierLoc());
4340     D.setInvalidType();
4341   }
4342   if (SC == SC_Static) {
4343     if (!D.isInvalidType())
4344       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4345         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4346         << SourceRange(D.getIdentifierLoc());
4347     D.setInvalidType();
4348     SC = SC_None;
4349   }
4350
4351   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4352   if (FTI.TypeQuals != 0) {
4353     if (FTI.TypeQuals & Qualifiers::Const)
4354       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4355         << "const" << SourceRange(D.getIdentifierLoc());
4356     if (FTI.TypeQuals & Qualifiers::Volatile)
4357       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4358         << "volatile" << SourceRange(D.getIdentifierLoc());
4359     if (FTI.TypeQuals & Qualifiers::Restrict)
4360       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4361         << "restrict" << SourceRange(D.getIdentifierLoc());
4362     D.setInvalidType();
4363   }
4364
4365   // C++0x [class.ctor]p4:
4366   //   A constructor shall not be declared with a ref-qualifier.
4367   if (FTI.hasRefQualifier()) {
4368     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4369       << FTI.RefQualifierIsLValueRef 
4370       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4371     D.setInvalidType();
4372   }
4373   
4374   // Rebuild the function type "R" without any type qualifiers (in
4375   // case any of the errors above fired) and with "void" as the
4376   // return type, since constructors don't have return types.
4377   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4378   if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4379     return R;
4380
4381   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4382   EPI.TypeQuals = 0;
4383   EPI.RefQualifier = RQ_None;
4384   
4385   return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
4386                                  Proto->getNumArgs(), EPI);
4387 }
4388
4389 /// CheckConstructor - Checks a fully-formed constructor for
4390 /// well-formedness, issuing any diagnostics required. Returns true if
4391 /// the constructor declarator is invalid.
4392 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
4393   CXXRecordDecl *ClassDecl
4394     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4395   if (!ClassDecl)
4396     return Constructor->setInvalidDecl();
4397
4398   // C++ [class.copy]p3:
4399   //   A declaration of a constructor for a class X is ill-formed if
4400   //   its first parameter is of type (optionally cv-qualified) X and
4401   //   either there are no other parameters or else all other
4402   //   parameters have default arguments.
4403   if (!Constructor->isInvalidDecl() &&
4404       ((Constructor->getNumParams() == 1) ||
4405        (Constructor->getNumParams() > 1 &&
4406         Constructor->getParamDecl(1)->hasDefaultArg())) &&
4407       Constructor->getTemplateSpecializationKind()
4408                                               != TSK_ImplicitInstantiation) {
4409     QualType ParamType = Constructor->getParamDecl(0)->getType();
4410     QualType ClassTy = Context.getTagDeclType(ClassDecl);
4411     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
4412       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
4413       const char *ConstRef 
4414         = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 
4415                                                         : " const &";
4416       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
4417         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
4418
4419       // FIXME: Rather that making the constructor invalid, we should endeavor
4420       // to fix the type.
4421       Constructor->setInvalidDecl();
4422     }
4423   }
4424 }
4425
4426 /// CheckDestructor - Checks a fully-formed destructor definition for
4427 /// well-formedness, issuing any diagnostics required.  Returns true
4428 /// on error.
4429 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
4430   CXXRecordDecl *RD = Destructor->getParent();
4431   
4432   if (Destructor->isVirtual()) {
4433     SourceLocation Loc;
4434     
4435     if (!Destructor->isImplicit())
4436       Loc = Destructor->getLocation();
4437     else
4438       Loc = RD->getLocation();
4439     
4440     // If we have a virtual destructor, look up the deallocation function
4441     FunctionDecl *OperatorDelete = 0;
4442     DeclarationName Name = 
4443     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4444     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
4445       return true;
4446
4447     MarkDeclarationReferenced(Loc, OperatorDelete);
4448     
4449     Destructor->setOperatorDelete(OperatorDelete);
4450   }
4451   
4452   return false;
4453 }
4454
4455 static inline bool
4456 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4457   return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4458           FTI.ArgInfo[0].Param &&
4459           cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
4460 }
4461
4462 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4463 /// the well-formednes of the destructor declarator @p D with type @p
4464 /// R. If there are any errors in the declarator, this routine will
4465 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
4466 /// will be updated to reflect a well-formed type for the destructor and
4467 /// returned.
4468 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
4469                                          StorageClass& SC) {
4470   // C++ [class.dtor]p1:
4471   //   [...] A typedef-name that names a class is a class-name
4472   //   (7.1.3); however, a typedef-name that names a class shall not
4473   //   be used as the identifier in the declarator for a destructor
4474   //   declaration.
4475   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
4476   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
4477     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4478       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
4479   else if (const TemplateSpecializationType *TST =
4480              DeclaratorType->getAs<TemplateSpecializationType>())
4481     if (TST->isTypeAlias())
4482       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4483         << DeclaratorType << 1;
4484
4485   // C++ [class.dtor]p2:
4486   //   A destructor is used to destroy objects of its class type. A
4487   //   destructor takes no parameters, and no return type can be
4488   //   specified for it (not even void). The address of a destructor
4489   //   shall not be taken. A destructor shall not be static. A
4490   //   destructor can be invoked for a const, volatile or const
4491   //   volatile object. A destructor shall not be declared const,
4492   //   volatile or const volatile (9.3.2).
4493   if (SC == SC_Static) {
4494     if (!D.isInvalidType())
4495       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4496         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4497         << SourceRange(D.getIdentifierLoc())
4498         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4499     
4500     SC = SC_None;
4501   }
4502   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
4503     // Destructors don't have return types, but the parser will
4504     // happily parse something like:
4505     //
4506     //   class X {
4507     //     float ~X();
4508     //   };
4509     //
4510     // The return type will be eliminated later.
4511     Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4512       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4513       << SourceRange(D.getIdentifierLoc());
4514   }
4515
4516   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4517   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
4518     if (FTI.TypeQuals & Qualifiers::Const)
4519       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4520         << "const" << SourceRange(D.getIdentifierLoc());
4521     if (FTI.TypeQuals & Qualifiers::Volatile)
4522       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4523         << "volatile" << SourceRange(D.getIdentifierLoc());
4524     if (FTI.TypeQuals & Qualifiers::Restrict)
4525       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4526         << "restrict" << SourceRange(D.getIdentifierLoc());
4527     D.setInvalidType();
4528   }
4529
4530   // C++0x [class.dtor]p2:
4531   //   A destructor shall not be declared with a ref-qualifier.
4532   if (FTI.hasRefQualifier()) {
4533     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4534       << FTI.RefQualifierIsLValueRef
4535       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4536     D.setInvalidType();
4537   }
4538   
4539   // Make sure we don't have any parameters.
4540   if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
4541     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4542
4543     // Delete the parameters.
4544     FTI.freeArgs();
4545     D.setInvalidType();
4546   }
4547
4548   // Make sure the destructor isn't variadic.
4549   if (FTI.isVariadic) {
4550     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
4551     D.setInvalidType();
4552   }
4553
4554   // Rebuild the function type "R" without any type qualifiers or
4555   // parameters (in case any of the errors above fired) and with
4556   // "void" as the return type, since destructors don't have return
4557   // types. 
4558   if (!D.isInvalidType())
4559     return R;
4560
4561   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4562   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4563   EPI.Variadic = false;
4564   EPI.TypeQuals = 0;
4565   EPI.RefQualifier = RQ_None;
4566   return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
4567 }
4568
4569 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4570 /// well-formednes of the conversion function declarator @p D with
4571 /// type @p R. If there are any errors in the declarator, this routine
4572 /// will emit diagnostics and return true. Otherwise, it will return
4573 /// false. Either way, the type @p R will be updated to reflect a
4574 /// well-formed type for the conversion operator.
4575 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
4576                                      StorageClass& SC) {
4577   // C++ [class.conv.fct]p1:
4578   //   Neither parameter types nor return type can be specified. The
4579   //   type of a conversion function (8.3.5) is "function taking no
4580   //   parameter returning conversion-type-id."
4581   if (SC == SC_Static) {
4582     if (!D.isInvalidType())
4583       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
4584         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4585         << SourceRange(D.getIdentifierLoc());
4586     D.setInvalidType();
4587     SC = SC_None;
4588   }
4589
4590   QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
4591
4592   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
4593     // Conversion functions don't have return types, but the parser will
4594     // happily parse something like:
4595     //
4596     //   class X {
4597     //     float operator bool();
4598     //   };
4599     //
4600     // The return type will be changed later anyway.
4601     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
4602       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4603       << SourceRange(D.getIdentifierLoc());
4604     D.setInvalidType();
4605   }
4606
4607   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4608
4609   // Make sure we don't have any parameters.
4610   if (Proto->getNumArgs() > 0) {
4611     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
4612
4613     // Delete the parameters.
4614     D.getFunctionTypeInfo().freeArgs();
4615     D.setInvalidType();
4616   } else if (Proto->isVariadic()) {
4617     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
4618     D.setInvalidType();
4619   }
4620
4621   // Diagnose "&operator bool()" and other such nonsense.  This
4622   // is actually a gcc extension which we don't support.
4623   if (Proto->getResultType() != ConvType) {
4624     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
4625       << Proto->getResultType();
4626     D.setInvalidType();
4627     ConvType = Proto->getResultType();
4628   }
4629
4630   // C++ [class.conv.fct]p4:
4631   //   The conversion-type-id shall not represent a function type nor
4632   //   an array type.
4633   if (ConvType->isArrayType()) {
4634     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
4635     ConvType = Context.getPointerType(ConvType);
4636     D.setInvalidType();
4637   } else if (ConvType->isFunctionType()) {
4638     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
4639     ConvType = Context.getPointerType(ConvType);
4640     D.setInvalidType();
4641   }
4642
4643   // Rebuild the function type "R" without any parameters (in case any
4644   // of the errors above fired) and with the conversion type as the
4645   // return type.
4646   if (D.isInvalidType())
4647     R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
4648
4649   // C++0x explicit conversion operators.
4650   if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
4651     Diag(D.getDeclSpec().getExplicitSpecLoc(),
4652          diag::warn_explicit_conversion_functions)
4653       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
4654 }
4655
4656 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
4657 /// the declaration of the given C++ conversion function. This routine
4658 /// is responsible for recording the conversion function in the C++
4659 /// class, if possible.
4660 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
4661   assert(Conversion && "Expected to receive a conversion function declaration");
4662
4663   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
4664
4665   // Make sure we aren't redeclaring the conversion function.
4666   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
4667
4668   // C++ [class.conv.fct]p1:
4669   //   [...] A conversion function is never used to convert a
4670   //   (possibly cv-qualified) object to the (possibly cv-qualified)
4671   //   same object type (or a reference to it), to a (possibly
4672   //   cv-qualified) base class of that type (or a reference to it),
4673   //   or to (possibly cv-qualified) void.
4674   // FIXME: Suppress this warning if the conversion function ends up being a
4675   // virtual function that overrides a virtual function in a base class.
4676   QualType ClassType
4677     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4678   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
4679     ConvType = ConvTypeRef->getPointeeType();
4680   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
4681       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
4682     /* Suppress diagnostics for instantiations. */;
4683   else if (ConvType->isRecordType()) {
4684     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
4685     if (ConvType == ClassType)
4686       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
4687         << ClassType;
4688     else if (IsDerivedFrom(ClassType, ConvType))
4689       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
4690         <<  ClassType << ConvType;
4691   } else if (ConvType->isVoidType()) {
4692     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
4693       << ClassType << ConvType;
4694   }
4695
4696   if (FunctionTemplateDecl *ConversionTemplate
4697                                 = Conversion->getDescribedFunctionTemplate())
4698     return ConversionTemplate;
4699   
4700   return Conversion;
4701 }
4702
4703 //===----------------------------------------------------------------------===//
4704 // Namespace Handling
4705 //===----------------------------------------------------------------------===//
4706
4707
4708
4709 /// ActOnStartNamespaceDef - This is called at the start of a namespace
4710 /// definition.
4711 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
4712                                    SourceLocation InlineLoc,
4713                                    SourceLocation NamespaceLoc,
4714                                    SourceLocation IdentLoc,
4715                                    IdentifierInfo *II,
4716                                    SourceLocation LBrace,
4717                                    AttributeList *AttrList) {
4718   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
4719   // For anonymous namespace, take the location of the left brace.
4720   SourceLocation Loc = II ? IdentLoc : LBrace;
4721   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
4722                                                  StartLoc, Loc, II);
4723   Namespc->setInline(InlineLoc.isValid());
4724
4725   Scope *DeclRegionScope = NamespcScope->getParent();
4726
4727   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
4728
4729   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
4730     PushNamespaceVisibilityAttr(Attr);
4731
4732   if (II) {
4733     // C++ [namespace.def]p2:
4734     //   The identifier in an original-namespace-definition shall not
4735     //   have been previously defined in the declarative region in
4736     //   which the original-namespace-definition appears. The
4737     //   identifier in an original-namespace-definition is the name of
4738     //   the namespace. Subsequently in that declarative region, it is
4739     //   treated as an original-namespace-name.
4740     //
4741     // Since namespace names are unique in their scope, and we don't
4742     // look through using directives, just look for any ordinary names.
4743     
4744     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 
4745       Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 
4746       Decl::IDNS_Namespace;
4747     NamedDecl *PrevDecl = 0;
4748     for (DeclContext::lookup_result R 
4749             = CurContext->getRedeclContext()->lookup(II);
4750          R.first != R.second; ++R.first) {
4751       if ((*R.first)->getIdentifierNamespace() & IDNS) {
4752         PrevDecl = *R.first;
4753         break;
4754       }
4755     }
4756     
4757     if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
4758       // This is an extended namespace definition.
4759       if (Namespc->isInline() != OrigNS->isInline()) {
4760         // inline-ness must match
4761         if (OrigNS->isInline()) {
4762           // The user probably just forgot the 'inline', so suggest that it
4763           // be added back.
4764           Diag(Namespc->getLocation(), 
4765                diag::warn_inline_namespace_reopened_noninline)
4766             << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
4767         } else {
4768           Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4769             << Namespc->isInline();
4770         }
4771         Diag(OrigNS->getLocation(), diag::note_previous_definition);
4772
4773         // Recover by ignoring the new namespace's inline status.
4774         Namespc->setInline(OrigNS->isInline());
4775       }
4776
4777       // Attach this namespace decl to the chain of extended namespace
4778       // definitions.
4779       OrigNS->setNextNamespace(Namespc);
4780       Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
4781
4782       // Remove the previous declaration from the scope.
4783       if (DeclRegionScope->isDeclScope(OrigNS)) {
4784         IdResolver.RemoveDecl(OrigNS);
4785         DeclRegionScope->RemoveDecl(OrigNS);
4786       }
4787     } else if (PrevDecl) {
4788       // This is an invalid name redefinition.
4789       Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
4790        << Namespc->getDeclName();
4791       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4792       Namespc->setInvalidDecl();
4793       // Continue on to push Namespc as current DeclContext and return it.
4794     } else if (II->isStr("std") && 
4795                CurContext->getRedeclContext()->isTranslationUnit()) {
4796       // This is the first "real" definition of the namespace "std", so update
4797       // our cache of the "std" namespace to point at this definition.
4798       if (NamespaceDecl *StdNS = getStdNamespace()) {
4799         // We had already defined a dummy namespace "std". Link this new 
4800         // namespace definition to the dummy namespace "std".
4801         StdNS->setNextNamespace(Namespc);
4802         StdNS->setLocation(IdentLoc);
4803         Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
4804       }
4805       
4806       // Make our StdNamespace cache point at the first real definition of the
4807       // "std" namespace.
4808       StdNamespace = Namespc;
4809     }
4810
4811     PushOnScopeChains(Namespc, DeclRegionScope);
4812   } else {
4813     // Anonymous namespaces.
4814     assert(Namespc->isAnonymousNamespace());
4815
4816     // Link the anonymous namespace into its parent.
4817     NamespaceDecl *PrevDecl;
4818     DeclContext *Parent = CurContext->getRedeclContext();
4819     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
4820       PrevDecl = TU->getAnonymousNamespace();
4821       TU->setAnonymousNamespace(Namespc);
4822     } else {
4823       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
4824       PrevDecl = ND->getAnonymousNamespace();
4825       ND->setAnonymousNamespace(Namespc);
4826     }
4827
4828     // Link the anonymous namespace with its previous declaration.
4829     if (PrevDecl) {
4830       assert(PrevDecl->isAnonymousNamespace());
4831       assert(!PrevDecl->getNextNamespace());
4832       Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4833       PrevDecl->setNextNamespace(Namespc);
4834
4835       if (Namespc->isInline() != PrevDecl->isInline()) {
4836         // inline-ness must match
4837         Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4838           << Namespc->isInline();
4839         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4840         Namespc->setInvalidDecl();
4841         // Recover by ignoring the new namespace's inline status.
4842         Namespc->setInline(PrevDecl->isInline());
4843       }
4844     }
4845
4846     CurContext->addDecl(Namespc);
4847
4848     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
4849     //   behaves as if it were replaced by
4850     //     namespace unique { /* empty body */ }
4851     //     using namespace unique;
4852     //     namespace unique { namespace-body }
4853     //   where all occurrences of 'unique' in a translation unit are
4854     //   replaced by the same identifier and this identifier differs
4855     //   from all other identifiers in the entire program.
4856
4857     // We just create the namespace with an empty name and then add an
4858     // implicit using declaration, just like the standard suggests.
4859     //
4860     // CodeGen enforces the "universally unique" aspect by giving all
4861     // declarations semantically contained within an anonymous
4862     // namespace internal linkage.
4863
4864     if (!PrevDecl) {
4865       UsingDirectiveDecl* UD
4866         = UsingDirectiveDecl::Create(Context, CurContext,
4867                                      /* 'using' */ LBrace,
4868                                      /* 'namespace' */ SourceLocation(),
4869                                      /* qualifier */ NestedNameSpecifierLoc(),
4870                                      /* identifier */ SourceLocation(),
4871                                      Namespc,
4872                                      /* Ancestor */ CurContext);
4873       UD->setImplicit();
4874       CurContext->addDecl(UD);
4875     }
4876   }
4877
4878   // Although we could have an invalid decl (i.e. the namespace name is a
4879   // redefinition), push it as current DeclContext and try to continue parsing.
4880   // FIXME: We should be able to push Namespc here, so that the each DeclContext
4881   // for the namespace has the declarations that showed up in that particular
4882   // namespace definition.
4883   PushDeclContext(NamespcScope, Namespc);
4884   return Namespc;
4885 }
4886
4887 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4888 /// is a namespace alias, returns the namespace it points to.
4889 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4890   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4891     return AD->getNamespace();
4892   return dyn_cast_or_null<NamespaceDecl>(D);
4893 }
4894
4895 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
4896 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
4897 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
4898   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4899   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
4900   Namespc->setRBraceLoc(RBrace);
4901   PopDeclContext();
4902   if (Namespc->hasAttr<VisibilityAttr>())
4903     PopPragmaVisibility();
4904 }
4905
4906 CXXRecordDecl *Sema::getStdBadAlloc() const {
4907   return cast_or_null<CXXRecordDecl>(
4908                                   StdBadAlloc.get(Context.getExternalSource()));
4909 }
4910
4911 NamespaceDecl *Sema::getStdNamespace() const {
4912   return cast_or_null<NamespaceDecl>(
4913                                  StdNamespace.get(Context.getExternalSource()));
4914 }
4915
4916 /// \brief Retrieve the special "std" namespace, which may require us to 
4917 /// implicitly define the namespace.
4918 NamespaceDecl *Sema::getOrCreateStdNamespace() {
4919   if (!StdNamespace) {
4920     // The "std" namespace has not yet been defined, so build one implicitly.
4921     StdNamespace = NamespaceDecl::Create(Context, 
4922                                          Context.getTranslationUnitDecl(),
4923                                          SourceLocation(), SourceLocation(),
4924                                          &PP.getIdentifierTable().get("std"));
4925     getStdNamespace()->setImplicit(true);
4926   }
4927   
4928   return getStdNamespace();
4929 }
4930
4931 /// \brief Determine whether a using statement is in a context where it will be
4932 /// apply in all contexts.
4933 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4934   switch (CurContext->getDeclKind()) {
4935     case Decl::TranslationUnit:
4936       return true;
4937     case Decl::LinkageSpec:
4938       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4939     default:
4940       return false;
4941   }
4942 }
4943
4944 Decl *Sema::ActOnUsingDirective(Scope *S,
4945                                           SourceLocation UsingLoc,
4946                                           SourceLocation NamespcLoc,
4947                                           CXXScopeSpec &SS,
4948                                           SourceLocation IdentLoc,
4949                                           IdentifierInfo *NamespcName,
4950                                           AttributeList *AttrList) {
4951   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4952   assert(NamespcName && "Invalid NamespcName.");
4953   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
4954
4955   // This can only happen along a recovery path.
4956   while (S->getFlags() & Scope::TemplateParamScope)
4957     S = S->getParent();
4958   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
4959
4960   UsingDirectiveDecl *UDir = 0;
4961   NestedNameSpecifier *Qualifier = 0;
4962   if (SS.isSet())
4963     Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4964   
4965   // Lookup namespace name.
4966   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4967   LookupParsedName(R, S, &SS);
4968   if (R.isAmbiguous())
4969     return 0;
4970
4971   if (R.empty()) {
4972     // Allow "using namespace std;" or "using namespace ::std;" even if 
4973     // "std" hasn't been defined yet, for GCC compatibility.
4974     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4975         NamespcName->isStr("std")) {
4976       Diag(IdentLoc, diag::ext_using_undefined_std);
4977       R.addDecl(getOrCreateStdNamespace());
4978       R.resolveKind();
4979     } 
4980     // Otherwise, attempt typo correction.
4981     else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false, 
4982                                                        CTC_NoKeywords, 0)) {
4983       if (R.getAsSingle<NamespaceDecl>() || 
4984           R.getAsSingle<NamespaceAliasDecl>()) {
4985         if (DeclContext *DC = computeDeclContext(SS, false))
4986           Diag(IdentLoc, diag::err_using_directive_member_suggest)
4987             << NamespcName << DC << Corrected << SS.getRange()
4988             << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());        
4989         else
4990           Diag(IdentLoc, diag::err_using_directive_suggest)
4991             << NamespcName << Corrected
4992             << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4993         Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4994           << Corrected;
4995         
4996         NamespcName = Corrected.getAsIdentifierInfo();
4997       } else {
4998         R.clear();
4999         R.setLookupName(NamespcName);
5000       }
5001     }
5002   }
5003   
5004   if (!R.empty()) {
5005     NamedDecl *Named = R.getFoundDecl();
5006     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5007         && "expected namespace decl");
5008     // C++ [namespace.udir]p1:
5009     //   A using-directive specifies that the names in the nominated
5010     //   namespace can be used in the scope in which the
5011     //   using-directive appears after the using-directive. During
5012     //   unqualified name lookup (3.4.1), the names appear as if they
5013     //   were declared in the nearest enclosing namespace which
5014     //   contains both the using-directive and the nominated
5015     //   namespace. [Note: in this context, "contains" means "contains
5016     //   directly or indirectly". ]
5017
5018     // Find enclosing context containing both using-directive and
5019     // nominated namespace.
5020     NamespaceDecl *NS = getNamespaceDecl(Named);
5021     DeclContext *CommonAncestor = cast<DeclContext>(NS);
5022     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5023       CommonAncestor = CommonAncestor->getParent();
5024
5025     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
5026                                       SS.getWithLocInContext(Context),
5027                                       IdentLoc, Named, CommonAncestor);
5028
5029     if (IsUsingDirectiveInToplevelContext(CurContext) &&
5030         !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
5031       Diag(IdentLoc, diag::warn_using_directive_in_header);
5032     }
5033
5034     PushUsingDirective(S, UDir);
5035   } else {
5036     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
5037   }
5038
5039   // FIXME: We ignore attributes for now.
5040   return UDir;
5041 }
5042
5043 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5044   // If scope has associated entity, then using directive is at namespace
5045   // or translation unit scope. We add UsingDirectiveDecls, into
5046   // it's lookup structure.
5047   if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
5048     Ctx->addDecl(UDir);
5049   else
5050     // Otherwise it is block-sope. using-directives will affect lookup
5051     // only to the end of scope.
5052     S->PushUsingDirective(UDir);
5053 }
5054
5055
5056 Decl *Sema::ActOnUsingDeclaration(Scope *S,
5057                                   AccessSpecifier AS,
5058                                   bool HasUsingKeyword,
5059                                   SourceLocation UsingLoc,
5060                                   CXXScopeSpec &SS,
5061                                   UnqualifiedId &Name,
5062                                   AttributeList *AttrList,
5063                                   bool IsTypeName,
5064                                   SourceLocation TypenameLoc) {
5065   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5066
5067   switch (Name.getKind()) {
5068   case UnqualifiedId::IK_Identifier:
5069   case UnqualifiedId::IK_OperatorFunctionId:
5070   case UnqualifiedId::IK_LiteralOperatorId:
5071   case UnqualifiedId::IK_ConversionFunctionId:
5072     break;
5073       
5074   case UnqualifiedId::IK_ConstructorName:
5075   case UnqualifiedId::IK_ConstructorTemplateId:
5076     // C++0x inherited constructors.
5077     if (getLangOptions().CPlusPlus0x) break;
5078
5079     Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5080       << SS.getRange();
5081     return 0;
5082       
5083   case UnqualifiedId::IK_DestructorName:
5084     Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5085       << SS.getRange();
5086     return 0;
5087       
5088   case UnqualifiedId::IK_TemplateId:
5089     Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5090       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
5091     return 0;
5092   }
5093
5094   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5095   DeclarationName TargetName = TargetNameInfo.getName();
5096   if (!TargetName)
5097     return 0;
5098
5099   // Warn about using declarations.
5100   // TODO: store that the declaration was written without 'using' and
5101   // talk about access decls instead of using decls in the
5102   // diagnostics.
5103   if (!HasUsingKeyword) {
5104     UsingLoc = Name.getSourceRange().getBegin();
5105     
5106     Diag(UsingLoc, diag::warn_access_decl_deprecated)
5107       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
5108   }
5109
5110   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5111       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5112     return 0;
5113
5114   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
5115                                         TargetNameInfo, AttrList,
5116                                         /* IsInstantiation */ false,
5117                                         IsTypeName, TypenameLoc);
5118   if (UD)
5119     PushOnScopeChains(UD, S, /*AddToContext*/ false);
5120
5121   return UD;
5122 }
5123
5124 /// \brief Determine whether a using declaration considers the given
5125 /// declarations as "equivalent", e.g., if they are redeclarations of
5126 /// the same entity or are both typedefs of the same type.
5127 static bool 
5128 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5129                          bool &SuppressRedeclaration) {
5130   if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5131     SuppressRedeclaration = false;
5132     return true;
5133   }
5134
5135   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5136     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
5137       SuppressRedeclaration = true;
5138       return Context.hasSameType(TD1->getUnderlyingType(),
5139                                  TD2->getUnderlyingType());
5140     }
5141
5142   return false;
5143 }
5144
5145
5146 /// Determines whether to create a using shadow decl for a particular
5147 /// decl, given the set of decls existing prior to this using lookup.
5148 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5149                                 const LookupResult &Previous) {
5150   // Diagnose finding a decl which is not from a base class of the
5151   // current class.  We do this now because there are cases where this
5152   // function will silently decide not to build a shadow decl, which
5153   // will pre-empt further diagnostics.
5154   //
5155   // We don't need to do this in C++0x because we do the check once on
5156   // the qualifier.
5157   //
5158   // FIXME: diagnose the following if we care enough:
5159   //   struct A { int foo; };
5160   //   struct B : A { using A::foo; };
5161   //   template <class T> struct C : A {};
5162   //   template <class T> struct D : C<T> { using B::foo; } // <---
5163   // This is invalid (during instantiation) in C++03 because B::foo
5164   // resolves to the using decl in B, which is not a base class of D<T>.
5165   // We can't diagnose it immediately because C<T> is an unknown
5166   // specialization.  The UsingShadowDecl in D<T> then points directly
5167   // to A::foo, which will look well-formed when we instantiate.
5168   // The right solution is to not collapse the shadow-decl chain.
5169   if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5170     DeclContext *OrigDC = Orig->getDeclContext();
5171
5172     // Handle enums and anonymous structs.
5173     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5174     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5175     while (OrigRec->isAnonymousStructOrUnion())
5176       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5177
5178     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5179       if (OrigDC == CurContext) {
5180         Diag(Using->getLocation(),
5181              diag::err_using_decl_nested_name_specifier_is_current_class)
5182           << Using->getQualifierLoc().getSourceRange();
5183         Diag(Orig->getLocation(), diag::note_using_decl_target);
5184         return true;
5185       }
5186
5187       Diag(Using->getQualifierLoc().getBeginLoc(),
5188            diag::err_using_decl_nested_name_specifier_is_not_base_class)
5189         << Using->getQualifier()
5190         << cast<CXXRecordDecl>(CurContext)
5191         << Using->getQualifierLoc().getSourceRange();
5192       Diag(Orig->getLocation(), diag::note_using_decl_target);
5193       return true;
5194     }
5195   }
5196
5197   if (Previous.empty()) return false;
5198
5199   NamedDecl *Target = Orig;
5200   if (isa<UsingShadowDecl>(Target))
5201     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5202
5203   // If the target happens to be one of the previous declarations, we
5204   // don't have a conflict.
5205   // 
5206   // FIXME: but we might be increasing its access, in which case we
5207   // should redeclare it.
5208   NamedDecl *NonTag = 0, *Tag = 0;
5209   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5210          I != E; ++I) {
5211     NamedDecl *D = (*I)->getUnderlyingDecl();
5212     bool Result;
5213     if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5214       return Result;
5215
5216     (isa<TagDecl>(D) ? Tag : NonTag) = D;
5217   }
5218
5219   if (Target->isFunctionOrFunctionTemplate()) {
5220     FunctionDecl *FD;
5221     if (isa<FunctionTemplateDecl>(Target))
5222       FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5223     else
5224       FD = cast<FunctionDecl>(Target);
5225
5226     NamedDecl *OldDecl = 0;
5227     switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
5228     case Ovl_Overload:
5229       return false;
5230
5231     case Ovl_NonFunction:
5232       Diag(Using->getLocation(), diag::err_using_decl_conflict);
5233       break;
5234       
5235     // We found a decl with the exact signature.
5236     case Ovl_Match:
5237       // If we're in a record, we want to hide the target, so we
5238       // return true (without a diagnostic) to tell the caller not to
5239       // build a shadow decl.
5240       if (CurContext->isRecord())
5241         return true;
5242
5243       // If we're not in a record, this is an error.
5244       Diag(Using->getLocation(), diag::err_using_decl_conflict);
5245       break;
5246     }
5247
5248     Diag(Target->getLocation(), diag::note_using_decl_target);
5249     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5250     return true;
5251   }
5252
5253   // Target is not a function.
5254
5255   if (isa<TagDecl>(Target)) {
5256     // No conflict between a tag and a non-tag.
5257     if (!Tag) return false;
5258
5259     Diag(Using->getLocation(), diag::err_using_decl_conflict);
5260     Diag(Target->getLocation(), diag::note_using_decl_target);
5261     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5262     return true;
5263   }
5264
5265   // No conflict between a tag and a non-tag.
5266   if (!NonTag) return false;
5267
5268   Diag(Using->getLocation(), diag::err_using_decl_conflict);
5269   Diag(Target->getLocation(), diag::note_using_decl_target);
5270   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5271   return true;
5272 }
5273
5274 /// Builds a shadow declaration corresponding to a 'using' declaration.
5275 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
5276                                             UsingDecl *UD,
5277                                             NamedDecl *Orig) {
5278
5279   // If we resolved to another shadow declaration, just coalesce them.
5280   NamedDecl *Target = Orig;
5281   if (isa<UsingShadowDecl>(Target)) {
5282     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5283     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
5284   }
5285   
5286   UsingShadowDecl *Shadow
5287     = UsingShadowDecl::Create(Context, CurContext,
5288                               UD->getLocation(), UD, Target);
5289   UD->addShadowDecl(Shadow);
5290   
5291   Shadow->setAccess(UD->getAccess());
5292   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5293     Shadow->setInvalidDecl();
5294   
5295   if (S)
5296     PushOnScopeChains(Shadow, S);
5297   else
5298     CurContext->addDecl(Shadow);
5299
5300
5301   return Shadow;
5302 }
5303
5304 /// Hides a using shadow declaration.  This is required by the current
5305 /// using-decl implementation when a resolvable using declaration in a
5306 /// class is followed by a declaration which would hide or override
5307 /// one or more of the using decl's targets; for example:
5308 ///
5309 ///   struct Base { void foo(int); };
5310 ///   struct Derived : Base {
5311 ///     using Base::foo;
5312 ///     void foo(int);
5313 ///   };
5314 ///
5315 /// The governing language is C++03 [namespace.udecl]p12:
5316 ///
5317 ///   When a using-declaration brings names from a base class into a
5318 ///   derived class scope, member functions in the derived class
5319 ///   override and/or hide member functions with the same name and
5320 ///   parameter types in a base class (rather than conflicting).
5321 ///
5322 /// There are two ways to implement this:
5323 ///   (1) optimistically create shadow decls when they're not hidden
5324 ///       by existing declarations, or
5325 ///   (2) don't create any shadow decls (or at least don't make them
5326 ///       visible) until we've fully parsed/instantiated the class.
5327 /// The problem with (1) is that we might have to retroactively remove
5328 /// a shadow decl, which requires several O(n) operations because the
5329 /// decl structures are (very reasonably) not designed for removal.
5330 /// (2) avoids this but is very fiddly and phase-dependent.
5331 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
5332   if (Shadow->getDeclName().getNameKind() ==
5333         DeclarationName::CXXConversionFunctionName)
5334     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5335
5336   // Remove it from the DeclContext...
5337   Shadow->getDeclContext()->removeDecl(Shadow);
5338
5339   // ...and the scope, if applicable...
5340   if (S) {
5341     S->RemoveDecl(Shadow);
5342     IdResolver.RemoveDecl(Shadow);
5343   }
5344
5345   // ...and the using decl.
5346   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5347
5348   // TODO: complain somehow if Shadow was used.  It shouldn't
5349   // be possible for this to happen, because...?
5350 }
5351
5352 /// Builds a using declaration.
5353 ///
5354 /// \param IsInstantiation - Whether this call arises from an
5355 ///   instantiation of an unresolved using declaration.  We treat
5356 ///   the lookup differently for these declarations.
5357 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5358                                        SourceLocation UsingLoc,
5359                                        CXXScopeSpec &SS,
5360                                        const DeclarationNameInfo &NameInfo,
5361                                        AttributeList *AttrList,
5362                                        bool IsInstantiation,
5363                                        bool IsTypeName,
5364                                        SourceLocation TypenameLoc) {
5365   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5366   SourceLocation IdentLoc = NameInfo.getLoc();
5367   assert(IdentLoc.isValid() && "Invalid TargetName location.");
5368
5369   // FIXME: We ignore attributes for now.
5370
5371   if (SS.isEmpty()) {
5372     Diag(IdentLoc, diag::err_using_requires_qualname);
5373     return 0;
5374   }
5375
5376   // Do the redeclaration lookup in the current scope.
5377   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
5378                         ForRedeclaration);
5379   Previous.setHideTags(false);
5380   if (S) {
5381     LookupName(Previous, S);
5382
5383     // It is really dumb that we have to do this.
5384     LookupResult::Filter F = Previous.makeFilter();
5385     while (F.hasNext()) {
5386       NamedDecl *D = F.next();
5387       if (!isDeclInScope(D, CurContext, S))
5388         F.erase();
5389     }
5390     F.done();
5391   } else {
5392     assert(IsInstantiation && "no scope in non-instantiation");
5393     assert(CurContext->isRecord() && "scope not record in instantiation");
5394     LookupQualifiedName(Previous, CurContext);
5395   }
5396
5397   // Check for invalid redeclarations.
5398   if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5399     return 0;
5400
5401   // Check for bad qualifiers.
5402   if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5403     return 0;
5404
5405   DeclContext *LookupContext = computeDeclContext(SS);
5406   NamedDecl *D;
5407   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
5408   if (!LookupContext) {
5409     if (IsTypeName) {
5410       // FIXME: not all declaration name kinds are legal here
5411       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5412                                               UsingLoc, TypenameLoc,
5413                                               QualifierLoc,
5414                                               IdentLoc, NameInfo.getName());
5415     } else {
5416       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 
5417                                            QualifierLoc, NameInfo);
5418     }
5419   } else {
5420     D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5421                           NameInfo, IsTypeName);
5422   }
5423   D->setAccess(AS);
5424   CurContext->addDecl(D);
5425
5426   if (!LookupContext) return D;
5427   UsingDecl *UD = cast<UsingDecl>(D);
5428
5429   if (RequireCompleteDeclContext(SS, LookupContext)) {
5430     UD->setInvalidDecl();
5431     return UD;
5432   }
5433
5434   // Constructor inheriting using decls get special treatment.
5435   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
5436     if (CheckInheritedConstructorUsingDecl(UD))
5437       UD->setInvalidDecl();
5438     return UD;
5439   }
5440
5441   // Otherwise, look up the target name.
5442
5443   LookupResult R(*this, NameInfo, LookupOrdinaryName);
5444   R.setUsingDeclaration(true);
5445
5446   // Unlike most lookups, we don't always want to hide tag
5447   // declarations: tag names are visible through the using declaration
5448   // even if hidden by ordinary names, *except* in a dependent context
5449   // where it's important for the sanity of two-phase lookup.
5450   if (!IsInstantiation)
5451     R.setHideTags(false);
5452
5453   LookupQualifiedName(R, LookupContext);
5454
5455   if (R.empty()) {
5456     Diag(IdentLoc, diag::err_no_member) 
5457       << NameInfo.getName() << LookupContext << SS.getRange();
5458     UD->setInvalidDecl();
5459     return UD;
5460   }
5461
5462   if (R.isAmbiguous()) {
5463     UD->setInvalidDecl();
5464     return UD;
5465   }
5466
5467   if (IsTypeName) {
5468     // If we asked for a typename and got a non-type decl, error out.
5469     if (!R.getAsSingle<TypeDecl>()) {
5470       Diag(IdentLoc, diag::err_using_typename_non_type);
5471       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5472         Diag((*I)->getUnderlyingDecl()->getLocation(),
5473              diag::note_using_decl_target);
5474       UD->setInvalidDecl();
5475       return UD;
5476     }
5477   } else {
5478     // If we asked for a non-typename and we got a type, error out,
5479     // but only if this is an instantiation of an unresolved using
5480     // decl.  Otherwise just silently find the type name.
5481     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
5482       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5483       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
5484       UD->setInvalidDecl();
5485       return UD;
5486     }
5487   }
5488
5489   // C++0x N2914 [namespace.udecl]p6:
5490   // A using-declaration shall not name a namespace.
5491   if (R.getAsSingle<NamespaceDecl>()) {
5492     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5493       << SS.getRange();
5494     UD->setInvalidDecl();
5495     return UD;
5496   }
5497
5498   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5499     if (!CheckUsingShadowDecl(UD, *I, Previous))
5500       BuildUsingShadowDecl(S, UD, *I);
5501   }
5502
5503   return UD;
5504 }
5505
5506 /// Additional checks for a using declaration referring to a constructor name.
5507 bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5508   if (UD->isTypeName()) {
5509     // FIXME: Cannot specify typename when specifying constructor
5510     return true;
5511   }
5512
5513   const Type *SourceType = UD->getQualifier()->getAsType();
5514   assert(SourceType &&
5515          "Using decl naming constructor doesn't have type in scope spec.");
5516   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5517
5518   // Check whether the named type is a direct base class.
5519   CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5520   CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5521   for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
5522        BaseIt != BaseE; ++BaseIt) {
5523     CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
5524     if (CanonicalSourceType == BaseType)
5525       break;
5526   }
5527
5528   if (BaseIt == BaseE) {
5529     // Did not find SourceType in the bases.
5530     Diag(UD->getUsingLocation(),
5531          diag::err_using_decl_constructor_not_in_direct_base)
5532       << UD->getNameInfo().getSourceRange()
5533       << QualType(SourceType, 0) << TargetClass;
5534     return true;
5535   }
5536
5537   BaseIt->setInheritConstructors();
5538
5539   return false;
5540 }
5541
5542 /// Checks that the given using declaration is not an invalid
5543 /// redeclaration.  Note that this is checking only for the using decl
5544 /// itself, not for any ill-formedness among the UsingShadowDecls.
5545 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5546                                        bool isTypeName,
5547                                        const CXXScopeSpec &SS,
5548                                        SourceLocation NameLoc,
5549                                        const LookupResult &Prev) {
5550   // C++03 [namespace.udecl]p8:
5551   // C++0x [namespace.udecl]p10:
5552   //   A using-declaration is a declaration and can therefore be used
5553   //   repeatedly where (and only where) multiple declarations are
5554   //   allowed.
5555   //
5556   // That's in non-member contexts.
5557   if (!CurContext->getRedeclContext()->isRecord())
5558     return false;
5559
5560   NestedNameSpecifier *Qual
5561     = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5562
5563   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
5564     NamedDecl *D = *I;
5565
5566     bool DTypename;
5567     NestedNameSpecifier *DQual;
5568     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
5569       DTypename = UD->isTypeName();
5570       DQual = UD->getQualifier();
5571     } else if (UnresolvedUsingValueDecl *UD
5572                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
5573       DTypename = false;
5574       DQual = UD->getQualifier();
5575     } else if (UnresolvedUsingTypenameDecl *UD
5576                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
5577       DTypename = true;
5578       DQual = UD->getQualifier();
5579     } else continue;
5580
5581     // using decls differ if one says 'typename' and the other doesn't.
5582     // FIXME: non-dependent using decls?
5583     if (isTypeName != DTypename) continue;
5584
5585     // using decls differ if they name different scopes (but note that
5586     // template instantiation can cause this check to trigger when it
5587     // didn't before instantiation).
5588     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
5589         Context.getCanonicalNestedNameSpecifier(DQual))
5590       continue;
5591
5592     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
5593     Diag(D->getLocation(), diag::note_using_decl) << 1;
5594     return true;
5595   }
5596
5597   return false;
5598 }
5599
5600
5601 /// Checks that the given nested-name qualifier used in a using decl
5602 /// in the current context is appropriately related to the current
5603 /// scope.  If an error is found, diagnoses it and returns true.
5604 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
5605                                    const CXXScopeSpec &SS,
5606                                    SourceLocation NameLoc) {
5607   DeclContext *NamedContext = computeDeclContext(SS);
5608
5609   if (!CurContext->isRecord()) {
5610     // C++03 [namespace.udecl]p3:
5611     // C++0x [namespace.udecl]p8:
5612     //   A using-declaration for a class member shall be a member-declaration.
5613
5614     // If we weren't able to compute a valid scope, it must be a
5615     // dependent class scope.
5616     if (!NamedContext || NamedContext->isRecord()) {
5617       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
5618         << SS.getRange();
5619       return true;
5620     }
5621
5622     // Otherwise, everything is known to be fine.
5623     return false;
5624   }
5625
5626   // The current scope is a record.
5627
5628   // If the named context is dependent, we can't decide much.
5629   if (!NamedContext) {
5630     // FIXME: in C++0x, we can diagnose if we can prove that the
5631     // nested-name-specifier does not refer to a base class, which is
5632     // still possible in some cases.
5633
5634     // Otherwise we have to conservatively report that things might be
5635     // okay.
5636     return false;
5637   }
5638
5639   if (!NamedContext->isRecord()) {
5640     // Ideally this would point at the last name in the specifier,
5641     // but we don't have that level of source info.
5642     Diag(SS.getRange().getBegin(),
5643          diag::err_using_decl_nested_name_specifier_is_not_class)
5644       << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
5645     return true;
5646   }
5647
5648   if (!NamedContext->isDependentContext() &&
5649       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
5650     return true;
5651
5652   if (getLangOptions().CPlusPlus0x) {
5653     // C++0x [namespace.udecl]p3:
5654     //   In a using-declaration used as a member-declaration, the
5655     //   nested-name-specifier shall name a base class of the class
5656     //   being defined.
5657
5658     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
5659                                  cast<CXXRecordDecl>(NamedContext))) {
5660       if (CurContext == NamedContext) {
5661         Diag(NameLoc,
5662              diag::err_using_decl_nested_name_specifier_is_current_class)
5663           << SS.getRange();
5664         return true;
5665       }
5666
5667       Diag(SS.getRange().getBegin(),
5668            diag::err_using_decl_nested_name_specifier_is_not_base_class)
5669         << (NestedNameSpecifier*) SS.getScopeRep()
5670         << cast<CXXRecordDecl>(CurContext)
5671         << SS.getRange();
5672       return true;
5673     }
5674
5675     return false;
5676   }
5677
5678   // C++03 [namespace.udecl]p4:
5679   //   A using-declaration used as a member-declaration shall refer
5680   //   to a member of a base class of the class being defined [etc.].
5681
5682   // Salient point: SS doesn't have to name a base class as long as
5683   // lookup only finds members from base classes.  Therefore we can
5684   // diagnose here only if we can prove that that can't happen,
5685   // i.e. if the class hierarchies provably don't intersect.
5686
5687   // TODO: it would be nice if "definitely valid" results were cached
5688   // in the UsingDecl and UsingShadowDecl so that these checks didn't
5689   // need to be repeated.
5690
5691   struct UserData {
5692     llvm::DenseSet<const CXXRecordDecl*> Bases;
5693
5694     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
5695       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5696       Data->Bases.insert(Base);
5697       return true;
5698     }
5699
5700     bool hasDependentBases(const CXXRecordDecl *Class) {
5701       return !Class->forallBases(collect, this);
5702     }
5703
5704     /// Returns true if the base is dependent or is one of the
5705     /// accumulated base classes.
5706     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
5707       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5708       return !Data->Bases.count(Base);
5709     }
5710
5711     bool mightShareBases(const CXXRecordDecl *Class) {
5712       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
5713     }
5714   };
5715
5716   UserData Data;
5717
5718   // Returns false if we find a dependent base.
5719   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
5720     return false;
5721
5722   // Returns false if the class has a dependent base or if it or one
5723   // of its bases is present in the base set of the current context.
5724   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
5725     return false;
5726
5727   Diag(SS.getRange().getBegin(),
5728        diag::err_using_decl_nested_name_specifier_is_not_base_class)
5729     << (NestedNameSpecifier*) SS.getScopeRep()
5730     << cast<CXXRecordDecl>(CurContext)
5731     << SS.getRange();
5732
5733   return true;
5734 }
5735
5736 Decl *Sema::ActOnAliasDeclaration(Scope *S,
5737                                   AccessSpecifier AS,
5738                                   MultiTemplateParamsArg TemplateParamLists,
5739                                   SourceLocation UsingLoc,
5740                                   UnqualifiedId &Name,
5741                                   TypeResult Type) {
5742   // Skip up to the relevant declaration scope.
5743   while (S->getFlags() & Scope::TemplateParamScope)
5744     S = S->getParent();
5745   assert((S->getFlags() & Scope::DeclScope) &&
5746          "got alias-declaration outside of declaration scope");
5747
5748   if (Type.isInvalid())
5749     return 0;
5750
5751   bool Invalid = false;
5752   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
5753   TypeSourceInfo *TInfo = 0;
5754   GetTypeFromParser(Type.get(), &TInfo);
5755
5756   if (DiagnoseClassNameShadow(CurContext, NameInfo))
5757     return 0;
5758
5759   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
5760                                       UPPC_DeclarationType)) {
5761     Invalid = true;
5762     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 
5763                                              TInfo->getTypeLoc().getBeginLoc());
5764   }
5765
5766   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
5767   LookupName(Previous, S);
5768
5769   // Warn about shadowing the name of a template parameter.
5770   if (Previous.isSingleResult() &&
5771       Previous.getFoundDecl()->isTemplateParameter()) {
5772     if (DiagnoseTemplateParameterShadow(Name.StartLocation,
5773                                         Previous.getFoundDecl()))
5774       Invalid = true;
5775     Previous.clear();
5776   }
5777
5778   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
5779          "name in alias declaration must be an identifier");
5780   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
5781                                                Name.StartLocation,
5782                                                Name.Identifier, TInfo);
5783
5784   NewTD->setAccess(AS);
5785
5786   if (Invalid)
5787     NewTD->setInvalidDecl();
5788
5789   CheckTypedefForVariablyModifiedType(S, NewTD);
5790   Invalid |= NewTD->isInvalidDecl();
5791
5792   bool Redeclaration = false;
5793
5794   NamedDecl *NewND;
5795   if (TemplateParamLists.size()) {
5796     TypeAliasTemplateDecl *OldDecl = 0;
5797     TemplateParameterList *OldTemplateParams = 0;
5798
5799     if (TemplateParamLists.size() != 1) {
5800       Diag(UsingLoc, diag::err_alias_template_extra_headers)
5801         << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
5802          TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
5803     }
5804     TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
5805
5806     // Only consider previous declarations in the same scope.
5807     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
5808                          /*ExplicitInstantiationOrSpecialization*/false);
5809     if (!Previous.empty()) {
5810       Redeclaration = true;
5811
5812       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
5813       if (!OldDecl && !Invalid) {
5814         Diag(UsingLoc, diag::err_redefinition_different_kind)
5815           << Name.Identifier;
5816
5817         NamedDecl *OldD = Previous.getRepresentativeDecl();
5818         if (OldD->getLocation().isValid())
5819           Diag(OldD->getLocation(), diag::note_previous_definition);
5820
5821         Invalid = true;
5822       }
5823
5824       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
5825         if (TemplateParameterListsAreEqual(TemplateParams,
5826                                            OldDecl->getTemplateParameters(),
5827                                            /*Complain=*/true,
5828                                            TPL_TemplateMatch))
5829           OldTemplateParams = OldDecl->getTemplateParameters();
5830         else
5831           Invalid = true;
5832
5833         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5834         if (!Invalid &&
5835             !Context.hasSameType(OldTD->getUnderlyingType(),
5836                                  NewTD->getUnderlyingType())) {
5837           // FIXME: The C++0x standard does not clearly say this is ill-formed,
5838           // but we can't reasonably accept it.
5839           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5840             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5841           if (OldTD->getLocation().isValid())
5842             Diag(OldTD->getLocation(), diag::note_previous_definition);
5843           Invalid = true;
5844         }
5845       }
5846     }
5847
5848     // Merge any previous default template arguments into our parameters,
5849     // and check the parameter list.
5850     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5851                                    TPC_TypeAliasTemplate))
5852       return 0;
5853
5854     TypeAliasTemplateDecl *NewDecl =
5855       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5856                                     Name.Identifier, TemplateParams,
5857                                     NewTD);
5858
5859     NewDecl->setAccess(AS);
5860
5861     if (Invalid)
5862       NewDecl->setInvalidDecl();
5863     else if (OldDecl)
5864       NewDecl->setPreviousDeclaration(OldDecl);
5865
5866     NewND = NewDecl;
5867   } else {
5868     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5869     NewND = NewTD;
5870   }
5871
5872   if (!Redeclaration)
5873     PushOnScopeChains(NewND, S);
5874
5875   return NewND;
5876 }
5877
5878 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
5879                                              SourceLocation NamespaceLoc,
5880                                              SourceLocation AliasLoc,
5881                                              IdentifierInfo *Alias,
5882                                              CXXScopeSpec &SS,
5883                                              SourceLocation IdentLoc,
5884                                              IdentifierInfo *Ident) {
5885
5886   // Lookup the namespace name.
5887   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5888   LookupParsedName(R, S, &SS);
5889
5890   // Check if we have a previous declaration with the same name.
5891   NamedDecl *PrevDecl
5892     = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 
5893                        ForRedeclaration);
5894   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5895     PrevDecl = 0;
5896
5897   if (PrevDecl) {
5898     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
5899       // We already have an alias with the same name that points to the same
5900       // namespace, so don't create a new one.
5901       // FIXME: At some point, we'll want to create the (redundant)
5902       // declaration to maintain better source information.
5903       if (!R.isAmbiguous() && !R.empty() &&
5904           AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
5905         return 0;
5906     }
5907
5908     unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5909       diag::err_redefinition_different_kind;
5910     Diag(AliasLoc, DiagID) << Alias;
5911     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5912     return 0;
5913   }
5914
5915   if (R.isAmbiguous())
5916     return 0;
5917
5918   if (R.empty()) {
5919     if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false, 
5920                                                 CTC_NoKeywords, 0)) {
5921       if (R.getAsSingle<NamespaceDecl>() || 
5922           R.getAsSingle<NamespaceAliasDecl>()) {
5923         if (DeclContext *DC = computeDeclContext(SS, false))
5924           Diag(IdentLoc, diag::err_using_directive_member_suggest)
5925             << Ident << DC << Corrected << SS.getRange()
5926             << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());        
5927         else
5928           Diag(IdentLoc, diag::err_using_directive_suggest)
5929             << Ident << Corrected
5930             << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5931         
5932         Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
5933           << Corrected;
5934         
5935         Ident = Corrected.getAsIdentifierInfo();
5936       } else {
5937         R.clear();
5938         R.setLookupName(Ident);
5939       }
5940     }
5941     
5942     if (R.empty()) {
5943       Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
5944       return 0;
5945     }
5946   }
5947
5948   NamespaceAliasDecl *AliasDecl =
5949     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
5950                                Alias, SS.getWithLocInContext(Context),
5951                                IdentLoc, R.getFoundDecl());
5952
5953   PushOnScopeChains(AliasDecl, S);
5954   return AliasDecl;
5955 }
5956
5957 namespace {
5958   /// \brief Scoped object used to handle the state changes required in Sema
5959   /// to implicitly define the body of a C++ member function;
5960   class ImplicitlyDefinedFunctionScope {
5961     Sema &S;
5962     Sema::ContextRAII SavedContext;
5963     
5964   public:
5965     ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
5966       : S(S), SavedContext(S, Method) 
5967     {
5968       S.PushFunctionScope();
5969       S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5970     }
5971     
5972     ~ImplicitlyDefinedFunctionScope() {
5973       S.PopExpressionEvaluationContext();
5974       S.PopFunctionOrBlockScope();
5975     }
5976   };
5977 }
5978
5979 Sema::ImplicitExceptionSpecification
5980 Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
5981   // C++ [except.spec]p14:
5982   //   An implicitly declared special member function (Clause 12) shall have an 
5983   //   exception-specification. [...]
5984   ImplicitExceptionSpecification ExceptSpec(Context);
5985
5986   // Direct base-class constructors.
5987   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5988                                        BEnd = ClassDecl->bases_end();
5989        B != BEnd; ++B) {
5990     if (B->isVirtual()) // Handled below.
5991       continue;
5992     
5993     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5994       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5995       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5996       // If this is a deleted function, add it anyway. This might be conformant
5997       // with the standard. This might not. I'm not sure. It might not matter.
5998       if (Constructor)
5999         ExceptSpec.CalledDecl(Constructor);
6000     }
6001   }
6002
6003   // Virtual base-class constructors.
6004   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6005                                        BEnd = ClassDecl->vbases_end();
6006        B != BEnd; ++B) {
6007     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6008       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6009       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6010       // If this is a deleted function, add it anyway. This might be conformant
6011       // with the standard. This might not. I'm not sure. It might not matter.
6012       if (Constructor)
6013         ExceptSpec.CalledDecl(Constructor);
6014     }
6015   }
6016
6017   // Field constructors.
6018   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6019                                FEnd = ClassDecl->field_end();
6020        F != FEnd; ++F) {
6021     if (F->hasInClassInitializer()) {
6022       if (Expr *E = F->getInClassInitializer())
6023         ExceptSpec.CalledExpr(E);
6024       else if (!F->isInvalidDecl())
6025         ExceptSpec.SetDelayed();
6026     } else if (const RecordType *RecordTy
6027               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
6028       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6029       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6030       // If this is a deleted function, add it anyway. This might be conformant
6031       // with the standard. This might not. I'm not sure. It might not matter.
6032       // In particular, the problem is that this function never gets called. It
6033       // might just be ill-formed because this function attempts to refer to
6034       // a deleted function here.
6035       if (Constructor)
6036         ExceptSpec.CalledDecl(Constructor);
6037     }
6038   }
6039
6040   return ExceptSpec;
6041 }
6042
6043 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6044                                                      CXXRecordDecl *ClassDecl) {
6045   // C++ [class.ctor]p5:
6046   //   A default constructor for a class X is a constructor of class X
6047   //   that can be called without an argument. If there is no
6048   //   user-declared constructor for class X, a default constructor is
6049   //   implicitly declared. An implicitly-declared default constructor
6050   //   is an inline public member of its class.
6051   assert(!ClassDecl->hasUserDeclaredConstructor() && 
6052          "Should not build implicit default constructor!");
6053
6054   ImplicitExceptionSpecification Spec = 
6055     ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6056   FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6057
6058   // Create the actual constructor declaration.
6059   CanQualType ClassType
6060     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6061   SourceLocation ClassLoc = ClassDecl->getLocation();
6062   DeclarationName Name
6063     = Context.DeclarationNames.getCXXConstructorName(ClassType);
6064   DeclarationNameInfo NameInfo(Name, ClassLoc);
6065   CXXConstructorDecl *DefaultCon
6066     = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
6067                                  Context.getFunctionType(Context.VoidTy,
6068                                                          0, 0, EPI),
6069                                  /*TInfo=*/0,
6070                                  /*isExplicit=*/false,
6071                                  /*isInline=*/true,
6072                                  /*isImplicitlyDeclared=*/true);
6073   DefaultCon->setAccess(AS_public);
6074   DefaultCon->setDefaulted();
6075   DefaultCon->setImplicit();
6076   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
6077   
6078   // Note that we have declared this constructor.
6079   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6080   
6081   if (Scope *S = getScopeForContext(ClassDecl))
6082     PushOnScopeChains(DefaultCon, S, false);
6083   ClassDecl->addDecl(DefaultCon);
6084
6085   if (ShouldDeleteDefaultConstructor(DefaultCon))
6086     DefaultCon->setDeletedAsWritten();
6087   
6088   return DefaultCon;
6089 }
6090
6091 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6092                                             CXXConstructorDecl *Constructor) {
6093   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6094           !Constructor->doesThisDeclarationHaveABody() &&
6095           !Constructor->isDeleted()) &&
6096     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
6097
6098   CXXRecordDecl *ClassDecl = Constructor->getParent();
6099   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
6100
6101   ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
6102   DiagnosticErrorTrap Trap(Diags);
6103   if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
6104       Trap.hasErrorOccurred()) {
6105     Diag(CurrentLocation, diag::note_member_synthesized_at) 
6106       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
6107     Constructor->setInvalidDecl();
6108     return;
6109   }
6110
6111   SourceLocation Loc = Constructor->getLocation();
6112   Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6113
6114   Constructor->setUsed();
6115   MarkVTableUsed(CurrentLocation, ClassDecl);
6116
6117   if (ASTMutationListener *L = getASTMutationListener()) {
6118     L->CompletedImplicitDefinition(Constructor);
6119   }
6120 }
6121
6122 /// Get any existing defaulted default constructor for the given class. Do not
6123 /// implicitly define one if it does not exist.
6124 static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6125                                                              CXXRecordDecl *D) {
6126   ASTContext &Context = Self.Context;
6127   QualType ClassType = Context.getTypeDeclType(D);
6128   DeclarationName ConstructorName
6129     = Context.DeclarationNames.getCXXConstructorName(
6130                       Context.getCanonicalType(ClassType.getUnqualifiedType()));
6131
6132   DeclContext::lookup_const_iterator Con, ConEnd;
6133   for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6134        Con != ConEnd; ++Con) {
6135     // A function template cannot be defaulted.
6136     if (isa<FunctionTemplateDecl>(*Con))
6137       continue;
6138
6139     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6140     if (Constructor->isDefaultConstructor())
6141       return Constructor->isDefaulted() ? Constructor : 0;
6142   }
6143   return 0;
6144 }
6145
6146 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6147   if (!D) return;
6148   AdjustDeclIfTemplate(D);
6149
6150   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6151   CXXConstructorDecl *CtorDecl
6152     = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6153
6154   if (!CtorDecl) return;
6155
6156   // Compute the exception specification for the default constructor.
6157   const FunctionProtoType *CtorTy =
6158     CtorDecl->getType()->castAs<FunctionProtoType>();
6159   if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6160     ImplicitExceptionSpecification Spec = 
6161       ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6162     FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6163     assert(EPI.ExceptionSpecType != EST_Delayed);
6164
6165     CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6166   }
6167
6168   // If the default constructor is explicitly defaulted, checking the exception
6169   // specification is deferred until now.
6170   if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6171       !ClassDecl->isDependentType())
6172     CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6173 }
6174
6175 void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6176   // We start with an initial pass over the base classes to collect those that
6177   // inherit constructors from. If there are none, we can forgo all further
6178   // processing.
6179   typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
6180   BasesVector BasesToInheritFrom;
6181   for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6182                                           BaseE = ClassDecl->bases_end();
6183          BaseIt != BaseE; ++BaseIt) {
6184     if (BaseIt->getInheritConstructors()) {
6185       QualType Base = BaseIt->getType();
6186       if (Base->isDependentType()) {
6187         // If we inherit constructors from anything that is dependent, just
6188         // abort processing altogether. We'll get another chance for the
6189         // instantiations.
6190         return;
6191       }
6192       BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6193     }
6194   }
6195   if (BasesToInheritFrom.empty())
6196     return;
6197
6198   // Now collect the constructors that we already have in the current class.
6199   // Those take precedence over inherited constructors.
6200   // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6201   //   unless there is a user-declared constructor with the same signature in
6202   //   the class where the using-declaration appears.
6203   llvm::SmallSet<const Type *, 8> ExistingConstructors;
6204   for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6205                                     CtorE = ClassDecl->ctor_end();
6206        CtorIt != CtorE; ++CtorIt) {
6207     ExistingConstructors.insert(
6208         Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6209   }
6210
6211   Scope *S = getScopeForContext(ClassDecl);
6212   DeclarationName CreatedCtorName =
6213       Context.DeclarationNames.getCXXConstructorName(
6214           ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6215
6216   // Now comes the true work.
6217   // First, we keep a map from constructor types to the base that introduced
6218   // them. Needed for finding conflicting constructors. We also keep the
6219   // actually inserted declarations in there, for pretty diagnostics.
6220   typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6221   typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6222   ConstructorToSourceMap InheritedConstructors;
6223   for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6224                              BaseE = BasesToInheritFrom.end();
6225        BaseIt != BaseE; ++BaseIt) {
6226     const RecordType *Base = *BaseIt;
6227     CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6228     CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6229     for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6230                                       CtorE = BaseDecl->ctor_end();
6231          CtorIt != CtorE; ++CtorIt) {
6232       // Find the using declaration for inheriting this base's constructors.
6233       DeclarationName Name =
6234           Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6235       UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6236           LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6237       SourceLocation UsingLoc = UD ? UD->getLocation() :
6238                                      ClassDecl->getLocation();
6239
6240       // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6241       //   from the class X named in the using-declaration consists of actual
6242       //   constructors and notional constructors that result from the
6243       //   transformation of defaulted parameters as follows:
6244       //   - all non-template default constructors of X, and
6245       //   - for each non-template constructor of X that has at least one
6246       //     parameter with a default argument, the set of constructors that
6247       //     results from omitting any ellipsis parameter specification and
6248       //     successively omitting parameters with a default argument from the
6249       //     end of the parameter-type-list.
6250       CXXConstructorDecl *BaseCtor = *CtorIt;
6251       bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6252       const FunctionProtoType *BaseCtorType =
6253           BaseCtor->getType()->getAs<FunctionProtoType>();
6254
6255       for (unsigned params = BaseCtor->getMinRequiredArguments(),
6256                     maxParams = BaseCtor->getNumParams();
6257            params <= maxParams; ++params) {
6258         // Skip default constructors. They're never inherited.
6259         if (params == 0)
6260           continue;
6261         // Skip copy and move constructors for the same reason.
6262         if (CanBeCopyOrMove && params == 1)
6263           continue;
6264
6265         // Build up a function type for this particular constructor.
6266         // FIXME: The working paper does not consider that the exception spec
6267         // for the inheriting constructor might be larger than that of the
6268         // source. This code doesn't yet, either. When it does, this code will
6269         // need to be delayed until after exception specifications and in-class
6270         // member initializers are attached.
6271         const Type *NewCtorType;
6272         if (params == maxParams)
6273           NewCtorType = BaseCtorType;
6274         else {
6275           llvm::SmallVector<QualType, 16> Args;
6276           for (unsigned i = 0; i < params; ++i) {
6277             Args.push_back(BaseCtorType->getArgType(i));
6278           }
6279           FunctionProtoType::ExtProtoInfo ExtInfo =
6280               BaseCtorType->getExtProtoInfo();
6281           ExtInfo.Variadic = false;
6282           NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6283                                                 Args.data(), params, ExtInfo)
6284                        .getTypePtr();
6285         }
6286         const Type *CanonicalNewCtorType =
6287             Context.getCanonicalType(NewCtorType);
6288
6289         // Now that we have the type, first check if the class already has a
6290         // constructor with this signature.
6291         if (ExistingConstructors.count(CanonicalNewCtorType))
6292           continue;
6293
6294         // Then we check if we have already declared an inherited constructor
6295         // with this signature.
6296         std::pair<ConstructorToSourceMap::iterator, bool> result =
6297             InheritedConstructors.insert(std::make_pair(
6298                 CanonicalNewCtorType,
6299                 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6300         if (!result.second) {
6301           // Already in the map. If it came from a different class, that's an
6302           // error. Not if it's from the same.
6303           CanQualType PreviousBase = result.first->second.first;
6304           if (CanonicalBase != PreviousBase) {
6305             const CXXConstructorDecl *PrevCtor = result.first->second.second;
6306             const CXXConstructorDecl *PrevBaseCtor =
6307                 PrevCtor->getInheritedConstructor();
6308             assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6309
6310             Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6311             Diag(BaseCtor->getLocation(),
6312                  diag::note_using_decl_constructor_conflict_current_ctor);
6313             Diag(PrevBaseCtor->getLocation(),
6314                  diag::note_using_decl_constructor_conflict_previous_ctor);
6315             Diag(PrevCtor->getLocation(),
6316                  diag::note_using_decl_constructor_conflict_previous_using);
6317           }
6318           continue;
6319         }
6320
6321         // OK, we're there, now add the constructor.
6322         // C++0x [class.inhctor]p8: [...] that would be performed by a
6323         //   user-writtern inline constructor [...]
6324         DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6325         CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
6326             Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6327             /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
6328             /*ImplicitlyDeclared=*/true);
6329         NewCtor->setAccess(BaseCtor->getAccess());
6330
6331         // Build up the parameter decls and add them.
6332         llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
6333         for (unsigned i = 0; i < params; ++i) {
6334           ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6335                                                    UsingLoc, UsingLoc,
6336                                                    /*IdentifierInfo=*/0,
6337                                                    BaseCtorType->getArgType(i),
6338                                                    /*TInfo=*/0, SC_None,
6339                                                    SC_None, /*DefaultArg=*/0));
6340         }
6341         NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6342         NewCtor->setInheritedConstructor(BaseCtor);
6343
6344         PushOnScopeChains(NewCtor, S, false);
6345         ClassDecl->addDecl(NewCtor);
6346         result.first->second.second = NewCtor;
6347       }
6348     }
6349   }
6350 }
6351
6352 Sema::ImplicitExceptionSpecification
6353 Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
6354   // C++ [except.spec]p14: 
6355   //   An implicitly declared special member function (Clause 12) shall have 
6356   //   an exception-specification.
6357   ImplicitExceptionSpecification ExceptSpec(Context);
6358   
6359   // Direct base-class destructors.
6360   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6361                                        BEnd = ClassDecl->bases_end();
6362        B != BEnd; ++B) {
6363     if (B->isVirtual()) // Handled below.
6364       continue;
6365     
6366     if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6367       ExceptSpec.CalledDecl(
6368                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
6369   }
6370
6371   // Virtual base-class destructors.
6372   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6373                                        BEnd = ClassDecl->vbases_end();
6374        B != BEnd; ++B) {
6375     if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6376       ExceptSpec.CalledDecl(
6377                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
6378   }
6379
6380   // Field destructors.
6381   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6382                                FEnd = ClassDecl->field_end();
6383        F != FEnd; ++F) {
6384     if (const RecordType *RecordTy
6385         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6386       ExceptSpec.CalledDecl(
6387                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
6388   }
6389
6390   return ExceptSpec;
6391 }
6392
6393 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6394   // C++ [class.dtor]p2:
6395   //   If a class has no user-declared destructor, a destructor is
6396   //   declared implicitly. An implicitly-declared destructor is an
6397   //   inline public member of its class.
6398   
6399   ImplicitExceptionSpecification Spec =
6400       ComputeDefaultedDtorExceptionSpec(ClassDecl); 
6401   FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6402
6403   // Create the actual destructor declaration.
6404   QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
6405
6406   CanQualType ClassType
6407     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6408   SourceLocation ClassLoc = ClassDecl->getLocation();
6409   DeclarationName Name
6410     = Context.DeclarationNames.getCXXDestructorName(ClassType);
6411   DeclarationNameInfo NameInfo(Name, ClassLoc);
6412   CXXDestructorDecl *Destructor
6413       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6414                                   /*isInline=*/true,
6415                                   /*isImplicitlyDeclared=*/true);
6416   Destructor->setAccess(AS_public);
6417   Destructor->setDefaulted();
6418   Destructor->setImplicit();
6419   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
6420   
6421   // Note that we have declared this destructor.
6422   ++ASTContext::NumImplicitDestructorsDeclared;
6423   
6424   // Introduce this destructor into its scope.
6425   if (Scope *S = getScopeForContext(ClassDecl))
6426     PushOnScopeChains(Destructor, S, false);
6427   ClassDecl->addDecl(Destructor);
6428   
6429   // This could be uniqued if it ever proves significant.
6430   Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
6431
6432   if (ShouldDeleteDestructor(Destructor))
6433     Destructor->setDeletedAsWritten();
6434   
6435   AddOverriddenMethods(ClassDecl, Destructor);
6436   
6437   return Destructor;
6438 }
6439
6440 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
6441                                     CXXDestructorDecl *Destructor) {
6442   assert((Destructor->isDefaulted() &&
6443           !Destructor->doesThisDeclarationHaveABody()) &&
6444          "DefineImplicitDestructor - call it for implicit default dtor");
6445   CXXRecordDecl *ClassDecl = Destructor->getParent();
6446   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
6447
6448   if (Destructor->isInvalidDecl())
6449     return;
6450
6451   ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
6452
6453   DiagnosticErrorTrap Trap(Diags);
6454   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6455                                          Destructor->getParent());
6456
6457   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
6458     Diag(CurrentLocation, diag::note_member_synthesized_at) 
6459       << CXXDestructor << Context.getTagDeclType(ClassDecl);
6460
6461     Destructor->setInvalidDecl();
6462     return;
6463   }
6464
6465   SourceLocation Loc = Destructor->getLocation();
6466   Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6467
6468   Destructor->setUsed();
6469   MarkVTableUsed(CurrentLocation, ClassDecl);
6470
6471   if (ASTMutationListener *L = getASTMutationListener()) {
6472     L->CompletedImplicitDefinition(Destructor);
6473   }
6474 }
6475
6476 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6477                                          CXXDestructorDecl *destructor) {
6478   // C++11 [class.dtor]p3:
6479   //   A declaration of a destructor that does not have an exception-
6480   //   specification is implicitly considered to have the same exception-
6481   //   specification as an implicit declaration.
6482   const FunctionProtoType *dtorType = destructor->getType()->
6483                                         getAs<FunctionProtoType>();
6484   if (dtorType->hasExceptionSpec())
6485     return;
6486
6487   ImplicitExceptionSpecification exceptSpec =
6488       ComputeDefaultedDtorExceptionSpec(classDecl);
6489
6490   // Replace the destructor's type.
6491   FunctionProtoType::ExtProtoInfo epi;
6492   epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6493   epi.NumExceptions = exceptSpec.size();
6494   epi.Exceptions = exceptSpec.data();
6495   QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6496
6497   destructor->setType(ty);
6498
6499   // FIXME: If the destructor has a body that could throw, and the newly created
6500   // spec doesn't allow exceptions, we should emit a warning, because this
6501   // change in behavior can break conforming C++03 programs at runtime.
6502   // However, we don't have a body yet, so it needs to be done somewhere else.
6503 }
6504
6505 /// \brief Builds a statement that copies the given entity from \p From to
6506 /// \c To.
6507 ///
6508 /// This routine is used to copy the members of a class with an
6509 /// implicitly-declared copy assignment operator. When the entities being
6510 /// copied are arrays, this routine builds for loops to copy them.
6511 ///
6512 /// \param S The Sema object used for type-checking.
6513 ///
6514 /// \param Loc The location where the implicit copy is being generated.
6515 ///
6516 /// \param T The type of the expressions being copied. Both expressions must
6517 /// have this type.
6518 ///
6519 /// \param To The expression we are copying to.
6520 ///
6521 /// \param From The expression we are copying from.
6522 ///
6523 /// \param CopyingBaseSubobject Whether we're copying a base subobject.
6524 /// Otherwise, it's a non-static member subobject.
6525 ///
6526 /// \param Depth Internal parameter recording the depth of the recursion.
6527 ///
6528 /// \returns A statement or a loop that copies the expressions.
6529 static StmtResult
6530 BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 
6531                       Expr *To, Expr *From,
6532                       bool CopyingBaseSubobject, unsigned Depth = 0) {
6533   // C++0x [class.copy]p30:
6534   //   Each subobject is assigned in the manner appropriate to its type:
6535   //
6536   //     - if the subobject is of class type, the copy assignment operator
6537   //       for the class is used (as if by explicit qualification; that is, 
6538   //       ignoring any possible virtual overriding functions in more derived 
6539   //       classes);
6540   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
6541     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6542     
6543     // Look for operator=.
6544     DeclarationName Name
6545       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6546     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
6547     S.LookupQualifiedName(OpLookup, ClassDecl, false);
6548     
6549     // Filter out any result that isn't a copy-assignment operator.
6550     LookupResult::Filter F = OpLookup.makeFilter();
6551     while (F.hasNext()) {
6552       NamedDecl *D = F.next();
6553       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
6554         if (Method->isCopyAssignmentOperator())
6555           continue;
6556       
6557       F.erase();
6558     }
6559     F.done();
6560     
6561     // Suppress the protected check (C++ [class.protected]) for each of the
6562     // assignment operators we found. This strange dance is required when 
6563     // we're assigning via a base classes's copy-assignment operator. To
6564     // ensure that we're getting the right base class subobject (without 
6565     // ambiguities), we need to cast "this" to that subobject type; to
6566     // ensure that we don't go through the virtual call mechanism, we need
6567     // to qualify the operator= name with the base class (see below). However,
6568     // this means that if the base class has a protected copy assignment
6569     // operator, the protected member access check will fail. So, we
6570     // rewrite "protected" access to "public" access in this case, since we
6571     // know by construction that we're calling from a derived class.
6572     if (CopyingBaseSubobject) {
6573       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
6574            L != LEnd; ++L) {
6575         if (L.getAccess() == AS_protected)
6576           L.setAccess(AS_public);
6577       }
6578     }
6579     
6580     // Create the nested-name-specifier that will be used to qualify the
6581     // reference to operator=; this is required to suppress the virtual
6582     // call mechanism.
6583     CXXScopeSpec SS;
6584     SS.MakeTrivial(S.Context, 
6585                    NestedNameSpecifier::Create(S.Context, 0, false, 
6586                                                T.getTypePtr()),
6587                    Loc);
6588     
6589     // Create the reference to operator=.
6590     ExprResult OpEqualRef
6591       = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 
6592                                    /*FirstQualifierInScope=*/0, OpLookup, 
6593                                    /*TemplateArgs=*/0,
6594                                    /*SuppressQualifierCheck=*/true);
6595     if (OpEqualRef.isInvalid())
6596       return StmtError();
6597     
6598     // Build the call to the assignment operator.
6599
6600     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 
6601                                                   OpEqualRef.takeAs<Expr>(),
6602                                                   Loc, &From, 1, Loc);
6603     if (Call.isInvalid())
6604       return StmtError();
6605     
6606     return S.Owned(Call.takeAs<Stmt>());
6607   }
6608
6609   //     - if the subobject is of scalar type, the built-in assignment 
6610   //       operator is used.
6611   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);  
6612   if (!ArrayTy) {
6613     ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
6614     if (Assignment.isInvalid())
6615       return StmtError();
6616     
6617     return S.Owned(Assignment.takeAs<Stmt>());
6618   }
6619     
6620   //     - if the subobject is an array, each element is assigned, in the 
6621   //       manner appropriate to the element type;
6622   
6623   // Construct a loop over the array bounds, e.g.,
6624   //
6625   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
6626   //
6627   // that will copy each of the array elements. 
6628   QualType SizeType = S.Context.getSizeType();
6629   
6630   // Create the iteration variable.
6631   IdentifierInfo *IterationVarName = 0;
6632   {
6633     llvm::SmallString<8> Str;
6634     llvm::raw_svector_ostream OS(Str);
6635     OS << "__i" << Depth;
6636     IterationVarName = &S.Context.Idents.get(OS.str());
6637   }
6638   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
6639                                           IterationVarName, SizeType,
6640                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
6641                                           SC_None, SC_None);
6642   
6643   // Initialize the iteration variable to zero.
6644   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
6645   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
6646
6647   // Create a reference to the iteration variable; we'll use this several
6648   // times throughout.
6649   Expr *IterationVarRef
6650     = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
6651   assert(IterationVarRef && "Reference to invented variable cannot fail!");
6652   
6653   // Create the DeclStmt that holds the iteration variable.
6654   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
6655   
6656   // Create the comparison against the array bound.
6657   llvm::APInt Upper
6658     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
6659   Expr *Comparison
6660     = new (S.Context) BinaryOperator(IterationVarRef,
6661                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
6662                                      BO_NE, S.Context.BoolTy,
6663                                      VK_RValue, OK_Ordinary, Loc);
6664   
6665   // Create the pre-increment of the iteration variable.
6666   Expr *Increment
6667     = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
6668                                     VK_LValue, OK_Ordinary, Loc);
6669   
6670   // Subscript the "from" and "to" expressions with the iteration variable.
6671   From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
6672                                                          IterationVarRef, Loc));
6673   To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
6674                                                        IterationVarRef, Loc));
6675   
6676   // Build the copy for an individual element of the array.
6677   StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
6678                                           To, From, CopyingBaseSubobject,
6679                                           Depth + 1);
6680   if (Copy.isInvalid())
6681     return StmtError();
6682   
6683   // Construct the loop that copies all elements of this array.
6684   return S.ActOnForStmt(Loc, Loc, InitStmt, 
6685                         S.MakeFullExpr(Comparison),
6686                         0, S.MakeFullExpr(Increment),
6687                         Loc, Copy.take());
6688 }
6689
6690 /// \brief Determine whether the given class has a copy assignment operator 
6691 /// that accepts a const-qualified argument.
6692 static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
6693   CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
6694   
6695   if (!Class->hasDeclaredCopyAssignment())
6696     S.DeclareImplicitCopyAssignment(Class);
6697   
6698   QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
6699   DeclarationName OpName 
6700     = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6701     
6702   DeclContext::lookup_const_iterator Op, OpEnd;
6703   for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
6704     // C++ [class.copy]p9:
6705     //   A user-declared copy assignment operator is a non-static non-template
6706     //   member function of class X with exactly one parameter of type X, X&,
6707     //   const X&, volatile X& or const volatile X&.
6708     const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
6709     if (!Method)
6710       continue;
6711     
6712     if (Method->isStatic())
6713       continue;
6714     if (Method->getPrimaryTemplate())
6715       continue;
6716     const FunctionProtoType *FnType =
6717     Method->getType()->getAs<FunctionProtoType>();
6718     assert(FnType && "Overloaded operator has no prototype.");
6719     // Don't assert on this; an invalid decl might have been left in the AST.
6720     if (FnType->getNumArgs() != 1 || FnType->isVariadic())
6721       continue;
6722     bool AcceptsConst = true;
6723     QualType ArgType = FnType->getArgType(0);
6724     if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
6725       ArgType = Ref->getPointeeType();
6726       // Is it a non-const lvalue reference?
6727       if (!ArgType.isConstQualified())
6728         AcceptsConst = false;
6729     }
6730     if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
6731       continue;
6732     
6733     // We have a single argument of type cv X or cv X&, i.e. we've found the
6734     // copy assignment operator. Return whether it accepts const arguments.
6735     return AcceptsConst;
6736   }
6737   assert(Class->isInvalidDecl() &&
6738          "No copy assignment operator declared in valid code.");
6739   return false;  
6740 }
6741
6742 std::pair<Sema::ImplicitExceptionSpecification, bool>
6743 Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
6744                                                    CXXRecordDecl *ClassDecl) {
6745   // C++ [class.copy]p10:
6746   //   If the class definition does not explicitly declare a copy
6747   //   assignment operator, one is declared implicitly.
6748   //   The implicitly-defined copy assignment operator for a class X
6749   //   will have the form
6750   //
6751   //       X& X::operator=(const X&)
6752   //
6753   //   if
6754   bool HasConstCopyAssignment = true;
6755   
6756   //       -- each direct base class B of X has a copy assignment operator
6757   //          whose parameter is of type const B&, const volatile B& or B,
6758   //          and
6759   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6760                                        BaseEnd = ClassDecl->bases_end();
6761        HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6762     assert(!Base->getType()->isDependentType() &&
6763            "Cannot generate implicit members for class with dependent bases.");
6764     const CXXRecordDecl *BaseClassDecl
6765       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6766     HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
6767   }
6768   
6769   //       -- for all the nonstatic data members of X that are of a class
6770   //          type M (or array thereof), each such class type has a copy
6771   //          assignment operator whose parameter is of type const M&,
6772   //          const volatile M& or M.
6773   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6774                                   FieldEnd = ClassDecl->field_end();
6775        HasConstCopyAssignment && Field != FieldEnd;
6776        ++Field) {
6777     QualType FieldType = Context.getBaseElementType((*Field)->getType());
6778     if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6779       const CXXRecordDecl *FieldClassDecl
6780         = cast<CXXRecordDecl>(FieldClassType->getDecl());
6781       HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
6782     }
6783   }
6784   
6785   //   Otherwise, the implicitly declared copy assignment operator will
6786   //   have the form
6787   //
6788   //       X& X::operator=(X&)
6789   
6790   // C++ [except.spec]p14:
6791   //   An implicitly declared special member function (Clause 12) shall have an 
6792   //   exception-specification. [...]
6793   ImplicitExceptionSpecification ExceptSpec(Context);
6794   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6795                                        BaseEnd = ClassDecl->bases_end();
6796        Base != BaseEnd; ++Base) {
6797     CXXRecordDecl *BaseClassDecl
6798       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6799     
6800     if (!BaseClassDecl->hasDeclaredCopyAssignment())
6801       DeclareImplicitCopyAssignment(BaseClassDecl);
6802
6803     if (CXXMethodDecl *CopyAssign
6804            = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
6805       ExceptSpec.CalledDecl(CopyAssign);
6806   }
6807   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6808                                   FieldEnd = ClassDecl->field_end();
6809        Field != FieldEnd;
6810        ++Field) {
6811     QualType FieldType = Context.getBaseElementType((*Field)->getType());
6812     if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6813       CXXRecordDecl *FieldClassDecl
6814         = cast<CXXRecordDecl>(FieldClassType->getDecl());
6815       
6816       if (!FieldClassDecl->hasDeclaredCopyAssignment())
6817         DeclareImplicitCopyAssignment(FieldClassDecl);
6818
6819       if (CXXMethodDecl *CopyAssign
6820             = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
6821         ExceptSpec.CalledDecl(CopyAssign);      
6822     }      
6823   }
6824
6825   return std::make_pair(ExceptSpec, HasConstCopyAssignment);
6826 }
6827
6828 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
6829   // Note: The following rules are largely analoguous to the copy
6830   // constructor rules. Note that virtual bases are not taken into account
6831   // for determining the argument type of the operator. Note also that
6832   // operators taking an object instead of a reference are allowed.
6833
6834   ImplicitExceptionSpecification Spec(Context);
6835   bool Const;
6836   llvm::tie(Spec, Const) =
6837     ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
6838
6839   QualType ArgType = Context.getTypeDeclType(ClassDecl);
6840   QualType RetType = Context.getLValueReferenceType(ArgType);
6841   if (Const)
6842     ArgType = ArgType.withConst();
6843   ArgType = Context.getLValueReferenceType(ArgType);
6844
6845   //   An implicitly-declared copy assignment operator is an inline public
6846   //   member of its class.
6847   FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6848   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6849   SourceLocation ClassLoc = ClassDecl->getLocation();
6850   DeclarationNameInfo NameInfo(Name, ClassLoc);
6851   CXXMethodDecl *CopyAssignment
6852     = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
6853                             Context.getFunctionType(RetType, &ArgType, 1, EPI),
6854                             /*TInfo=*/0, /*isStatic=*/false,
6855                             /*StorageClassAsWritten=*/SC_None,
6856                             /*isInline=*/true,
6857                             SourceLocation());
6858   CopyAssignment->setAccess(AS_public);
6859   CopyAssignment->setDefaulted();
6860   CopyAssignment->setImplicit();
6861   CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
6862   
6863   // Add the parameter to the operator.
6864   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
6865                                                ClassLoc, ClassLoc, /*Id=*/0,
6866                                                ArgType, /*TInfo=*/0,
6867                                                SC_None,
6868                                                SC_None, 0);
6869   CopyAssignment->setParams(&FromParam, 1);
6870   
6871   // Note that we have added this copy-assignment operator.
6872   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
6873
6874   if (Scope *S = getScopeForContext(ClassDecl))
6875     PushOnScopeChains(CopyAssignment, S, false);
6876   ClassDecl->addDecl(CopyAssignment);
6877   
6878   if (ShouldDeleteCopyAssignmentOperator(CopyAssignment))
6879     CopyAssignment->setDeletedAsWritten();
6880   
6881   AddOverriddenMethods(ClassDecl, CopyAssignment);
6882   return CopyAssignment;
6883 }
6884
6885 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6886                                         CXXMethodDecl *CopyAssignOperator) {
6887   assert((CopyAssignOperator->isDefaulted() && 
6888           CopyAssignOperator->isOverloadedOperator() &&
6889           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
6890           !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
6891          "DefineImplicitCopyAssignment called for wrong function");
6892
6893   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
6894
6895   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
6896     CopyAssignOperator->setInvalidDecl();
6897     return;
6898   }
6899   
6900   CopyAssignOperator->setUsed();
6901
6902   ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
6903   DiagnosticErrorTrap Trap(Diags);
6904
6905   // C++0x [class.copy]p30:
6906   //   The implicitly-defined or explicitly-defaulted copy assignment operator
6907   //   for a non-union class X performs memberwise copy assignment of its 
6908   //   subobjects. The direct base classes of X are assigned first, in the 
6909   //   order of their declaration in the base-specifier-list, and then the 
6910   //   immediate non-static data members of X are assigned, in the order in 
6911   //   which they were declared in the class definition.
6912   
6913   // The statements that form the synthesized function body.
6914   ASTOwningVector<Stmt*> Statements(*this);
6915   
6916   // The parameter for the "other" object, which we are copying from.
6917   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
6918   Qualifiers OtherQuals = Other->getType().getQualifiers();
6919   QualType OtherRefType = Other->getType();
6920   if (const LValueReferenceType *OtherRef
6921                                 = OtherRefType->getAs<LValueReferenceType>()) {
6922     OtherRefType = OtherRef->getPointeeType();
6923     OtherQuals = OtherRefType.getQualifiers();
6924   }
6925   
6926   // Our location for everything implicitly-generated.
6927   SourceLocation Loc = CopyAssignOperator->getLocation();
6928   
6929   // Construct a reference to the "other" object. We'll be using this 
6930   // throughout the generated ASTs.
6931   Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
6932   assert(OtherRef && "Reference to parameter cannot fail!");
6933   
6934   // Construct the "this" pointer. We'll be using this throughout the generated
6935   // ASTs.
6936   Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6937   assert(This && "Reference to this cannot fail!");
6938   
6939   // Assign base classes.
6940   bool Invalid = false;
6941   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6942        E = ClassDecl->bases_end(); Base != E; ++Base) {
6943     // Form the assignment:
6944     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6945     QualType BaseType = Base->getType().getUnqualifiedType();
6946     if (!BaseType->isRecordType()) {
6947       Invalid = true;
6948       continue;
6949     }
6950
6951     CXXCastPath BasePath;
6952     BasePath.push_back(Base);
6953
6954     // Construct the "from" expression, which is an implicit cast to the
6955     // appropriately-qualified base type.
6956     Expr *From = OtherRef;
6957     From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6958                              CK_UncheckedDerivedToBase,
6959                              VK_LValue, &BasePath).take();
6960
6961     // Dereference "this".
6962     ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
6963     
6964     // Implicitly cast "this" to the appropriately-qualified base type.
6965     To = ImpCastExprToType(To.take(), 
6966                            Context.getCVRQualifiedType(BaseType,
6967                                      CopyAssignOperator->getTypeQualifiers()),
6968                            CK_UncheckedDerivedToBase, 
6969                            VK_LValue, &BasePath);
6970
6971     // Build the copy.
6972     StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
6973                                             To.get(), From,
6974                                             /*CopyingBaseSubobject=*/true);
6975     if (Copy.isInvalid()) {
6976       Diag(CurrentLocation, diag::note_member_synthesized_at) 
6977         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6978       CopyAssignOperator->setInvalidDecl();
6979       return;
6980     }
6981     
6982     // Success! Record the copy.
6983     Statements.push_back(Copy.takeAs<Expr>());
6984   }
6985   
6986   // \brief Reference to the __builtin_memcpy function.
6987   Expr *BuiltinMemCpyRef = 0;
6988   // \brief Reference to the __builtin_objc_memmove_collectable function.
6989   Expr *CollectableMemCpyRef = 0;
6990   
6991   // Assign non-static members.
6992   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6993                                   FieldEnd = ClassDecl->field_end(); 
6994        Field != FieldEnd; ++Field) {
6995     // Check for members of reference type; we can't copy those.
6996     if (Field->getType()->isReferenceType()) {
6997       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6998         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
6999       Diag(Field->getLocation(), diag::note_declared_at);
7000       Diag(CurrentLocation, diag::note_member_synthesized_at) 
7001         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7002       Invalid = true;
7003       continue;
7004     }
7005     
7006     // Check for members of const-qualified, non-class type.
7007     QualType BaseType = Context.getBaseElementType(Field->getType());
7008     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7009       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7010         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7011       Diag(Field->getLocation(), diag::note_declared_at);
7012       Diag(CurrentLocation, diag::note_member_synthesized_at) 
7013         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7014       Invalid = true;      
7015       continue;
7016     }
7017     
7018     QualType FieldType = Field->getType().getNonReferenceType();
7019     if (FieldType->isIncompleteArrayType()) {
7020       assert(ClassDecl->hasFlexibleArrayMember() && 
7021              "Incomplete array type is not valid");
7022       continue;
7023     }
7024     
7025     // Build references to the field in the object we're copying from and to.
7026     CXXScopeSpec SS; // Intentionally empty
7027     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7028                               LookupMemberName);
7029     MemberLookup.addDecl(*Field);
7030     MemberLookup.resolveKind();
7031     ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7032                                                Loc, /*IsArrow=*/false,
7033                                                SS, 0, MemberLookup, 0);
7034     ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7035                                              Loc, /*IsArrow=*/true,
7036                                              SS, 0, MemberLookup, 0);
7037     assert(!From.isInvalid() && "Implicit field reference cannot fail");
7038     assert(!To.isInvalid() && "Implicit field reference cannot fail");
7039     
7040     // If the field should be copied with __builtin_memcpy rather than via
7041     // explicit assignments, do so. This optimization only applies for arrays 
7042     // of scalars and arrays of class type with trivial copy-assignment 
7043     // operators.
7044     if (FieldType->isArrayType() &&
7045         (!BaseType->isRecordType() || 
7046          cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
7047            ->hasTrivialCopyAssignment())) {
7048       // Compute the size of the memory buffer to be copied.
7049       QualType SizeType = Context.getSizeType();
7050       llvm::APInt Size(Context.getTypeSize(SizeType), 
7051                        Context.getTypeSizeInChars(BaseType).getQuantity());
7052       for (const ConstantArrayType *Array
7053               = Context.getAsConstantArrayType(FieldType);
7054            Array; 
7055            Array = Context.getAsConstantArrayType(Array->getElementType())) {
7056         llvm::APInt ArraySize
7057           = Array->getSize().zextOrTrunc(Size.getBitWidth());
7058         Size *= ArraySize;
7059       }
7060           
7061       // Take the address of the field references for "from" and "to".
7062       From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7063       To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
7064           
7065       bool NeedsCollectableMemCpy = 
7066           (BaseType->isRecordType() && 
7067            BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7068           
7069       if (NeedsCollectableMemCpy) {
7070         if (!CollectableMemCpyRef) {
7071           // Create a reference to the __builtin_objc_memmove_collectable function.
7072           LookupResult R(*this, 
7073                          &Context.Idents.get("__builtin_objc_memmove_collectable"), 
7074                          Loc, LookupOrdinaryName);
7075           LookupName(R, TUScope, true);
7076         
7077           FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7078           if (!CollectableMemCpy) {
7079             // Something went horribly wrong earlier, and we will have 
7080             // complained about it.
7081             Invalid = true;
7082             continue;
7083           }
7084         
7085           CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 
7086                                                   CollectableMemCpy->getType(),
7087                                                   VK_LValue, Loc, 0).take();
7088           assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7089         }
7090       }
7091       // Create a reference to the __builtin_memcpy builtin function.
7092       else if (!BuiltinMemCpyRef) {
7093         LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7094                        LookupOrdinaryName);
7095         LookupName(R, TUScope, true);
7096         
7097         FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7098         if (!BuiltinMemCpy) {
7099           // Something went horribly wrong earlier, and we will have complained
7100           // about it.
7101           Invalid = true;
7102           continue;
7103         }
7104
7105         BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 
7106                                             BuiltinMemCpy->getType(),
7107                                             VK_LValue, Loc, 0).take();
7108         assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7109       }
7110           
7111       ASTOwningVector<Expr*> CallArgs(*this);
7112       CallArgs.push_back(To.takeAs<Expr>());
7113       CallArgs.push_back(From.takeAs<Expr>());
7114       CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
7115       ExprResult Call = ExprError();
7116       if (NeedsCollectableMemCpy)
7117         Call = ActOnCallExpr(/*Scope=*/0,
7118                              CollectableMemCpyRef,
7119                              Loc, move_arg(CallArgs), 
7120                              Loc);
7121       else
7122         Call = ActOnCallExpr(/*Scope=*/0,
7123                              BuiltinMemCpyRef,
7124                              Loc, move_arg(CallArgs), 
7125                              Loc);
7126           
7127       assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7128       Statements.push_back(Call.takeAs<Expr>());
7129       continue;
7130     }
7131     
7132     // Build the copy of this field.
7133     StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType, 
7134                                                   To.get(), From.get(),
7135                                               /*CopyingBaseSubobject=*/false);
7136     if (Copy.isInvalid()) {
7137       Diag(CurrentLocation, diag::note_member_synthesized_at) 
7138         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7139       CopyAssignOperator->setInvalidDecl();
7140       return;
7141     }
7142     
7143     // Success! Record the copy.
7144     Statements.push_back(Copy.takeAs<Stmt>());
7145   }
7146
7147   if (!Invalid) {
7148     // Add a "return *this;"
7149     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7150     
7151     StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
7152     if (Return.isInvalid())
7153       Invalid = true;
7154     else {
7155       Statements.push_back(Return.takeAs<Stmt>());
7156
7157       if (Trap.hasErrorOccurred()) {
7158         Diag(CurrentLocation, diag::note_member_synthesized_at) 
7159           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7160         Invalid = true;
7161       }
7162     }
7163   }
7164
7165   if (Invalid) {
7166     CopyAssignOperator->setInvalidDecl();
7167     return;
7168   }
7169   
7170   StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7171                                             /*isStmtExpr=*/false);
7172   assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7173   CopyAssignOperator->setBody(Body.takeAs<Stmt>());
7174
7175   if (ASTMutationListener *L = getASTMutationListener()) {
7176     L->CompletedImplicitDefinition(CopyAssignOperator);
7177   }
7178 }
7179
7180 std::pair<Sema::ImplicitExceptionSpecification, bool>
7181 Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
7182   // C++ [class.copy]p5:
7183   //   The implicitly-declared copy constructor for a class X will
7184   //   have the form
7185   //
7186   //       X::X(const X&)
7187   //
7188   //   if
7189   // FIXME: It ought to be possible to store this on the record.
7190   bool HasConstCopyConstructor = true;
7191   
7192   //     -- each direct or virtual base class B of X has a copy
7193   //        constructor whose first parameter is of type const B& or
7194   //        const volatile B&, and
7195   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7196                                        BaseEnd = ClassDecl->bases_end();
7197        HasConstCopyConstructor && Base != BaseEnd; 
7198        ++Base) {
7199     // Virtual bases are handled below.
7200     if (Base->isVirtual())
7201       continue;
7202     
7203     CXXRecordDecl *BaseClassDecl
7204       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7205     LookupCopyConstructor(BaseClassDecl, Qualifiers::Const,
7206                           &HasConstCopyConstructor);
7207   }
7208
7209   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7210                                        BaseEnd = ClassDecl->vbases_end();
7211        HasConstCopyConstructor && Base != BaseEnd; 
7212        ++Base) {
7213     CXXRecordDecl *BaseClassDecl
7214       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7215     LookupCopyConstructor(BaseClassDecl, Qualifiers::Const,
7216                           &HasConstCopyConstructor);
7217   }
7218   
7219   //     -- for all the nonstatic data members of X that are of a
7220   //        class type M (or array thereof), each such class type
7221   //        has a copy constructor whose first parameter is of type
7222   //        const M& or const volatile M&.
7223   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7224                                   FieldEnd = ClassDecl->field_end();
7225        HasConstCopyConstructor && Field != FieldEnd;
7226        ++Field) {
7227     QualType FieldType = Context.getBaseElementType((*Field)->getType());
7228     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7229       LookupCopyConstructor(FieldClassDecl, Qualifiers::Const,
7230                             &HasConstCopyConstructor);
7231     }
7232   }
7233   //   Otherwise, the implicitly declared copy constructor will have
7234   //   the form
7235   //
7236   //       X::X(X&)
7237  
7238   // C++ [except.spec]p14:
7239   //   An implicitly declared special member function (Clause 12) shall have an 
7240   //   exception-specification. [...]
7241   ImplicitExceptionSpecification ExceptSpec(Context);
7242   unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
7243   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7244                                        BaseEnd = ClassDecl->bases_end();
7245        Base != BaseEnd; 
7246        ++Base) {
7247     // Virtual bases are handled below.
7248     if (Base->isVirtual())
7249       continue;
7250     
7251     CXXRecordDecl *BaseClassDecl
7252       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7253     if (CXXConstructorDecl *CopyConstructor =
7254           LookupCopyConstructor(BaseClassDecl, Quals))
7255       ExceptSpec.CalledDecl(CopyConstructor);
7256   }
7257   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7258                                        BaseEnd = ClassDecl->vbases_end();
7259        Base != BaseEnd; 
7260        ++Base) {
7261     CXXRecordDecl *BaseClassDecl
7262       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7263     if (CXXConstructorDecl *CopyConstructor =
7264           LookupCopyConstructor(BaseClassDecl, Quals))
7265       ExceptSpec.CalledDecl(CopyConstructor);
7266   }
7267   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7268                                   FieldEnd = ClassDecl->field_end();
7269        Field != FieldEnd;
7270        ++Field) {
7271     QualType FieldType = Context.getBaseElementType((*Field)->getType());
7272     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7273       if (CXXConstructorDecl *CopyConstructor =
7274         LookupCopyConstructor(FieldClassDecl, Quals))
7275       ExceptSpec.CalledDecl(CopyConstructor);
7276     }
7277   }
7278
7279   return std::make_pair(ExceptSpec, HasConstCopyConstructor);
7280 }
7281
7282 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
7283                                                     CXXRecordDecl *ClassDecl) {
7284   // C++ [class.copy]p4:
7285   //   If the class definition does not explicitly declare a copy
7286   //   constructor, one is declared implicitly.
7287
7288   ImplicitExceptionSpecification Spec(Context);
7289   bool Const;
7290   llvm::tie(Spec, Const) =
7291     ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
7292
7293   QualType ClassType = Context.getTypeDeclType(ClassDecl);
7294   QualType ArgType = ClassType;
7295   if (Const)
7296     ArgType = ArgType.withConst();
7297   ArgType = Context.getLValueReferenceType(ArgType);
7298  
7299   FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7300
7301   DeclarationName Name
7302     = Context.DeclarationNames.getCXXConstructorName(
7303                                            Context.getCanonicalType(ClassType));
7304   SourceLocation ClassLoc = ClassDecl->getLocation();
7305   DeclarationNameInfo NameInfo(Name, ClassLoc);
7306
7307   //   An implicitly-declared copy constructor is an inline public
7308   //   member of its class. 
7309   CXXConstructorDecl *CopyConstructor
7310     = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7311                                  Context.getFunctionType(Context.VoidTy,
7312                                                          &ArgType, 1, EPI),
7313                                  /*TInfo=*/0,
7314                                  /*isExplicit=*/false,
7315                                  /*isInline=*/true,
7316                                  /*isImplicitlyDeclared=*/true);
7317   CopyConstructor->setAccess(AS_public);
7318   CopyConstructor->setDefaulted();
7319   CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
7320   
7321   // Note that we have declared this constructor.
7322   ++ASTContext::NumImplicitCopyConstructorsDeclared;
7323   
7324   // Add the parameter to the constructor.
7325   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
7326                                                ClassLoc, ClassLoc,
7327                                                /*IdentifierInfo=*/0,
7328                                                ArgType, /*TInfo=*/0,
7329                                                SC_None,
7330                                                SC_None, 0);
7331   CopyConstructor->setParams(&FromParam, 1);
7332
7333   if (Scope *S = getScopeForContext(ClassDecl))
7334     PushOnScopeChains(CopyConstructor, S, false);
7335   ClassDecl->addDecl(CopyConstructor);
7336
7337   if (ShouldDeleteCopyConstructor(CopyConstructor))
7338     CopyConstructor->setDeletedAsWritten();
7339   
7340   return CopyConstructor;
7341 }
7342
7343 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
7344                                    CXXConstructorDecl *CopyConstructor) {
7345   assert((CopyConstructor->isDefaulted() &&
7346           CopyConstructor->isCopyConstructor() &&
7347           !CopyConstructor->doesThisDeclarationHaveABody()) &&
7348          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
7349
7350   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
7351   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
7352
7353   ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
7354   DiagnosticErrorTrap Trap(Diags);
7355
7356   if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
7357       Trap.hasErrorOccurred()) {
7358     Diag(CurrentLocation, diag::note_member_synthesized_at) 
7359       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
7360     CopyConstructor->setInvalidDecl();
7361   }  else {
7362     CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
7363                                                CopyConstructor->getLocation(),
7364                                                MultiStmtArg(*this, 0, 0), 
7365                                                /*isStmtExpr=*/false)
7366                                                               .takeAs<Stmt>());
7367   }
7368   
7369   CopyConstructor->setUsed();
7370
7371   if (ASTMutationListener *L = getASTMutationListener()) {
7372     L->CompletedImplicitDefinition(CopyConstructor);
7373   }
7374 }
7375
7376 ExprResult
7377 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7378                             CXXConstructorDecl *Constructor,
7379                             MultiExprArg ExprArgs,
7380                             bool RequiresZeroInit,
7381                             unsigned ConstructKind,
7382                             SourceRange ParenRange) {
7383   bool Elidable = false;
7384
7385   // C++0x [class.copy]p34:
7386   //   When certain criteria are met, an implementation is allowed to
7387   //   omit the copy/move construction of a class object, even if the
7388   //   copy/move constructor and/or destructor for the object have
7389   //   side effects. [...]
7390   //     - when a temporary class object that has not been bound to a
7391   //       reference (12.2) would be copied/moved to a class object
7392   //       with the same cv-unqualified type, the copy/move operation
7393   //       can be omitted by constructing the temporary object
7394   //       directly into the target of the omitted copy/move
7395   if (ConstructKind == CXXConstructExpr::CK_Complete &&
7396       Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
7397     Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
7398     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
7399   }
7400
7401   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
7402                                Elidable, move(ExprArgs), RequiresZeroInit,
7403                                ConstructKind, ParenRange);
7404 }
7405
7406 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
7407 /// including handling of its default argument expressions.
7408 ExprResult
7409 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7410                             CXXConstructorDecl *Constructor, bool Elidable,
7411                             MultiExprArg ExprArgs,
7412                             bool RequiresZeroInit,
7413                             unsigned ConstructKind,
7414                             SourceRange ParenRange) {
7415   unsigned NumExprs = ExprArgs.size();
7416   Expr **Exprs = (Expr **)ExprArgs.release();
7417
7418   for (specific_attr_iterator<NonNullAttr>
7419            i = Constructor->specific_attr_begin<NonNullAttr>(),
7420            e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
7421     const NonNullAttr *NonNull = *i;
7422     CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
7423   }
7424
7425   MarkDeclarationReferenced(ConstructLoc, Constructor);
7426   return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
7427                                         Constructor, Elidable, Exprs, NumExprs, 
7428                                         RequiresZeroInit,
7429               static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
7430                                         ParenRange));
7431 }
7432
7433 bool Sema::InitializeVarWithConstructor(VarDecl *VD,
7434                                         CXXConstructorDecl *Constructor,
7435                                         MultiExprArg Exprs) {
7436   // FIXME: Provide the correct paren SourceRange when available.
7437   ExprResult TempResult =
7438     BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
7439                           move(Exprs), false, CXXConstructExpr::CK_Complete,
7440                           SourceRange());
7441   if (TempResult.isInvalid())
7442     return true;
7443
7444   Expr *Temp = TempResult.takeAs<Expr>();
7445   CheckImplicitConversions(Temp, VD->getLocation());
7446   MarkDeclarationReferenced(VD->getLocation(), Constructor);
7447   Temp = MaybeCreateExprWithCleanups(Temp);
7448   VD->setInit(Temp);
7449
7450   return false;
7451 }
7452
7453 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
7454   if (VD->isInvalidDecl()) return;
7455
7456   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
7457   if (ClassDecl->isInvalidDecl()) return;
7458   if (ClassDecl->hasTrivialDestructor()) return;
7459   if (ClassDecl->isDependentContext()) return;
7460
7461   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7462   MarkDeclarationReferenced(VD->getLocation(), Destructor);
7463   CheckDestructorAccess(VD->getLocation(), Destructor,
7464                         PDiag(diag::err_access_dtor_var)
7465                         << VD->getDeclName()
7466                         << VD->getType());
7467
7468   if (!VD->hasGlobalStorage()) return;
7469
7470   // Emit warning for non-trivial dtor in global scope (a real global,
7471   // class-static, function-static).
7472   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
7473
7474   // TODO: this should be re-enabled for static locals by !CXAAtExit
7475   if (!VD->isStaticLocal())
7476     Diag(VD->getLocation(), diag::warn_global_destructor);
7477 }
7478
7479 /// AddCXXDirectInitializerToDecl - This action is called immediately after
7480 /// ActOnDeclarator, when a C++ direct initializer is present.
7481 /// e.g: "int x(1);"
7482 void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
7483                                          SourceLocation LParenLoc,
7484                                          MultiExprArg Exprs,
7485                                          SourceLocation RParenLoc,
7486                                          bool TypeMayContainAuto) {
7487   assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
7488
7489   // If there is no declaration, there was an error parsing it.  Just ignore
7490   // the initializer.
7491   if (RealDecl == 0)
7492     return;
7493
7494   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7495   if (!VDecl) {
7496     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7497     RealDecl->setInvalidDecl();
7498     return;
7499   }
7500
7501   // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7502   if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
7503     // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
7504     if (Exprs.size() > 1) {
7505       Diag(Exprs.get()[1]->getSourceRange().getBegin(),
7506            diag::err_auto_var_init_multiple_expressions)
7507         << VDecl->getDeclName() << VDecl->getType()
7508         << VDecl->getSourceRange();
7509       RealDecl->setInvalidDecl();
7510       return;
7511     }
7512
7513     Expr *Init = Exprs.get()[0];
7514     TypeSourceInfo *DeducedType = 0;
7515     if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
7516       Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
7517         << VDecl->getDeclName() << VDecl->getType() << Init->getType()
7518         << Init->getSourceRange();
7519     if (!DeducedType) {
7520       RealDecl->setInvalidDecl();
7521       return;
7522     }
7523     VDecl->setTypeSourceInfo(DeducedType);
7524     VDecl->setType(DeducedType->getType());
7525
7526     // If this is a redeclaration, check that the type we just deduced matches
7527     // the previously declared type.
7528     if (VarDecl *Old = VDecl->getPreviousDeclaration())
7529       MergeVarDeclTypes(VDecl, Old);
7530   }
7531
7532   // We will represent direct-initialization similarly to copy-initialization:
7533   //    int x(1);  -as-> int x = 1;
7534   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
7535   //
7536   // Clients that want to distinguish between the two forms, can check for
7537   // direct initializer using VarDecl::hasCXXDirectInitializer().
7538   // A major benefit is that clients that don't particularly care about which
7539   // exactly form was it (like the CodeGen) can handle both cases without
7540   // special case code.
7541
7542   // C++ 8.5p11:
7543   // The form of initialization (using parentheses or '=') is generally
7544   // insignificant, but does matter when the entity being initialized has a
7545   // class type.
7546
7547   if (!VDecl->getType()->isDependentType() &&
7548       RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
7549                           diag::err_typecheck_decl_incomplete_type)) {
7550     VDecl->setInvalidDecl();
7551     return;
7552   }
7553
7554   // The variable can not have an abstract class type.
7555   if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
7556                              diag::err_abstract_type_in_decl,
7557                              AbstractVariableType))
7558     VDecl->setInvalidDecl();
7559
7560   const VarDecl *Def;
7561   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
7562     Diag(VDecl->getLocation(), diag::err_redefinition)
7563     << VDecl->getDeclName();
7564     Diag(Def->getLocation(), diag::note_previous_definition);
7565     VDecl->setInvalidDecl();
7566     return;
7567   }
7568
7569   // C++ [class.static.data]p4
7570   //   If a static data member is of const integral or const
7571   //   enumeration type, its declaration in the class definition can
7572   //   specify a constant-initializer which shall be an integral
7573   //   constant expression (5.19). In that case, the member can appear
7574   //   in integral constant expressions. The member shall still be
7575   //   defined in a namespace scope if it is used in the program and the
7576   //   namespace scope definition shall not contain an initializer.
7577   //
7578   // We already performed a redefinition check above, but for static
7579   // data members we also need to check whether there was an in-class
7580   // declaration with an initializer.
7581   const VarDecl* PrevInit = 0;
7582   if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
7583     Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
7584     Diag(PrevInit->getLocation(), diag::note_previous_definition);
7585     return;
7586   } 
7587
7588   bool IsDependent = false;
7589   for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
7590     if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
7591       VDecl->setInvalidDecl();
7592       return;
7593     }
7594
7595     if (Exprs.get()[I]->isTypeDependent())
7596       IsDependent = true;
7597   }
7598
7599   // If either the declaration has a dependent type or if any of the
7600   // expressions is type-dependent, we represent the initialization
7601   // via a ParenListExpr for later use during template instantiation.
7602   if (VDecl->getType()->isDependentType() || IsDependent) {
7603     // Let clients know that initialization was done with a direct initializer.
7604     VDecl->setCXXDirectInitializer(true);
7605
7606     // Store the initialization expressions as a ParenListExpr.
7607     unsigned NumExprs = Exprs.size();
7608     VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
7609                                                (Expr **)Exprs.release(),
7610                                                NumExprs, RParenLoc));
7611     return;
7612   }
7613   
7614   // Capture the variable that is being initialized and the style of
7615   // initialization.
7616   InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
7617   
7618   // FIXME: Poor source location information.
7619   InitializationKind Kind
7620     = InitializationKind::CreateDirect(VDecl->getLocation(),
7621                                        LParenLoc, RParenLoc);
7622   
7623   InitializationSequence InitSeq(*this, Entity, Kind, 
7624                                  Exprs.get(), Exprs.size());
7625   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
7626   if (Result.isInvalid()) {
7627     VDecl->setInvalidDecl();
7628     return;
7629   }
7630
7631   CheckImplicitConversions(Result.get(), LParenLoc);
7632   
7633   Result = MaybeCreateExprWithCleanups(Result);
7634   VDecl->setInit(Result.takeAs<Expr>());
7635   VDecl->setCXXDirectInitializer(true);
7636
7637   CheckCompleteVariableDeclaration(VDecl);
7638 }
7639
7640 /// \brief Given a constructor and the set of arguments provided for the
7641 /// constructor, convert the arguments and add any required default arguments
7642 /// to form a proper call to this constructor.
7643 ///
7644 /// \returns true if an error occurred, false otherwise.
7645 bool 
7646 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
7647                               MultiExprArg ArgsPtr,
7648                               SourceLocation Loc,                                    
7649                               ASTOwningVector<Expr*> &ConvertedArgs) {
7650   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
7651   unsigned NumArgs = ArgsPtr.size();
7652   Expr **Args = (Expr **)ArgsPtr.get();
7653
7654   const FunctionProtoType *Proto 
7655     = Constructor->getType()->getAs<FunctionProtoType>();
7656   assert(Proto && "Constructor without a prototype?");
7657   unsigned NumArgsInProto = Proto->getNumArgs();
7658   
7659   // If too few arguments are available, we'll fill in the rest with defaults.
7660   if (NumArgs < NumArgsInProto)
7661     ConvertedArgs.reserve(NumArgsInProto);
7662   else
7663     ConvertedArgs.reserve(NumArgs);
7664
7665   VariadicCallType CallType = 
7666     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
7667   llvm::SmallVector<Expr *, 8> AllArgs;
7668   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
7669                                         Proto, 0, Args, NumArgs, AllArgs, 
7670                                         CallType);
7671   for (unsigned i =0, size = AllArgs.size(); i < size; i++)
7672     ConvertedArgs.push_back(AllArgs[i]);
7673   return Invalid;
7674 }
7675
7676 static inline bool
7677 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 
7678                                        const FunctionDecl *FnDecl) {
7679   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
7680   if (isa<NamespaceDecl>(DC)) {
7681     return SemaRef.Diag(FnDecl->getLocation(), 
7682                         diag::err_operator_new_delete_declared_in_namespace)
7683       << FnDecl->getDeclName();
7684   }
7685   
7686   if (isa<TranslationUnitDecl>(DC) && 
7687       FnDecl->getStorageClass() == SC_Static) {
7688     return SemaRef.Diag(FnDecl->getLocation(),
7689                         diag::err_operator_new_delete_declared_static)
7690       << FnDecl->getDeclName();
7691   }
7692   
7693   return false;
7694 }
7695
7696 static inline bool
7697 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
7698                             CanQualType ExpectedResultType,
7699                             CanQualType ExpectedFirstParamType,
7700                             unsigned DependentParamTypeDiag,
7701                             unsigned InvalidParamTypeDiag) {
7702   QualType ResultType = 
7703     FnDecl->getType()->getAs<FunctionType>()->getResultType();
7704
7705   // Check that the result type is not dependent.
7706   if (ResultType->isDependentType())
7707     return SemaRef.Diag(FnDecl->getLocation(),
7708                         diag::err_operator_new_delete_dependent_result_type)
7709     << FnDecl->getDeclName() << ExpectedResultType;
7710
7711   // Check that the result type is what we expect.
7712   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
7713     return SemaRef.Diag(FnDecl->getLocation(),
7714                         diag::err_operator_new_delete_invalid_result_type) 
7715     << FnDecl->getDeclName() << ExpectedResultType;
7716   
7717   // A function template must have at least 2 parameters.
7718   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
7719     return SemaRef.Diag(FnDecl->getLocation(),
7720                       diag::err_operator_new_delete_template_too_few_parameters)
7721         << FnDecl->getDeclName();
7722   
7723   // The function decl must have at least 1 parameter.
7724   if (FnDecl->getNumParams() == 0)
7725     return SemaRef.Diag(FnDecl->getLocation(),
7726                         diag::err_operator_new_delete_too_few_parameters)
7727       << FnDecl->getDeclName();
7728  
7729   // Check the the first parameter type is not dependent.
7730   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
7731   if (FirstParamType->isDependentType())
7732     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
7733       << FnDecl->getDeclName() << ExpectedFirstParamType;
7734
7735   // Check that the first parameter type is what we expect.
7736   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 
7737       ExpectedFirstParamType)
7738     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
7739     << FnDecl->getDeclName() << ExpectedFirstParamType;
7740   
7741   return false;
7742 }
7743
7744 static bool
7745 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7746   // C++ [basic.stc.dynamic.allocation]p1:
7747   //   A program is ill-formed if an allocation function is declared in a
7748   //   namespace scope other than global scope or declared static in global 
7749   //   scope.
7750   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7751     return true;
7752
7753   CanQualType SizeTy = 
7754     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
7755
7756   // C++ [basic.stc.dynamic.allocation]p1:
7757   //  The return type shall be void*. The first parameter shall have type 
7758   //  std::size_t.
7759   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 
7760                                   SizeTy,
7761                                   diag::err_operator_new_dependent_param_type,
7762                                   diag::err_operator_new_param_type))
7763     return true;
7764
7765   // C++ [basic.stc.dynamic.allocation]p1:
7766   //  The first parameter shall not have an associated default argument.
7767   if (FnDecl->getParamDecl(0)->hasDefaultArg())
7768     return SemaRef.Diag(FnDecl->getLocation(),
7769                         diag::err_operator_new_default_arg)
7770       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
7771
7772   return false;
7773 }
7774
7775 static bool
7776 CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7777   // C++ [basic.stc.dynamic.deallocation]p1:
7778   //   A program is ill-formed if deallocation functions are declared in a
7779   //   namespace scope other than global scope or declared static in global 
7780   //   scope.
7781   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7782     return true;
7783
7784   // C++ [basic.stc.dynamic.deallocation]p2:
7785   //   Each deallocation function shall return void and its first parameter 
7786   //   shall be void*.
7787   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 
7788                                   SemaRef.Context.VoidPtrTy,
7789                                  diag::err_operator_delete_dependent_param_type,
7790                                  diag::err_operator_delete_param_type))
7791     return true;
7792
7793   return false;
7794 }
7795
7796 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
7797 /// of this overloaded operator is well-formed. If so, returns false;
7798 /// otherwise, emits appropriate diagnostics and returns true.
7799 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
7800   assert(FnDecl && FnDecl->isOverloadedOperator() &&
7801          "Expected an overloaded operator declaration");
7802
7803   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
7804
7805   // C++ [over.oper]p5:
7806   //   The allocation and deallocation functions, operator new,
7807   //   operator new[], operator delete and operator delete[], are
7808   //   described completely in 3.7.3. The attributes and restrictions
7809   //   found in the rest of this subclause do not apply to them unless
7810   //   explicitly stated in 3.7.3.
7811   if (Op == OO_Delete || Op == OO_Array_Delete)
7812     return CheckOperatorDeleteDeclaration(*this, FnDecl);
7813   
7814   if (Op == OO_New || Op == OO_Array_New)
7815     return CheckOperatorNewDeclaration(*this, FnDecl);
7816
7817   // C++ [over.oper]p6:
7818   //   An operator function shall either be a non-static member
7819   //   function or be a non-member function and have at least one
7820   //   parameter whose type is a class, a reference to a class, an
7821   //   enumeration, or a reference to an enumeration.
7822   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
7823     if (MethodDecl->isStatic())
7824       return Diag(FnDecl->getLocation(),
7825                   diag::err_operator_overload_static) << FnDecl->getDeclName();
7826   } else {
7827     bool ClassOrEnumParam = false;
7828     for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
7829                                    ParamEnd = FnDecl->param_end();
7830          Param != ParamEnd; ++Param) {
7831       QualType ParamType = (*Param)->getType().getNonReferenceType();
7832       if (ParamType->isDependentType() || ParamType->isRecordType() ||
7833           ParamType->isEnumeralType()) {
7834         ClassOrEnumParam = true;
7835         break;
7836       }
7837     }
7838
7839     if (!ClassOrEnumParam)
7840       return Diag(FnDecl->getLocation(),
7841                   diag::err_operator_overload_needs_class_or_enum)
7842         << FnDecl->getDeclName();
7843   }
7844
7845   // C++ [over.oper]p8:
7846   //   An operator function cannot have default arguments (8.3.6),
7847   //   except where explicitly stated below.
7848   //
7849   // Only the function-call operator allows default arguments
7850   // (C++ [over.call]p1).
7851   if (Op != OO_Call) {
7852     for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
7853          Param != FnDecl->param_end(); ++Param) {
7854       if ((*Param)->hasDefaultArg())
7855         return Diag((*Param)->getLocation(),
7856                     diag::err_operator_overload_default_arg)
7857           << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
7858     }
7859   }
7860
7861   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
7862     { false, false, false }
7863 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7864     , { Unary, Binary, MemberOnly }
7865 #include "clang/Basic/OperatorKinds.def"
7866   };
7867
7868   bool CanBeUnaryOperator = OperatorUses[Op][0];
7869   bool CanBeBinaryOperator = OperatorUses[Op][1];
7870   bool MustBeMemberOperator = OperatorUses[Op][2];
7871
7872   // C++ [over.oper]p8:
7873   //   [...] Operator functions cannot have more or fewer parameters
7874   //   than the number required for the corresponding operator, as
7875   //   described in the rest of this subclause.
7876   unsigned NumParams = FnDecl->getNumParams()
7877                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
7878   if (Op != OO_Call &&
7879       ((NumParams == 1 && !CanBeUnaryOperator) ||
7880        (NumParams == 2 && !CanBeBinaryOperator) ||
7881        (NumParams < 1) || (NumParams > 2))) {
7882     // We have the wrong number of parameters.
7883     unsigned ErrorKind;
7884     if (CanBeUnaryOperator && CanBeBinaryOperator) {
7885       ErrorKind = 2;  // 2 -> unary or binary.
7886     } else if (CanBeUnaryOperator) {
7887       ErrorKind = 0;  // 0 -> unary
7888     } else {
7889       assert(CanBeBinaryOperator &&
7890              "All non-call overloaded operators are unary or binary!");
7891       ErrorKind = 1;  // 1 -> binary
7892     }
7893
7894     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
7895       << FnDecl->getDeclName() << NumParams << ErrorKind;
7896   }
7897
7898   // Overloaded operators other than operator() cannot be variadic.
7899   if (Op != OO_Call &&
7900       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
7901     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
7902       << FnDecl->getDeclName();
7903   }
7904
7905   // Some operators must be non-static member functions.
7906   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
7907     return Diag(FnDecl->getLocation(),
7908                 diag::err_operator_overload_must_be_member)
7909       << FnDecl->getDeclName();
7910   }
7911
7912   // C++ [over.inc]p1:
7913   //   The user-defined function called operator++ implements the
7914   //   prefix and postfix ++ operator. If this function is a member
7915   //   function with no parameters, or a non-member function with one
7916   //   parameter of class or enumeration type, it defines the prefix
7917   //   increment operator ++ for objects of that type. If the function
7918   //   is a member function with one parameter (which shall be of type
7919   //   int) or a non-member function with two parameters (the second
7920   //   of which shall be of type int), it defines the postfix
7921   //   increment operator ++ for objects of that type.
7922   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7923     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7924     bool ParamIsInt = false;
7925     if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
7926       ParamIsInt = BT->getKind() == BuiltinType::Int;
7927
7928     if (!ParamIsInt)
7929       return Diag(LastParam->getLocation(),
7930                   diag::err_operator_overload_post_incdec_must_be_int)
7931         << LastParam->getType() << (Op == OO_MinusMinus);
7932   }
7933
7934   return false;
7935 }
7936
7937 /// CheckLiteralOperatorDeclaration - Check whether the declaration
7938 /// of this literal operator function is well-formed. If so, returns
7939 /// false; otherwise, emits appropriate diagnostics and returns true.
7940 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7941   DeclContext *DC = FnDecl->getDeclContext();
7942   Decl::Kind Kind = DC->getDeclKind();
7943   if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7944       Kind != Decl::LinkageSpec) {
7945     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7946       << FnDecl->getDeclName();
7947     return true;
7948   }
7949
7950   bool Valid = false;
7951
7952   // template <char...> type operator "" name() is the only valid template
7953   // signature, and the only valid signature with no parameters.
7954   if (FnDecl->param_size() == 0) {
7955     if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7956       // Must have only one template parameter
7957       TemplateParameterList *Params = TpDecl->getTemplateParameters();
7958       if (Params->size() == 1) {
7959         NonTypeTemplateParmDecl *PmDecl =
7960           cast<NonTypeTemplateParmDecl>(Params->getParam(0));
7961
7962         // The template parameter must be a char parameter pack.
7963         if (PmDecl && PmDecl->isTemplateParameterPack() &&
7964             Context.hasSameType(PmDecl->getType(), Context.CharTy))
7965           Valid = true;
7966       }
7967     }
7968   } else {
7969     // Check the first parameter
7970     FunctionDecl::param_iterator Param = FnDecl->param_begin();
7971
7972     QualType T = (*Param)->getType();
7973
7974     // unsigned long long int, long double, and any character type are allowed
7975     // as the only parameters.
7976     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7977         Context.hasSameType(T, Context.LongDoubleTy) ||
7978         Context.hasSameType(T, Context.CharTy) ||
7979         Context.hasSameType(T, Context.WCharTy) ||
7980         Context.hasSameType(T, Context.Char16Ty) ||
7981         Context.hasSameType(T, Context.Char32Ty)) {
7982       if (++Param == FnDecl->param_end())
7983         Valid = true;
7984       goto FinishedParams;
7985     }
7986
7987     // Otherwise it must be a pointer to const; let's strip those qualifiers.
7988     const PointerType *PT = T->getAs<PointerType>();
7989     if (!PT)
7990       goto FinishedParams;
7991     T = PT->getPointeeType();
7992     if (!T.isConstQualified())
7993       goto FinishedParams;
7994     T = T.getUnqualifiedType();
7995
7996     // Move on to the second parameter;
7997     ++Param;
7998
7999     // If there is no second parameter, the first must be a const char *
8000     if (Param == FnDecl->param_end()) {
8001       if (Context.hasSameType(T, Context.CharTy))
8002         Valid = true;
8003       goto FinishedParams;
8004     }
8005
8006     // const char *, const wchar_t*, const char16_t*, and const char32_t*
8007     // are allowed as the first parameter to a two-parameter function
8008     if (!(Context.hasSameType(T, Context.CharTy) ||
8009           Context.hasSameType(T, Context.WCharTy) ||
8010           Context.hasSameType(T, Context.Char16Ty) ||
8011           Context.hasSameType(T, Context.Char32Ty)))
8012       goto FinishedParams;
8013
8014     // The second and final parameter must be an std::size_t
8015     T = (*Param)->getType().getUnqualifiedType();
8016     if (Context.hasSameType(T, Context.getSizeType()) &&
8017         ++Param == FnDecl->param_end())
8018       Valid = true;
8019   }
8020
8021   // FIXME: This diagnostic is absolutely terrible.
8022 FinishedParams:
8023   if (!Valid) {
8024     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
8025       << FnDecl->getDeclName();
8026     return true;
8027   }
8028
8029   return false;
8030 }
8031
8032 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
8033 /// linkage specification, including the language and (if present)
8034 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is
8035 /// the location of the language string literal, which is provided
8036 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of
8037 /// the '{' brace. Otherwise, this linkage specification does not
8038 /// have any braces.
8039 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
8040                                            SourceLocation LangLoc,
8041                                            llvm::StringRef Lang,
8042                                            SourceLocation LBraceLoc) {
8043   LinkageSpecDecl::LanguageIDs Language;
8044   if (Lang == "\"C\"")
8045     Language = LinkageSpecDecl::lang_c;
8046   else if (Lang == "\"C++\"")
8047     Language = LinkageSpecDecl::lang_cxx;
8048   else {
8049     Diag(LangLoc, diag::err_bad_language);
8050     return 0;
8051   }
8052
8053   // FIXME: Add all the various semantics of linkage specifications
8054
8055   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
8056                                                ExternLoc, LangLoc, Language);
8057   CurContext->addDecl(D);
8058   PushDeclContext(S, D);
8059   return D;
8060 }
8061
8062 /// ActOnFinishLinkageSpecification - Complete the definition of
8063 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
8064 /// valid, it's the position of the closing '}' brace in a linkage
8065 /// specification that uses braces.
8066 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
8067                                             Decl *LinkageSpec,
8068                                             SourceLocation RBraceLoc) {
8069   if (LinkageSpec) {
8070     if (RBraceLoc.isValid()) {
8071       LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
8072       LSDecl->setRBraceLoc(RBraceLoc);
8073     }
8074     PopDeclContext();
8075   }
8076   return LinkageSpec;
8077 }
8078
8079 /// \brief Perform semantic analysis for the variable declaration that
8080 /// occurs within a C++ catch clause, returning the newly-created
8081 /// variable.
8082 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
8083                                          TypeSourceInfo *TInfo,
8084                                          SourceLocation StartLoc,
8085                                          SourceLocation Loc,
8086                                          IdentifierInfo *Name) {
8087   bool Invalid = false;
8088   QualType ExDeclType = TInfo->getType();
8089   
8090   // Arrays and functions decay.
8091   if (ExDeclType->isArrayType())
8092     ExDeclType = Context.getArrayDecayedType(ExDeclType);
8093   else if (ExDeclType->isFunctionType())
8094     ExDeclType = Context.getPointerType(ExDeclType);
8095
8096   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
8097   // The exception-declaration shall not denote a pointer or reference to an
8098   // incomplete type, other than [cv] void*.
8099   // N2844 forbids rvalue references.
8100   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
8101     Diag(Loc, diag::err_catch_rvalue_ref);
8102     Invalid = true;
8103   }
8104
8105   // GCC allows catching pointers and references to incomplete types
8106   // as an extension; so do we, but we warn by default.
8107
8108   QualType BaseType = ExDeclType;
8109   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
8110   unsigned DK = diag::err_catch_incomplete;
8111   bool IncompleteCatchIsInvalid = true;
8112   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
8113     BaseType = Ptr->getPointeeType();
8114     Mode = 1;
8115     DK = diag::ext_catch_incomplete_ptr;
8116     IncompleteCatchIsInvalid = false;
8117   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
8118     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
8119     BaseType = Ref->getPointeeType();
8120     Mode = 2;
8121     DK = diag::ext_catch_incomplete_ref;
8122     IncompleteCatchIsInvalid = false;
8123   }
8124   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
8125       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
8126       IncompleteCatchIsInvalid)
8127     Invalid = true;
8128
8129   if (!Invalid && !ExDeclType->isDependentType() &&
8130       RequireNonAbstractType(Loc, ExDeclType,
8131                              diag::err_abstract_type_in_decl,
8132                              AbstractVariableType))
8133     Invalid = true;
8134
8135   // Only the non-fragile NeXT runtime currently supports C++ catches
8136   // of ObjC types, and no runtime supports catching ObjC types by value.
8137   if (!Invalid && getLangOptions().ObjC1) {
8138     QualType T = ExDeclType;
8139     if (const ReferenceType *RT = T->getAs<ReferenceType>())
8140       T = RT->getPointeeType();
8141
8142     if (T->isObjCObjectType()) {
8143       Diag(Loc, diag::err_objc_object_catch);
8144       Invalid = true;
8145     } else if (T->isObjCObjectPointerType()) {
8146       if (!getLangOptions().ObjCNonFragileABI) {
8147         Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
8148         Invalid = true;
8149       }
8150     }
8151   }
8152
8153   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
8154                                     ExDeclType, TInfo, SC_None, SC_None);
8155   ExDecl->setExceptionVariable(true);
8156   
8157   if (!Invalid) {
8158     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
8159       // C++ [except.handle]p16:
8160       //   The object declared in an exception-declaration or, if the 
8161       //   exception-declaration does not specify a name, a temporary (12.2) is 
8162       //   copy-initialized (8.5) from the exception object. [...]
8163       //   The object is destroyed when the handler exits, after the destruction
8164       //   of any automatic objects initialized within the handler.
8165       //
8166       // We just pretend to initialize the object with itself, then make sure 
8167       // it can be destroyed later.
8168       QualType initType = ExDeclType;
8169
8170       InitializedEntity entity =
8171         InitializedEntity::InitializeVariable(ExDecl);
8172       InitializationKind initKind =
8173         InitializationKind::CreateCopy(Loc, SourceLocation());
8174
8175       Expr *opaqueValue =
8176         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
8177       InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
8178       ExprResult result = sequence.Perform(*this, entity, initKind,
8179                                            MultiExprArg(&opaqueValue, 1));
8180       if (result.isInvalid())
8181         Invalid = true;
8182       else {
8183         // If the constructor used was non-trivial, set this as the
8184         // "initializer".
8185         CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
8186         if (!construct->getConstructor()->isTrivial()) {
8187           Expr *init = MaybeCreateExprWithCleanups(construct);
8188           ExDecl->setInit(init);
8189         }
8190         
8191         // And make sure it's destructable.
8192         FinalizeVarWithDestructor(ExDecl, recordType);
8193       }
8194     }
8195   }
8196   
8197   if (Invalid)
8198     ExDecl->setInvalidDecl();
8199
8200   return ExDecl;
8201 }
8202
8203 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
8204 /// handler.
8205 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
8206   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8207   bool Invalid = D.isInvalidType();
8208
8209   // Check for unexpanded parameter packs.
8210   if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8211                                                UPPC_ExceptionType)) {
8212     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 
8213                                              D.getIdentifierLoc());
8214     Invalid = true;
8215   }
8216
8217   IdentifierInfo *II = D.getIdentifier();
8218   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
8219                                              LookupOrdinaryName,
8220                                              ForRedeclaration)) {
8221     // The scope should be freshly made just for us. There is just no way
8222     // it contains any previous declaration.
8223     assert(!S->isDeclScope(PrevDecl));
8224     if (PrevDecl->isTemplateParameter()) {
8225       // Maybe we will complain about the shadowed template parameter.
8226       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
8227     }
8228   }
8229
8230   if (D.getCXXScopeSpec().isSet() && !Invalid) {
8231     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
8232       << D.getCXXScopeSpec().getRange();
8233     Invalid = true;
8234   }
8235
8236   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
8237                                               D.getSourceRange().getBegin(),
8238                                               D.getIdentifierLoc(),
8239                                               D.getIdentifier());
8240   if (Invalid)
8241     ExDecl->setInvalidDecl();
8242
8243   // Add the exception declaration into this scope.
8244   if (II)
8245     PushOnScopeChains(ExDecl, S);
8246   else
8247     CurContext->addDecl(ExDecl);
8248
8249   ProcessDeclAttributes(S, ExDecl, D);
8250   return ExDecl;
8251 }
8252
8253 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
8254                                          Expr *AssertExpr,
8255                                          Expr *AssertMessageExpr_,
8256                                          SourceLocation RParenLoc) {
8257   StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
8258
8259   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
8260     llvm::APSInt Value(32);
8261     if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
8262       Diag(StaticAssertLoc,
8263            diag::err_static_assert_expression_is_not_constant) <<
8264         AssertExpr->getSourceRange();
8265       return 0;
8266     }
8267
8268     if (Value == 0) {
8269       Diag(StaticAssertLoc, diag::err_static_assert_failed)
8270         << AssertMessage->getString() << AssertExpr->getSourceRange();
8271     }
8272   }
8273
8274   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
8275     return 0;
8276
8277   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
8278                                         AssertExpr, AssertMessage, RParenLoc);
8279
8280   CurContext->addDecl(Decl);
8281   return Decl;
8282 }
8283
8284 /// \brief Perform semantic analysis of the given friend type declaration.
8285 ///
8286 /// \returns A friend declaration that.
8287 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc, 
8288                                       TypeSourceInfo *TSInfo) {
8289   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
8290   
8291   QualType T = TSInfo->getType();
8292   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
8293   
8294   if (!getLangOptions().CPlusPlus0x) {
8295     // C++03 [class.friend]p2:
8296     //   An elaborated-type-specifier shall be used in a friend declaration
8297     //   for a class.*
8298     //
8299     //   * The class-key of the elaborated-type-specifier is required.
8300     if (!ActiveTemplateInstantiations.empty()) {
8301       // Do not complain about the form of friend template types during
8302       // template instantiation; we will already have complained when the
8303       // template was declared.
8304     } else if (!T->isElaboratedTypeSpecifier()) {
8305       // If we evaluated the type to a record type, suggest putting
8306       // a tag in front.
8307       if (const RecordType *RT = T->getAs<RecordType>()) {
8308         RecordDecl *RD = RT->getDecl();
8309         
8310         std::string InsertionText = std::string(" ") + RD->getKindName();
8311         
8312         Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
8313           << (unsigned) RD->getTagKind()
8314           << T
8315           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
8316                                         InsertionText);
8317       } else {
8318         Diag(FriendLoc, diag::ext_nonclass_type_friend)
8319           << T
8320           << SourceRange(FriendLoc, TypeRange.getEnd());
8321       }
8322     } else if (T->getAs<EnumType>()) {
8323       Diag(FriendLoc, diag::ext_enum_friend)
8324         << T
8325         << SourceRange(FriendLoc, TypeRange.getEnd());
8326     }
8327   }
8328   
8329   // C++0x [class.friend]p3:
8330   //   If the type specifier in a friend declaration designates a (possibly
8331   //   cv-qualified) class type, that class is declared as a friend; otherwise, 
8332   //   the friend declaration is ignored.
8333   
8334   // FIXME: C++0x has some syntactic restrictions on friend type declarations
8335   // in [class.friend]p3 that we do not implement.
8336   
8337   return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
8338 }
8339
8340 /// Handle a friend tag declaration where the scope specifier was
8341 /// templated.
8342 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
8343                                     unsigned TagSpec, SourceLocation TagLoc,
8344                                     CXXScopeSpec &SS,
8345                                     IdentifierInfo *Name, SourceLocation NameLoc,
8346                                     AttributeList *Attr,
8347                                     MultiTemplateParamsArg TempParamLists) {
8348   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8349
8350   bool isExplicitSpecialization = false;
8351   bool Invalid = false;
8352
8353   if (TemplateParameterList *TemplateParams
8354         = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
8355                                                   TempParamLists.get(),
8356                                                   TempParamLists.size(),
8357                                                   /*friend*/ true,
8358                                                   isExplicitSpecialization,
8359                                                   Invalid)) {
8360     if (TemplateParams->size() > 0) {
8361       // This is a declaration of a class template.
8362       if (Invalid)
8363         return 0;
8364
8365       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
8366                                 SS, Name, NameLoc, Attr,
8367                                 TemplateParams, AS_public,
8368                                 TempParamLists.size() - 1,
8369                    (TemplateParameterList**) TempParamLists.release()).take();
8370     } else {
8371       // The "template<>" header is extraneous.
8372       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8373         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8374       isExplicitSpecialization = true;
8375     }
8376   }
8377
8378   if (Invalid) return 0;
8379
8380   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
8381
8382   bool isAllExplicitSpecializations = true;
8383   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
8384     if (TempParamLists.get()[I]->size()) {
8385       isAllExplicitSpecializations = false;
8386       break;
8387     }
8388   }
8389
8390   // FIXME: don't ignore attributes.
8391
8392   // If it's explicit specializations all the way down, just forget
8393   // about the template header and build an appropriate non-templated
8394   // friend.  TODO: for source fidelity, remember the headers.
8395   if (isAllExplicitSpecializations) {
8396     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8397     ElaboratedTypeKeyword Keyword
8398       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8399     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
8400                                    *Name, NameLoc);
8401     if (T.isNull())
8402       return 0;
8403
8404     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8405     if (isa<DependentNameType>(T)) {
8406       DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8407       TL.setKeywordLoc(TagLoc);
8408       TL.setQualifierLoc(QualifierLoc);
8409       TL.setNameLoc(NameLoc);
8410     } else {
8411       ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
8412       TL.setKeywordLoc(TagLoc);
8413       TL.setQualifierLoc(QualifierLoc);
8414       cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
8415     }
8416
8417     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8418                                             TSI, FriendLoc);
8419     Friend->setAccess(AS_public);
8420     CurContext->addDecl(Friend);
8421     return Friend;
8422   }
8423
8424   // Handle the case of a templated-scope friend class.  e.g.
8425   //   template <class T> class A<T>::B;
8426   // FIXME: we don't support these right now.
8427   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8428   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
8429   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8430   DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8431   TL.setKeywordLoc(TagLoc);
8432   TL.setQualifierLoc(SS.getWithLocInContext(Context));
8433   TL.setNameLoc(NameLoc);
8434
8435   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8436                                           TSI, FriendLoc);
8437   Friend->setAccess(AS_public);
8438   Friend->setUnsupportedFriend(true);
8439   CurContext->addDecl(Friend);
8440   return Friend;
8441 }
8442
8443
8444 /// Handle a friend type declaration.  This works in tandem with
8445 /// ActOnTag.
8446 ///
8447 /// Notes on friend class templates:
8448 ///
8449 /// We generally treat friend class declarations as if they were
8450 /// declaring a class.  So, for example, the elaborated type specifier
8451 /// in a friend declaration is required to obey the restrictions of a
8452 /// class-head (i.e. no typedefs in the scope chain), template
8453 /// parameters are required to match up with simple template-ids, &c.
8454 /// However, unlike when declaring a template specialization, it's
8455 /// okay to refer to a template specialization without an empty
8456 /// template parameter declaration, e.g.
8457 ///   friend class A<T>::B<unsigned>;
8458 /// We permit this as a special case; if there are any template
8459 /// parameters present at all, require proper matching, i.e.
8460 ///   template <> template <class T> friend class A<int>::B;
8461 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
8462                                 MultiTemplateParamsArg TempParams) {
8463   SourceLocation Loc = DS.getSourceRange().getBegin();
8464
8465   assert(DS.isFriendSpecified());
8466   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8467
8468   // Try to convert the decl specifier to a type.  This works for
8469   // friend templates because ActOnTag never produces a ClassTemplateDecl
8470   // for a TUK_Friend.
8471   Declarator TheDeclarator(DS, Declarator::MemberContext);
8472   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
8473   QualType T = TSI->getType();
8474   if (TheDeclarator.isInvalidType())
8475     return 0;
8476
8477   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
8478     return 0;
8479
8480   // This is definitely an error in C++98.  It's probably meant to
8481   // be forbidden in C++0x, too, but the specification is just
8482   // poorly written.
8483   //
8484   // The problem is with declarations like the following:
8485   //   template <T> friend A<T>::foo;
8486   // where deciding whether a class C is a friend or not now hinges
8487   // on whether there exists an instantiation of A that causes
8488   // 'foo' to equal C.  There are restrictions on class-heads
8489   // (which we declare (by fiat) elaborated friend declarations to
8490   // be) that makes this tractable.
8491   //
8492   // FIXME: handle "template <> friend class A<T>;", which
8493   // is possibly well-formed?  Who even knows?
8494   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
8495     Diag(Loc, diag::err_tagless_friend_type_template)
8496       << DS.getSourceRange();
8497     return 0;
8498   }
8499   
8500   // C++98 [class.friend]p1: A friend of a class is a function
8501   //   or class that is not a member of the class . . .
8502   // This is fixed in DR77, which just barely didn't make the C++03
8503   // deadline.  It's also a very silly restriction that seriously
8504   // affects inner classes and which nobody else seems to implement;
8505   // thus we never diagnose it, not even in -pedantic.
8506   //
8507   // But note that we could warn about it: it's always useless to
8508   // friend one of your own members (it's not, however, worthless to
8509   // friend a member of an arbitrary specialization of your template).
8510
8511   Decl *D;
8512   if (unsigned NumTempParamLists = TempParams.size())
8513     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
8514                                    NumTempParamLists,
8515                                    TempParams.release(),
8516                                    TSI,
8517                                    DS.getFriendSpecLoc());
8518   else
8519     D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
8520   
8521   if (!D)
8522     return 0;
8523   
8524   D->setAccess(AS_public);
8525   CurContext->addDecl(D);
8526
8527   return D;
8528 }
8529
8530 Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
8531                                     MultiTemplateParamsArg TemplateParams) {
8532   const DeclSpec &DS = D.getDeclSpec();
8533
8534   assert(DS.isFriendSpecified());
8535   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8536
8537   SourceLocation Loc = D.getIdentifierLoc();
8538   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8539   QualType T = TInfo->getType();
8540
8541   // C++ [class.friend]p1
8542   //   A friend of a class is a function or class....
8543   // Note that this sees through typedefs, which is intended.
8544   // It *doesn't* see through dependent types, which is correct
8545   // according to [temp.arg.type]p3:
8546   //   If a declaration acquires a function type through a
8547   //   type dependent on a template-parameter and this causes
8548   //   a declaration that does not use the syntactic form of a
8549   //   function declarator to have a function type, the program
8550   //   is ill-formed.
8551   if (!T->isFunctionType()) {
8552     Diag(Loc, diag::err_unexpected_friend);
8553
8554     // It might be worthwhile to try to recover by creating an
8555     // appropriate declaration.
8556     return 0;
8557   }
8558
8559   // C++ [namespace.memdef]p3
8560   //  - If a friend declaration in a non-local class first declares a
8561   //    class or function, the friend class or function is a member
8562   //    of the innermost enclosing namespace.
8563   //  - The name of the friend is not found by simple name lookup
8564   //    until a matching declaration is provided in that namespace
8565   //    scope (either before or after the class declaration granting
8566   //    friendship).
8567   //  - If a friend function is called, its name may be found by the
8568   //    name lookup that considers functions from namespaces and
8569   //    classes associated with the types of the function arguments.
8570   //  - When looking for a prior declaration of a class or a function
8571   //    declared as a friend, scopes outside the innermost enclosing
8572   //    namespace scope are not considered.
8573
8574   CXXScopeSpec &SS = D.getCXXScopeSpec();
8575   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8576   DeclarationName Name = NameInfo.getName();
8577   assert(Name);
8578
8579   // Check for unexpanded parameter packs.
8580   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
8581       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
8582       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
8583     return 0;
8584
8585   // The context we found the declaration in, or in which we should
8586   // create the declaration.
8587   DeclContext *DC;
8588   Scope *DCScope = S;
8589   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8590                         ForRedeclaration);
8591
8592   // FIXME: there are different rules in local classes
8593
8594   // There are four cases here.
8595   //   - There's no scope specifier, in which case we just go to the
8596   //     appropriate scope and look for a function or function template
8597   //     there as appropriate.
8598   // Recover from invalid scope qualifiers as if they just weren't there.
8599   if (SS.isInvalid() || !SS.isSet()) {
8600     // C++0x [namespace.memdef]p3:
8601     //   If the name in a friend declaration is neither qualified nor
8602     //   a template-id and the declaration is a function or an
8603     //   elaborated-type-specifier, the lookup to determine whether
8604     //   the entity has been previously declared shall not consider
8605     //   any scopes outside the innermost enclosing namespace.
8606     // C++0x [class.friend]p11:
8607     //   If a friend declaration appears in a local class and the name
8608     //   specified is an unqualified name, a prior declaration is
8609     //   looked up without considering scopes that are outside the
8610     //   innermost enclosing non-class scope. For a friend function
8611     //   declaration, if there is no prior declaration, the program is
8612     //   ill-formed.
8613     bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
8614     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
8615
8616     // Find the appropriate context according to the above.
8617     DC = CurContext;
8618     while (true) {
8619       // Skip class contexts.  If someone can cite chapter and verse
8620       // for this behavior, that would be nice --- it's what GCC and
8621       // EDG do, and it seems like a reasonable intent, but the spec
8622       // really only says that checks for unqualified existing
8623       // declarations should stop at the nearest enclosing namespace,
8624       // not that they should only consider the nearest enclosing
8625       // namespace.
8626       while (DC->isRecord()) 
8627         DC = DC->getParent();
8628
8629       LookupQualifiedName(Previous, DC);
8630
8631       // TODO: decide what we think about using declarations.
8632       if (isLocal || !Previous.empty())
8633         break;
8634
8635       if (isTemplateId) {
8636         if (isa<TranslationUnitDecl>(DC)) break;
8637       } else {
8638         if (DC->isFileContext()) break;
8639       }
8640       DC = DC->getParent();
8641     }
8642
8643     // C++ [class.friend]p1: A friend of a class is a function or
8644     //   class that is not a member of the class . . .
8645     // C++0x changes this for both friend types and functions.
8646     // Most C++ 98 compilers do seem to give an error here, so
8647     // we do, too.
8648     if (!Previous.empty() && DC->Equals(CurContext)
8649         && !getLangOptions().CPlusPlus0x)
8650       Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8651
8652     DCScope = getScopeForDeclContext(S, DC);
8653
8654   //   - There's a non-dependent scope specifier, in which case we
8655   //     compute it and do a previous lookup there for a function
8656   //     or function template.
8657   } else if (!SS.getScopeRep()->isDependent()) {
8658     DC = computeDeclContext(SS);
8659     if (!DC) return 0;
8660
8661     if (RequireCompleteDeclContext(SS, DC)) return 0;
8662
8663     LookupQualifiedName(Previous, DC);
8664
8665     // Ignore things found implicitly in the wrong scope.
8666     // TODO: better diagnostics for this case.  Suggesting the right
8667     // qualified scope would be nice...
8668     LookupResult::Filter F = Previous.makeFilter();
8669     while (F.hasNext()) {
8670       NamedDecl *D = F.next();
8671       if (!DC->InEnclosingNamespaceSetOf(
8672               D->getDeclContext()->getRedeclContext()))
8673         F.erase();
8674     }
8675     F.done();
8676
8677     if (Previous.empty()) {
8678       D.setInvalidType();
8679       Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
8680       return 0;
8681     }
8682
8683     // C++ [class.friend]p1: A friend of a class is a function or
8684     //   class that is not a member of the class . . .
8685     if (DC->Equals(CurContext))
8686       Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8687
8688   //   - There's a scope specifier that does not match any template
8689   //     parameter lists, in which case we use some arbitrary context,
8690   //     create a method or method template, and wait for instantiation.
8691   //   - There's a scope specifier that does match some template
8692   //     parameter lists, which we don't handle right now.
8693   } else {
8694     DC = CurContext;
8695     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
8696   }
8697
8698   if (!DC->isRecord()) {
8699     // This implies that it has to be an operator or function.
8700     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
8701         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
8702         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
8703       Diag(Loc, diag::err_introducing_special_friend) <<
8704         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
8705          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
8706       return 0;
8707     }
8708   }
8709
8710   bool Redeclaration = false;
8711   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
8712                                           move(TemplateParams),
8713                                           IsDefinition,
8714                                           Redeclaration);
8715   if (!ND) return 0;
8716
8717   assert(ND->getDeclContext() == DC);
8718   assert(ND->getLexicalDeclContext() == CurContext);
8719
8720   // Add the function declaration to the appropriate lookup tables,
8721   // adjusting the redeclarations list as necessary.  We don't
8722   // want to do this yet if the friending class is dependent.
8723   //
8724   // Also update the scope-based lookup if the target context's
8725   // lookup context is in lexical scope.
8726   if (!CurContext->isDependentContext()) {
8727     DC = DC->getRedeclContext();
8728     DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
8729     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
8730       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
8731   }
8732
8733   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
8734                                        D.getIdentifierLoc(), ND,
8735                                        DS.getFriendSpecLoc());
8736   FrD->setAccess(AS_public);
8737   CurContext->addDecl(FrD);
8738
8739   if (ND->isInvalidDecl())
8740     FrD->setInvalidDecl();
8741   else {
8742     FunctionDecl *FD;
8743     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
8744       FD = FTD->getTemplatedDecl();
8745     else
8746       FD = cast<FunctionDecl>(ND);
8747
8748     // Mark templated-scope function declarations as unsupported.
8749     if (FD->getNumTemplateParameterLists())
8750       FrD->setUnsupportedFriend(true);
8751   }
8752
8753   return ND;
8754 }
8755
8756 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
8757   AdjustDeclIfTemplate(Dcl);
8758
8759   FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
8760   if (!Fn) {
8761     Diag(DelLoc, diag::err_deleted_non_function);
8762     return;
8763   }
8764   if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
8765     Diag(DelLoc, diag::err_deleted_decl_not_first);
8766     Diag(Prev->getLocation(), diag::note_previous_declaration);
8767     // If the declaration wasn't the first, we delete the function anyway for
8768     // recovery.
8769   }
8770   Fn->setDeletedAsWritten();
8771 }
8772
8773 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
8774   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
8775
8776   if (MD) {
8777     if (MD->getParent()->isDependentType()) {
8778       MD->setDefaulted();
8779       MD->setExplicitlyDefaulted();
8780       return;
8781     }
8782
8783     CXXSpecialMember Member = getSpecialMember(MD);
8784     if (Member == CXXInvalid) {
8785       Diag(DefaultLoc, diag::err_default_special_members);
8786       return;
8787     }
8788
8789     MD->setDefaulted();
8790     MD->setExplicitlyDefaulted();
8791
8792     // If this definition appears within the record, do the checking when
8793     // the record is complete.
8794     const FunctionDecl *Primary = MD;
8795     if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
8796       // Find the uninstantiated declaration that actually had the '= default'
8797       // on it.
8798       MD->getTemplateInstantiationPattern()->isDefined(Primary);
8799
8800     if (Primary == Primary->getCanonicalDecl())
8801       return;
8802
8803     switch (Member) {
8804     case CXXDefaultConstructor: {
8805       CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8806       CheckExplicitlyDefaultedDefaultConstructor(CD);
8807       if (!CD->isInvalidDecl())
8808         DefineImplicitDefaultConstructor(DefaultLoc, CD);
8809       break;
8810     }
8811
8812     case CXXCopyConstructor: {
8813       CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8814       CheckExplicitlyDefaultedCopyConstructor(CD);
8815       if (!CD->isInvalidDecl())
8816         DefineImplicitCopyConstructor(DefaultLoc, CD);
8817       break;
8818     }
8819
8820     case CXXCopyAssignment: {
8821       CheckExplicitlyDefaultedCopyAssignment(MD);
8822       if (!MD->isInvalidDecl())
8823         DefineImplicitCopyAssignment(DefaultLoc, MD);
8824       break;
8825     }
8826
8827     case CXXDestructor: {
8828       CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
8829       CheckExplicitlyDefaultedDestructor(DD);
8830       if (!DD->isInvalidDecl())
8831         DefineImplicitDestructor(DefaultLoc, DD);
8832       break;
8833     }
8834
8835     case CXXMoveConstructor:
8836     case CXXMoveAssignment:
8837       Diag(Dcl->getLocation(), diag::err_defaulted_move_unsupported);
8838       break;
8839
8840     default:
8841       // FIXME: Do the rest once we have move functions
8842       break;
8843     }
8844   } else {
8845     Diag(DefaultLoc, diag::err_default_special_members);
8846   }
8847 }
8848
8849 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
8850   for (Stmt::child_range CI = S->children(); CI; ++CI) {
8851     Stmt *SubStmt = *CI;
8852     if (!SubStmt)
8853       continue;
8854     if (isa<ReturnStmt>(SubStmt))
8855       Self.Diag(SubStmt->getSourceRange().getBegin(),
8856            diag::err_return_in_constructor_handler);
8857     if (!isa<Expr>(SubStmt))
8858       SearchForReturnInStmt(Self, SubStmt);
8859   }
8860 }
8861
8862 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
8863   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
8864     CXXCatchStmt *Handler = TryBlock->getHandler(I);
8865     SearchForReturnInStmt(*this, Handler);
8866   }
8867 }
8868
8869 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
8870                                              const CXXMethodDecl *Old) {
8871   QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
8872   QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
8873
8874   if (Context.hasSameType(NewTy, OldTy) ||
8875       NewTy->isDependentType() || OldTy->isDependentType())
8876     return false;
8877
8878   // Check if the return types are covariant
8879   QualType NewClassTy, OldClassTy;
8880
8881   /// Both types must be pointers or references to classes.
8882   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
8883     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
8884       NewClassTy = NewPT->getPointeeType();
8885       OldClassTy = OldPT->getPointeeType();
8886     }
8887   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
8888     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
8889       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
8890         NewClassTy = NewRT->getPointeeType();
8891         OldClassTy = OldRT->getPointeeType();
8892       }
8893     }
8894   }
8895
8896   // The return types aren't either both pointers or references to a class type.
8897   if (NewClassTy.isNull()) {
8898     Diag(New->getLocation(),
8899          diag::err_different_return_type_for_overriding_virtual_function)
8900       << New->getDeclName() << NewTy << OldTy;
8901     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8902
8903     return true;
8904   }
8905
8906   // C++ [class.virtual]p6:
8907   //   If the return type of D::f differs from the return type of B::f, the 
8908   //   class type in the return type of D::f shall be complete at the point of
8909   //   declaration of D::f or shall be the class type D.
8910   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
8911     if (!RT->isBeingDefined() &&
8912         RequireCompleteType(New->getLocation(), NewClassTy, 
8913                             PDiag(diag::err_covariant_return_incomplete)
8914                               << New->getDeclName()))
8915     return true;
8916   }
8917
8918   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
8919     // Check if the new class derives from the old class.
8920     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
8921       Diag(New->getLocation(),
8922            diag::err_covariant_return_not_derived)
8923       << New->getDeclName() << NewTy << OldTy;
8924       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8925       return true;
8926     }
8927
8928     // Check if we the conversion from derived to base is valid.
8929     if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
8930                     diag::err_covariant_return_inaccessible_base,
8931                     diag::err_covariant_return_ambiguous_derived_to_base_conv,
8932                     // FIXME: Should this point to the return type?
8933                     New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
8934       // FIXME: this note won't trigger for delayed access control
8935       // diagnostics, and it's impossible to get an undelayed error
8936       // here from access control during the original parse because
8937       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
8938       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8939       return true;
8940     }
8941   }
8942
8943   // The qualifiers of the return types must be the same.
8944   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
8945     Diag(New->getLocation(),
8946          diag::err_covariant_return_type_different_qualifications)
8947     << New->getDeclName() << NewTy << OldTy;
8948     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8949     return true;
8950   };
8951
8952
8953   // The new class type must have the same or less qualifiers as the old type.
8954   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8955     Diag(New->getLocation(),
8956          diag::err_covariant_return_type_class_type_more_qualified)
8957     << New->getDeclName() << NewTy << OldTy;
8958     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8959     return true;
8960   };
8961
8962   return false;
8963 }
8964
8965 /// \brief Mark the given method pure.
8966 ///
8967 /// \param Method the method to be marked pure.
8968 ///
8969 /// \param InitRange the source range that covers the "0" initializer.
8970 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
8971   SourceLocation EndLoc = InitRange.getEnd();
8972   if (EndLoc.isValid())
8973     Method->setRangeEnd(EndLoc);
8974
8975   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8976     Method->setPure();
8977     return false;
8978   }
8979
8980   if (!Method->isInvalidDecl())
8981     Diag(Method->getLocation(), diag::err_non_virtual_pure)
8982       << Method->getDeclName() << InitRange;
8983   return true;
8984 }
8985
8986 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8987 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
8988 /// is a fresh scope pushed for just this purpose.
8989 ///
8990 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8991 /// static data member of class X, names should be looked up in the scope of
8992 /// class X.
8993 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
8994   // If there is no declaration, there was an error parsing it.
8995   if (D == 0 || D->isInvalidDecl()) return;
8996
8997   // We should only get called for declarations with scope specifiers, like:
8998   //   int foo::bar;
8999   assert(D->isOutOfLine());
9000   EnterDeclaratorContext(S, D->getDeclContext());
9001 }
9002
9003 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
9004 /// initializer for the out-of-line declaration 'D'.
9005 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
9006   // If there is no declaration, there was an error parsing it.
9007   if (D == 0 || D->isInvalidDecl()) return;
9008
9009   assert(D->isOutOfLine());
9010   ExitDeclaratorContext(S);
9011 }
9012
9013 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
9014 /// C++ if/switch/while/for statement.
9015 /// e.g: "if (int x = f()) {...}"
9016 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
9017   // C++ 6.4p2:
9018   // The declarator shall not specify a function or an array.
9019   // The type-specifier-seq shall not contain typedef and shall not declare a
9020   // new class or enumeration.
9021   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
9022          "Parser allowed 'typedef' as storage class of condition decl.");
9023   
9024   TagDecl *OwnedTag = 0;
9025   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
9026   QualType Ty = TInfo->getType();
9027   
9028   if (Ty->isFunctionType()) { // The declarator shall not specify a function...
9029                               // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
9030                               // would be created and CXXConditionDeclExpr wants a VarDecl.
9031     Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
9032       << D.getSourceRange();
9033     return DeclResult();
9034   } else if (OwnedTag && OwnedTag->isDefinition()) {
9035     // The type-specifier-seq shall not declare a new class or enumeration.
9036     Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
9037   }
9038   
9039   Decl *Dcl = ActOnDeclarator(S, D);
9040   if (!Dcl)
9041     return DeclResult();
9042
9043   return Dcl;
9044 }
9045
9046 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
9047                           bool DefinitionRequired) {
9048   // Ignore any vtable uses in unevaluated operands or for classes that do
9049   // not have a vtable.
9050   if (!Class->isDynamicClass() || Class->isDependentContext() ||
9051       CurContext->isDependentContext() ||
9052       ExprEvalContexts.back().Context == Unevaluated)
9053     return;
9054
9055   // Try to insert this class into the map.
9056   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9057   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
9058     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
9059   if (!Pos.second) {
9060     // If we already had an entry, check to see if we are promoting this vtable
9061     // to required a definition. If so, we need to reappend to the VTableUses
9062     // list, since we may have already processed the first entry.
9063     if (DefinitionRequired && !Pos.first->second) {
9064       Pos.first->second = true;
9065     } else {
9066       // Otherwise, we can early exit.
9067       return;
9068     }
9069   }
9070
9071   // Local classes need to have their virtual members marked
9072   // immediately. For all other classes, we mark their virtual members
9073   // at the end of the translation unit.
9074   if (Class->isLocalClass())
9075     MarkVirtualMembersReferenced(Loc, Class);
9076   else
9077     VTableUses.push_back(std::make_pair(Class, Loc));
9078 }
9079
9080 bool Sema::DefineUsedVTables() {
9081   if (VTableUses.empty())
9082     return false;
9083
9084   // Note: The VTableUses vector could grow as a result of marking
9085   // the members of a class as "used", so we check the size each
9086   // time through the loop and prefer indices (with are stable) to
9087   // iterators (which are not).
9088   bool DefinedAnything = false;
9089   for (unsigned I = 0; I != VTableUses.size(); ++I) {
9090     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
9091     if (!Class)
9092       continue;
9093
9094     SourceLocation Loc = VTableUses[I].second;
9095
9096     // If this class has a key function, but that key function is
9097     // defined in another translation unit, we don't need to emit the
9098     // vtable even though we're using it.
9099     const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
9100     if (KeyFunction && !KeyFunction->hasBody()) {
9101       switch (KeyFunction->getTemplateSpecializationKind()) {
9102       case TSK_Undeclared:
9103       case TSK_ExplicitSpecialization:
9104       case TSK_ExplicitInstantiationDeclaration:
9105         // The key function is in another translation unit.
9106         continue;
9107
9108       case TSK_ExplicitInstantiationDefinition:
9109       case TSK_ImplicitInstantiation:
9110         // We will be instantiating the key function.
9111         break;
9112       }
9113     } else if (!KeyFunction) {
9114       // If we have a class with no key function that is the subject
9115       // of an explicit instantiation declaration, suppress the
9116       // vtable; it will live with the explicit instantiation
9117       // definition.
9118       bool IsExplicitInstantiationDeclaration
9119         = Class->getTemplateSpecializationKind()
9120                                       == TSK_ExplicitInstantiationDeclaration;
9121       for (TagDecl::redecl_iterator R = Class->redecls_begin(),
9122                                  REnd = Class->redecls_end();
9123            R != REnd; ++R) {
9124         TemplateSpecializationKind TSK
9125           = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
9126         if (TSK == TSK_ExplicitInstantiationDeclaration)
9127           IsExplicitInstantiationDeclaration = true;
9128         else if (TSK == TSK_ExplicitInstantiationDefinition) {
9129           IsExplicitInstantiationDeclaration = false;
9130           break;
9131         }
9132       }
9133
9134       if (IsExplicitInstantiationDeclaration)
9135         continue;
9136     }
9137
9138     // Mark all of the virtual members of this class as referenced, so
9139     // that we can build a vtable. Then, tell the AST consumer that a
9140     // vtable for this class is required.
9141     DefinedAnything = true;
9142     MarkVirtualMembersReferenced(Loc, Class);
9143     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9144     Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
9145
9146     // Optionally warn if we're emitting a weak vtable.
9147     if (Class->getLinkage() == ExternalLinkage &&
9148         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
9149       if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
9150         Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
9151     }
9152   }
9153   VTableUses.clear();
9154
9155   return DefinedAnything;
9156 }
9157
9158 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
9159                                         const CXXRecordDecl *RD) {
9160   for (CXXRecordDecl::method_iterator i = RD->method_begin(), 
9161        e = RD->method_end(); i != e; ++i) {
9162     CXXMethodDecl *MD = *i;
9163
9164     // C++ [basic.def.odr]p2:
9165     //   [...] A virtual member function is used if it is not pure. [...]
9166     if (MD->isVirtual() && !MD->isPure())
9167       MarkDeclarationReferenced(Loc, MD);
9168   }
9169
9170   // Only classes that have virtual bases need a VTT.
9171   if (RD->getNumVBases() == 0)
9172     return;
9173
9174   for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
9175            e = RD->bases_end(); i != e; ++i) {
9176     const CXXRecordDecl *Base =
9177         cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
9178     if (Base->getNumVBases() == 0)
9179       continue;
9180     MarkVirtualMembersReferenced(Loc, Base);
9181   }
9182 }
9183
9184 /// SetIvarInitializers - This routine builds initialization ASTs for the
9185 /// Objective-C implementation whose ivars need be initialized.
9186 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
9187   if (!getLangOptions().CPlusPlus)
9188     return;
9189   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
9190     llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
9191     CollectIvarsToConstructOrDestruct(OID, ivars);
9192     if (ivars.empty())
9193       return;
9194     llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
9195     for (unsigned i = 0; i < ivars.size(); i++) {
9196       FieldDecl *Field = ivars[i];
9197       if (Field->isInvalidDecl())
9198         continue;
9199       
9200       CXXCtorInitializer *Member;
9201       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
9202       InitializationKind InitKind = 
9203         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
9204       
9205       InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
9206       ExprResult MemberInit = 
9207         InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
9208       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
9209       // Note, MemberInit could actually come back empty if no initialization 
9210       // is required (e.g., because it would call a trivial default constructor)
9211       if (!MemberInit.get() || MemberInit.isInvalid())
9212         continue;
9213
9214       Member =
9215         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
9216                                          SourceLocation(),
9217                                          MemberInit.takeAs<Expr>(),
9218                                          SourceLocation());
9219       AllToInit.push_back(Member);
9220       
9221       // Be sure that the destructor is accessible and is marked as referenced.
9222       if (const RecordType *RecordTy
9223                   = Context.getBaseElementType(Field->getType())
9224                                                         ->getAs<RecordType>()) {
9225                     CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
9226         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
9227           MarkDeclarationReferenced(Field->getLocation(), Destructor);
9228           CheckDestructorAccess(Field->getLocation(), Destructor,
9229                             PDiag(diag::err_access_dtor_ivar)
9230                               << Context.getBaseElementType(Field->getType()));
9231         }
9232       }      
9233     }
9234     ObjCImplementation->setIvarInitializers(Context, 
9235                                             AllToInit.data(), AllToInit.size());
9236   }
9237 }
9238
9239 static
9240 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
9241                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
9242                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
9243                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
9244                            Sema &S) {
9245   llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9246                                                    CE = Current.end();
9247   if (Ctor->isInvalidDecl())
9248     return;
9249
9250   const FunctionDecl *FNTarget = 0;
9251   CXXConstructorDecl *Target;
9252   
9253   // We ignore the result here since if we don't have a body, Target will be
9254   // null below.
9255   (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
9256   Target
9257 = const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
9258
9259   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
9260                      // Avoid dereferencing a null pointer here.
9261                      *TCanonical = Target ? Target->getCanonicalDecl() : 0;
9262
9263   if (!Current.insert(Canonical))
9264     return;
9265
9266   // We know that beyond here, we aren't chaining into a cycle.
9267   if (!Target || !Target->isDelegatingConstructor() ||
9268       Target->isInvalidDecl() || Valid.count(TCanonical)) {
9269     for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9270       Valid.insert(*CI);
9271     Current.clear();
9272   // We've hit a cycle.
9273   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
9274              Current.count(TCanonical)) {
9275     // If we haven't diagnosed this cycle yet, do so now.
9276     if (!Invalid.count(TCanonical)) {
9277       S.Diag((*Ctor->init_begin())->getSourceLocation(),
9278              diag::warn_delegating_ctor_cycle)
9279         << Ctor;
9280
9281       // Don't add a note for a function delegating directo to itself.
9282       if (TCanonical != Canonical)
9283         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
9284
9285       CXXConstructorDecl *C = Target;
9286       while (C->getCanonicalDecl() != Canonical) {
9287         (void)C->getTargetConstructor()->hasBody(FNTarget);
9288         assert(FNTarget && "Ctor cycle through bodiless function");
9289
9290         C
9291        = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
9292         S.Diag(C->getLocation(), diag::note_which_delegates_to);
9293       }
9294     }
9295
9296     for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9297       Invalid.insert(*CI);
9298     Current.clear();
9299   } else {
9300     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
9301   }
9302 }
9303    
9304
9305 void Sema::CheckDelegatingCtorCycles() {
9306   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
9307
9308   llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9309                                                    CE = Current.end();
9310
9311   for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
9312          I = DelegatingCtorDecls.begin(),
9313          E = DelegatingCtorDecls.end();
9314        I != E; ++I) {
9315    DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
9316   }
9317
9318   for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
9319     (*CI)->setInvalidDecl();
9320 }