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/Sema/ScopeInfo.h"
20 #include "clang/AST/ASTConsumer.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/ASTMutationListener.h"
23 #include "clang/AST/CharUnits.h"
24 #include "clang/AST/CXXInheritance.h"
25 #include "clang/AST/DeclVisitor.h"
26 #include "clang/AST/EvaluatedExprVisitor.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/RecordLayout.h"
29 #include "clang/AST/RecursiveASTVisitor.h"
30 #include "clang/AST/StmtVisitor.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/AST/TypeOrdering.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/ParsedTemplate.h"
35 #include "clang/Basic/PartialDiagnostic.h"
36 #include "clang/Lex/Preprocessor.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include <map>
40 #include <set>
41 
42 using namespace clang;
43 
44 //===----------------------------------------------------------------------===//
45 // CheckDefaultArgumentVisitor
46 //===----------------------------------------------------------------------===//
47 
48 namespace {
49   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
50   /// the default argument of a parameter to determine whether it
51   /// contains any ill-formed subexpressions. For example, this will
52   /// diagnose the use of local variables or parameters within the
53   /// default argument expression.
54   class CheckDefaultArgumentVisitor
55     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
56     Expr *DefaultArg;
57     Sema *S;
58 
59   public:
60     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
61       : DefaultArg(defarg), S(s) {}
62 
63     bool VisitExpr(Expr *Node);
64     bool VisitDeclRefExpr(DeclRefExpr *DRE);
65     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
66     bool VisitLambdaExpr(LambdaExpr *Lambda);
67   };
68 
69   /// VisitExpr - Visit all of the children of this expression.
70   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
71     bool IsInvalid = false;
72     for (Stmt::child_range I = Node->children(); I; ++I)
73       IsInvalid |= Visit(*I);
74     return IsInvalid;
75   }
76 
77   /// VisitDeclRefExpr - Visit a reference to a declaration, to
78   /// determine whether this declaration can be used in the default
79   /// argument expression.
80   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
81     NamedDecl *Decl = DRE->getDecl();
82     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
83       // C++ [dcl.fct.default]p9
84       //   Default arguments are evaluated each time the function is
85       //   called. The order of evaluation of function arguments is
86       //   unspecified. Consequently, parameters of a function shall not
87       //   be used in default argument expressions, even if they are not
88       //   evaluated. Parameters of a function declared before a default
89       //   argument expression are in scope and can hide namespace and
90       //   class member names.
91       return S->Diag(DRE->getLocStart(),
92                      diag::err_param_default_argument_references_param)
93          << Param->getDeclName() << DefaultArg->getSourceRange();
94     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
95       // C++ [dcl.fct.default]p7
96       //   Local variables shall not be used in default argument
97       //   expressions.
98       if (VDecl->isLocalVarDecl())
99         return S->Diag(DRE->getLocStart(),
100                        diag::err_param_default_argument_references_local)
101           << VDecl->getDeclName() << DefaultArg->getSourceRange();
102     }
103 
104     return false;
105   }
106 
107   /// VisitCXXThisExpr - Visit a C++ "this" expression.
108   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
109     // C++ [dcl.fct.default]p8:
110     //   The keyword this shall not be used in a default argument of a
111     //   member function.
112     return S->Diag(ThisE->getLocStart(),
113                    diag::err_param_default_argument_references_this)
114                << ThisE->getSourceRange();
115   }
116 
117   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
118     // C++11 [expr.lambda.prim]p13:
119     //   A lambda-expression appearing in a default argument shall not
120     //   implicitly or explicitly capture any entity.
121     if (Lambda->capture_begin() == Lambda->capture_end())
122       return false;
123 
124     return S->Diag(Lambda->getLocStart(),
125                    diag::err_lambda_capture_default_arg);
126   }
127 }
128 
129 void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
130                                                       CXXMethodDecl *Method) {
131   // If we have an MSAny spec already, don't bother.
132   if (!Method || ComputedEST == EST_MSAny)
133     return;
134 
135   const FunctionProtoType *Proto
136     = Method->getType()->getAs<FunctionProtoType>();
137   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
138   if (!Proto)
139     return;
140 
141   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
142 
143   // If this function can throw any exceptions, make a note of that.
144   if (EST == EST_MSAny || EST == EST_None) {
145     ClearExceptions();
146     ComputedEST = EST;
147     return;
148   }
149 
150   // FIXME: If the call to this decl is using any of its default arguments, we
151   // need to search them for potentially-throwing calls.
152 
153   // If this function has a basic noexcept, it doesn't affect the outcome.
154   if (EST == EST_BasicNoexcept)
155     return;
156 
157   // If we have a throw-all spec at this point, ignore the function.
158   if (ComputedEST == EST_None)
159     return;
160 
161   // If we're still at noexcept(true) and there's a nothrow() callee,
162   // change to that specification.
163   if (EST == EST_DynamicNone) {
164     if (ComputedEST == EST_BasicNoexcept)
165       ComputedEST = EST_DynamicNone;
166     return;
167   }
168 
169   // Check out noexcept specs.
170   if (EST == EST_ComputedNoexcept) {
171     FunctionProtoType::NoexceptResult NR =
172         Proto->getNoexceptSpec(Self->Context);
173     assert(NR != FunctionProtoType::NR_NoNoexcept &&
174            "Must have noexcept result for EST_ComputedNoexcept.");
175     assert(NR != FunctionProtoType::NR_Dependent &&
176            "Should not generate implicit declarations for dependent cases, "
177            "and don't know how to handle them anyway.");
178 
179     // noexcept(false) -> no spec on the new function
180     if (NR == FunctionProtoType::NR_Throw) {
181       ClearExceptions();
182       ComputedEST = EST_None;
183     }
184     // noexcept(true) won't change anything either.
185     return;
186   }
187 
188   assert(EST == EST_Dynamic && "EST case not considered earlier.");
189   assert(ComputedEST != EST_None &&
190          "Shouldn't collect exceptions when throw-all is guaranteed.");
191   ComputedEST = EST_Dynamic;
192   // Record the exceptions in this function's exception specification.
193   for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
194                                           EEnd = Proto->exception_end();
195        E != EEnd; ++E)
196     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
197       Exceptions.push_back(*E);
198 }
199 
200 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
201   if (!E || ComputedEST == EST_MSAny)
202     return;
203 
204   // FIXME:
205   //
206   // C++0x [except.spec]p14:
207   //   [An] implicit exception-specification specifies the type-id T if and
208   // only if T is allowed by the exception-specification of a function directly
209   // invoked by f's implicit definition; f shall allow all exceptions if any
210   // function it directly invokes allows all exceptions, and f shall allow no
211   // exceptions if every function it directly invokes allows no exceptions.
212   //
213   // Note in particular that if an implicit exception-specification is generated
214   // for a function containing a throw-expression, that specification can still
215   // be noexcept(true).
216   //
217   // Note also that 'directly invoked' is not defined in the standard, and there
218   // is no indication that we should only consider potentially-evaluated calls.
219   //
220   // Ultimately we should implement the intent of the standard: the exception
221   // specification should be the set of exceptions which can be thrown by the
222   // implicit definition. For now, we assume that any non-nothrow expression can
223   // throw any exception.
224 
225   if (Self->canThrow(E))
226     ComputedEST = EST_None;
227 }
228 
229 bool
230 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
231                               SourceLocation EqualLoc) {
232   if (RequireCompleteType(Param->getLocation(), Param->getType(),
233                           diag::err_typecheck_decl_incomplete_type)) {
234     Param->setInvalidDecl();
235     return true;
236   }
237 
238   // C++ [dcl.fct.default]p5
239   //   A default argument expression is implicitly converted (clause
240   //   4) to the parameter type. The default argument expression has
241   //   the same semantic constraints as the initializer expression in
242   //   a declaration of a variable of the parameter type, using the
243   //   copy-initialization semantics (8.5).
244   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
245                                                                     Param);
246   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
247                                                            EqualLoc);
248   InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
249   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
250   if (Result.isInvalid())
251     return true;
252   Arg = Result.takeAs<Expr>();
253 
254   CheckImplicitConversions(Arg, EqualLoc);
255   Arg = MaybeCreateExprWithCleanups(Arg);
256 
257   // Okay: add the default argument to the parameter
258   Param->setDefaultArg(Arg);
259 
260   // We have already instantiated this parameter; provide each of the
261   // instantiations with the uninstantiated default argument.
262   UnparsedDefaultArgInstantiationsMap::iterator InstPos
263     = UnparsedDefaultArgInstantiations.find(Param);
264   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
265     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
266       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
267 
268     // We're done tracking this parameter's instantiations.
269     UnparsedDefaultArgInstantiations.erase(InstPos);
270   }
271 
272   return false;
273 }
274 
275 /// ActOnParamDefaultArgument - Check whether the default argument
276 /// provided for a function parameter is well-formed. If so, attach it
277 /// to the parameter declaration.
278 void
279 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
280                                 Expr *DefaultArg) {
281   if (!param || !DefaultArg)
282     return;
283 
284   ParmVarDecl *Param = cast<ParmVarDecl>(param);
285   UnparsedDefaultArgLocs.erase(Param);
286 
287   // Default arguments are only permitted in C++
288   if (!getLangOpts().CPlusPlus) {
289     Diag(EqualLoc, diag::err_param_default_argument)
290       << DefaultArg->getSourceRange();
291     Param->setInvalidDecl();
292     return;
293   }
294 
295   // Check for unexpanded parameter packs.
296   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
297     Param->setInvalidDecl();
298     return;
299   }
300 
301   // Check that the default argument is well-formed
302   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
303   if (DefaultArgChecker.Visit(DefaultArg)) {
304     Param->setInvalidDecl();
305     return;
306   }
307 
308   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
309 }
310 
311 /// ActOnParamUnparsedDefaultArgument - We've seen a default
312 /// argument for a function parameter, but we can't parse it yet
313 /// because we're inside a class definition. Note that this default
314 /// argument will be parsed later.
315 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
316                                              SourceLocation EqualLoc,
317                                              SourceLocation ArgLoc) {
318   if (!param)
319     return;
320 
321   ParmVarDecl *Param = cast<ParmVarDecl>(param);
322   if (Param)
323     Param->setUnparsedDefaultArg();
324 
325   UnparsedDefaultArgLocs[Param] = ArgLoc;
326 }
327 
328 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
329 /// the default argument for the parameter param failed.
330 void Sema::ActOnParamDefaultArgumentError(Decl *param) {
331   if (!param)
332     return;
333 
334   ParmVarDecl *Param = cast<ParmVarDecl>(param);
335 
336   Param->setInvalidDecl();
337 
338   UnparsedDefaultArgLocs.erase(Param);
339 }
340 
341 /// CheckExtraCXXDefaultArguments - Check for any extra default
342 /// arguments in the declarator, which is not a function declaration
343 /// or definition and therefore is not permitted to have default
344 /// arguments. This routine should be invoked for every declarator
345 /// that is not a function declaration or definition.
346 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
347   // C++ [dcl.fct.default]p3
348   //   A default argument expression shall be specified only in the
349   //   parameter-declaration-clause of a function declaration or in a
350   //   template-parameter (14.1). It shall not be specified for a
351   //   parameter pack. If it is specified in a
352   //   parameter-declaration-clause, it shall not occur within a
353   //   declarator or abstract-declarator of a parameter-declaration.
354   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
355     DeclaratorChunk &chunk = D.getTypeObject(i);
356     if (chunk.Kind == DeclaratorChunk::Function) {
357       for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
358         ParmVarDecl *Param =
359           cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
360         if (Param->hasUnparsedDefaultArg()) {
361           CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
362           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
363             << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
364           delete Toks;
365           chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
366         } else if (Param->getDefaultArg()) {
367           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
368             << Param->getDefaultArg()->getSourceRange();
369           Param->setDefaultArg(0);
370         }
371       }
372     }
373   }
374 }
375 
376 // MergeCXXFunctionDecl - Merge two declarations of the same C++
377 // function, once we already know that they have the same
378 // type. Subroutine of MergeFunctionDecl. Returns true if there was an
379 // error, false otherwise.
380 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
381                                 Scope *S) {
382   bool Invalid = false;
383 
384   // C++ [dcl.fct.default]p4:
385   //   For non-template functions, default arguments can be added in
386   //   later declarations of a function in the same
387   //   scope. Declarations in different scopes have completely
388   //   distinct sets of default arguments. That is, declarations in
389   //   inner scopes do not acquire default arguments from
390   //   declarations in outer scopes, and vice versa. In a given
391   //   function declaration, all parameters subsequent to a
392   //   parameter with a default argument shall have default
393   //   arguments supplied in this or previous declarations. A
394   //   default argument shall not be redefined by a later
395   //   declaration (not even to the same value).
396   //
397   // C++ [dcl.fct.default]p6:
398   //   Except for member functions of class templates, the default arguments
399   //   in a member function definition that appears outside of the class
400   //   definition are added to the set of default arguments provided by the
401   //   member function declaration in the class definition.
402   for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
403     ParmVarDecl *OldParam = Old->getParamDecl(p);
404     ParmVarDecl *NewParam = New->getParamDecl(p);
405 
406     bool OldParamHasDfl = OldParam->hasDefaultArg();
407     bool NewParamHasDfl = NewParam->hasDefaultArg();
408 
409     NamedDecl *ND = Old;
410     if (S && !isDeclInScope(ND, New->getDeclContext(), S))
411       // Ignore default parameters of old decl if they are not in
412       // the same scope.
413       OldParamHasDfl = false;
414 
415     if (OldParamHasDfl && NewParamHasDfl) {
416 
417       unsigned DiagDefaultParamID =
418         diag::err_param_default_argument_redefinition;
419 
420       // MSVC accepts that default parameters be redefined for member functions
421       // of template class. The new default parameter's value is ignored.
422       Invalid = true;
423       if (getLangOpts().MicrosoftExt) {
424         CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
425         if (MD && MD->getParent()->getDescribedClassTemplate()) {
426           // Merge the old default argument into the new parameter.
427           NewParam->setHasInheritedDefaultArg();
428           if (OldParam->hasUninstantiatedDefaultArg())
429             NewParam->setUninstantiatedDefaultArg(
430                                       OldParam->getUninstantiatedDefaultArg());
431           else
432             NewParam->setDefaultArg(OldParam->getInit());
433           DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
434           Invalid = false;
435         }
436       }
437 
438       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
439       // hint here. Alternatively, we could walk the type-source information
440       // for NewParam to find the last source location in the type... but it
441       // isn't worth the effort right now. This is the kind of test case that
442       // is hard to get right:
443       //   int f(int);
444       //   void g(int (*fp)(int) = f);
445       //   void g(int (*fp)(int) = &f);
446       Diag(NewParam->getLocation(), DiagDefaultParamID)
447         << NewParam->getDefaultArgRange();
448 
449       // Look for the function declaration where the default argument was
450       // actually written, which may be a declaration prior to Old.
451       for (FunctionDecl *Older = Old->getPreviousDecl();
452            Older; Older = Older->getPreviousDecl()) {
453         if (!Older->getParamDecl(p)->hasDefaultArg())
454           break;
455 
456         OldParam = Older->getParamDecl(p);
457       }
458 
459       Diag(OldParam->getLocation(), diag::note_previous_definition)
460         << OldParam->getDefaultArgRange();
461     } else if (OldParamHasDfl) {
462       // Merge the old default argument into the new parameter.
463       // It's important to use getInit() here;  getDefaultArg()
464       // strips off any top-level ExprWithCleanups.
465       NewParam->setHasInheritedDefaultArg();
466       if (OldParam->hasUninstantiatedDefaultArg())
467         NewParam->setUninstantiatedDefaultArg(
468                                       OldParam->getUninstantiatedDefaultArg());
469       else
470         NewParam->setDefaultArg(OldParam->getInit());
471     } else if (NewParamHasDfl) {
472       if (New->getDescribedFunctionTemplate()) {
473         // Paragraph 4, quoted above, only applies to non-template functions.
474         Diag(NewParam->getLocation(),
475              diag::err_param_default_argument_template_redecl)
476           << NewParam->getDefaultArgRange();
477         Diag(Old->getLocation(), diag::note_template_prev_declaration)
478           << false;
479       } else if (New->getTemplateSpecializationKind()
480                    != TSK_ImplicitInstantiation &&
481                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
482         // C++ [temp.expr.spec]p21:
483         //   Default function arguments shall not be specified in a declaration
484         //   or a definition for one of the following explicit specializations:
485         //     - the explicit specialization of a function template;
486         //     - the explicit specialization of a member function template;
487         //     - the explicit specialization of a member function of a class
488         //       template where the class template specialization to which the
489         //       member function specialization belongs is implicitly
490         //       instantiated.
491         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
492           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
493           << New->getDeclName()
494           << NewParam->getDefaultArgRange();
495       } else if (New->getDeclContext()->isDependentContext()) {
496         // C++ [dcl.fct.default]p6 (DR217):
497         //   Default arguments for a member function of a class template shall
498         //   be specified on the initial declaration of the member function
499         //   within the class template.
500         //
501         // Reading the tea leaves a bit in DR217 and its reference to DR205
502         // leads me to the conclusion that one cannot add default function
503         // arguments for an out-of-line definition of a member function of a
504         // dependent type.
505         int WhichKind = 2;
506         if (CXXRecordDecl *Record
507               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
508           if (Record->getDescribedClassTemplate())
509             WhichKind = 0;
510           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
511             WhichKind = 1;
512           else
513             WhichKind = 2;
514         }
515 
516         Diag(NewParam->getLocation(),
517              diag::err_param_default_argument_member_template_redecl)
518           << WhichKind
519           << NewParam->getDefaultArgRange();
520       } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
521         CXXSpecialMember NewSM = getSpecialMember(Ctor),
522                          OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
523         if (NewSM != OldSM) {
524           Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
525             << NewParam->getDefaultArgRange() << NewSM;
526           Diag(Old->getLocation(), diag::note_previous_declaration_special)
527             << OldSM;
528         }
529       }
530     }
531   }
532 
533   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
534   // template has a constexpr specifier then all its declarations shall
535   // contain the constexpr specifier.
536   if (New->isConstexpr() != Old->isConstexpr()) {
537     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
538       << New << New->isConstexpr();
539     Diag(Old->getLocation(), diag::note_previous_declaration);
540     Invalid = true;
541   }
542 
543   if (CheckEquivalentExceptionSpec(Old, New))
544     Invalid = true;
545 
546   return Invalid;
547 }
548 
549 /// \brief Merge the exception specifications of two variable declarations.
550 ///
551 /// This is called when there's a redeclaration of a VarDecl. The function
552 /// checks if the redeclaration might have an exception specification and
553 /// validates compatibility and merges the specs if necessary.
554 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
555   // Shortcut if exceptions are disabled.
556   if (!getLangOpts().CXXExceptions)
557     return;
558 
559   assert(Context.hasSameType(New->getType(), Old->getType()) &&
560          "Should only be called if types are otherwise the same.");
561 
562   QualType NewType = New->getType();
563   QualType OldType = Old->getType();
564 
565   // We're only interested in pointers and references to functions, as well
566   // as pointers to member functions.
567   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
568     NewType = R->getPointeeType();
569     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
570   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
571     NewType = P->getPointeeType();
572     OldType = OldType->getAs<PointerType>()->getPointeeType();
573   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
574     NewType = M->getPointeeType();
575     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
576   }
577 
578   if (!NewType->isFunctionProtoType())
579     return;
580 
581   // There's lots of special cases for functions. For function pointers, system
582   // libraries are hopefully not as broken so that we don't need these
583   // workarounds.
584   if (CheckEquivalentExceptionSpec(
585         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
586         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
587     New->setInvalidDecl();
588   }
589 }
590 
591 /// CheckCXXDefaultArguments - Verify that the default arguments for a
592 /// function declaration are well-formed according to C++
593 /// [dcl.fct.default].
594 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
595   unsigned NumParams = FD->getNumParams();
596   unsigned p;
597 
598   bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
599                   isa<CXXMethodDecl>(FD) &&
600                   cast<CXXMethodDecl>(FD)->getParent()->isLambda();
601 
602   // Find first parameter with a default argument
603   for (p = 0; p < NumParams; ++p) {
604     ParmVarDecl *Param = FD->getParamDecl(p);
605     if (Param->hasDefaultArg()) {
606       // C++11 [expr.prim.lambda]p5:
607       //   [...] Default arguments (8.3.6) shall not be specified in the
608       //   parameter-declaration-clause of a lambda-declarator.
609       //
610       // FIXME: Core issue 974 strikes this sentence, we only provide an
611       // extension warning.
612       if (IsLambda)
613         Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
614           << Param->getDefaultArgRange();
615       break;
616     }
617   }
618 
619   // C++ [dcl.fct.default]p4:
620   //   In a given function declaration, all parameters
621   //   subsequent to a parameter with a default argument shall
622   //   have default arguments supplied in this or previous
623   //   declarations. A default argument shall not be redefined
624   //   by a later declaration (not even to the same value).
625   unsigned LastMissingDefaultArg = 0;
626   for (; p < NumParams; ++p) {
627     ParmVarDecl *Param = FD->getParamDecl(p);
628     if (!Param->hasDefaultArg()) {
629       if (Param->isInvalidDecl())
630         /* We already complained about this parameter. */;
631       else if (Param->getIdentifier())
632         Diag(Param->getLocation(),
633              diag::err_param_default_argument_missing_name)
634           << Param->getIdentifier();
635       else
636         Diag(Param->getLocation(),
637              diag::err_param_default_argument_missing);
638 
639       LastMissingDefaultArg = p;
640     }
641   }
642 
643   if (LastMissingDefaultArg > 0) {
644     // Some default arguments were missing. Clear out all of the
645     // default arguments up to (and including) the last missing
646     // default argument, so that we leave the function parameters
647     // in a semantically valid state.
648     for (p = 0; p <= LastMissingDefaultArg; ++p) {
649       ParmVarDecl *Param = FD->getParamDecl(p);
650       if (Param->hasDefaultArg()) {
651         Param->setDefaultArg(0);
652       }
653     }
654   }
655 }
656 
657 // CheckConstexprParameterTypes - Check whether a function's parameter types
658 // are all literal types. If so, return true. If not, produce a suitable
659 // diagnostic and return false.
660 static bool CheckConstexprParameterTypes(Sema &SemaRef,
661                                          const FunctionDecl *FD) {
662   unsigned ArgIndex = 0;
663   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
664   for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
665        e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
666     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
667     SourceLocation ParamLoc = PD->getLocation();
668     if (!(*i)->isDependentType() &&
669         SemaRef.RequireLiteralType(ParamLoc, *i,
670                                    diag::err_constexpr_non_literal_param,
671                                    ArgIndex+1, PD->getSourceRange(),
672                                    isa<CXXConstructorDecl>(FD)))
673       return false;
674   }
675   return true;
676 }
677 
678 /// \brief Get diagnostic %select index for tag kind for
679 /// record diagnostic message.
680 /// WARNING: Indexes apply to particular diagnostics only!
681 ///
682 /// \returns diagnostic %select index.
683 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
684   switch (Tag) {
685   case TTK_Struct: return 0;
686   case TTK_Interface: return 1;
687   case TTK_Class:  return 2;
688   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
689   }
690 }
691 
692 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
693 // the requirements of a constexpr function definition or a constexpr
694 // constructor definition. If so, return true. If not, produce appropriate
695 // diagnostics and return false.
696 //
697 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
698 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
699   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
700   if (MD && MD->isInstance()) {
701     // C++11 [dcl.constexpr]p4:
702     //  The definition of a constexpr constructor shall satisfy the following
703     //  constraints:
704     //  - the class shall not have any virtual base classes;
705     const CXXRecordDecl *RD = MD->getParent();
706     if (RD->getNumVBases()) {
707       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
708         << isa<CXXConstructorDecl>(NewFD)
709         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
710       for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
711              E = RD->vbases_end(); I != E; ++I)
712         Diag(I->getLocStart(),
713              diag::note_constexpr_virtual_base_here) << I->getSourceRange();
714       return false;
715     }
716   }
717 
718   if (!isa<CXXConstructorDecl>(NewFD)) {
719     // C++11 [dcl.constexpr]p3:
720     //  The definition of a constexpr function shall satisfy the following
721     //  constraints:
722     // - it shall not be virtual;
723     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
724     if (Method && Method->isVirtual()) {
725       Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
726 
727       // If it's not obvious why this function is virtual, find an overridden
728       // function which uses the 'virtual' keyword.
729       const CXXMethodDecl *WrittenVirtual = Method;
730       while (!WrittenVirtual->isVirtualAsWritten())
731         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
732       if (WrittenVirtual != Method)
733         Diag(WrittenVirtual->getLocation(),
734              diag::note_overridden_virtual_function);
735       return false;
736     }
737 
738     // - its return type shall be a literal type;
739     QualType RT = NewFD->getResultType();
740     if (!RT->isDependentType() &&
741         RequireLiteralType(NewFD->getLocation(), RT,
742                            diag::err_constexpr_non_literal_return))
743       return false;
744   }
745 
746   // - each of its parameter types shall be a literal type;
747   if (!CheckConstexprParameterTypes(*this, NewFD))
748     return false;
749 
750   return true;
751 }
752 
753 /// Check the given declaration statement is legal within a constexpr function
754 /// body. C++0x [dcl.constexpr]p3,p4.
755 ///
756 /// \return true if the body is OK, false if we have diagnosed a problem.
757 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
758                                    DeclStmt *DS) {
759   // C++0x [dcl.constexpr]p3 and p4:
760   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
761   //  contain only
762   for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
763          DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
764     switch ((*DclIt)->getKind()) {
765     case Decl::StaticAssert:
766     case Decl::Using:
767     case Decl::UsingShadow:
768     case Decl::UsingDirective:
769     case Decl::UnresolvedUsingTypename:
770       //   - static_assert-declarations
771       //   - using-declarations,
772       //   - using-directives,
773       continue;
774 
775     case Decl::Typedef:
776     case Decl::TypeAlias: {
777       //   - typedef declarations and alias-declarations that do not define
778       //     classes or enumerations,
779       TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
780       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
781         // Don't allow variably-modified types in constexpr functions.
782         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
783         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
784           << TL.getSourceRange() << TL.getType()
785           << isa<CXXConstructorDecl>(Dcl);
786         return false;
787       }
788       continue;
789     }
790 
791     case Decl::Enum:
792     case Decl::CXXRecord:
793       // As an extension, we allow the declaration (but not the definition) of
794       // classes and enumerations in all declarations, not just in typedef and
795       // alias declarations.
796       if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
797         SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
798           << isa<CXXConstructorDecl>(Dcl);
799         return false;
800       }
801       continue;
802 
803     case Decl::Var:
804       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
805         << isa<CXXConstructorDecl>(Dcl);
806       return false;
807 
808     default:
809       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
810         << isa<CXXConstructorDecl>(Dcl);
811       return false;
812     }
813   }
814 
815   return true;
816 }
817 
818 /// Check that the given field is initialized within a constexpr constructor.
819 ///
820 /// \param Dcl The constexpr constructor being checked.
821 /// \param Field The field being checked. This may be a member of an anonymous
822 ///        struct or union nested within the class being checked.
823 /// \param Inits All declarations, including anonymous struct/union members and
824 ///        indirect members, for which any initialization was provided.
825 /// \param Diagnosed Set to true if an error is produced.
826 static void CheckConstexprCtorInitializer(Sema &SemaRef,
827                                           const FunctionDecl *Dcl,
828                                           FieldDecl *Field,
829                                           llvm::SmallSet<Decl*, 16> &Inits,
830                                           bool &Diagnosed) {
831   if (Field->isUnnamedBitfield())
832     return;
833 
834   if (Field->isAnonymousStructOrUnion() &&
835       Field->getType()->getAsCXXRecordDecl()->isEmpty())
836     return;
837 
838   if (!Inits.count(Field)) {
839     if (!Diagnosed) {
840       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
841       Diagnosed = true;
842     }
843     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
844   } else if (Field->isAnonymousStructOrUnion()) {
845     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
846     for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
847          I != E; ++I)
848       // If an anonymous union contains an anonymous struct of which any member
849       // is initialized, all members must be initialized.
850       if (!RD->isUnion() || Inits.count(*I))
851         CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
852   }
853 }
854 
855 /// Check the body for the given constexpr function declaration only contains
856 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
857 ///
858 /// \return true if the body is OK, false if we have diagnosed a problem.
859 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
860   if (isa<CXXTryStmt>(Body)) {
861     // C++11 [dcl.constexpr]p3:
862     //  The definition of a constexpr function shall satisfy the following
863     //  constraints: [...]
864     // - its function-body shall be = delete, = default, or a
865     //   compound-statement
866     //
867     // C++11 [dcl.constexpr]p4:
868     //  In the definition of a constexpr constructor, [...]
869     // - its function-body shall not be a function-try-block;
870     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
871       << isa<CXXConstructorDecl>(Dcl);
872     return false;
873   }
874 
875   // - its function-body shall be [...] a compound-statement that contains only
876   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
877 
878   llvm::SmallVector<SourceLocation, 4> ReturnStmts;
879   for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
880          BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
881     switch ((*BodyIt)->getStmtClass()) {
882     case Stmt::NullStmtClass:
883       //   - null statements,
884       continue;
885 
886     case Stmt::DeclStmtClass:
887       //   - static_assert-declarations
888       //   - using-declarations,
889       //   - using-directives,
890       //   - typedef declarations and alias-declarations that do not define
891       //     classes or enumerations,
892       if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
893         return false;
894       continue;
895 
896     case Stmt::ReturnStmtClass:
897       //   - and exactly one return statement;
898       if (isa<CXXConstructorDecl>(Dcl))
899         break;
900 
901       ReturnStmts.push_back((*BodyIt)->getLocStart());
902       continue;
903 
904     default:
905       break;
906     }
907 
908     Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
909       << isa<CXXConstructorDecl>(Dcl);
910     return false;
911   }
912 
913   if (const CXXConstructorDecl *Constructor
914         = dyn_cast<CXXConstructorDecl>(Dcl)) {
915     const CXXRecordDecl *RD = Constructor->getParent();
916     // DR1359:
917     // - every non-variant non-static data member and base class sub-object
918     //   shall be initialized;
919     // - if the class is a non-empty union, or for each non-empty anonymous
920     //   union member of a non-union class, exactly one non-static data member
921     //   shall be initialized;
922     if (RD->isUnion()) {
923       if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
924         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
925         return false;
926       }
927     } else if (!Constructor->isDependentContext() &&
928                !Constructor->isDelegatingConstructor()) {
929       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
930 
931       // Skip detailed checking if we have enough initializers, and we would
932       // allow at most one initializer per member.
933       bool AnyAnonStructUnionMembers = false;
934       unsigned Fields = 0;
935       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
936            E = RD->field_end(); I != E; ++I, ++Fields) {
937         if (I->isAnonymousStructOrUnion()) {
938           AnyAnonStructUnionMembers = true;
939           break;
940         }
941       }
942       if (AnyAnonStructUnionMembers ||
943           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
944         // Check initialization of non-static data members. Base classes are
945         // always initialized so do not need to be checked. Dependent bases
946         // might not have initializers in the member initializer list.
947         llvm::SmallSet<Decl*, 16> Inits;
948         for (CXXConstructorDecl::init_const_iterator
949                I = Constructor->init_begin(), E = Constructor->init_end();
950              I != E; ++I) {
951           if (FieldDecl *FD = (*I)->getMember())
952             Inits.insert(FD);
953           else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
954             Inits.insert(ID->chain_begin(), ID->chain_end());
955         }
956 
957         bool Diagnosed = false;
958         for (CXXRecordDecl::field_iterator I = RD->field_begin(),
959              E = RD->field_end(); I != E; ++I)
960           CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
961         if (Diagnosed)
962           return false;
963       }
964     }
965   } else {
966     if (ReturnStmts.empty()) {
967       Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
968       return false;
969     }
970     if (ReturnStmts.size() > 1) {
971       Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
972       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
973         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
974       return false;
975     }
976   }
977 
978   // C++11 [dcl.constexpr]p5:
979   //   if no function argument values exist such that the function invocation
980   //   substitution would produce a constant expression, the program is
981   //   ill-formed; no diagnostic required.
982   // C++11 [dcl.constexpr]p3:
983   //   - every constructor call and implicit conversion used in initializing the
984   //     return value shall be one of those allowed in a constant expression.
985   // C++11 [dcl.constexpr]p4:
986   //   - every constructor involved in initializing non-static data members and
987   //     base class sub-objects shall be a constexpr constructor.
988   llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
989   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
990     Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
991       << isa<CXXConstructorDecl>(Dcl);
992     for (size_t I = 0, N = Diags.size(); I != N; ++I)
993       Diag(Diags[I].first, Diags[I].second);
994     return false;
995   }
996 
997   return true;
998 }
999 
1000 /// isCurrentClassName - Determine whether the identifier II is the
1001 /// name of the class type currently being defined. In the case of
1002 /// nested classes, this will only return true if II is the name of
1003 /// the innermost class.
1004 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1005                               const CXXScopeSpec *SS) {
1006   assert(getLangOpts().CPlusPlus && "No class names in C!");
1007 
1008   CXXRecordDecl *CurDecl;
1009   if (SS && SS->isSet() && !SS->isInvalid()) {
1010     DeclContext *DC = computeDeclContext(*SS, true);
1011     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1012   } else
1013     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1014 
1015   if (CurDecl && CurDecl->getIdentifier())
1016     return &II == CurDecl->getIdentifier();
1017   else
1018     return false;
1019 }
1020 
1021 /// \brief Check the validity of a C++ base class specifier.
1022 ///
1023 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1024 /// and returns NULL otherwise.
1025 CXXBaseSpecifier *
1026 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1027                          SourceRange SpecifierRange,
1028                          bool Virtual, AccessSpecifier Access,
1029                          TypeSourceInfo *TInfo,
1030                          SourceLocation EllipsisLoc) {
1031   QualType BaseType = TInfo->getType();
1032 
1033   // C++ [class.union]p1:
1034   //   A union shall not have base classes.
1035   if (Class->isUnion()) {
1036     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1037       << SpecifierRange;
1038     return 0;
1039   }
1040 
1041   if (EllipsisLoc.isValid() &&
1042       !TInfo->getType()->containsUnexpandedParameterPack()) {
1043     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1044       << TInfo->getTypeLoc().getSourceRange();
1045     EllipsisLoc = SourceLocation();
1046   }
1047 
1048   if (BaseType->isDependentType())
1049     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1050                                           Class->getTagKind() == TTK_Class,
1051                                           Access, TInfo, EllipsisLoc);
1052 
1053   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1054 
1055   // Base specifiers must be record types.
1056   if (!BaseType->isRecordType()) {
1057     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1058     return 0;
1059   }
1060 
1061   // C++ [class.union]p1:
1062   //   A union shall not be used as a base class.
1063   if (BaseType->isUnionType()) {
1064     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1065     return 0;
1066   }
1067 
1068   // C++ [class.derived]p2:
1069   //   The class-name in a base-specifier shall not be an incompletely
1070   //   defined class.
1071   if (RequireCompleteType(BaseLoc, BaseType,
1072                           diag::err_incomplete_base_class, SpecifierRange)) {
1073     Class->setInvalidDecl();
1074     return 0;
1075   }
1076 
1077   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1078   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1079   assert(BaseDecl && "Record type has no declaration");
1080   BaseDecl = BaseDecl->getDefinition();
1081   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1082   CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1083   assert(CXXBaseDecl && "Base type is not a C++ type");
1084 
1085   // C++ [class]p3:
1086   //   If a class is marked final and it appears as a base-type-specifier in
1087   //   base-clause, the program is ill-formed.
1088   if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1089     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1090       << CXXBaseDecl->getDeclName();
1091     Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1092       << CXXBaseDecl->getDeclName();
1093     return 0;
1094   }
1095 
1096   if (BaseDecl->isInvalidDecl())
1097     Class->setInvalidDecl();
1098 
1099   // Create the base specifier.
1100   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1101                                         Class->getTagKind() == TTK_Class,
1102                                         Access, TInfo, EllipsisLoc);
1103 }
1104 
1105 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1106 /// one entry in the base class list of a class specifier, for
1107 /// example:
1108 ///    class foo : public bar, virtual private baz {
1109 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1110 BaseResult
1111 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1112                          bool Virtual, AccessSpecifier Access,
1113                          ParsedType basetype, SourceLocation BaseLoc,
1114                          SourceLocation EllipsisLoc) {
1115   if (!classdecl)
1116     return true;
1117 
1118   AdjustDeclIfTemplate(classdecl);
1119   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1120   if (!Class)
1121     return true;
1122 
1123   TypeSourceInfo *TInfo = 0;
1124   GetTypeFromParser(basetype, &TInfo);
1125 
1126   if (EllipsisLoc.isInvalid() &&
1127       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1128                                       UPPC_BaseType))
1129     return true;
1130 
1131   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1132                                                       Virtual, Access, TInfo,
1133                                                       EllipsisLoc))
1134     return BaseSpec;
1135   else
1136     Class->setInvalidDecl();
1137 
1138   return true;
1139 }
1140 
1141 /// \brief Performs the actual work of attaching the given base class
1142 /// specifiers to a C++ class.
1143 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1144                                 unsigned NumBases) {
1145  if (NumBases == 0)
1146     return false;
1147 
1148   // Used to keep track of which base types we have already seen, so
1149   // that we can properly diagnose redundant direct base types. Note
1150   // that the key is always the unqualified canonical type of the base
1151   // class.
1152   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1153 
1154   // Copy non-redundant base specifiers into permanent storage.
1155   unsigned NumGoodBases = 0;
1156   bool Invalid = false;
1157   for (unsigned idx = 0; idx < NumBases; ++idx) {
1158     QualType NewBaseType
1159       = Context.getCanonicalType(Bases[idx]->getType());
1160     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1161 
1162     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1163     if (KnownBase) {
1164       // C++ [class.mi]p3:
1165       //   A class shall not be specified as a direct base class of a
1166       //   derived class more than once.
1167       Diag(Bases[idx]->getLocStart(),
1168            diag::err_duplicate_base_class)
1169         << KnownBase->getType()
1170         << Bases[idx]->getSourceRange();
1171 
1172       // Delete the duplicate base class specifier; we're going to
1173       // overwrite its pointer later.
1174       Context.Deallocate(Bases[idx]);
1175 
1176       Invalid = true;
1177     } else {
1178       // Okay, add this new base class.
1179       KnownBase = Bases[idx];
1180       Bases[NumGoodBases++] = Bases[idx];
1181       if (const RecordType *Record = NewBaseType->getAs<RecordType>())
1182         if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1183           if (RD->hasAttr<WeakAttr>())
1184             Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1185     }
1186   }
1187 
1188   // Attach the remaining base class specifiers to the derived class.
1189   Class->setBases(Bases, NumGoodBases);
1190 
1191   // Delete the remaining (good) base class specifiers, since their
1192   // data has been copied into the CXXRecordDecl.
1193   for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1194     Context.Deallocate(Bases[idx]);
1195 
1196   return Invalid;
1197 }
1198 
1199 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1200 /// class, after checking whether there are any duplicate base
1201 /// classes.
1202 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1203                                unsigned NumBases) {
1204   if (!ClassDecl || !Bases || !NumBases)
1205     return;
1206 
1207   AdjustDeclIfTemplate(ClassDecl);
1208   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1209                        (CXXBaseSpecifier**)(Bases), NumBases);
1210 }
1211 
1212 static CXXRecordDecl *GetClassForType(QualType T) {
1213   if (const RecordType *RT = T->getAs<RecordType>())
1214     return cast<CXXRecordDecl>(RT->getDecl());
1215   else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1216     return ICT->getDecl();
1217   else
1218     return 0;
1219 }
1220 
1221 /// \brief Determine whether the type \p Derived is a C++ class that is
1222 /// derived from the type \p Base.
1223 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1224   if (!getLangOpts().CPlusPlus)
1225     return false;
1226 
1227   CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1228   if (!DerivedRD)
1229     return false;
1230 
1231   CXXRecordDecl *BaseRD = GetClassForType(Base);
1232   if (!BaseRD)
1233     return false;
1234 
1235   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1236   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1237 }
1238 
1239 /// \brief Determine whether the type \p Derived is a C++ class that is
1240 /// derived from the type \p Base.
1241 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1242   if (!getLangOpts().CPlusPlus)
1243     return false;
1244 
1245   CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1246   if (!DerivedRD)
1247     return false;
1248 
1249   CXXRecordDecl *BaseRD = GetClassForType(Base);
1250   if (!BaseRD)
1251     return false;
1252 
1253   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1254 }
1255 
1256 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1257                               CXXCastPath &BasePathArray) {
1258   assert(BasePathArray.empty() && "Base path array must be empty!");
1259   assert(Paths.isRecordingPaths() && "Must record paths!");
1260 
1261   const CXXBasePath &Path = Paths.front();
1262 
1263   // We first go backward and check if we have a virtual base.
1264   // FIXME: It would be better if CXXBasePath had the base specifier for
1265   // the nearest virtual base.
1266   unsigned Start = 0;
1267   for (unsigned I = Path.size(); I != 0; --I) {
1268     if (Path[I - 1].Base->isVirtual()) {
1269       Start = I - 1;
1270       break;
1271     }
1272   }
1273 
1274   // Now add all bases.
1275   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1276     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1277 }
1278 
1279 /// \brief Determine whether the given base path includes a virtual
1280 /// base class.
1281 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1282   for (CXXCastPath::const_iterator B = BasePath.begin(),
1283                                 BEnd = BasePath.end();
1284        B != BEnd; ++B)
1285     if ((*B)->isVirtual())
1286       return true;
1287 
1288   return false;
1289 }
1290 
1291 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1292 /// conversion (where Derived and Base are class types) is
1293 /// well-formed, meaning that the conversion is unambiguous (and
1294 /// that all of the base classes are accessible). Returns true
1295 /// and emits a diagnostic if the code is ill-formed, returns false
1296 /// otherwise. Loc is the location where this routine should point to
1297 /// if there is an error, and Range is the source range to highlight
1298 /// if there is an error.
1299 bool
1300 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1301                                    unsigned InaccessibleBaseID,
1302                                    unsigned AmbigiousBaseConvID,
1303                                    SourceLocation Loc, SourceRange Range,
1304                                    DeclarationName Name,
1305                                    CXXCastPath *BasePath) {
1306   // First, determine whether the path from Derived to Base is
1307   // ambiguous. This is slightly more expensive than checking whether
1308   // the Derived to Base conversion exists, because here we need to
1309   // explore multiple paths to determine if there is an ambiguity.
1310   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1311                      /*DetectVirtual=*/false);
1312   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1313   assert(DerivationOkay &&
1314          "Can only be used with a derived-to-base conversion");
1315   (void)DerivationOkay;
1316 
1317   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1318     if (InaccessibleBaseID) {
1319       // Check that the base class can be accessed.
1320       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1321                                    InaccessibleBaseID)) {
1322         case AR_inaccessible:
1323           return true;
1324         case AR_accessible:
1325         case AR_dependent:
1326         case AR_delayed:
1327           break;
1328       }
1329     }
1330 
1331     // Build a base path if necessary.
1332     if (BasePath)
1333       BuildBasePathArray(Paths, *BasePath);
1334     return false;
1335   }
1336 
1337   // We know that the derived-to-base conversion is ambiguous, and
1338   // we're going to produce a diagnostic. Perform the derived-to-base
1339   // search just one more time to compute all of the possible paths so
1340   // that we can print them out. This is more expensive than any of
1341   // the previous derived-to-base checks we've done, but at this point
1342   // performance isn't as much of an issue.
1343   Paths.clear();
1344   Paths.setRecordingPaths(true);
1345   bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1346   assert(StillOkay && "Can only be used with a derived-to-base conversion");
1347   (void)StillOkay;
1348 
1349   // Build up a textual representation of the ambiguous paths, e.g.,
1350   // D -> B -> A, that will be used to illustrate the ambiguous
1351   // conversions in the diagnostic. We only print one of the paths
1352   // to each base class subobject.
1353   std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1354 
1355   Diag(Loc, AmbigiousBaseConvID)
1356   << Derived << Base << PathDisplayStr << Range << Name;
1357   return true;
1358 }
1359 
1360 bool
1361 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1362                                    SourceLocation Loc, SourceRange Range,
1363                                    CXXCastPath *BasePath,
1364                                    bool IgnoreAccess) {
1365   return CheckDerivedToBaseConversion(Derived, Base,
1366                                       IgnoreAccess ? 0
1367                                        : diag::err_upcast_to_inaccessible_base,
1368                                       diag::err_ambiguous_derived_to_base_conv,
1369                                       Loc, Range, DeclarationName(),
1370                                       BasePath);
1371 }
1372 
1373 
1374 /// @brief Builds a string representing ambiguous paths from a
1375 /// specific derived class to different subobjects of the same base
1376 /// class.
1377 ///
1378 /// This function builds a string that can be used in error messages
1379 /// to show the different paths that one can take through the
1380 /// inheritance hierarchy to go from the derived class to different
1381 /// subobjects of a base class. The result looks something like this:
1382 /// @code
1383 /// struct D -> struct B -> struct A
1384 /// struct D -> struct C -> struct A
1385 /// @endcode
1386 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1387   std::string PathDisplayStr;
1388   std::set<unsigned> DisplayedPaths;
1389   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1390        Path != Paths.end(); ++Path) {
1391     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1392       // We haven't displayed a path to this particular base
1393       // class subobject yet.
1394       PathDisplayStr += "\n    ";
1395       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1396       for (CXXBasePath::const_iterator Element = Path->begin();
1397            Element != Path->end(); ++Element)
1398         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1399     }
1400   }
1401 
1402   return PathDisplayStr;
1403 }
1404 
1405 //===----------------------------------------------------------------------===//
1406 // C++ class member Handling
1407 //===----------------------------------------------------------------------===//
1408 
1409 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1410 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1411                                 SourceLocation ASLoc,
1412                                 SourceLocation ColonLoc,
1413                                 AttributeList *Attrs) {
1414   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1415   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1416                                                   ASLoc, ColonLoc);
1417   CurContext->addHiddenDecl(ASDecl);
1418   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1419 }
1420 
1421 /// CheckOverrideControl - Check C++11 override control semantics.
1422 void Sema::CheckOverrideControl(Decl *D) {
1423   if (D->isInvalidDecl())
1424     return;
1425 
1426   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1427 
1428   // Do we know which functions this declaration might be overriding?
1429   bool OverridesAreKnown = !MD ||
1430       (!MD->getParent()->hasAnyDependentBases() &&
1431        !MD->getType()->isDependentType());
1432 
1433   if (!MD || !MD->isVirtual()) {
1434     if (OverridesAreKnown) {
1435       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1436         Diag(OA->getLocation(),
1437              diag::override_keyword_only_allowed_on_virtual_member_functions)
1438           << "override" << FixItHint::CreateRemoval(OA->getLocation());
1439         D->dropAttr<OverrideAttr>();
1440       }
1441       if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1442         Diag(FA->getLocation(),
1443              diag::override_keyword_only_allowed_on_virtual_member_functions)
1444           << "final" << FixItHint::CreateRemoval(FA->getLocation());
1445         D->dropAttr<FinalAttr>();
1446       }
1447     }
1448     return;
1449   }
1450 
1451   if (!OverridesAreKnown)
1452     return;
1453 
1454   // C++11 [class.virtual]p5:
1455   //   If a virtual function is marked with the virt-specifier override and
1456   //   does not override a member function of a base class, the program is
1457   //   ill-formed.
1458   bool HasOverriddenMethods =
1459     MD->begin_overridden_methods() != MD->end_overridden_methods();
1460   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1461     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1462       << MD->getDeclName();
1463 }
1464 
1465 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1466 /// function overrides a virtual member function marked 'final', according to
1467 /// C++11 [class.virtual]p4.
1468 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1469                                                   const CXXMethodDecl *Old) {
1470   if (!Old->hasAttr<FinalAttr>())
1471     return false;
1472 
1473   Diag(New->getLocation(), diag::err_final_function_overridden)
1474     << New->getDeclName();
1475   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1476   return true;
1477 }
1478 
1479 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1480   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1481   // FIXME: Destruction of ObjC lifetime types has side-effects.
1482   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1483     return !RD->isCompleteDefinition() ||
1484            !RD->hasTrivialDefaultConstructor() ||
1485            !RD->hasTrivialDestructor();
1486   return false;
1487 }
1488 
1489 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1490 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1491 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1492 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1493 /// present (but parsing it has been deferred).
1494 Decl *
1495 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1496                                MultiTemplateParamsArg TemplateParameterLists,
1497                                Expr *BW, const VirtSpecifiers &VS,
1498                                InClassInitStyle InitStyle) {
1499   const DeclSpec &DS = D.getDeclSpec();
1500   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1501   DeclarationName Name = NameInfo.getName();
1502   SourceLocation Loc = NameInfo.getLoc();
1503 
1504   // For anonymous bitfields, the location should point to the type.
1505   if (Loc.isInvalid())
1506     Loc = D.getLocStart();
1507 
1508   Expr *BitWidth = static_cast<Expr*>(BW);
1509 
1510   assert(isa<CXXRecordDecl>(CurContext));
1511   assert(!DS.isFriendSpecified());
1512 
1513   bool isFunc = D.isDeclarationOfFunction();
1514 
1515   // C++ 9.2p6: A member shall not be declared to have automatic storage
1516   // duration (auto, register) or with the extern storage-class-specifier.
1517   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1518   // data members and cannot be applied to names declared const or static,
1519   // and cannot be applied to reference members.
1520   switch (DS.getStorageClassSpec()) {
1521     case DeclSpec::SCS_unspecified:
1522     case DeclSpec::SCS_typedef:
1523     case DeclSpec::SCS_static:
1524       // FALL THROUGH.
1525       break;
1526     case DeclSpec::SCS_mutable:
1527       if (isFunc) {
1528         if (DS.getStorageClassSpecLoc().isValid())
1529           Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1530         else
1531           Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1532 
1533         // FIXME: It would be nicer if the keyword was ignored only for this
1534         // declarator. Otherwise we could get follow-up errors.
1535         D.getMutableDeclSpec().ClearStorageClassSpecs();
1536       }
1537       break;
1538     default:
1539       if (DS.getStorageClassSpecLoc().isValid())
1540         Diag(DS.getStorageClassSpecLoc(),
1541              diag::err_storageclass_invalid_for_member);
1542       else
1543         Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1544       D.getMutableDeclSpec().ClearStorageClassSpecs();
1545   }
1546 
1547   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1548                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1549                       !isFunc);
1550 
1551   Decl *Member;
1552   if (isInstField) {
1553     CXXScopeSpec &SS = D.getCXXScopeSpec();
1554 
1555     // Data members must have identifiers for names.
1556     if (!Name.isIdentifier()) {
1557       Diag(Loc, diag::err_bad_variable_name)
1558         << Name;
1559       return 0;
1560     }
1561 
1562     IdentifierInfo *II = Name.getAsIdentifierInfo();
1563 
1564     // Member field could not be with "template" keyword.
1565     // So TemplateParameterLists should be empty in this case.
1566     if (TemplateParameterLists.size()) {
1567       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1568       if (TemplateParams->size()) {
1569         // There is no such thing as a member field template.
1570         Diag(D.getIdentifierLoc(), diag::err_template_member)
1571             << II
1572             << SourceRange(TemplateParams->getTemplateLoc(),
1573                 TemplateParams->getRAngleLoc());
1574       } else {
1575         // There is an extraneous 'template<>' for this member.
1576         Diag(TemplateParams->getTemplateLoc(),
1577             diag::err_template_member_noparams)
1578             << II
1579             << SourceRange(TemplateParams->getTemplateLoc(),
1580                 TemplateParams->getRAngleLoc());
1581       }
1582       return 0;
1583     }
1584 
1585     if (SS.isSet() && !SS.isInvalid()) {
1586       // The user provided a superfluous scope specifier inside a class
1587       // definition:
1588       //
1589       // class X {
1590       //   int X::member;
1591       // };
1592       if (DeclContext *DC = computeDeclContext(SS, false))
1593         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1594       else
1595         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1596           << Name << SS.getRange();
1597 
1598       SS.clear();
1599     }
1600 
1601     Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1602                          InitStyle, AS);
1603     assert(Member && "HandleField never returns null");
1604   } else {
1605     assert(InitStyle == ICIS_NoInit);
1606 
1607     Member = HandleDeclarator(S, D, TemplateParameterLists);
1608     if (!Member) {
1609       return 0;
1610     }
1611 
1612     // Non-instance-fields can't have a bitfield.
1613     if (BitWidth) {
1614       if (Member->isInvalidDecl()) {
1615         // don't emit another diagnostic.
1616       } else if (isa<VarDecl>(Member)) {
1617         // C++ 9.6p3: A bit-field shall not be a static member.
1618         // "static member 'A' cannot be a bit-field"
1619         Diag(Loc, diag::err_static_not_bitfield)
1620           << Name << BitWidth->getSourceRange();
1621       } else if (isa<TypedefDecl>(Member)) {
1622         // "typedef member 'x' cannot be a bit-field"
1623         Diag(Loc, diag::err_typedef_not_bitfield)
1624           << Name << BitWidth->getSourceRange();
1625       } else {
1626         // A function typedef ("typedef int f(); f a;").
1627         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1628         Diag(Loc, diag::err_not_integral_type_bitfield)
1629           << Name << cast<ValueDecl>(Member)->getType()
1630           << BitWidth->getSourceRange();
1631       }
1632 
1633       BitWidth = 0;
1634       Member->setInvalidDecl();
1635     }
1636 
1637     Member->setAccess(AS);
1638 
1639     // If we have declared a member function template, set the access of the
1640     // templated declaration as well.
1641     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1642       FunTmpl->getTemplatedDecl()->setAccess(AS);
1643   }
1644 
1645   if (VS.isOverrideSpecified())
1646     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1647   if (VS.isFinalSpecified())
1648     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1649 
1650   if (VS.getLastLocation().isValid()) {
1651     // Update the end location of a method that has a virt-specifiers.
1652     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1653       MD->setRangeEnd(VS.getLastLocation());
1654   }
1655 
1656   CheckOverrideControl(Member);
1657 
1658   assert((Name || isInstField) && "No identifier for non-field ?");
1659 
1660   if (isInstField) {
1661     FieldDecl *FD = cast<FieldDecl>(Member);
1662     FieldCollector->Add(FD);
1663 
1664     if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1665                                  FD->getLocation())
1666           != DiagnosticsEngine::Ignored) {
1667       // Remember all explicit private FieldDecls that have a name, no side
1668       // effects and are not part of a dependent type declaration.
1669       if (!FD->isImplicit() && FD->getDeclName() &&
1670           FD->getAccess() == AS_private &&
1671           !FD->hasAttr<UnusedAttr>() &&
1672           !FD->getParent()->isDependentContext() &&
1673           !InitializationHasSideEffects(*FD))
1674         UnusedPrivateFields.insert(FD);
1675     }
1676   }
1677 
1678   return Member;
1679 }
1680 
1681 /// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1682 /// in-class initializer for a non-static C++ class member, and after
1683 /// instantiating an in-class initializer in a class template. Such actions
1684 /// are deferred until the class is complete.
1685 void
1686 Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
1687                                        Expr *InitExpr) {
1688   FieldDecl *FD = cast<FieldDecl>(D);
1689   assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1690          "must set init style when field is created");
1691 
1692   if (!InitExpr) {
1693     FD->setInvalidDecl();
1694     FD->removeInClassInitializer();
1695     return;
1696   }
1697 
1698   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1699     FD->setInvalidDecl();
1700     FD->removeInClassInitializer();
1701     return;
1702   }
1703 
1704   ExprResult Init = InitExpr;
1705   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent() &&
1706       !FD->getDeclContext()->isDependentContext()) {
1707     // Note: We don't type-check when we're in a dependent context, because
1708     // the initialization-substitution code does not properly handle direct
1709     // list initialization. We have the same hackaround for ctor-initializers.
1710     if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
1711       Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
1712         << /*at end of ctor*/1 << InitExpr->getSourceRange();
1713     }
1714     Expr **Inits = &InitExpr;
1715     unsigned NumInits = 1;
1716     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1717     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
1718         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1719         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
1720     InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1721     Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
1722     if (Init.isInvalid()) {
1723       FD->setInvalidDecl();
1724       return;
1725     }
1726 
1727     CheckImplicitConversions(Init.get(), InitLoc);
1728   }
1729 
1730   // C++0x [class.base.init]p7:
1731   //   The initialization of each base and member constitutes a
1732   //   full-expression.
1733   Init = MaybeCreateExprWithCleanups(Init);
1734   if (Init.isInvalid()) {
1735     FD->setInvalidDecl();
1736     return;
1737   }
1738 
1739   InitExpr = Init.release();
1740 
1741   FD->setInClassInitializer(InitExpr);
1742 }
1743 
1744 /// \brief Find the direct and/or virtual base specifiers that
1745 /// correspond to the given base type, for use in base initialization
1746 /// within a constructor.
1747 static bool FindBaseInitializer(Sema &SemaRef,
1748                                 CXXRecordDecl *ClassDecl,
1749                                 QualType BaseType,
1750                                 const CXXBaseSpecifier *&DirectBaseSpec,
1751                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
1752   // First, check for a direct base class.
1753   DirectBaseSpec = 0;
1754   for (CXXRecordDecl::base_class_const_iterator Base
1755          = ClassDecl->bases_begin();
1756        Base != ClassDecl->bases_end(); ++Base) {
1757     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1758       // We found a direct base of this type. That's what we're
1759       // initializing.
1760       DirectBaseSpec = &*Base;
1761       break;
1762     }
1763   }
1764 
1765   // Check for a virtual base class.
1766   // FIXME: We might be able to short-circuit this if we know in advance that
1767   // there are no virtual bases.
1768   VirtualBaseSpec = 0;
1769   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1770     // We haven't found a base yet; search the class hierarchy for a
1771     // virtual base class.
1772     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1773                        /*DetectVirtual=*/false);
1774     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1775                               BaseType, Paths)) {
1776       for (CXXBasePaths::paths_iterator Path = Paths.begin();
1777            Path != Paths.end(); ++Path) {
1778         if (Path->back().Base->isVirtual()) {
1779           VirtualBaseSpec = Path->back().Base;
1780           break;
1781         }
1782       }
1783     }
1784   }
1785 
1786   return DirectBaseSpec || VirtualBaseSpec;
1787 }
1788 
1789 /// \brief Handle a C++ member initializer using braced-init-list syntax.
1790 MemInitResult
1791 Sema::ActOnMemInitializer(Decl *ConstructorD,
1792                           Scope *S,
1793                           CXXScopeSpec &SS,
1794                           IdentifierInfo *MemberOrBase,
1795                           ParsedType TemplateTypeTy,
1796                           const DeclSpec &DS,
1797                           SourceLocation IdLoc,
1798                           Expr *InitList,
1799                           SourceLocation EllipsisLoc) {
1800   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1801                              DS, IdLoc, InitList,
1802                              EllipsisLoc);
1803 }
1804 
1805 /// \brief Handle a C++ member initializer using parentheses syntax.
1806 MemInitResult
1807 Sema::ActOnMemInitializer(Decl *ConstructorD,
1808                           Scope *S,
1809                           CXXScopeSpec &SS,
1810                           IdentifierInfo *MemberOrBase,
1811                           ParsedType TemplateTypeTy,
1812                           const DeclSpec &DS,
1813                           SourceLocation IdLoc,
1814                           SourceLocation LParenLoc,
1815                           Expr **Args, unsigned NumArgs,
1816                           SourceLocation RParenLoc,
1817                           SourceLocation EllipsisLoc) {
1818   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
1819                                            llvm::makeArrayRef(Args, NumArgs),
1820                                            RParenLoc);
1821   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1822                              DS, IdLoc, List, EllipsisLoc);
1823 }
1824 
1825 namespace {
1826 
1827 // Callback to only accept typo corrections that can be a valid C++ member
1828 // intializer: either a non-static field member or a base class.
1829 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1830  public:
1831   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1832       : ClassDecl(ClassDecl) {}
1833 
1834   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1835     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1836       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1837         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1838       else
1839         return isa<TypeDecl>(ND);
1840     }
1841     return false;
1842   }
1843 
1844  private:
1845   CXXRecordDecl *ClassDecl;
1846 };
1847 
1848 }
1849 
1850 /// \brief Handle a C++ member initializer.
1851 MemInitResult
1852 Sema::BuildMemInitializer(Decl *ConstructorD,
1853                           Scope *S,
1854                           CXXScopeSpec &SS,
1855                           IdentifierInfo *MemberOrBase,
1856                           ParsedType TemplateTypeTy,
1857                           const DeclSpec &DS,
1858                           SourceLocation IdLoc,
1859                           Expr *Init,
1860                           SourceLocation EllipsisLoc) {
1861   if (!ConstructorD)
1862     return true;
1863 
1864   AdjustDeclIfTemplate(ConstructorD);
1865 
1866   CXXConstructorDecl *Constructor
1867     = dyn_cast<CXXConstructorDecl>(ConstructorD);
1868   if (!Constructor) {
1869     // The user wrote a constructor initializer on a function that is
1870     // not a C++ constructor. Ignore the error for now, because we may
1871     // have more member initializers coming; we'll diagnose it just
1872     // once in ActOnMemInitializers.
1873     return true;
1874   }
1875 
1876   CXXRecordDecl *ClassDecl = Constructor->getParent();
1877 
1878   // C++ [class.base.init]p2:
1879   //   Names in a mem-initializer-id are looked up in the scope of the
1880   //   constructor's class and, if not found in that scope, are looked
1881   //   up in the scope containing the constructor's definition.
1882   //   [Note: if the constructor's class contains a member with the
1883   //   same name as a direct or virtual base class of the class, a
1884   //   mem-initializer-id naming the member or base class and composed
1885   //   of a single identifier refers to the class member. A
1886   //   mem-initializer-id for the hidden base class may be specified
1887   //   using a qualified name. ]
1888   if (!SS.getScopeRep() && !TemplateTypeTy) {
1889     // Look for a member, first.
1890     DeclContext::lookup_result Result
1891       = ClassDecl->lookup(MemberOrBase);
1892     if (Result.first != Result.second) {
1893       ValueDecl *Member;
1894       if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1895           (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
1896         if (EllipsisLoc.isValid())
1897           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1898             << MemberOrBase
1899             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
1900 
1901         return BuildMemberInitializer(Member, Init, IdLoc);
1902       }
1903     }
1904   }
1905   // It didn't name a member, so see if it names a class.
1906   QualType BaseType;
1907   TypeSourceInfo *TInfo = 0;
1908 
1909   if (TemplateTypeTy) {
1910     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1911   } else if (DS.getTypeSpecType() == TST_decltype) {
1912     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
1913   } else {
1914     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1915     LookupParsedName(R, S, &SS);
1916 
1917     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1918     if (!TyD) {
1919       if (R.isAmbiguous()) return true;
1920 
1921       // We don't want access-control diagnostics here.
1922       R.suppressDiagnostics();
1923 
1924       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1925         bool NotUnknownSpecialization = false;
1926         DeclContext *DC = computeDeclContext(SS, false);
1927         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1928           NotUnknownSpecialization = !Record->hasAnyDependentBases();
1929 
1930         if (!NotUnknownSpecialization) {
1931           // When the scope specifier can refer to a member of an unknown
1932           // specialization, we take it as a type name.
1933           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1934                                        SS.getWithLocInContext(Context),
1935                                        *MemberOrBase, IdLoc);
1936           if (BaseType.isNull())
1937             return true;
1938 
1939           R.clear();
1940           R.setLookupName(MemberOrBase);
1941         }
1942       }
1943 
1944       // If no results were found, try to correct typos.
1945       TypoCorrection Corr;
1946       MemInitializerValidatorCCC Validator(ClassDecl);
1947       if (R.empty() && BaseType.isNull() &&
1948           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1949                               Validator, ClassDecl))) {
1950         std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1951         std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
1952         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
1953           // We have found a non-static data member with a similar
1954           // name to what was typed; complain and initialize that
1955           // member.
1956           Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1957             << MemberOrBase << true << CorrectedQuotedStr
1958             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1959           Diag(Member->getLocation(), diag::note_previous_decl)
1960             << CorrectedQuotedStr;
1961 
1962           return BuildMemberInitializer(Member, Init, IdLoc);
1963         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
1964           const CXXBaseSpecifier *DirectBaseSpec;
1965           const CXXBaseSpecifier *VirtualBaseSpec;
1966           if (FindBaseInitializer(*this, ClassDecl,
1967                                   Context.getTypeDeclType(Type),
1968                                   DirectBaseSpec, VirtualBaseSpec)) {
1969             // We have found a direct or virtual base class with a
1970             // similar name to what was typed; complain and initialize
1971             // that base class.
1972             Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1973               << MemberOrBase << false << CorrectedQuotedStr
1974               << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1975 
1976             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1977                                                              : VirtualBaseSpec;
1978             Diag(BaseSpec->getLocStart(),
1979                  diag::note_base_class_specified_here)
1980               << BaseSpec->getType()
1981               << BaseSpec->getSourceRange();
1982 
1983             TyD = Type;
1984           }
1985         }
1986       }
1987 
1988       if (!TyD && BaseType.isNull()) {
1989         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1990           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
1991         return true;
1992       }
1993     }
1994 
1995     if (BaseType.isNull()) {
1996       BaseType = Context.getTypeDeclType(TyD);
1997       if (SS.isSet()) {
1998         NestedNameSpecifier *Qualifier =
1999           static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2000 
2001         // FIXME: preserve source range information
2002         BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
2003       }
2004     }
2005   }
2006 
2007   if (!TInfo)
2008     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2009 
2010   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2011 }
2012 
2013 /// Checks a member initializer expression for cases where reference (or
2014 /// pointer) members are bound to by-value parameters (or their addresses).
2015 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2016                                                Expr *Init,
2017                                                SourceLocation IdLoc) {
2018   QualType MemberTy = Member->getType();
2019 
2020   // We only handle pointers and references currently.
2021   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2022   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2023     return;
2024 
2025   const bool IsPointer = MemberTy->isPointerType();
2026   if (IsPointer) {
2027     if (const UnaryOperator *Op
2028           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2029       // The only case we're worried about with pointers requires taking the
2030       // address.
2031       if (Op->getOpcode() != UO_AddrOf)
2032         return;
2033 
2034       Init = Op->getSubExpr();
2035     } else {
2036       // We only handle address-of expression initializers for pointers.
2037       return;
2038     }
2039   }
2040 
2041   if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2042     // Taking the address of a temporary will be diagnosed as a hard error.
2043     if (IsPointer)
2044       return;
2045 
2046     S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2047       << Member << Init->getSourceRange();
2048   } else if (const DeclRefExpr *DRE
2049                = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2050     // We only warn when referring to a non-reference parameter declaration.
2051     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2052     if (!Parameter || Parameter->getType()->isReferenceType())
2053       return;
2054 
2055     S.Diag(Init->getExprLoc(),
2056            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2057                      : diag::warn_bind_ref_member_to_parameter)
2058       << Member << Parameter << Init->getSourceRange();
2059   } else {
2060     // Other initializers are fine.
2061     return;
2062   }
2063 
2064   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2065     << (unsigned)IsPointer;
2066 }
2067 
2068 namespace {
2069   class UninitializedFieldVisitor
2070       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2071     Sema &S;
2072     ValueDecl *VD;
2073   public:
2074     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2075     UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
2076                                                         S(S), VD(VD) {
2077     }
2078 
2079     void HandleExpr(Expr *E) {
2080       if (!E) return;
2081 
2082       // Expressions like x(x) sometimes lack the surrounding expressions
2083       // but need to be checked anyways.
2084       HandleValue(E);
2085       Visit(E);
2086     }
2087 
2088     void HandleValue(Expr *E) {
2089       E = E->IgnoreParens();
2090 
2091       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2092         if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2093             return;
2094         Expr *Base = E;
2095         while (isa<MemberExpr>(Base)) {
2096           ME = dyn_cast<MemberExpr>(Base);
2097           if (VarDecl *VarD = dyn_cast<VarDecl>(ME->getMemberDecl()))
2098             if (VarD->hasGlobalStorage())
2099               return;
2100           Base = ME->getBase();
2101         }
2102 
2103         if (VD == ME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
2104           unsigned diag = VD->getType()->isReferenceType()
2105               ? diag::warn_reference_field_is_uninit
2106               : diag::warn_field_is_uninit;
2107           S.Diag(ME->getExprLoc(), diag);
2108           return;
2109         }
2110       }
2111 
2112       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2113         HandleValue(CO->getTrueExpr());
2114         HandleValue(CO->getFalseExpr());
2115         return;
2116       }
2117 
2118       if (BinaryConditionalOperator *BCO =
2119               dyn_cast<BinaryConditionalOperator>(E)) {
2120         HandleValue(BCO->getCommon());
2121         HandleValue(BCO->getFalseExpr());
2122         return;
2123       }
2124 
2125       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2126         switch (BO->getOpcode()) {
2127         default:
2128           return;
2129         case(BO_PtrMemD):
2130         case(BO_PtrMemI):
2131           HandleValue(BO->getLHS());
2132           return;
2133         case(BO_Comma):
2134           HandleValue(BO->getRHS());
2135           return;
2136         }
2137       }
2138     }
2139 
2140     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2141       if (E->getCastKind() == CK_LValueToRValue)
2142         HandleValue(E->getSubExpr());
2143 
2144       Inherited::VisitImplicitCastExpr(E);
2145     }
2146 
2147     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2148       Expr *Callee = E->getCallee();
2149       if (isa<MemberExpr>(Callee))
2150         HandleValue(Callee);
2151 
2152       Inherited::VisitCXXMemberCallExpr(E);
2153     }
2154   };
2155   static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2156                                                        ValueDecl *VD) {
2157     UninitializedFieldVisitor(S, VD).HandleExpr(E);
2158   }
2159 } // namespace
2160 
2161 MemInitResult
2162 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2163                              SourceLocation IdLoc) {
2164   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2165   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2166   assert((DirectMember || IndirectMember) &&
2167          "Member must be a FieldDecl or IndirectFieldDecl");
2168 
2169   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2170     return true;
2171 
2172   if (Member->isInvalidDecl())
2173     return true;
2174 
2175   // Diagnose value-uses of fields to initialize themselves, e.g.
2176   //   foo(foo)
2177   // where foo is not also a parameter to the constructor.
2178   // TODO: implement -Wuninitialized and fold this into that framework.
2179   Expr **Args;
2180   unsigned NumArgs;
2181   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2182     Args = ParenList->getExprs();
2183     NumArgs = ParenList->getNumExprs();
2184   } else {
2185     InitListExpr *InitList = cast<InitListExpr>(Init);
2186     Args = InitList->getInits();
2187     NumArgs = InitList->getNumInits();
2188   }
2189 
2190   if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2191         != DiagnosticsEngine::Ignored)
2192     for (unsigned i = 0; i < NumArgs; ++i)
2193       // FIXME: Warn about the case when other fields are used before being
2194       // uninitialized. For example, let this field be the i'th field. When
2195       // initializing the i'th field, throw a warning if any of the >= i'th
2196       // fields are used, as they are not yet initialized.
2197       // Right now we are only handling the case where the i'th field uses
2198       // itself in its initializer.
2199       CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
2200 
2201   SourceRange InitRange = Init->getSourceRange();
2202 
2203   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2204     // Can't check initialization for a member of dependent type or when
2205     // any of the arguments are type-dependent expressions.
2206     DiscardCleanupsInEvaluationContext();
2207   } else {
2208     bool InitList = false;
2209     if (isa<InitListExpr>(Init)) {
2210       InitList = true;
2211       Args = &Init;
2212       NumArgs = 1;
2213 
2214       if (isStdInitializerList(Member->getType(), 0)) {
2215         Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2216             << /*at end of ctor*/1 << InitRange;
2217       }
2218     }
2219 
2220     // Initialize the member.
2221     InitializedEntity MemberEntity =
2222       DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2223                    : InitializedEntity::InitializeMember(IndirectMember, 0);
2224     InitializationKind Kind =
2225       InitList ? InitializationKind::CreateDirectList(IdLoc)
2226                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2227                                                   InitRange.getEnd());
2228 
2229     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2230     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2231                                             MultiExprArg(Args, NumArgs),
2232                                             0);
2233     if (MemberInit.isInvalid())
2234       return true;
2235 
2236     CheckImplicitConversions(MemberInit.get(),
2237                              InitRange.getBegin());
2238 
2239     // C++0x [class.base.init]p7:
2240     //   The initialization of each base and member constitutes a
2241     //   full-expression.
2242     MemberInit = MaybeCreateExprWithCleanups(MemberInit);
2243     if (MemberInit.isInvalid())
2244       return true;
2245 
2246     // If we are in a dependent context, template instantiation will
2247     // perform this type-checking again. Just save the arguments that we
2248     // received.
2249     // FIXME: This isn't quite ideal, since our ASTs don't capture all
2250     // of the information that we have about the member
2251     // initializer. However, deconstructing the ASTs is a dicey process,
2252     // and this approach is far more likely to get the corner cases right.
2253     if (CurContext->isDependentContext()) {
2254       // The existing Init will do fine.
2255     } else {
2256       Init = MemberInit.get();
2257       CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2258     }
2259   }
2260 
2261   if (DirectMember) {
2262     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2263                                             InitRange.getBegin(), Init,
2264                                             InitRange.getEnd());
2265   } else {
2266     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2267                                             InitRange.getBegin(), Init,
2268                                             InitRange.getEnd());
2269   }
2270 }
2271 
2272 MemInitResult
2273 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2274                                  CXXRecordDecl *ClassDecl) {
2275   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2276   if (!LangOpts.CPlusPlus0x)
2277     return Diag(NameLoc, diag::err_delegating_ctor)
2278       << TInfo->getTypeLoc().getLocalSourceRange();
2279   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2280 
2281   bool InitList = true;
2282   Expr **Args = &Init;
2283   unsigned NumArgs = 1;
2284   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2285     InitList = false;
2286     Args = ParenList->getExprs();
2287     NumArgs = ParenList->getNumExprs();
2288   }
2289 
2290   SourceRange InitRange = Init->getSourceRange();
2291   // Initialize the object.
2292   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2293                                      QualType(ClassDecl->getTypeForDecl(), 0));
2294   InitializationKind Kind =
2295     InitList ? InitializationKind::CreateDirectList(NameLoc)
2296              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2297                                                 InitRange.getEnd());
2298   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2299   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2300                                               MultiExprArg(Args, NumArgs),
2301                                               0);
2302   if (DelegationInit.isInvalid())
2303     return true;
2304 
2305   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2306          "Delegating constructor with no target?");
2307 
2308   CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
2309 
2310   // C++0x [class.base.init]p7:
2311   //   The initialization of each base and member constitutes a
2312   //   full-expression.
2313   DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2314   if (DelegationInit.isInvalid())
2315     return true;
2316 
2317   // If we are in a dependent context, template instantiation will
2318   // perform this type-checking again. Just save the arguments that we
2319   // received in a ParenListExpr.
2320   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2321   // of the information that we have about the base
2322   // initializer. However, deconstructing the ASTs is a dicey process,
2323   // and this approach is far more likely to get the corner cases right.
2324   if (CurContext->isDependentContext())
2325     DelegationInit = Owned(Init);
2326 
2327   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2328                                           DelegationInit.takeAs<Expr>(),
2329                                           InitRange.getEnd());
2330 }
2331 
2332 MemInitResult
2333 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2334                            Expr *Init, CXXRecordDecl *ClassDecl,
2335                            SourceLocation EllipsisLoc) {
2336   SourceLocation BaseLoc
2337     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2338 
2339   if (!BaseType->isDependentType() && !BaseType->isRecordType())
2340     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2341              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2342 
2343   // C++ [class.base.init]p2:
2344   //   [...] Unless the mem-initializer-id names a nonstatic data
2345   //   member of the constructor's class or a direct or virtual base
2346   //   of that class, the mem-initializer is ill-formed. A
2347   //   mem-initializer-list can initialize a base class using any
2348   //   name that denotes that base class type.
2349   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2350 
2351   SourceRange InitRange = Init->getSourceRange();
2352   if (EllipsisLoc.isValid()) {
2353     // This is a pack expansion.
2354     if (!BaseType->containsUnexpandedParameterPack())  {
2355       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2356         << SourceRange(BaseLoc, InitRange.getEnd());
2357 
2358       EllipsisLoc = SourceLocation();
2359     }
2360   } else {
2361     // Check for any unexpanded parameter packs.
2362     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2363       return true;
2364 
2365     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2366       return true;
2367   }
2368 
2369   // Check for direct and virtual base classes.
2370   const CXXBaseSpecifier *DirectBaseSpec = 0;
2371   const CXXBaseSpecifier *VirtualBaseSpec = 0;
2372   if (!Dependent) {
2373     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2374                                        BaseType))
2375       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2376 
2377     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2378                         VirtualBaseSpec);
2379 
2380     // C++ [base.class.init]p2:
2381     // Unless the mem-initializer-id names a nonstatic data member of the
2382     // constructor's class or a direct or virtual base of that class, the
2383     // mem-initializer is ill-formed.
2384     if (!DirectBaseSpec && !VirtualBaseSpec) {
2385       // If the class has any dependent bases, then it's possible that
2386       // one of those types will resolve to the same type as
2387       // BaseType. Therefore, just treat this as a dependent base
2388       // class initialization.  FIXME: Should we try to check the
2389       // initialization anyway? It seems odd.
2390       if (ClassDecl->hasAnyDependentBases())
2391         Dependent = true;
2392       else
2393         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2394           << BaseType << Context.getTypeDeclType(ClassDecl)
2395           << BaseTInfo->getTypeLoc().getLocalSourceRange();
2396     }
2397   }
2398 
2399   if (Dependent) {
2400     DiscardCleanupsInEvaluationContext();
2401 
2402     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2403                                             /*IsVirtual=*/false,
2404                                             InitRange.getBegin(), Init,
2405                                             InitRange.getEnd(), EllipsisLoc);
2406   }
2407 
2408   // C++ [base.class.init]p2:
2409   //   If a mem-initializer-id is ambiguous because it designates both
2410   //   a direct non-virtual base class and an inherited virtual base
2411   //   class, the mem-initializer is ill-formed.
2412   if (DirectBaseSpec && VirtualBaseSpec)
2413     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2414       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2415 
2416   CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2417   if (!BaseSpec)
2418     BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2419 
2420   // Initialize the base.
2421   bool InitList = true;
2422   Expr **Args = &Init;
2423   unsigned NumArgs = 1;
2424   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2425     InitList = false;
2426     Args = ParenList->getExprs();
2427     NumArgs = ParenList->getNumExprs();
2428   }
2429 
2430   InitializedEntity BaseEntity =
2431     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2432   InitializationKind Kind =
2433     InitList ? InitializationKind::CreateDirectList(BaseLoc)
2434              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2435                                                 InitRange.getEnd());
2436   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2437   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2438                                         MultiExprArg(Args, NumArgs), 0);
2439   if (BaseInit.isInvalid())
2440     return true;
2441 
2442   CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
2443 
2444   // C++0x [class.base.init]p7:
2445   //   The initialization of each base and member constitutes a
2446   //   full-expression.
2447   BaseInit = MaybeCreateExprWithCleanups(BaseInit);
2448   if (BaseInit.isInvalid())
2449     return true;
2450 
2451   // If we are in a dependent context, template instantiation will
2452   // perform this type-checking again. Just save the arguments that we
2453   // received in a ParenListExpr.
2454   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2455   // of the information that we have about the base
2456   // initializer. However, deconstructing the ASTs is a dicey process,
2457   // and this approach is far more likely to get the corner cases right.
2458   if (CurContext->isDependentContext())
2459     BaseInit = Owned(Init);
2460 
2461   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2462                                           BaseSpec->isVirtual(),
2463                                           InitRange.getBegin(),
2464                                           BaseInit.takeAs<Expr>(),
2465                                           InitRange.getEnd(), EllipsisLoc);
2466 }
2467 
2468 // Create a static_cast\<T&&>(expr).
2469 static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2470   QualType ExprType = E->getType();
2471   QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2472   SourceLocation ExprLoc = E->getLocStart();
2473   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2474       TargetType, ExprLoc);
2475 
2476   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2477                                    SourceRange(ExprLoc, ExprLoc),
2478                                    E->getSourceRange()).take();
2479 }
2480 
2481 /// ImplicitInitializerKind - How an implicit base or member initializer should
2482 /// initialize its base or member.
2483 enum ImplicitInitializerKind {
2484   IIK_Default,
2485   IIK_Copy,
2486   IIK_Move
2487 };
2488 
2489 static bool
2490 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2491                              ImplicitInitializerKind ImplicitInitKind,
2492                              CXXBaseSpecifier *BaseSpec,
2493                              bool IsInheritedVirtualBase,
2494                              CXXCtorInitializer *&CXXBaseInit) {
2495   InitializedEntity InitEntity
2496     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2497                                         IsInheritedVirtualBase);
2498 
2499   ExprResult BaseInit;
2500 
2501   switch (ImplicitInitKind) {
2502   case IIK_Default: {
2503     InitializationKind InitKind
2504       = InitializationKind::CreateDefault(Constructor->getLocation());
2505     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2506     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2507     break;
2508   }
2509 
2510   case IIK_Move:
2511   case IIK_Copy: {
2512     bool Moving = ImplicitInitKind == IIK_Move;
2513     ParmVarDecl *Param = Constructor->getParamDecl(0);
2514     QualType ParamType = Param->getType().getNonReferenceType();
2515 
2516     Expr *CopyCtorArg =
2517       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2518                           SourceLocation(), Param, false,
2519                           Constructor->getLocation(), ParamType,
2520                           VK_LValue, 0);
2521 
2522     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2523 
2524     // Cast to the base class to avoid ambiguities.
2525     QualType ArgTy =
2526       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2527                                        ParamType.getQualifiers());
2528 
2529     if (Moving) {
2530       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2531     }
2532 
2533     CXXCastPath BasePath;
2534     BasePath.push_back(BaseSpec);
2535     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2536                                             CK_UncheckedDerivedToBase,
2537                                             Moving ? VK_XValue : VK_LValue,
2538                                             &BasePath).take();
2539 
2540     InitializationKind InitKind
2541       = InitializationKind::CreateDirect(Constructor->getLocation(),
2542                                          SourceLocation(), SourceLocation());
2543     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2544                                    &CopyCtorArg, 1);
2545     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2546                                MultiExprArg(&CopyCtorArg, 1));
2547     break;
2548   }
2549   }
2550 
2551   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2552   if (BaseInit.isInvalid())
2553     return true;
2554 
2555   CXXBaseInit =
2556     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2557                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2558                                                         SourceLocation()),
2559                                              BaseSpec->isVirtual(),
2560                                              SourceLocation(),
2561                                              BaseInit.takeAs<Expr>(),
2562                                              SourceLocation(),
2563                                              SourceLocation());
2564 
2565   return false;
2566 }
2567 
2568 static bool RefersToRValueRef(Expr *MemRef) {
2569   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2570   return Referenced->getType()->isRValueReferenceType();
2571 }
2572 
2573 static bool
2574 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2575                                ImplicitInitializerKind ImplicitInitKind,
2576                                FieldDecl *Field, IndirectFieldDecl *Indirect,
2577                                CXXCtorInitializer *&CXXMemberInit) {
2578   if (Field->isInvalidDecl())
2579     return true;
2580 
2581   SourceLocation Loc = Constructor->getLocation();
2582 
2583   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2584     bool Moving = ImplicitInitKind == IIK_Move;
2585     ParmVarDecl *Param = Constructor->getParamDecl(0);
2586     QualType ParamType = Param->getType().getNonReferenceType();
2587 
2588     // Suppress copying zero-width bitfields.
2589     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2590       return false;
2591 
2592     Expr *MemberExprBase =
2593       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2594                           SourceLocation(), Param, false,
2595                           Loc, ParamType, VK_LValue, 0);
2596 
2597     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2598 
2599     if (Moving) {
2600       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2601     }
2602 
2603     // Build a reference to this field within the parameter.
2604     CXXScopeSpec SS;
2605     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2606                               Sema::LookupMemberName);
2607     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2608                                   : cast<ValueDecl>(Field), AS_public);
2609     MemberLookup.resolveKind();
2610     ExprResult CtorArg
2611       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2612                                          ParamType, Loc,
2613                                          /*IsArrow=*/false,
2614                                          SS,
2615                                          /*TemplateKWLoc=*/SourceLocation(),
2616                                          /*FirstQualifierInScope=*/0,
2617                                          MemberLookup,
2618                                          /*TemplateArgs=*/0);
2619     if (CtorArg.isInvalid())
2620       return true;
2621 
2622     // C++11 [class.copy]p15:
2623     //   - if a member m has rvalue reference type T&&, it is direct-initialized
2624     //     with static_cast<T&&>(x.m);
2625     if (RefersToRValueRef(CtorArg.get())) {
2626       CtorArg = CastForMoving(SemaRef, CtorArg.take());
2627     }
2628 
2629     // When the field we are copying is an array, create index variables for
2630     // each dimension of the array. We use these index variables to subscript
2631     // the source array, and other clients (e.g., CodeGen) will perform the
2632     // necessary iteration with these index variables.
2633     SmallVector<VarDecl *, 4> IndexVariables;
2634     QualType BaseType = Field->getType();
2635     QualType SizeType = SemaRef.Context.getSizeType();
2636     bool InitializingArray = false;
2637     while (const ConstantArrayType *Array
2638                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2639       InitializingArray = true;
2640       // Create the iteration variable for this array index.
2641       IdentifierInfo *IterationVarName = 0;
2642       {
2643         SmallString<8> Str;
2644         llvm::raw_svector_ostream OS(Str);
2645         OS << "__i" << IndexVariables.size();
2646         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2647       }
2648       VarDecl *IterationVar
2649         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2650                           IterationVarName, SizeType,
2651                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2652                           SC_None, SC_None);
2653       IndexVariables.push_back(IterationVar);
2654 
2655       // Create a reference to the iteration variable.
2656       ExprResult IterationVarRef
2657         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
2658       assert(!IterationVarRef.isInvalid() &&
2659              "Reference to invented variable cannot fail!");
2660       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2661       assert(!IterationVarRef.isInvalid() &&
2662              "Conversion of invented variable cannot fail!");
2663 
2664       // Subscript the array with this iteration variable.
2665       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
2666                                                         IterationVarRef.take(),
2667                                                         Loc);
2668       if (CtorArg.isInvalid())
2669         return true;
2670 
2671       BaseType = Array->getElementType();
2672     }
2673 
2674     // The array subscript expression is an lvalue, which is wrong for moving.
2675     if (Moving && InitializingArray)
2676       CtorArg = CastForMoving(SemaRef, CtorArg.take());
2677 
2678     // Construct the entity that we will be initializing. For an array, this
2679     // will be first element in the array, which may require several levels
2680     // of array-subscript entities.
2681     SmallVector<InitializedEntity, 4> Entities;
2682     Entities.reserve(1 + IndexVariables.size());
2683     if (Indirect)
2684       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2685     else
2686       Entities.push_back(InitializedEntity::InitializeMember(Field));
2687     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2688       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2689                                                               0,
2690                                                               Entities.back()));
2691 
2692     // Direct-initialize to use the copy constructor.
2693     InitializationKind InitKind =
2694       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2695 
2696     Expr *CtorArgE = CtorArg.takeAs<Expr>();
2697     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2698                                    &CtorArgE, 1);
2699 
2700     ExprResult MemberInit
2701       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2702                         MultiExprArg(&CtorArgE, 1));
2703     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2704     if (MemberInit.isInvalid())
2705       return true;
2706 
2707     if (Indirect) {
2708       assert(IndexVariables.size() == 0 &&
2709              "Indirect field improperly initialized");
2710       CXXMemberInit
2711         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2712                                                    Loc, Loc,
2713                                                    MemberInit.takeAs<Expr>(),
2714                                                    Loc);
2715     } else
2716       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2717                                                  Loc, MemberInit.takeAs<Expr>(),
2718                                                  Loc,
2719                                                  IndexVariables.data(),
2720                                                  IndexVariables.size());
2721     return false;
2722   }
2723 
2724   assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2725 
2726   QualType FieldBaseElementType =
2727     SemaRef.Context.getBaseElementType(Field->getType());
2728 
2729   if (FieldBaseElementType->isRecordType()) {
2730     InitializedEntity InitEntity
2731       = Indirect? InitializedEntity::InitializeMember(Indirect)
2732                 : InitializedEntity::InitializeMember(Field);
2733     InitializationKind InitKind =
2734       InitializationKind::CreateDefault(Loc);
2735 
2736     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2737     ExprResult MemberInit =
2738       InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2739 
2740     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2741     if (MemberInit.isInvalid())
2742       return true;
2743 
2744     if (Indirect)
2745       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2746                                                                Indirect, Loc,
2747                                                                Loc,
2748                                                                MemberInit.get(),
2749                                                                Loc);
2750     else
2751       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2752                                                                Field, Loc, Loc,
2753                                                                MemberInit.get(),
2754                                                                Loc);
2755     return false;
2756   }
2757 
2758   if (!Field->getParent()->isUnion()) {
2759     if (FieldBaseElementType->isReferenceType()) {
2760       SemaRef.Diag(Constructor->getLocation(),
2761                    diag::err_uninitialized_member_in_ctor)
2762       << (int)Constructor->isImplicit()
2763       << SemaRef.Context.getTagDeclType(Constructor->getParent())
2764       << 0 << Field->getDeclName();
2765       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2766       return true;
2767     }
2768 
2769     if (FieldBaseElementType.isConstQualified()) {
2770       SemaRef.Diag(Constructor->getLocation(),
2771                    diag::err_uninitialized_member_in_ctor)
2772       << (int)Constructor->isImplicit()
2773       << SemaRef.Context.getTagDeclType(Constructor->getParent())
2774       << 1 << Field->getDeclName();
2775       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2776       return true;
2777     }
2778   }
2779 
2780   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2781       FieldBaseElementType->isObjCRetainableType() &&
2782       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2783       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2784     // ARC:
2785     //   Default-initialize Objective-C pointers to NULL.
2786     CXXMemberInit
2787       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2788                                                  Loc, Loc,
2789                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2790                                                  Loc);
2791     return false;
2792   }
2793 
2794   // Nothing to initialize.
2795   CXXMemberInit = 0;
2796   return false;
2797 }
2798 
2799 namespace {
2800 struct BaseAndFieldInfo {
2801   Sema &S;
2802   CXXConstructorDecl *Ctor;
2803   bool AnyErrorsInInits;
2804   ImplicitInitializerKind IIK;
2805   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2806   SmallVector<CXXCtorInitializer*, 8> AllToInit;
2807 
2808   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2809     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2810     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2811     if (Generated && Ctor->isCopyConstructor())
2812       IIK = IIK_Copy;
2813     else if (Generated && Ctor->isMoveConstructor())
2814       IIK = IIK_Move;
2815     else
2816       IIK = IIK_Default;
2817   }
2818 
2819   bool isImplicitCopyOrMove() const {
2820     switch (IIK) {
2821     case IIK_Copy:
2822     case IIK_Move:
2823       return true;
2824 
2825     case IIK_Default:
2826       return false;
2827     }
2828 
2829     llvm_unreachable("Invalid ImplicitInitializerKind!");
2830   }
2831 
2832   bool addFieldInitializer(CXXCtorInitializer *Init) {
2833     AllToInit.push_back(Init);
2834 
2835     // Check whether this initializer makes the field "used".
2836     if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2837       S.UnusedPrivateFields.remove(Init->getAnyMember());
2838 
2839     return false;
2840   }
2841 };
2842 }
2843 
2844 /// \brief Determine whether the given indirect field declaration is somewhere
2845 /// within an anonymous union.
2846 static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2847   for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2848                                       CEnd = F->chain_end();
2849        C != CEnd; ++C)
2850     if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2851       if (Record->isUnion())
2852         return true;
2853 
2854   return false;
2855 }
2856 
2857 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
2858 /// array type.
2859 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2860   if (T->isIncompleteArrayType())
2861     return true;
2862 
2863   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2864     if (!ArrayT->getSize())
2865       return true;
2866 
2867     T = ArrayT->getElementType();
2868   }
2869 
2870   return false;
2871 }
2872 
2873 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
2874                                     FieldDecl *Field,
2875                                     IndirectFieldDecl *Indirect = 0) {
2876 
2877   // Overwhelmingly common case: we have a direct initializer for this field.
2878   if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
2879     return Info.addFieldInitializer(Init);
2880 
2881   // C++11 [class.base.init]p8: if the entity is a non-static data member that
2882   // has a brace-or-equal-initializer, the entity is initialized as specified
2883   // in [dcl.init].
2884   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
2885     CXXCtorInitializer *Init;
2886     if (Indirect)
2887       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2888                                                       SourceLocation(),
2889                                                       SourceLocation(), 0,
2890                                                       SourceLocation());
2891     else
2892       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2893                                                       SourceLocation(),
2894                                                       SourceLocation(), 0,
2895                                                       SourceLocation());
2896     return Info.addFieldInitializer(Init);
2897   }
2898 
2899   // Don't build an implicit initializer for union members if none was
2900   // explicitly specified.
2901   if (Field->getParent()->isUnion() ||
2902       (Indirect && isWithinAnonymousUnion(Indirect)))
2903     return false;
2904 
2905   // Don't initialize incomplete or zero-length arrays.
2906   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2907     return false;
2908 
2909   // Don't try to build an implicit initializer if there were semantic
2910   // errors in any of the initializers (and therefore we might be
2911   // missing some that the user actually wrote).
2912   if (Info.AnyErrorsInInits || Field->isInvalidDecl())
2913     return false;
2914 
2915   CXXCtorInitializer *Init = 0;
2916   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2917                                      Indirect, Init))
2918     return true;
2919 
2920   if (!Init)
2921     return false;
2922 
2923   return Info.addFieldInitializer(Init);
2924 }
2925 
2926 bool
2927 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2928                                CXXCtorInitializer *Initializer) {
2929   assert(Initializer->isDelegatingInitializer());
2930   Constructor->setNumCtorInitializers(1);
2931   CXXCtorInitializer **initializer =
2932     new (Context) CXXCtorInitializer*[1];
2933   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2934   Constructor->setCtorInitializers(initializer);
2935 
2936   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2937     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
2938     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2939   }
2940 
2941   DelegatingCtorDecls.push_back(Constructor);
2942 
2943   return false;
2944 }
2945 
2946 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2947                                CXXCtorInitializer **Initializers,
2948                                unsigned NumInitializers,
2949                                bool AnyErrors) {
2950   if (Constructor->isDependentContext()) {
2951     // Just store the initializers as written, they will be checked during
2952     // instantiation.
2953     if (NumInitializers > 0) {
2954       Constructor->setNumCtorInitializers(NumInitializers);
2955       CXXCtorInitializer **baseOrMemberInitializers =
2956         new (Context) CXXCtorInitializer*[NumInitializers];
2957       memcpy(baseOrMemberInitializers, Initializers,
2958              NumInitializers * sizeof(CXXCtorInitializer*));
2959       Constructor->setCtorInitializers(baseOrMemberInitializers);
2960     }
2961 
2962     return false;
2963   }
2964 
2965   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
2966 
2967   // We need to build the initializer AST according to order of construction
2968   // and not what user specified in the Initializers list.
2969   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
2970   if (!ClassDecl)
2971     return true;
2972 
2973   bool HadError = false;
2974 
2975   for (unsigned i = 0; i < NumInitializers; i++) {
2976     CXXCtorInitializer *Member = Initializers[i];
2977 
2978     if (Member->isBaseInitializer())
2979       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
2980     else
2981       Info.AllBaseFields[Member->getAnyMember()] = Member;
2982   }
2983 
2984   // Keep track of the direct virtual bases.
2985   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2986   for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2987        E = ClassDecl->bases_end(); I != E; ++I) {
2988     if (I->isVirtual())
2989       DirectVBases.insert(I);
2990   }
2991 
2992   // Push virtual bases before others.
2993   for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2994        E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2995 
2996     if (CXXCtorInitializer *Value
2997         = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2998       Info.AllToInit.push_back(Value);
2999     } else if (!AnyErrors) {
3000       bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3001       CXXCtorInitializer *CXXBaseInit;
3002       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3003                                        VBase, IsInheritedVirtualBase,
3004                                        CXXBaseInit)) {
3005         HadError = true;
3006         continue;
3007       }
3008 
3009       Info.AllToInit.push_back(CXXBaseInit);
3010     }
3011   }
3012 
3013   // Non-virtual bases.
3014   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3015        E = ClassDecl->bases_end(); Base != E; ++Base) {
3016     // Virtuals are in the virtual base list and already constructed.
3017     if (Base->isVirtual())
3018       continue;
3019 
3020     if (CXXCtorInitializer *Value
3021           = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3022       Info.AllToInit.push_back(Value);
3023     } else if (!AnyErrors) {
3024       CXXCtorInitializer *CXXBaseInit;
3025       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3026                                        Base, /*IsInheritedVirtualBase=*/false,
3027                                        CXXBaseInit)) {
3028         HadError = true;
3029         continue;
3030       }
3031 
3032       Info.AllToInit.push_back(CXXBaseInit);
3033     }
3034   }
3035 
3036   // Fields.
3037   for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3038                                MemEnd = ClassDecl->decls_end();
3039        Mem != MemEnd; ++Mem) {
3040     if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3041       // C++ [class.bit]p2:
3042       //   A declaration for a bit-field that omits the identifier declares an
3043       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3044       //   initialized.
3045       if (F->isUnnamedBitfield())
3046         continue;
3047 
3048       // If we're not generating the implicit copy/move constructor, then we'll
3049       // handle anonymous struct/union fields based on their individual
3050       // indirect fields.
3051       if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3052         continue;
3053 
3054       if (CollectFieldInitializer(*this, Info, F))
3055         HadError = true;
3056       continue;
3057     }
3058 
3059     // Beyond this point, we only consider default initialization.
3060     if (Info.IIK != IIK_Default)
3061       continue;
3062 
3063     if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3064       if (F->getType()->isIncompleteArrayType()) {
3065         assert(ClassDecl->hasFlexibleArrayMember() &&
3066                "Incomplete array type is not valid");
3067         continue;
3068       }
3069 
3070       // Initialize each field of an anonymous struct individually.
3071       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3072         HadError = true;
3073 
3074       continue;
3075     }
3076   }
3077 
3078   NumInitializers = Info.AllToInit.size();
3079   if (NumInitializers > 0) {
3080     Constructor->setNumCtorInitializers(NumInitializers);
3081     CXXCtorInitializer **baseOrMemberInitializers =
3082       new (Context) CXXCtorInitializer*[NumInitializers];
3083     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3084            NumInitializers * sizeof(CXXCtorInitializer*));
3085     Constructor->setCtorInitializers(baseOrMemberInitializers);
3086 
3087     // Constructors implicitly reference the base and member
3088     // destructors.
3089     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3090                                            Constructor->getParent());
3091   }
3092 
3093   return HadError;
3094 }
3095 
3096 static void *GetKeyForTopLevelField(FieldDecl *Field) {
3097   // For anonymous unions, use the class declaration as the key.
3098   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3099     if (RT->getDecl()->isAnonymousStructOrUnion())
3100       return static_cast<void *>(RT->getDecl());
3101   }
3102   return static_cast<void *>(Field);
3103 }
3104 
3105 static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3106   return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3107 }
3108 
3109 static void *GetKeyForMember(ASTContext &Context,
3110                              CXXCtorInitializer *Member) {
3111   if (!Member->isAnyMemberInitializer())
3112     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3113 
3114   // For fields injected into the class via declaration of an anonymous union,
3115   // use its anonymous union class declaration as the unique key.
3116   FieldDecl *Field = Member->getAnyMember();
3117 
3118   // If the field is a member of an anonymous struct or union, our key
3119   // is the anonymous record decl that's a direct child of the class.
3120   RecordDecl *RD = Field->getParent();
3121   if (RD->isAnonymousStructOrUnion()) {
3122     while (true) {
3123       RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3124       if (Parent->isAnonymousStructOrUnion())
3125         RD = Parent;
3126       else
3127         break;
3128     }
3129 
3130     return static_cast<void *>(RD);
3131   }
3132 
3133   return static_cast<void *>(Field);
3134 }
3135 
3136 static void
3137 DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
3138                                   const CXXConstructorDecl *Constructor,
3139                                   CXXCtorInitializer **Inits,
3140                                   unsigned NumInits) {
3141   if (Constructor->getDeclContext()->isDependentContext())
3142     return;
3143 
3144   // Don't check initializers order unless the warning is enabled at the
3145   // location of at least one initializer.
3146   bool ShouldCheckOrder = false;
3147   for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3148     CXXCtorInitializer *Init = Inits[InitIndex];
3149     if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3150                                          Init->getSourceLocation())
3151           != DiagnosticsEngine::Ignored) {
3152       ShouldCheckOrder = true;
3153       break;
3154     }
3155   }
3156   if (!ShouldCheckOrder)
3157     return;
3158 
3159   // Build the list of bases and members in the order that they'll
3160   // actually be initialized.  The explicit initializers should be in
3161   // this same order but may be missing things.
3162   SmallVector<const void*, 32> IdealInitKeys;
3163 
3164   const CXXRecordDecl *ClassDecl = Constructor->getParent();
3165 
3166   // 1. Virtual bases.
3167   for (CXXRecordDecl::base_class_const_iterator VBase =
3168        ClassDecl->vbases_begin(),
3169        E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3170     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3171 
3172   // 2. Non-virtual bases.
3173   for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3174        E = ClassDecl->bases_end(); Base != E; ++Base) {
3175     if (Base->isVirtual())
3176       continue;
3177     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3178   }
3179 
3180   // 3. Direct fields.
3181   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3182        E = ClassDecl->field_end(); Field != E; ++Field) {
3183     if (Field->isUnnamedBitfield())
3184       continue;
3185 
3186     IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
3187   }
3188 
3189   unsigned NumIdealInits = IdealInitKeys.size();
3190   unsigned IdealIndex = 0;
3191 
3192   CXXCtorInitializer *PrevInit = 0;
3193   for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3194     CXXCtorInitializer *Init = Inits[InitIndex];
3195     void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3196 
3197     // Scan forward to try to find this initializer in the idealized
3198     // initializers list.
3199     for (; IdealIndex != NumIdealInits; ++IdealIndex)
3200       if (InitKey == IdealInitKeys[IdealIndex])
3201         break;
3202 
3203     // If we didn't find this initializer, it must be because we
3204     // scanned past it on a previous iteration.  That can only
3205     // happen if we're out of order;  emit a warning.
3206     if (IdealIndex == NumIdealInits && PrevInit) {
3207       Sema::SemaDiagnosticBuilder D =
3208         SemaRef.Diag(PrevInit->getSourceLocation(),
3209                      diag::warn_initializer_out_of_order);
3210 
3211       if (PrevInit->isAnyMemberInitializer())
3212         D << 0 << PrevInit->getAnyMember()->getDeclName();
3213       else
3214         D << 1 << PrevInit->getTypeSourceInfo()->getType();
3215 
3216       if (Init->isAnyMemberInitializer())
3217         D << 0 << Init->getAnyMember()->getDeclName();
3218       else
3219         D << 1 << Init->getTypeSourceInfo()->getType();
3220 
3221       // Move back to the initializer's location in the ideal list.
3222       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3223         if (InitKey == IdealInitKeys[IdealIndex])
3224           break;
3225 
3226       assert(IdealIndex != NumIdealInits &&
3227              "initializer not found in initializer list");
3228     }
3229 
3230     PrevInit = Init;
3231   }
3232 }
3233 
3234 namespace {
3235 bool CheckRedundantInit(Sema &S,
3236                         CXXCtorInitializer *Init,
3237                         CXXCtorInitializer *&PrevInit) {
3238   if (!PrevInit) {
3239     PrevInit = Init;
3240     return false;
3241   }
3242 
3243   if (FieldDecl *Field = Init->getMember())
3244     S.Diag(Init->getSourceLocation(),
3245            diag::err_multiple_mem_initialization)
3246       << Field->getDeclName()
3247       << Init->getSourceRange();
3248   else {
3249     const Type *BaseClass = Init->getBaseClass();
3250     assert(BaseClass && "neither field nor base");
3251     S.Diag(Init->getSourceLocation(),
3252            diag::err_multiple_base_initialization)
3253       << QualType(BaseClass, 0)
3254       << Init->getSourceRange();
3255   }
3256   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3257     << 0 << PrevInit->getSourceRange();
3258 
3259   return true;
3260 }
3261 
3262 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3263 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3264 
3265 bool CheckRedundantUnionInit(Sema &S,
3266                              CXXCtorInitializer *Init,
3267                              RedundantUnionMap &Unions) {
3268   FieldDecl *Field = Init->getAnyMember();
3269   RecordDecl *Parent = Field->getParent();
3270   NamedDecl *Child = Field;
3271 
3272   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3273     if (Parent->isUnion()) {
3274       UnionEntry &En = Unions[Parent];
3275       if (En.first && En.first != Child) {
3276         S.Diag(Init->getSourceLocation(),
3277                diag::err_multiple_mem_union_initialization)
3278           << Field->getDeclName()
3279           << Init->getSourceRange();
3280         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3281           << 0 << En.second->getSourceRange();
3282         return true;
3283       }
3284       if (!En.first) {
3285         En.first = Child;
3286         En.second = Init;
3287       }
3288       if (!Parent->isAnonymousStructOrUnion())
3289         return false;
3290     }
3291 
3292     Child = Parent;
3293     Parent = cast<RecordDecl>(Parent->getDeclContext());
3294   }
3295 
3296   return false;
3297 }
3298 }
3299 
3300 /// ActOnMemInitializers - Handle the member initializers for a constructor.
3301 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3302                                 SourceLocation ColonLoc,
3303                                 CXXCtorInitializer **meminits,
3304                                 unsigned NumMemInits,
3305                                 bool AnyErrors) {
3306   if (!ConstructorDecl)
3307     return;
3308 
3309   AdjustDeclIfTemplate(ConstructorDecl);
3310 
3311   CXXConstructorDecl *Constructor
3312     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3313 
3314   if (!Constructor) {
3315     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3316     return;
3317   }
3318 
3319   CXXCtorInitializer **MemInits =
3320     reinterpret_cast<CXXCtorInitializer **>(meminits);
3321 
3322   // Mapping for the duplicate initializers check.
3323   // For member initializers, this is keyed with a FieldDecl*.
3324   // For base initializers, this is keyed with a Type*.
3325   llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3326 
3327   // Mapping for the inconsistent anonymous-union initializers check.
3328   RedundantUnionMap MemberUnions;
3329 
3330   bool HadError = false;
3331   for (unsigned i = 0; i < NumMemInits; i++) {
3332     CXXCtorInitializer *Init = MemInits[i];
3333 
3334     // Set the source order index.
3335     Init->setSourceOrder(i);
3336 
3337     if (Init->isAnyMemberInitializer()) {
3338       FieldDecl *Field = Init->getAnyMember();
3339       if (CheckRedundantInit(*this, Init, Members[Field]) ||
3340           CheckRedundantUnionInit(*this, Init, MemberUnions))
3341         HadError = true;
3342     } else if (Init->isBaseInitializer()) {
3343       void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3344       if (CheckRedundantInit(*this, Init, Members[Key]))
3345         HadError = true;
3346     } else {
3347       assert(Init->isDelegatingInitializer());
3348       // This must be the only initializer
3349       if (i != 0 || NumMemInits > 1) {
3350         Diag(MemInits[0]->getSourceLocation(),
3351              diag::err_delegating_initializer_alone)
3352           << MemInits[0]->getSourceRange();
3353         HadError = true;
3354         // We will treat this as being the only initializer.
3355       }
3356       SetDelegatingInitializer(Constructor, MemInits[i]);
3357       // Return immediately as the initializer is set.
3358       return;
3359     }
3360   }
3361 
3362   if (HadError)
3363     return;
3364 
3365   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
3366 
3367   SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
3368 }
3369 
3370 void
3371 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3372                                              CXXRecordDecl *ClassDecl) {
3373   // Ignore dependent contexts. Also ignore unions, since their members never
3374   // have destructors implicitly called.
3375   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3376     return;
3377 
3378   // FIXME: all the access-control diagnostics are positioned on the
3379   // field/base declaration.  That's probably good; that said, the
3380   // user might reasonably want to know why the destructor is being
3381   // emitted, and we currently don't say.
3382 
3383   // Non-static data members.
3384   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3385        E = ClassDecl->field_end(); I != E; ++I) {
3386     FieldDecl *Field = *I;
3387     if (Field->isInvalidDecl())
3388       continue;
3389 
3390     // Don't destroy incomplete or zero-length arrays.
3391     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3392       continue;
3393 
3394     QualType FieldType = Context.getBaseElementType(Field->getType());
3395 
3396     const RecordType* RT = FieldType->getAs<RecordType>();
3397     if (!RT)
3398       continue;
3399 
3400     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3401     if (FieldClassDecl->isInvalidDecl())
3402       continue;
3403     if (FieldClassDecl->hasIrrelevantDestructor())
3404       continue;
3405     // The destructor for an implicit anonymous union member is never invoked.
3406     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3407       continue;
3408 
3409     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3410     assert(Dtor && "No dtor found for FieldClassDecl!");
3411     CheckDestructorAccess(Field->getLocation(), Dtor,
3412                           PDiag(diag::err_access_dtor_field)
3413                             << Field->getDeclName()
3414                             << FieldType);
3415 
3416     MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3417     DiagnoseUseOfDecl(Dtor, Location);
3418   }
3419 
3420   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3421 
3422   // Bases.
3423   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3424        E = ClassDecl->bases_end(); Base != E; ++Base) {
3425     // Bases are always records in a well-formed non-dependent class.
3426     const RecordType *RT = Base->getType()->getAs<RecordType>();
3427 
3428     // Remember direct virtual bases.
3429     if (Base->isVirtual())
3430       DirectVirtualBases.insert(RT);
3431 
3432     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3433     // If our base class is invalid, we probably can't get its dtor anyway.
3434     if (BaseClassDecl->isInvalidDecl())
3435       continue;
3436     if (BaseClassDecl->hasIrrelevantDestructor())
3437       continue;
3438 
3439     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3440     assert(Dtor && "No dtor found for BaseClassDecl!");
3441 
3442     // FIXME: caret should be on the start of the class name
3443     CheckDestructorAccess(Base->getLocStart(), Dtor,
3444                           PDiag(diag::err_access_dtor_base)
3445                             << Base->getType()
3446                             << Base->getSourceRange(),
3447                           Context.getTypeDeclType(ClassDecl));
3448 
3449     MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3450     DiagnoseUseOfDecl(Dtor, Location);
3451   }
3452 
3453   // Virtual bases.
3454   for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3455        E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3456 
3457     // Bases are always records in a well-formed non-dependent class.
3458     const RecordType *RT = VBase->getType()->castAs<RecordType>();
3459 
3460     // Ignore direct virtual bases.
3461     if (DirectVirtualBases.count(RT))
3462       continue;
3463 
3464     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3465     // If our base class is invalid, we probably can't get its dtor anyway.
3466     if (BaseClassDecl->isInvalidDecl())
3467       continue;
3468     if (BaseClassDecl->hasIrrelevantDestructor())
3469       continue;
3470 
3471     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3472     assert(Dtor && "No dtor found for BaseClassDecl!");
3473     CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3474                           PDiag(diag::err_access_dtor_vbase)
3475                             << VBase->getType(),
3476                           Context.getTypeDeclType(ClassDecl));
3477 
3478     MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3479     DiagnoseUseOfDecl(Dtor, Location);
3480   }
3481 }
3482 
3483 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3484   if (!CDtorDecl)
3485     return;
3486 
3487   if (CXXConstructorDecl *Constructor
3488       = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3489     SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
3490 }
3491 
3492 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3493                                   unsigned DiagID, AbstractDiagSelID SelID) {
3494   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3495     unsigned DiagID;
3496     AbstractDiagSelID SelID;
3497 
3498   public:
3499     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3500       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3501 
3502     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3503       if (Suppressed) return;
3504       if (SelID == -1)
3505         S.Diag(Loc, DiagID) << T;
3506       else
3507         S.Diag(Loc, DiagID) << SelID << T;
3508     }
3509   } Diagnoser(DiagID, SelID);
3510 
3511   return RequireNonAbstractType(Loc, T, Diagnoser);
3512 }
3513 
3514 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3515                                   TypeDiagnoser &Diagnoser) {
3516   if (!getLangOpts().CPlusPlus)
3517     return false;
3518 
3519   if (const ArrayType *AT = Context.getAsArrayType(T))
3520     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3521 
3522   if (const PointerType *PT = T->getAs<PointerType>()) {
3523     // Find the innermost pointer type.
3524     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3525       PT = T;
3526 
3527     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3528       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3529   }
3530 
3531   const RecordType *RT = T->getAs<RecordType>();
3532   if (!RT)
3533     return false;
3534 
3535   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3536 
3537   // We can't answer whether something is abstract until it has a
3538   // definition.  If it's currently being defined, we'll walk back
3539   // over all the declarations when we have a full definition.
3540   const CXXRecordDecl *Def = RD->getDefinition();
3541   if (!Def || Def->isBeingDefined())
3542     return false;
3543 
3544   if (!RD->isAbstract())
3545     return false;
3546 
3547   Diagnoser.diagnose(*this, Loc, T);
3548   DiagnoseAbstractType(RD);
3549 
3550   return true;
3551 }
3552 
3553 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3554   // Check if we've already emitted the list of pure virtual functions
3555   // for this class.
3556   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3557     return;
3558 
3559   CXXFinalOverriderMap FinalOverriders;
3560   RD->getFinalOverriders(FinalOverriders);
3561 
3562   // Keep a set of seen pure methods so we won't diagnose the same method
3563   // more than once.
3564   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3565 
3566   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3567                                    MEnd = FinalOverriders.end();
3568        M != MEnd;
3569        ++M) {
3570     for (OverridingMethods::iterator SO = M->second.begin(),
3571                                   SOEnd = M->second.end();
3572          SO != SOEnd; ++SO) {
3573       // C++ [class.abstract]p4:
3574       //   A class is abstract if it contains or inherits at least one
3575       //   pure virtual function for which the final overrider is pure
3576       //   virtual.
3577 
3578       //
3579       if (SO->second.size() != 1)
3580         continue;
3581 
3582       if (!SO->second.front().Method->isPure())
3583         continue;
3584 
3585       if (!SeenPureMethods.insert(SO->second.front().Method))
3586         continue;
3587 
3588       Diag(SO->second.front().Method->getLocation(),
3589            diag::note_pure_virtual_function)
3590         << SO->second.front().Method->getDeclName() << RD->getDeclName();
3591     }
3592   }
3593 
3594   if (!PureVirtualClassDiagSet)
3595     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3596   PureVirtualClassDiagSet->insert(RD);
3597 }
3598 
3599 namespace {
3600 struct AbstractUsageInfo {
3601   Sema &S;
3602   CXXRecordDecl *Record;
3603   CanQualType AbstractType;
3604   bool Invalid;
3605 
3606   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3607     : S(S), Record(Record),
3608       AbstractType(S.Context.getCanonicalType(
3609                    S.Context.getTypeDeclType(Record))),
3610       Invalid(false) {}
3611 
3612   void DiagnoseAbstractType() {
3613     if (Invalid) return;
3614     S.DiagnoseAbstractType(Record);
3615     Invalid = true;
3616   }
3617 
3618   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3619 };
3620 
3621 struct CheckAbstractUsage {
3622   AbstractUsageInfo &Info;
3623   const NamedDecl *Ctx;
3624 
3625   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3626     : Info(Info), Ctx(Ctx) {}
3627 
3628   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3629     switch (TL.getTypeLocClass()) {
3630 #define ABSTRACT_TYPELOC(CLASS, PARENT)
3631 #define TYPELOC(CLASS, PARENT) \
3632     case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3633 #include "clang/AST/TypeLocNodes.def"
3634     }
3635   }
3636 
3637   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3638     Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3639     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3640       if (!TL.getArg(I))
3641         continue;
3642 
3643       TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3644       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3645     }
3646   }
3647 
3648   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3649     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3650   }
3651 
3652   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3653     // Visit the type parameters from a permissive context.
3654     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3655       TemplateArgumentLoc TAL = TL.getArgLoc(I);
3656       if (TAL.getArgument().getKind() == TemplateArgument::Type)
3657         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3658           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3659       // TODO: other template argument types?
3660     }
3661   }
3662 
3663   // Visit pointee types from a permissive context.
3664 #define CheckPolymorphic(Type) \
3665   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3666     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3667   }
3668   CheckPolymorphic(PointerTypeLoc)
3669   CheckPolymorphic(ReferenceTypeLoc)
3670   CheckPolymorphic(MemberPointerTypeLoc)
3671   CheckPolymorphic(BlockPointerTypeLoc)
3672   CheckPolymorphic(AtomicTypeLoc)
3673 
3674   /// Handle all the types we haven't given a more specific
3675   /// implementation for above.
3676   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3677     // Every other kind of type that we haven't called out already
3678     // that has an inner type is either (1) sugar or (2) contains that
3679     // inner type in some way as a subobject.
3680     if (TypeLoc Next = TL.getNextTypeLoc())
3681       return Visit(Next, Sel);
3682 
3683     // If there's no inner type and we're in a permissive context,
3684     // don't diagnose.
3685     if (Sel == Sema::AbstractNone) return;
3686 
3687     // Check whether the type matches the abstract type.
3688     QualType T = TL.getType();
3689     if (T->isArrayType()) {
3690       Sel = Sema::AbstractArrayType;
3691       T = Info.S.Context.getBaseElementType(T);
3692     }
3693     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3694     if (CT != Info.AbstractType) return;
3695 
3696     // It matched; do some magic.
3697     if (Sel == Sema::AbstractArrayType) {
3698       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3699         << T << TL.getSourceRange();
3700     } else {
3701       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3702         << Sel << T << TL.getSourceRange();
3703     }
3704     Info.DiagnoseAbstractType();
3705   }
3706 };
3707 
3708 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3709                                   Sema::AbstractDiagSelID Sel) {
3710   CheckAbstractUsage(*this, D).Visit(TL, Sel);
3711 }
3712 
3713 }
3714 
3715 /// Check for invalid uses of an abstract type in a method declaration.
3716 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3717                                     CXXMethodDecl *MD) {
3718   // No need to do the check on definitions, which require that
3719   // the return/param types be complete.
3720   if (MD->doesThisDeclarationHaveABody())
3721     return;
3722 
3723   // For safety's sake, just ignore it if we don't have type source
3724   // information.  This should never happen for non-implicit methods,
3725   // but...
3726   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3727     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3728 }
3729 
3730 /// Check for invalid uses of an abstract type within a class definition.
3731 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3732                                     CXXRecordDecl *RD) {
3733   for (CXXRecordDecl::decl_iterator
3734          I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3735     Decl *D = *I;
3736     if (D->isImplicit()) continue;
3737 
3738     // Methods and method templates.
3739     if (isa<CXXMethodDecl>(D)) {
3740       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3741     } else if (isa<FunctionTemplateDecl>(D)) {
3742       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3743       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3744 
3745     // Fields and static variables.
3746     } else if (isa<FieldDecl>(D)) {
3747       FieldDecl *FD = cast<FieldDecl>(D);
3748       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3749         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3750     } else if (isa<VarDecl>(D)) {
3751       VarDecl *VD = cast<VarDecl>(D);
3752       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3753         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3754 
3755     // Nested classes and class templates.
3756     } else if (isa<CXXRecordDecl>(D)) {
3757       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3758     } else if (isa<ClassTemplateDecl>(D)) {
3759       CheckAbstractClassUsage(Info,
3760                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3761     }
3762   }
3763 }
3764 
3765 /// \brief Perform semantic checks on a class definition that has been
3766 /// completing, introducing implicitly-declared members, checking for
3767 /// abstract types, etc.
3768 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3769   if (!Record)
3770     return;
3771 
3772   if (Record->isAbstract() && !Record->isInvalidDecl()) {
3773     AbstractUsageInfo Info(*this, Record);
3774     CheckAbstractClassUsage(Info, Record);
3775   }
3776 
3777   // If this is not an aggregate type and has no user-declared constructor,
3778   // complain about any non-static data members of reference or const scalar
3779   // type, since they will never get initializers.
3780   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3781       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3782       !Record->isLambda()) {
3783     bool Complained = false;
3784     for (RecordDecl::field_iterator F = Record->field_begin(),
3785                                  FEnd = Record->field_end();
3786          F != FEnd; ++F) {
3787       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
3788         continue;
3789 
3790       if (F->getType()->isReferenceType() ||
3791           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3792         if (!Complained) {
3793           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3794             << Record->getTagKind() << Record;
3795           Complained = true;
3796         }
3797 
3798         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3799           << F->getType()->isReferenceType()
3800           << F->getDeclName();
3801       }
3802     }
3803   }
3804 
3805   if (Record->isDynamicClass() && !Record->isDependentType())
3806     DynamicClasses.push_back(Record);
3807 
3808   if (Record->getIdentifier()) {
3809     // C++ [class.mem]p13:
3810     //   If T is the name of a class, then each of the following shall have a
3811     //   name different from T:
3812     //     - every member of every anonymous union that is a member of class T.
3813     //
3814     // C++ [class.mem]p14:
3815     //   In addition, if class T has a user-declared constructor (12.1), every
3816     //   non-static data member of class T shall have a name different from T.
3817     for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3818          R.first != R.second; ++R.first) {
3819       NamedDecl *D = *R.first;
3820       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3821           isa<IndirectFieldDecl>(D)) {
3822         Diag(D->getLocation(), diag::err_member_name_of_class)
3823           << D->getDeclName();
3824         break;
3825       }
3826     }
3827   }
3828 
3829   // Warn if the class has virtual methods but non-virtual public destructor.
3830   if (Record->isPolymorphic() && !Record->isDependentType()) {
3831     CXXDestructorDecl *dtor = Record->getDestructor();
3832     if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3833       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3834            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3835   }
3836 
3837   // See if a method overloads virtual methods in a base
3838   /// class without overriding any.
3839   if (!Record->isDependentType()) {
3840     for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3841                                      MEnd = Record->method_end();
3842          M != MEnd; ++M) {
3843       if (!M->isStatic())
3844         DiagnoseHiddenVirtualMethods(Record, *M);
3845     }
3846   }
3847 
3848   // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3849   // function that is not a constructor declares that member function to be
3850   // const. [...] The class of which that function is a member shall be
3851   // a literal type.
3852   //
3853   // If the class has virtual bases, any constexpr members will already have
3854   // been diagnosed by the checks performed on the member declaration, so
3855   // suppress this (less useful) diagnostic.
3856   if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3857       !Record->isLiteral() && !Record->getNumVBases()) {
3858     for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3859                                      MEnd = Record->method_end();
3860          M != MEnd; ++M) {
3861       if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
3862         switch (Record->getTemplateSpecializationKind()) {
3863         case TSK_ImplicitInstantiation:
3864         case TSK_ExplicitInstantiationDeclaration:
3865         case TSK_ExplicitInstantiationDefinition:
3866           // If a template instantiates to a non-literal type, but its members
3867           // instantiate to constexpr functions, the template is technically
3868           // ill-formed, but we allow it for sanity.
3869           continue;
3870 
3871         case TSK_Undeclared:
3872         case TSK_ExplicitSpecialization:
3873           RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
3874                              diag::err_constexpr_method_non_literal);
3875           break;
3876         }
3877 
3878         // Only produce one error per class.
3879         break;
3880       }
3881     }
3882   }
3883 
3884   // Declare inherited constructors. We do this eagerly here because:
3885   // - The standard requires an eager diagnostic for conflicting inherited
3886   //   constructors from different classes.
3887   // - The lazy declaration of the other implicit constructors is so as to not
3888   //   waste space and performance on classes that are not meant to be
3889   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
3890   //   have inherited constructors.
3891   DeclareInheritedConstructors(Record);
3892 }
3893 
3894 void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3895   for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3896                                       ME = Record->method_end();
3897        MI != ME; ++MI)
3898     if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
3899       CheckExplicitlyDefaultedSpecialMember(*MI);
3900 }
3901 
3902 /// Is the special member function which would be selected to perform the
3903 /// specified operation on the specified class type a constexpr constructor?
3904 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3905                                      Sema::CXXSpecialMember CSM,
3906                                      bool ConstArg) {
3907   Sema::SpecialMemberOverloadResult *SMOR =
3908       S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
3909                             false, false, false, false);
3910   if (!SMOR || !SMOR->getMethod())
3911     // A constructor we wouldn't select can't be "involved in initializing"
3912     // anything.
3913     return true;
3914   return SMOR->getMethod()->isConstexpr();
3915 }
3916 
3917 /// Determine whether the specified special member function would be constexpr
3918 /// if it were implicitly defined.
3919 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3920                                               Sema::CXXSpecialMember CSM,
3921                                               bool ConstArg) {
3922   if (!S.getLangOpts().CPlusPlus0x)
3923     return false;
3924 
3925   // C++11 [dcl.constexpr]p4:
3926   // In the definition of a constexpr constructor [...]
3927   switch (CSM) {
3928   case Sema::CXXDefaultConstructor:
3929     // Since default constructor lookup is essentially trivial (and cannot
3930     // involve, for instance, template instantiation), we compute whether a
3931     // defaulted default constructor is constexpr directly within CXXRecordDecl.
3932     //
3933     // This is important for performance; we need to know whether the default
3934     // constructor is constexpr to determine whether the type is a literal type.
3935     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
3936 
3937   case Sema::CXXCopyConstructor:
3938   case Sema::CXXMoveConstructor:
3939     // For copy or move constructors, we need to perform overload resolution.
3940     break;
3941 
3942   case Sema::CXXCopyAssignment:
3943   case Sema::CXXMoveAssignment:
3944   case Sema::CXXDestructor:
3945   case Sema::CXXInvalid:
3946     return false;
3947   }
3948 
3949   //   -- if the class is a non-empty union, or for each non-empty anonymous
3950   //      union member of a non-union class, exactly one non-static data member
3951   //      shall be initialized; [DR1359]
3952   //
3953   // If we squint, this is guaranteed, since exactly one non-static data member
3954   // will be initialized (if the constructor isn't deleted), we just don't know
3955   // which one.
3956   if (ClassDecl->isUnion())
3957     return true;
3958 
3959   //   -- the class shall not have any virtual base classes;
3960   if (ClassDecl->getNumVBases())
3961     return false;
3962 
3963   //   -- every constructor involved in initializing [...] base class
3964   //      sub-objects shall be a constexpr constructor;
3965   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
3966                                        BEnd = ClassDecl->bases_end();
3967        B != BEnd; ++B) {
3968     const RecordType *BaseType = B->getType()->getAs<RecordType>();
3969     if (!BaseType) continue;
3970 
3971     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
3972     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
3973       return false;
3974   }
3975 
3976   //   -- every constructor involved in initializing non-static data members
3977   //      [...] shall be a constexpr constructor;
3978   //   -- every non-static data member and base class sub-object shall be
3979   //      initialized
3980   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
3981                                FEnd = ClassDecl->field_end();
3982        F != FEnd; ++F) {
3983     if (F->isInvalidDecl())
3984       continue;
3985     if (const RecordType *RecordTy =
3986             S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
3987       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
3988       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
3989         return false;
3990     }
3991   }
3992 
3993   // All OK, it's constexpr!
3994   return true;
3995 }
3996 
3997 static Sema::ImplicitExceptionSpecification
3998 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
3999   switch (S.getSpecialMember(MD)) {
4000   case Sema::CXXDefaultConstructor:
4001     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4002   case Sema::CXXCopyConstructor:
4003     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4004   case Sema::CXXCopyAssignment:
4005     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4006   case Sema::CXXMoveConstructor:
4007     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4008   case Sema::CXXMoveAssignment:
4009     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4010   case Sema::CXXDestructor:
4011     return S.ComputeDefaultedDtorExceptionSpec(MD);
4012   case Sema::CXXInvalid:
4013     break;
4014   }
4015   llvm_unreachable("only special members have implicit exception specs");
4016 }
4017 
4018 static void
4019 updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4020                     const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4021   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4022   ExceptSpec.getEPI(EPI);
4023   const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4024     S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4025                               FPT->getNumArgs(), EPI));
4026   FD->setType(QualType(NewFPT, 0));
4027 }
4028 
4029 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4030   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4031   if (FPT->getExceptionSpecType() != EST_Unevaluated)
4032     return;
4033 
4034   // Evaluate the exception specification.
4035   ImplicitExceptionSpecification ExceptSpec =
4036       computeImplicitExceptionSpec(*this, Loc, MD);
4037 
4038   // Update the type of the special member to use it.
4039   updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4040 
4041   // A user-provided destructor can be defined outside the class. When that
4042   // happens, be sure to update the exception specification on both
4043   // declarations.
4044   const FunctionProtoType *CanonicalFPT =
4045     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4046   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4047     updateExceptionSpec(*this, MD->getCanonicalDecl(),
4048                         CanonicalFPT, ExceptSpec);
4049 }
4050 
4051 static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4052 static bool isImplicitCopyAssignmentArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4053 
4054 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4055   CXXRecordDecl *RD = MD->getParent();
4056   CXXSpecialMember CSM = getSpecialMember(MD);
4057 
4058   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4059          "not an explicitly-defaulted special member");
4060 
4061   // Whether this was the first-declared instance of the constructor.
4062   // This affects whether we implicitly add an exception spec and constexpr.
4063   bool First = MD == MD->getCanonicalDecl();
4064 
4065   bool HadError = false;
4066 
4067   // C++11 [dcl.fct.def.default]p1:
4068   //   A function that is explicitly defaulted shall
4069   //     -- be a special member function (checked elsewhere),
4070   //     -- have the same type (except for ref-qualifiers, and except that a
4071   //        copy operation can take a non-const reference) as an implicit
4072   //        declaration, and
4073   //     -- not have default arguments.
4074   unsigned ExpectedParams = 1;
4075   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4076     ExpectedParams = 0;
4077   if (MD->getNumParams() != ExpectedParams) {
4078     // This also checks for default arguments: a copy or move constructor with a
4079     // default argument is classified as a default constructor, and assignment
4080     // operations and destructors can't have default arguments.
4081     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4082       << CSM << MD->getSourceRange();
4083     HadError = true;
4084   }
4085 
4086   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4087 
4088   // Compute argument constness, constexpr, and triviality.
4089   bool CanHaveConstParam = false;
4090   bool Trivial;
4091   switch (CSM) {
4092   case CXXDefaultConstructor:
4093     Trivial = RD->hasTrivialDefaultConstructor();
4094     break;
4095   case CXXCopyConstructor:
4096     CanHaveConstParam = isImplicitCopyCtorArgConst(*this, RD);
4097     Trivial = RD->hasTrivialCopyConstructor();
4098     break;
4099   case CXXCopyAssignment:
4100     CanHaveConstParam = isImplicitCopyAssignmentArgConst(*this, RD);
4101     Trivial = RD->hasTrivialCopyAssignment();
4102     break;
4103   case CXXMoveConstructor:
4104     Trivial = RD->hasTrivialMoveConstructor();
4105     break;
4106   case CXXMoveAssignment:
4107     Trivial = RD->hasTrivialMoveAssignment();
4108     break;
4109   case CXXDestructor:
4110     Trivial = RD->hasTrivialDestructor();
4111     break;
4112   case CXXInvalid:
4113     llvm_unreachable("non-special member explicitly defaulted!");
4114   }
4115 
4116   QualType ReturnType = Context.VoidTy;
4117   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4118     // Check for return type matching.
4119     ReturnType = Type->getResultType();
4120     QualType ExpectedReturnType =
4121         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4122     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4123       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4124         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4125       HadError = true;
4126     }
4127 
4128     // A defaulted special member cannot have cv-qualifiers.
4129     if (Type->getTypeQuals()) {
4130       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4131         << (CSM == CXXMoveAssignment);
4132       HadError = true;
4133     }
4134   }
4135 
4136   // Check for parameter type matching.
4137   QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4138   bool HasConstParam = false;
4139   if (ExpectedParams && ArgType->isReferenceType()) {
4140     // Argument must be reference to possibly-const T.
4141     QualType ReferentType = ArgType->getPointeeType();
4142     HasConstParam = ReferentType.isConstQualified();
4143 
4144     if (ReferentType.isVolatileQualified()) {
4145       Diag(MD->getLocation(),
4146            diag::err_defaulted_special_member_volatile_param) << CSM;
4147       HadError = true;
4148     }
4149 
4150     if (HasConstParam && !CanHaveConstParam) {
4151       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4152         Diag(MD->getLocation(),
4153              diag::err_defaulted_special_member_copy_const_param)
4154           << (CSM == CXXCopyAssignment);
4155         // FIXME: Explain why this special member can't be const.
4156       } else {
4157         Diag(MD->getLocation(),
4158              diag::err_defaulted_special_member_move_const_param)
4159           << (CSM == CXXMoveAssignment);
4160       }
4161       HadError = true;
4162     }
4163 
4164     // If a function is explicitly defaulted on its first declaration, it shall
4165     // have the same parameter type as if it had been implicitly declared.
4166     // (Presumably this is to prevent it from being trivial?)
4167     if (!HasConstParam && CanHaveConstParam && First)
4168       Diag(MD->getLocation(),
4169            diag::err_defaulted_special_member_copy_non_const_param)
4170         << (CSM == CXXCopyAssignment);
4171   } else if (ExpectedParams) {
4172     // A copy assignment operator can take its argument by value, but a
4173     // defaulted one cannot.
4174     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4175     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4176     HadError = true;
4177   }
4178 
4179   // Rebuild the type with the implicit exception specification added, if we
4180   // are going to need it.
4181   const FunctionProtoType *ImplicitType = 0;
4182   if (First || Type->hasExceptionSpec()) {
4183     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4184     computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4185     ImplicitType = cast<FunctionProtoType>(
4186       Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
4187   }
4188 
4189   // C++11 [dcl.fct.def.default]p2:
4190   //   An explicitly-defaulted function may be declared constexpr only if it
4191   //   would have been implicitly declared as constexpr,
4192   // Do not apply this rule to members of class templates, since core issue 1358
4193   // makes such functions always instantiate to constexpr functions. For
4194   // non-constructors, this is checked elsewhere.
4195   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4196                                                      HasConstParam);
4197   if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4198       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4199     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4200     // FIXME: Explain why the constructor can't be constexpr.
4201     HadError = true;
4202   }
4203   //   and may have an explicit exception-specification only if it is compatible
4204   //   with the exception-specification on the implicit declaration.
4205   if (Type->hasExceptionSpec() &&
4206       CheckEquivalentExceptionSpec(
4207         PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
4208         PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
4209     HadError = true;
4210 
4211   //   If a function is explicitly defaulted on its first declaration,
4212   if (First) {
4213     //  -- it is implicitly considered to be constexpr if the implicit
4214     //     definition would be,
4215     MD->setConstexpr(Constexpr);
4216 
4217     //  -- it is implicitly considered to have the same exception-specification
4218     //     as if it had been implicitly declared,
4219     MD->setType(QualType(ImplicitType, 0));
4220 
4221     // Such a function is also trivial if the implicitly-declared function
4222     // would have been.
4223     MD->setTrivial(Trivial);
4224   }
4225 
4226   if (ShouldDeleteSpecialMember(MD, CSM)) {
4227     if (First) {
4228       MD->setDeletedAsWritten();
4229     } else {
4230       // C++11 [dcl.fct.def.default]p4:
4231       //   [For a] user-provided explicitly-defaulted function [...] if such a
4232       //   function is implicitly defined as deleted, the program is ill-formed.
4233       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4234       HadError = true;
4235     }
4236   }
4237 
4238   if (HadError)
4239     MD->setInvalidDecl();
4240 }
4241 
4242 namespace {
4243 struct SpecialMemberDeletionInfo {
4244   Sema &S;
4245   CXXMethodDecl *MD;
4246   Sema::CXXSpecialMember CSM;
4247   bool Diagnose;
4248 
4249   // Properties of the special member, computed for convenience.
4250   bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4251   SourceLocation Loc;
4252 
4253   bool AllFieldsAreConst;
4254 
4255   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4256                             Sema::CXXSpecialMember CSM, bool Diagnose)
4257     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4258       IsConstructor(false), IsAssignment(false), IsMove(false),
4259       ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4260       AllFieldsAreConst(true) {
4261     switch (CSM) {
4262       case Sema::CXXDefaultConstructor:
4263       case Sema::CXXCopyConstructor:
4264         IsConstructor = true;
4265         break;
4266       case Sema::CXXMoveConstructor:
4267         IsConstructor = true;
4268         IsMove = true;
4269         break;
4270       case Sema::CXXCopyAssignment:
4271         IsAssignment = true;
4272         break;
4273       case Sema::CXXMoveAssignment:
4274         IsAssignment = true;
4275         IsMove = true;
4276         break;
4277       case Sema::CXXDestructor:
4278         break;
4279       case Sema::CXXInvalid:
4280         llvm_unreachable("invalid special member kind");
4281     }
4282 
4283     if (MD->getNumParams()) {
4284       ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4285       VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4286     }
4287   }
4288 
4289   bool inUnion() const { return MD->getParent()->isUnion(); }
4290 
4291   /// Look up the corresponding special member in the given class.
4292   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4293                                               unsigned Quals) {
4294     unsigned TQ = MD->getTypeQualifiers();
4295     // cv-qualifiers on class members don't affect default ctor / dtor calls.
4296     if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4297       Quals = 0;
4298     return S.LookupSpecialMember(Class, CSM,
4299                                  ConstArg || (Quals & Qualifiers::Const),
4300                                  VolatileArg || (Quals & Qualifiers::Volatile),
4301                                  MD->getRefQualifier() == RQ_RValue,
4302                                  TQ & Qualifiers::Const,
4303                                  TQ & Qualifiers::Volatile);
4304   }
4305 
4306   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4307 
4308   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4309   bool shouldDeleteForField(FieldDecl *FD);
4310   bool shouldDeleteForAllConstMembers();
4311 
4312   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4313                                      unsigned Quals);
4314   bool shouldDeleteForSubobjectCall(Subobject Subobj,
4315                                     Sema::SpecialMemberOverloadResult *SMOR,
4316                                     bool IsDtorCallInCtor);
4317 
4318   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4319 };
4320 }
4321 
4322 /// Is the given special member inaccessible when used on the given
4323 /// sub-object.
4324 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4325                                              CXXMethodDecl *target) {
4326   /// If we're operating on a base class, the object type is the
4327   /// type of this special member.
4328   QualType objectTy;
4329   AccessSpecifier access = target->getAccess();
4330   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4331     objectTy = S.Context.getTypeDeclType(MD->getParent());
4332     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4333 
4334   // If we're operating on a field, the object type is the type of the field.
4335   } else {
4336     objectTy = S.Context.getTypeDeclType(target->getParent());
4337   }
4338 
4339   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4340 }
4341 
4342 /// Check whether we should delete a special member due to the implicit
4343 /// definition containing a call to a special member of a subobject.
4344 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4345     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4346     bool IsDtorCallInCtor) {
4347   CXXMethodDecl *Decl = SMOR->getMethod();
4348   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4349 
4350   int DiagKind = -1;
4351 
4352   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4353     DiagKind = !Decl ? 0 : 1;
4354   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4355     DiagKind = 2;
4356   else if (!isAccessible(Subobj, Decl))
4357     DiagKind = 3;
4358   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4359            !Decl->isTrivial()) {
4360     // A member of a union must have a trivial corresponding special member.
4361     // As a weird special case, a destructor call from a union's constructor
4362     // must be accessible and non-deleted, but need not be trivial. Such a
4363     // destructor is never actually called, but is semantically checked as
4364     // if it were.
4365     DiagKind = 4;
4366   }
4367 
4368   if (DiagKind == -1)
4369     return false;
4370 
4371   if (Diagnose) {
4372     if (Field) {
4373       S.Diag(Field->getLocation(),
4374              diag::note_deleted_special_member_class_subobject)
4375         << CSM << MD->getParent() << /*IsField*/true
4376         << Field << DiagKind << IsDtorCallInCtor;
4377     } else {
4378       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4379       S.Diag(Base->getLocStart(),
4380              diag::note_deleted_special_member_class_subobject)
4381         << CSM << MD->getParent() << /*IsField*/false
4382         << Base->getType() << DiagKind << IsDtorCallInCtor;
4383     }
4384 
4385     if (DiagKind == 1)
4386       S.NoteDeletedFunction(Decl);
4387     // FIXME: Explain inaccessibility if DiagKind == 3.
4388   }
4389 
4390   return true;
4391 }
4392 
4393 /// Check whether we should delete a special member function due to having a
4394 /// direct or virtual base class or non-static data member of class type M.
4395 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4396     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
4397   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4398 
4399   // C++11 [class.ctor]p5:
4400   // -- any direct or virtual base class, or non-static data member with no
4401   //    brace-or-equal-initializer, has class type M (or array thereof) and
4402   //    either M has no default constructor or overload resolution as applied
4403   //    to M's default constructor results in an ambiguity or in a function
4404   //    that is deleted or inaccessible
4405   // C++11 [class.copy]p11, C++11 [class.copy]p23:
4406   // -- a direct or virtual base class B that cannot be copied/moved because
4407   //    overload resolution, as applied to B's corresponding special member,
4408   //    results in an ambiguity or a function that is deleted or inaccessible
4409   //    from the defaulted special member
4410   // C++11 [class.dtor]p5:
4411   // -- any direct or virtual base class [...] has a type with a destructor
4412   //    that is deleted or inaccessible
4413   if (!(CSM == Sema::CXXDefaultConstructor &&
4414         Field && Field->hasInClassInitializer()) &&
4415       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
4416     return true;
4417 
4418   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4419   // -- any direct or virtual base class or non-static data member has a
4420   //    type with a destructor that is deleted or inaccessible
4421   if (IsConstructor) {
4422     Sema::SpecialMemberOverloadResult *SMOR =
4423         S.LookupSpecialMember(Class, Sema::CXXDestructor,
4424                               false, false, false, false, false);
4425     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4426       return true;
4427   }
4428 
4429   return false;
4430 }
4431 
4432 /// Check whether we should delete a special member function due to the class
4433 /// having a particular direct or virtual base class.
4434 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4435   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4436   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
4437 }
4438 
4439 /// Check whether we should delete a special member function due to the class
4440 /// having a particular non-static data member.
4441 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4442   QualType FieldType = S.Context.getBaseElementType(FD->getType());
4443   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4444 
4445   if (CSM == Sema::CXXDefaultConstructor) {
4446     // For a default constructor, all references must be initialized in-class
4447     // and, if a union, it must have a non-const member.
4448     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4449       if (Diagnose)
4450         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4451           << MD->getParent() << FD << FieldType << /*Reference*/0;
4452       return true;
4453     }
4454     // C++11 [class.ctor]p5: any non-variant non-static data member of
4455     // const-qualified type (or array thereof) with no
4456     // brace-or-equal-initializer does not have a user-provided default
4457     // constructor.
4458     if (!inUnion() && FieldType.isConstQualified() &&
4459         !FD->hasInClassInitializer() &&
4460         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4461       if (Diagnose)
4462         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4463           << MD->getParent() << FD << FD->getType() << /*Const*/1;
4464       return true;
4465     }
4466 
4467     if (inUnion() && !FieldType.isConstQualified())
4468       AllFieldsAreConst = false;
4469   } else if (CSM == Sema::CXXCopyConstructor) {
4470     // For a copy constructor, data members must not be of rvalue reference
4471     // type.
4472     if (FieldType->isRValueReferenceType()) {
4473       if (Diagnose)
4474         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4475           << MD->getParent() << FD << FieldType;
4476       return true;
4477     }
4478   } else if (IsAssignment) {
4479     // For an assignment operator, data members must not be of reference type.
4480     if (FieldType->isReferenceType()) {
4481       if (Diagnose)
4482         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4483           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4484       return true;
4485     }
4486     if (!FieldRecord && FieldType.isConstQualified()) {
4487       // C++11 [class.copy]p23:
4488       // -- a non-static data member of const non-class type (or array thereof)
4489       if (Diagnose)
4490         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4491           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
4492       return true;
4493     }
4494   }
4495 
4496   if (FieldRecord) {
4497     // Some additional restrictions exist on the variant members.
4498     if (!inUnion() && FieldRecord->isUnion() &&
4499         FieldRecord->isAnonymousStructOrUnion()) {
4500       bool AllVariantFieldsAreConst = true;
4501 
4502       // FIXME: Handle anonymous unions declared within anonymous unions.
4503       for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4504                                          UE = FieldRecord->field_end();
4505            UI != UE; ++UI) {
4506         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4507 
4508         if (!UnionFieldType.isConstQualified())
4509           AllVariantFieldsAreConst = false;
4510 
4511         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4512         if (UnionFieldRecord &&
4513             shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4514                                           UnionFieldType.getCVRQualifiers()))
4515           return true;
4516       }
4517 
4518       // At least one member in each anonymous union must be non-const
4519       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4520           FieldRecord->field_begin() != FieldRecord->field_end()) {
4521         if (Diagnose)
4522           S.Diag(FieldRecord->getLocation(),
4523                  diag::note_deleted_default_ctor_all_const)
4524             << MD->getParent() << /*anonymous union*/1;
4525         return true;
4526       }
4527 
4528       // Don't check the implicit member of the anonymous union type.
4529       // This is technically non-conformant, but sanity demands it.
4530       return false;
4531     }
4532 
4533     if (shouldDeleteForClassSubobject(FieldRecord, FD,
4534                                       FieldType.getCVRQualifiers()))
4535       return true;
4536   }
4537 
4538   return false;
4539 }
4540 
4541 /// C++11 [class.ctor] p5:
4542 ///   A defaulted default constructor for a class X is defined as deleted if
4543 /// X is a union and all of its variant members are of const-qualified type.
4544 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4545   // This is a silly definition, because it gives an empty union a deleted
4546   // default constructor. Don't do that.
4547   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4548       (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4549     if (Diagnose)
4550       S.Diag(MD->getParent()->getLocation(),
4551              diag::note_deleted_default_ctor_all_const)
4552         << MD->getParent() << /*not anonymous union*/0;
4553     return true;
4554   }
4555   return false;
4556 }
4557 
4558 /// Determine whether a defaulted special member function should be defined as
4559 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4560 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
4561 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4562                                      bool Diagnose) {
4563   if (MD->isInvalidDecl())
4564     return false;
4565   CXXRecordDecl *RD = MD->getParent();
4566   assert(!RD->isDependentType() && "do deletion after instantiation");
4567   if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4568     return false;
4569 
4570   // C++11 [expr.lambda.prim]p19:
4571   //   The closure type associated with a lambda-expression has a
4572   //   deleted (8.4.3) default constructor and a deleted copy
4573   //   assignment operator.
4574   if (RD->isLambda() &&
4575       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4576     if (Diagnose)
4577       Diag(RD->getLocation(), diag::note_lambda_decl);
4578     return true;
4579   }
4580 
4581   // For an anonymous struct or union, the copy and assignment special members
4582   // will never be used, so skip the check. For an anonymous union declared at
4583   // namespace scope, the constructor and destructor are used.
4584   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4585       RD->isAnonymousStructOrUnion())
4586     return false;
4587 
4588   // C++11 [class.copy]p7, p18:
4589   //   If the class definition declares a move constructor or move assignment
4590   //   operator, an implicitly declared copy constructor or copy assignment
4591   //   operator is defined as deleted.
4592   if (MD->isImplicit() &&
4593       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4594     CXXMethodDecl *UserDeclaredMove = 0;
4595 
4596     // In Microsoft mode, a user-declared move only causes the deletion of the
4597     // corresponding copy operation, not both copy operations.
4598     if (RD->hasUserDeclaredMoveConstructor() &&
4599         (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4600       if (!Diagnose) return true;
4601       UserDeclaredMove = RD->getMoveConstructor();
4602       assert(UserDeclaredMove);
4603     } else if (RD->hasUserDeclaredMoveAssignment() &&
4604                (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4605       if (!Diagnose) return true;
4606       UserDeclaredMove = RD->getMoveAssignmentOperator();
4607       assert(UserDeclaredMove);
4608     }
4609 
4610     if (UserDeclaredMove) {
4611       Diag(UserDeclaredMove->getLocation(),
4612            diag::note_deleted_copy_user_declared_move)
4613         << (CSM == CXXCopyAssignment) << RD
4614         << UserDeclaredMove->isMoveAssignmentOperator();
4615       return true;
4616     }
4617   }
4618 
4619   // Do access control from the special member function
4620   ContextRAII MethodContext(*this, MD);
4621 
4622   // C++11 [class.dtor]p5:
4623   // -- for a virtual destructor, lookup of the non-array deallocation function
4624   //    results in an ambiguity or in a function that is deleted or inaccessible
4625   if (CSM == CXXDestructor && MD->isVirtual()) {
4626     FunctionDecl *OperatorDelete = 0;
4627     DeclarationName Name =
4628       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4629     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
4630                                  OperatorDelete, false)) {
4631       if (Diagnose)
4632         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
4633       return true;
4634     }
4635   }
4636 
4637   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
4638 
4639   for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4640                                           BE = RD->bases_end(); BI != BE; ++BI)
4641     if (!BI->isVirtual() &&
4642         SMI.shouldDeleteForBase(BI))
4643       return true;
4644 
4645   for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4646                                           BE = RD->vbases_end(); BI != BE; ++BI)
4647     if (SMI.shouldDeleteForBase(BI))
4648       return true;
4649 
4650   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4651                                      FE = RD->field_end(); FI != FE; ++FI)
4652     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4653         SMI.shouldDeleteForField(*FI))
4654       return true;
4655 
4656   if (SMI.shouldDeleteForAllConstMembers())
4657     return true;
4658 
4659   return false;
4660 }
4661 
4662 /// \brief Data used with FindHiddenVirtualMethod
4663 namespace {
4664   struct FindHiddenVirtualMethodData {
4665     Sema *S;
4666     CXXMethodDecl *Method;
4667     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4668     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4669   };
4670 }
4671 
4672 /// \brief Member lookup function that determines whether a given C++
4673 /// method overloads virtual methods in a base class without overriding any,
4674 /// to be used with CXXRecordDecl::lookupInBases().
4675 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4676                                     CXXBasePath &Path,
4677                                     void *UserData) {
4678   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4679 
4680   FindHiddenVirtualMethodData &Data
4681     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4682 
4683   DeclarationName Name = Data.Method->getDeclName();
4684   assert(Name.getNameKind() == DeclarationName::Identifier);
4685 
4686   bool foundSameNameMethod = false;
4687   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4688   for (Path.Decls = BaseRecord->lookup(Name);
4689        Path.Decls.first != Path.Decls.second;
4690        ++Path.Decls.first) {
4691     NamedDecl *D = *Path.Decls.first;
4692     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4693       MD = MD->getCanonicalDecl();
4694       foundSameNameMethod = true;
4695       // Interested only in hidden virtual methods.
4696       if (!MD->isVirtual())
4697         continue;
4698       // If the method we are checking overrides a method from its base
4699       // don't warn about the other overloaded methods.
4700       if (!Data.S->IsOverload(Data.Method, MD, false))
4701         return true;
4702       // Collect the overload only if its hidden.
4703       if (!Data.OverridenAndUsingBaseMethods.count(MD))
4704         overloadedMethods.push_back(MD);
4705     }
4706   }
4707 
4708   if (foundSameNameMethod)
4709     Data.OverloadedMethods.append(overloadedMethods.begin(),
4710                                    overloadedMethods.end());
4711   return foundSameNameMethod;
4712 }
4713 
4714 /// \brief See if a method overloads virtual methods in a base class without
4715 /// overriding any.
4716 void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4717   if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4718                                MD->getLocation()) == DiagnosticsEngine::Ignored)
4719     return;
4720   if (!MD->getDeclName().isIdentifier())
4721     return;
4722 
4723   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4724                      /*bool RecordPaths=*/false,
4725                      /*bool DetectVirtual=*/false);
4726   FindHiddenVirtualMethodData Data;
4727   Data.Method = MD;
4728   Data.S = this;
4729 
4730   // Keep the base methods that were overriden or introduced in the subclass
4731   // by 'using' in a set. A base method not in this set is hidden.
4732   for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4733        res.first != res.second; ++res.first) {
4734     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4735       for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4736                                           E = MD->end_overridden_methods();
4737            I != E; ++I)
4738         Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
4739     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4740       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
4741         Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
4742   }
4743 
4744   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4745       !Data.OverloadedMethods.empty()) {
4746     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4747       << MD << (Data.OverloadedMethods.size() > 1);
4748 
4749     for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4750       CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4751       Diag(overloadedMD->getLocation(),
4752            diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4753     }
4754   }
4755 }
4756 
4757 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4758                                              Decl *TagDecl,
4759                                              SourceLocation LBrac,
4760                                              SourceLocation RBrac,
4761                                              AttributeList *AttrList) {
4762   if (!TagDecl)
4763     return;
4764 
4765   AdjustDeclIfTemplate(TagDecl);
4766 
4767   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4768     if (l->getKind() != AttributeList::AT_Visibility)
4769       continue;
4770     l->setInvalid();
4771     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
4772       l->getName();
4773   }
4774 
4775   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
4776               // strict aliasing violation!
4777               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
4778               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
4779 
4780   CheckCompletedCXXClass(
4781                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
4782 }
4783 
4784 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4785 /// special functions, such as the default constructor, copy
4786 /// constructor, or destructor, to the given C++ class (C++
4787 /// [special]p1).  This routine can only be executed just before the
4788 /// definition of the class is complete.
4789 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
4790   if (!ClassDecl->hasUserDeclaredConstructor())
4791     ++ASTContext::NumImplicitDefaultConstructors;
4792 
4793   if (!ClassDecl->hasUserDeclaredCopyConstructor())
4794     ++ASTContext::NumImplicitCopyConstructors;
4795 
4796   if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
4797     ++ASTContext::NumImplicitMoveConstructors;
4798 
4799   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4800     ++ASTContext::NumImplicitCopyAssignmentOperators;
4801 
4802     // If we have a dynamic class, then the copy assignment operator may be
4803     // virtual, so we have to declare it immediately. This ensures that, e.g.,
4804     // it shows up in the right place in the vtable and that we diagnose
4805     // problems with the implicit exception specification.
4806     if (ClassDecl->isDynamicClass())
4807       DeclareImplicitCopyAssignment(ClassDecl);
4808   }
4809 
4810   if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
4811     ++ASTContext::NumImplicitMoveAssignmentOperators;
4812 
4813     // Likewise for the move assignment operator.
4814     if (ClassDecl->isDynamicClass())
4815       DeclareImplicitMoveAssignment(ClassDecl);
4816   }
4817 
4818   if (!ClassDecl->hasUserDeclaredDestructor()) {
4819     ++ASTContext::NumImplicitDestructors;
4820 
4821     // If we have a dynamic class, then the destructor may be virtual, so we
4822     // have to declare the destructor immediately. This ensures that, e.g., it
4823     // shows up in the right place in the vtable and that we diagnose problems
4824     // with the implicit exception specification.
4825     if (ClassDecl->isDynamicClass())
4826       DeclareImplicitDestructor(ClassDecl);
4827   }
4828 }
4829 
4830 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4831   if (!D)
4832     return;
4833 
4834   int NumParamList = D->getNumTemplateParameterLists();
4835   for (int i = 0; i < NumParamList; i++) {
4836     TemplateParameterList* Params = D->getTemplateParameterList(i);
4837     for (TemplateParameterList::iterator Param = Params->begin(),
4838                                       ParamEnd = Params->end();
4839           Param != ParamEnd; ++Param) {
4840       NamedDecl *Named = cast<NamedDecl>(*Param);
4841       if (Named->getDeclName()) {
4842         S->AddDecl(Named);
4843         IdResolver.AddDecl(Named);
4844       }
4845     }
4846   }
4847 }
4848 
4849 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
4850   if (!D)
4851     return;
4852 
4853   TemplateParameterList *Params = 0;
4854   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4855     Params = Template->getTemplateParameters();
4856   else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4857            = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4858     Params = PartialSpec->getTemplateParameters();
4859   else
4860     return;
4861 
4862   for (TemplateParameterList::iterator Param = Params->begin(),
4863                                     ParamEnd = Params->end();
4864        Param != ParamEnd; ++Param) {
4865     NamedDecl *Named = cast<NamedDecl>(*Param);
4866     if (Named->getDeclName()) {
4867       S->AddDecl(Named);
4868       IdResolver.AddDecl(Named);
4869     }
4870   }
4871 }
4872 
4873 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4874   if (!RecordD) return;
4875   AdjustDeclIfTemplate(RecordD);
4876   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
4877   PushDeclContext(S, Record);
4878 }
4879 
4880 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4881   if (!RecordD) return;
4882   PopDeclContext();
4883 }
4884 
4885 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
4886 /// parsing a top-level (non-nested) C++ class, and we are now
4887 /// parsing those parts of the given Method declaration that could
4888 /// not be parsed earlier (C++ [class.mem]p2), such as default
4889 /// arguments. This action should enter the scope of the given
4890 /// Method declaration as if we had just parsed the qualified method
4891 /// name. However, it should not bring the parameters into scope;
4892 /// that will be performed by ActOnDelayedCXXMethodParameter.
4893 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4894 }
4895 
4896 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
4897 /// C++ method declaration. We're (re-)introducing the given
4898 /// function parameter into scope for use in parsing later parts of
4899 /// the method declaration. For example, we could see an
4900 /// ActOnParamDefaultArgument event for this parameter.
4901 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
4902   if (!ParamD)
4903     return;
4904 
4905   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
4906 
4907   // If this parameter has an unparsed default argument, clear it out
4908   // to make way for the parsed default argument.
4909   if (Param->hasUnparsedDefaultArg())
4910     Param->setDefaultArg(0);
4911 
4912   S->AddDecl(Param);
4913   if (Param->getDeclName())
4914     IdResolver.AddDecl(Param);
4915 }
4916 
4917 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4918 /// processing the delayed method declaration for Method. The method
4919 /// declaration is now considered finished. There may be a separate
4920 /// ActOnStartOfFunctionDef action later (not necessarily
4921 /// immediately!) for this method, if it was also defined inside the
4922 /// class body.
4923 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4924   if (!MethodD)
4925     return;
4926 
4927   AdjustDeclIfTemplate(MethodD);
4928 
4929   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
4930 
4931   // Now that we have our default arguments, check the constructor
4932   // again. It could produce additional diagnostics or affect whether
4933   // the class has implicitly-declared destructors, among other
4934   // things.
4935   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4936     CheckConstructor(Constructor);
4937 
4938   // Check the default arguments, which we may have added.
4939   if (!Method->isInvalidDecl())
4940     CheckCXXDefaultArguments(Method);
4941 }
4942 
4943 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
4944 /// the well-formedness of the constructor declarator @p D with type @p
4945 /// R. If there are any errors in the declarator, this routine will
4946 /// emit diagnostics and set the invalid bit to true.  In any case, the type
4947 /// will be updated to reflect a well-formed type for the constructor and
4948 /// returned.
4949 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
4950                                           StorageClass &SC) {
4951   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4952 
4953   // C++ [class.ctor]p3:
4954   //   A constructor shall not be virtual (10.3) or static (9.4). A
4955   //   constructor can be invoked for a const, volatile or const
4956   //   volatile object. A constructor shall not be declared const,
4957   //   volatile, or const volatile (9.3.2).
4958   if (isVirtual) {
4959     if (!D.isInvalidType())
4960       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4961         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4962         << SourceRange(D.getIdentifierLoc());
4963     D.setInvalidType();
4964   }
4965   if (SC == SC_Static) {
4966     if (!D.isInvalidType())
4967       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4968         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4969         << SourceRange(D.getIdentifierLoc());
4970     D.setInvalidType();
4971     SC = SC_None;
4972   }
4973 
4974   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4975   if (FTI.TypeQuals != 0) {
4976     if (FTI.TypeQuals & Qualifiers::Const)
4977       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4978         << "const" << SourceRange(D.getIdentifierLoc());
4979     if (FTI.TypeQuals & Qualifiers::Volatile)
4980       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4981         << "volatile" << SourceRange(D.getIdentifierLoc());
4982     if (FTI.TypeQuals & Qualifiers::Restrict)
4983       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4984         << "restrict" << SourceRange(D.getIdentifierLoc());
4985     D.setInvalidType();
4986   }
4987 
4988   // C++0x [class.ctor]p4:
4989   //   A constructor shall not be declared with a ref-qualifier.
4990   if (FTI.hasRefQualifier()) {
4991     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4992       << FTI.RefQualifierIsLValueRef
4993       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4994     D.setInvalidType();
4995   }
4996 
4997   // Rebuild the function type "R" without any type qualifiers (in
4998   // case any of the errors above fired) and with "void" as the
4999   // return type, since constructors don't have return types.
5000   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5001   if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5002     return R;
5003 
5004   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5005   EPI.TypeQuals = 0;
5006   EPI.RefQualifier = RQ_None;
5007 
5008   return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
5009                                  Proto->getNumArgs(), EPI);
5010 }
5011 
5012 /// CheckConstructor - Checks a fully-formed constructor for
5013 /// well-formedness, issuing any diagnostics required. Returns true if
5014 /// the constructor declarator is invalid.
5015 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5016   CXXRecordDecl *ClassDecl
5017     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5018   if (!ClassDecl)
5019     return Constructor->setInvalidDecl();
5020 
5021   // C++ [class.copy]p3:
5022   //   A declaration of a constructor for a class X is ill-formed if
5023   //   its first parameter is of type (optionally cv-qualified) X and
5024   //   either there are no other parameters or else all other
5025   //   parameters have default arguments.
5026   if (!Constructor->isInvalidDecl() &&
5027       ((Constructor->getNumParams() == 1) ||
5028        (Constructor->getNumParams() > 1 &&
5029         Constructor->getParamDecl(1)->hasDefaultArg())) &&
5030       Constructor->getTemplateSpecializationKind()
5031                                               != TSK_ImplicitInstantiation) {
5032     QualType ParamType = Constructor->getParamDecl(0)->getType();
5033     QualType ClassTy = Context.getTagDeclType(ClassDecl);
5034     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5035       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5036       const char *ConstRef
5037         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5038                                                         : " const &";
5039       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5040         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5041 
5042       // FIXME: Rather that making the constructor invalid, we should endeavor
5043       // to fix the type.
5044       Constructor->setInvalidDecl();
5045     }
5046   }
5047 }
5048 
5049 /// CheckDestructor - Checks a fully-formed destructor definition for
5050 /// well-formedness, issuing any diagnostics required.  Returns true
5051 /// on error.
5052 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5053   CXXRecordDecl *RD = Destructor->getParent();
5054 
5055   if (Destructor->isVirtual()) {
5056     SourceLocation Loc;
5057 
5058     if (!Destructor->isImplicit())
5059       Loc = Destructor->getLocation();
5060     else
5061       Loc = RD->getLocation();
5062 
5063     // If we have a virtual destructor, look up the deallocation function
5064     FunctionDecl *OperatorDelete = 0;
5065     DeclarationName Name =
5066     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5067     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5068       return true;
5069 
5070     MarkFunctionReferenced(Loc, OperatorDelete);
5071 
5072     Destructor->setOperatorDelete(OperatorDelete);
5073   }
5074 
5075   return false;
5076 }
5077 
5078 static inline bool
5079 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5080   return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5081           FTI.ArgInfo[0].Param &&
5082           cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5083 }
5084 
5085 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5086 /// the well-formednes of the destructor declarator @p D with type @p
5087 /// R. If there are any errors in the declarator, this routine will
5088 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
5089 /// will be updated to reflect a well-formed type for the destructor and
5090 /// returned.
5091 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5092                                          StorageClass& SC) {
5093   // C++ [class.dtor]p1:
5094   //   [...] A typedef-name that names a class is a class-name
5095   //   (7.1.3); however, a typedef-name that names a class shall not
5096   //   be used as the identifier in the declarator for a destructor
5097   //   declaration.
5098   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5099   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5100     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5101       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5102   else if (const TemplateSpecializationType *TST =
5103              DeclaratorType->getAs<TemplateSpecializationType>())
5104     if (TST->isTypeAlias())
5105       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5106         << DeclaratorType << 1;
5107 
5108   // C++ [class.dtor]p2:
5109   //   A destructor is used to destroy objects of its class type. A
5110   //   destructor takes no parameters, and no return type can be
5111   //   specified for it (not even void). The address of a destructor
5112   //   shall not be taken. A destructor shall not be static. A
5113   //   destructor can be invoked for a const, volatile or const
5114   //   volatile object. A destructor shall not be declared const,
5115   //   volatile or const volatile (9.3.2).
5116   if (SC == SC_Static) {
5117     if (!D.isInvalidType())
5118       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5119         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5120         << SourceRange(D.getIdentifierLoc())
5121         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5122 
5123     SC = SC_None;
5124   }
5125   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5126     // Destructors don't have return types, but the parser will
5127     // happily parse something like:
5128     //
5129     //   class X {
5130     //     float ~X();
5131     //   };
5132     //
5133     // The return type will be eliminated later.
5134     Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5135       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5136       << SourceRange(D.getIdentifierLoc());
5137   }
5138 
5139   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5140   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5141     if (FTI.TypeQuals & Qualifiers::Const)
5142       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5143         << "const" << SourceRange(D.getIdentifierLoc());
5144     if (FTI.TypeQuals & Qualifiers::Volatile)
5145       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5146         << "volatile" << SourceRange(D.getIdentifierLoc());
5147     if (FTI.TypeQuals & Qualifiers::Restrict)
5148       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5149         << "restrict" << SourceRange(D.getIdentifierLoc());
5150     D.setInvalidType();
5151   }
5152 
5153   // C++0x [class.dtor]p2:
5154   //   A destructor shall not be declared with a ref-qualifier.
5155   if (FTI.hasRefQualifier()) {
5156     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5157       << FTI.RefQualifierIsLValueRef
5158       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5159     D.setInvalidType();
5160   }
5161 
5162   // Make sure we don't have any parameters.
5163   if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5164     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5165 
5166     // Delete the parameters.
5167     FTI.freeArgs();
5168     D.setInvalidType();
5169   }
5170 
5171   // Make sure the destructor isn't variadic.
5172   if (FTI.isVariadic) {
5173     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5174     D.setInvalidType();
5175   }
5176 
5177   // Rebuild the function type "R" without any type qualifiers or
5178   // parameters (in case any of the errors above fired) and with
5179   // "void" as the return type, since destructors don't have return
5180   // types.
5181   if (!D.isInvalidType())
5182     return R;
5183 
5184   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5185   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5186   EPI.Variadic = false;
5187   EPI.TypeQuals = 0;
5188   EPI.RefQualifier = RQ_None;
5189   return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
5190 }
5191 
5192 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5193 /// well-formednes of the conversion function declarator @p D with
5194 /// type @p R. If there are any errors in the declarator, this routine
5195 /// will emit diagnostics and return true. Otherwise, it will return
5196 /// false. Either way, the type @p R will be updated to reflect a
5197 /// well-formed type for the conversion operator.
5198 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
5199                                      StorageClass& SC) {
5200   // C++ [class.conv.fct]p1:
5201   //   Neither parameter types nor return type can be specified. The
5202   //   type of a conversion function (8.3.5) is "function taking no
5203   //   parameter returning conversion-type-id."
5204   if (SC == SC_Static) {
5205     if (!D.isInvalidType())
5206       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5207         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5208         << SourceRange(D.getIdentifierLoc());
5209     D.setInvalidType();
5210     SC = SC_None;
5211   }
5212 
5213   QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5214 
5215   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5216     // Conversion functions don't have return types, but the parser will
5217     // happily parse something like:
5218     //
5219     //   class X {
5220     //     float operator bool();
5221     //   };
5222     //
5223     // The return type will be changed later anyway.
5224     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5225       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5226       << SourceRange(D.getIdentifierLoc());
5227     D.setInvalidType();
5228   }
5229 
5230   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5231 
5232   // Make sure we don't have any parameters.
5233   if (Proto->getNumArgs() > 0) {
5234     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5235 
5236     // Delete the parameters.
5237     D.getFunctionTypeInfo().freeArgs();
5238     D.setInvalidType();
5239   } else if (Proto->isVariadic()) {
5240     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
5241     D.setInvalidType();
5242   }
5243 
5244   // Diagnose "&operator bool()" and other such nonsense.  This
5245   // is actually a gcc extension which we don't support.
5246   if (Proto->getResultType() != ConvType) {
5247     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5248       << Proto->getResultType();
5249     D.setInvalidType();
5250     ConvType = Proto->getResultType();
5251   }
5252 
5253   // C++ [class.conv.fct]p4:
5254   //   The conversion-type-id shall not represent a function type nor
5255   //   an array type.
5256   if (ConvType->isArrayType()) {
5257     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5258     ConvType = Context.getPointerType(ConvType);
5259     D.setInvalidType();
5260   } else if (ConvType->isFunctionType()) {
5261     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5262     ConvType = Context.getPointerType(ConvType);
5263     D.setInvalidType();
5264   }
5265 
5266   // Rebuild the function type "R" without any parameters (in case any
5267   // of the errors above fired) and with the conversion type as the
5268   // return type.
5269   if (D.isInvalidType())
5270     R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
5271 
5272   // C++0x explicit conversion operators.
5273   if (D.getDeclSpec().isExplicitSpecified())
5274     Diag(D.getDeclSpec().getExplicitSpecLoc(),
5275          getLangOpts().CPlusPlus0x ?
5276            diag::warn_cxx98_compat_explicit_conversion_functions :
5277            diag::ext_explicit_conversion_functions)
5278       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
5279 }
5280 
5281 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5282 /// the declaration of the given C++ conversion function. This routine
5283 /// is responsible for recording the conversion function in the C++
5284 /// class, if possible.
5285 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
5286   assert(Conversion && "Expected to receive a conversion function declaration");
5287 
5288   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
5289 
5290   // Make sure we aren't redeclaring the conversion function.
5291   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
5292 
5293   // C++ [class.conv.fct]p1:
5294   //   [...] A conversion function is never used to convert a
5295   //   (possibly cv-qualified) object to the (possibly cv-qualified)
5296   //   same object type (or a reference to it), to a (possibly
5297   //   cv-qualified) base class of that type (or a reference to it),
5298   //   or to (possibly cv-qualified) void.
5299   // FIXME: Suppress this warning if the conversion function ends up being a
5300   // virtual function that overrides a virtual function in a base class.
5301   QualType ClassType
5302     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5303   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
5304     ConvType = ConvTypeRef->getPointeeType();
5305   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5306       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5307     /* Suppress diagnostics for instantiations. */;
5308   else if (ConvType->isRecordType()) {
5309     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5310     if (ConvType == ClassType)
5311       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
5312         << ClassType;
5313     else if (IsDerivedFrom(ClassType, ConvType))
5314       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
5315         <<  ClassType << ConvType;
5316   } else if (ConvType->isVoidType()) {
5317     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
5318       << ClassType << ConvType;
5319   }
5320 
5321   if (FunctionTemplateDecl *ConversionTemplate
5322                                 = Conversion->getDescribedFunctionTemplate())
5323     return ConversionTemplate;
5324 
5325   return Conversion;
5326 }
5327 
5328 //===----------------------------------------------------------------------===//
5329 // Namespace Handling
5330 //===----------------------------------------------------------------------===//
5331 
5332 
5333 
5334 /// ActOnStartNamespaceDef - This is called at the start of a namespace
5335 /// definition.
5336 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
5337                                    SourceLocation InlineLoc,
5338                                    SourceLocation NamespaceLoc,
5339                                    SourceLocation IdentLoc,
5340                                    IdentifierInfo *II,
5341                                    SourceLocation LBrace,
5342                                    AttributeList *AttrList) {
5343   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5344   // For anonymous namespace, take the location of the left brace.
5345   SourceLocation Loc = II ? IdentLoc : LBrace;
5346   bool IsInline = InlineLoc.isValid();
5347   bool IsInvalid = false;
5348   bool IsStd = false;
5349   bool AddToKnown = false;
5350   Scope *DeclRegionScope = NamespcScope->getParent();
5351 
5352   NamespaceDecl *PrevNS = 0;
5353   if (II) {
5354     // C++ [namespace.def]p2:
5355     //   The identifier in an original-namespace-definition shall not
5356     //   have been previously defined in the declarative region in
5357     //   which the original-namespace-definition appears. The
5358     //   identifier in an original-namespace-definition is the name of
5359     //   the namespace. Subsequently in that declarative region, it is
5360     //   treated as an original-namespace-name.
5361     //
5362     // Since namespace names are unique in their scope, and we don't
5363     // look through using directives, just look for any ordinary names.
5364 
5365     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5366     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5367     Decl::IDNS_Namespace;
5368     NamedDecl *PrevDecl = 0;
5369     for (DeclContext::lookup_result R
5370          = CurContext->getRedeclContext()->lookup(II);
5371          R.first != R.second; ++R.first) {
5372       if ((*R.first)->getIdentifierNamespace() & IDNS) {
5373         PrevDecl = *R.first;
5374         break;
5375       }
5376     }
5377 
5378     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5379 
5380     if (PrevNS) {
5381       // This is an extended namespace definition.
5382       if (IsInline != PrevNS->isInline()) {
5383         // inline-ness must match
5384         if (PrevNS->isInline()) {
5385           // The user probably just forgot the 'inline', so suggest that it
5386           // be added back.
5387           Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5388             << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5389         } else {
5390           Diag(Loc, diag::err_inline_namespace_mismatch)
5391             << IsInline;
5392         }
5393         Diag(PrevNS->getLocation(), diag::note_previous_definition);
5394 
5395         IsInline = PrevNS->isInline();
5396       }
5397     } else if (PrevDecl) {
5398       // This is an invalid name redefinition.
5399       Diag(Loc, diag::err_redefinition_different_kind)
5400         << II;
5401       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5402       IsInvalid = true;
5403       // Continue on to push Namespc as current DeclContext and return it.
5404     } else if (II->isStr("std") &&
5405                CurContext->getRedeclContext()->isTranslationUnit()) {
5406       // This is the first "real" definition of the namespace "std", so update
5407       // our cache of the "std" namespace to point at this definition.
5408       PrevNS = getStdNamespace();
5409       IsStd = true;
5410       AddToKnown = !IsInline;
5411     } else {
5412       // We've seen this namespace for the first time.
5413       AddToKnown = !IsInline;
5414     }
5415   } else {
5416     // Anonymous namespaces.
5417 
5418     // Determine whether the parent already has an anonymous namespace.
5419     DeclContext *Parent = CurContext->getRedeclContext();
5420     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5421       PrevNS = TU->getAnonymousNamespace();
5422     } else {
5423       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5424       PrevNS = ND->getAnonymousNamespace();
5425     }
5426 
5427     if (PrevNS && IsInline != PrevNS->isInline()) {
5428       // inline-ness must match
5429       Diag(Loc, diag::err_inline_namespace_mismatch)
5430         << IsInline;
5431       Diag(PrevNS->getLocation(), diag::note_previous_definition);
5432 
5433       // Recover by ignoring the new namespace's inline status.
5434       IsInline = PrevNS->isInline();
5435     }
5436   }
5437 
5438   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5439                                                  StartLoc, Loc, II, PrevNS);
5440   if (IsInvalid)
5441     Namespc->setInvalidDecl();
5442 
5443   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5444 
5445   // FIXME: Should we be merging attributes?
5446   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5447     PushNamespaceVisibilityAttr(Attr, Loc);
5448 
5449   if (IsStd)
5450     StdNamespace = Namespc;
5451   if (AddToKnown)
5452     KnownNamespaces[Namespc] = false;
5453 
5454   if (II) {
5455     PushOnScopeChains(Namespc, DeclRegionScope);
5456   } else {
5457     // Link the anonymous namespace into its parent.
5458     DeclContext *Parent = CurContext->getRedeclContext();
5459     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5460       TU->setAnonymousNamespace(Namespc);
5461     } else {
5462       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
5463     }
5464 
5465     CurContext->addDecl(Namespc);
5466 
5467     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
5468     //   behaves as if it were replaced by
5469     //     namespace unique { /* empty body */ }
5470     //     using namespace unique;
5471     //     namespace unique { namespace-body }
5472     //   where all occurrences of 'unique' in a translation unit are
5473     //   replaced by the same identifier and this identifier differs
5474     //   from all other identifiers in the entire program.
5475 
5476     // We just create the namespace with an empty name and then add an
5477     // implicit using declaration, just like the standard suggests.
5478     //
5479     // CodeGen enforces the "universally unique" aspect by giving all
5480     // declarations semantically contained within an anonymous
5481     // namespace internal linkage.
5482 
5483     if (!PrevNS) {
5484       UsingDirectiveDecl* UD
5485         = UsingDirectiveDecl::Create(Context, CurContext,
5486                                      /* 'using' */ LBrace,
5487                                      /* 'namespace' */ SourceLocation(),
5488                                      /* qualifier */ NestedNameSpecifierLoc(),
5489                                      /* identifier */ SourceLocation(),
5490                                      Namespc,
5491                                      /* Ancestor */ CurContext);
5492       UD->setImplicit();
5493       CurContext->addDecl(UD);
5494     }
5495   }
5496 
5497   ActOnDocumentableDecl(Namespc);
5498 
5499   // Although we could have an invalid decl (i.e. the namespace name is a
5500   // redefinition), push it as current DeclContext and try to continue parsing.
5501   // FIXME: We should be able to push Namespc here, so that the each DeclContext
5502   // for the namespace has the declarations that showed up in that particular
5503   // namespace definition.
5504   PushDeclContext(NamespcScope, Namespc);
5505   return Namespc;
5506 }
5507 
5508 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5509 /// is a namespace alias, returns the namespace it points to.
5510 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5511   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5512     return AD->getNamespace();
5513   return dyn_cast_or_null<NamespaceDecl>(D);
5514 }
5515 
5516 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5517 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5518 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
5519   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5520   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
5521   Namespc->setRBraceLoc(RBrace);
5522   PopDeclContext();
5523   if (Namespc->hasAttr<VisibilityAttr>())
5524     PopPragmaVisibility(true, RBrace);
5525 }
5526 
5527 CXXRecordDecl *Sema::getStdBadAlloc() const {
5528   return cast_or_null<CXXRecordDecl>(
5529                                   StdBadAlloc.get(Context.getExternalSource()));
5530 }
5531 
5532 NamespaceDecl *Sema::getStdNamespace() const {
5533   return cast_or_null<NamespaceDecl>(
5534                                  StdNamespace.get(Context.getExternalSource()));
5535 }
5536 
5537 /// \brief Retrieve the special "std" namespace, which may require us to
5538 /// implicitly define the namespace.
5539 NamespaceDecl *Sema::getOrCreateStdNamespace() {
5540   if (!StdNamespace) {
5541     // The "std" namespace has not yet been defined, so build one implicitly.
5542     StdNamespace = NamespaceDecl::Create(Context,
5543                                          Context.getTranslationUnitDecl(),
5544                                          /*Inline=*/false,
5545                                          SourceLocation(), SourceLocation(),
5546                                          &PP.getIdentifierTable().get("std"),
5547                                          /*PrevDecl=*/0);
5548     getStdNamespace()->setImplicit(true);
5549   }
5550 
5551   return getStdNamespace();
5552 }
5553 
5554 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5555   assert(getLangOpts().CPlusPlus &&
5556          "Looking for std::initializer_list outside of C++.");
5557 
5558   // We're looking for implicit instantiations of
5559   // template <typename E> class std::initializer_list.
5560 
5561   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5562     return false;
5563 
5564   ClassTemplateDecl *Template = 0;
5565   const TemplateArgument *Arguments = 0;
5566 
5567   if (const RecordType *RT = Ty->getAs<RecordType>()) {
5568 
5569     ClassTemplateSpecializationDecl *Specialization =
5570         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5571     if (!Specialization)
5572       return false;
5573 
5574     Template = Specialization->getSpecializedTemplate();
5575     Arguments = Specialization->getTemplateArgs().data();
5576   } else if (const TemplateSpecializationType *TST =
5577                  Ty->getAs<TemplateSpecializationType>()) {
5578     Template = dyn_cast_or_null<ClassTemplateDecl>(
5579         TST->getTemplateName().getAsTemplateDecl());
5580     Arguments = TST->getArgs();
5581   }
5582   if (!Template)
5583     return false;
5584 
5585   if (!StdInitializerList) {
5586     // Haven't recognized std::initializer_list yet, maybe this is it.
5587     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5588     if (TemplateClass->getIdentifier() !=
5589             &PP.getIdentifierTable().get("initializer_list") ||
5590         !getStdNamespace()->InEnclosingNamespaceSetOf(
5591             TemplateClass->getDeclContext()))
5592       return false;
5593     // This is a template called std::initializer_list, but is it the right
5594     // template?
5595     TemplateParameterList *Params = Template->getTemplateParameters();
5596     if (Params->getMinRequiredArguments() != 1)
5597       return false;
5598     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5599       return false;
5600 
5601     // It's the right template.
5602     StdInitializerList = Template;
5603   }
5604 
5605   if (Template != StdInitializerList)
5606     return false;
5607 
5608   // This is an instance of std::initializer_list. Find the argument type.
5609   if (Element)
5610     *Element = Arguments[0].getAsType();
5611   return true;
5612 }
5613 
5614 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5615   NamespaceDecl *Std = S.getStdNamespace();
5616   if (!Std) {
5617     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5618     return 0;
5619   }
5620 
5621   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5622                       Loc, Sema::LookupOrdinaryName);
5623   if (!S.LookupQualifiedName(Result, Std)) {
5624     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5625     return 0;
5626   }
5627   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5628   if (!Template) {
5629     Result.suppressDiagnostics();
5630     // We found something weird. Complain about the first thing we found.
5631     NamedDecl *Found = *Result.begin();
5632     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5633     return 0;
5634   }
5635 
5636   // We found some template called std::initializer_list. Now verify that it's
5637   // correct.
5638   TemplateParameterList *Params = Template->getTemplateParameters();
5639   if (Params->getMinRequiredArguments() != 1 ||
5640       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5641     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5642     return 0;
5643   }
5644 
5645   return Template;
5646 }
5647 
5648 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5649   if (!StdInitializerList) {
5650     StdInitializerList = LookupStdInitializerList(*this, Loc);
5651     if (!StdInitializerList)
5652       return QualType();
5653   }
5654 
5655   TemplateArgumentListInfo Args(Loc, Loc);
5656   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5657                                        Context.getTrivialTypeSourceInfo(Element,
5658                                                                         Loc)));
5659   return Context.getCanonicalType(
5660       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5661 }
5662 
5663 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5664   // C++ [dcl.init.list]p2:
5665   //   A constructor is an initializer-list constructor if its first parameter
5666   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
5667   //   std::initializer_list<E> for some type E, and either there are no other
5668   //   parameters or else all other parameters have default arguments.
5669   if (Ctor->getNumParams() < 1 ||
5670       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5671     return false;
5672 
5673   QualType ArgType = Ctor->getParamDecl(0)->getType();
5674   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5675     ArgType = RT->getPointeeType().getUnqualifiedType();
5676 
5677   return isStdInitializerList(ArgType, 0);
5678 }
5679 
5680 /// \brief Determine whether a using statement is in a context where it will be
5681 /// apply in all contexts.
5682 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5683   switch (CurContext->getDeclKind()) {
5684     case Decl::TranslationUnit:
5685       return true;
5686     case Decl::LinkageSpec:
5687       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5688     default:
5689       return false;
5690   }
5691 }
5692 
5693 namespace {
5694 
5695 // Callback to only accept typo corrections that are namespaces.
5696 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5697  public:
5698   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5699     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5700       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5701     }
5702     return false;
5703   }
5704 };
5705 
5706 }
5707 
5708 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5709                                        CXXScopeSpec &SS,
5710                                        SourceLocation IdentLoc,
5711                                        IdentifierInfo *Ident) {
5712   NamespaceValidatorCCC Validator;
5713   R.clear();
5714   if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5715                                                R.getLookupKind(), Sc, &SS,
5716                                                Validator)) {
5717     std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5718     std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
5719     if (DeclContext *DC = S.computeDeclContext(SS, false))
5720       S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5721         << Ident << DC << CorrectedQuotedStr << SS.getRange()
5722         << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5723     else
5724       S.Diag(IdentLoc, diag::err_using_directive_suggest)
5725         << Ident << CorrectedQuotedStr
5726         << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5727 
5728     S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5729          diag::note_namespace_defined_here) << CorrectedQuotedStr;
5730 
5731     R.addDecl(Corrected.getCorrectionDecl());
5732     return true;
5733   }
5734   return false;
5735 }
5736 
5737 Decl *Sema::ActOnUsingDirective(Scope *S,
5738                                           SourceLocation UsingLoc,
5739                                           SourceLocation NamespcLoc,
5740                                           CXXScopeSpec &SS,
5741                                           SourceLocation IdentLoc,
5742                                           IdentifierInfo *NamespcName,
5743                                           AttributeList *AttrList) {
5744   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5745   assert(NamespcName && "Invalid NamespcName.");
5746   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
5747 
5748   // This can only happen along a recovery path.
5749   while (S->getFlags() & Scope::TemplateParamScope)
5750     S = S->getParent();
5751   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5752 
5753   UsingDirectiveDecl *UDir = 0;
5754   NestedNameSpecifier *Qualifier = 0;
5755   if (SS.isSet())
5756     Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5757 
5758   // Lookup namespace name.
5759   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5760   LookupParsedName(R, S, &SS);
5761   if (R.isAmbiguous())
5762     return 0;
5763 
5764   if (R.empty()) {
5765     R.clear();
5766     // Allow "using namespace std;" or "using namespace ::std;" even if
5767     // "std" hasn't been defined yet, for GCC compatibility.
5768     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5769         NamespcName->isStr("std")) {
5770       Diag(IdentLoc, diag::ext_using_undefined_std);
5771       R.addDecl(getOrCreateStdNamespace());
5772       R.resolveKind();
5773     }
5774     // Otherwise, attempt typo correction.
5775     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
5776   }
5777 
5778   if (!R.empty()) {
5779     NamedDecl *Named = R.getFoundDecl();
5780     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5781         && "expected namespace decl");
5782     // C++ [namespace.udir]p1:
5783     //   A using-directive specifies that the names in the nominated
5784     //   namespace can be used in the scope in which the
5785     //   using-directive appears after the using-directive. During
5786     //   unqualified name lookup (3.4.1), the names appear as if they
5787     //   were declared in the nearest enclosing namespace which
5788     //   contains both the using-directive and the nominated
5789     //   namespace. [Note: in this context, "contains" means "contains
5790     //   directly or indirectly". ]
5791 
5792     // Find enclosing context containing both using-directive and
5793     // nominated namespace.
5794     NamespaceDecl *NS = getNamespaceDecl(Named);
5795     DeclContext *CommonAncestor = cast<DeclContext>(NS);
5796     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5797       CommonAncestor = CommonAncestor->getParent();
5798 
5799     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
5800                                       SS.getWithLocInContext(Context),
5801                                       IdentLoc, Named, CommonAncestor);
5802 
5803     if (IsUsingDirectiveInToplevelContext(CurContext) &&
5804         !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
5805       Diag(IdentLoc, diag::warn_using_directive_in_header);
5806     }
5807 
5808     PushUsingDirective(S, UDir);
5809   } else {
5810     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
5811   }
5812 
5813   // FIXME: We ignore attributes for now.
5814   return UDir;
5815 }
5816 
5817 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5818   // If the scope has an associated entity and the using directive is at
5819   // namespace or translation unit scope, add the UsingDirectiveDecl into
5820   // its lookup structure so qualified name lookup can find it.
5821   DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5822   if (Ctx && !Ctx->isFunctionOrMethod())
5823     Ctx->addDecl(UDir);
5824   else
5825     // Otherwise, it is at block sope. The using-directives will affect lookup
5826     // only to the end of the scope.
5827     S->PushUsingDirective(UDir);
5828 }
5829 
5830 
5831 Decl *Sema::ActOnUsingDeclaration(Scope *S,
5832                                   AccessSpecifier AS,
5833                                   bool HasUsingKeyword,
5834                                   SourceLocation UsingLoc,
5835                                   CXXScopeSpec &SS,
5836                                   UnqualifiedId &Name,
5837                                   AttributeList *AttrList,
5838                                   bool IsTypeName,
5839                                   SourceLocation TypenameLoc) {
5840   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5841 
5842   switch (Name.getKind()) {
5843   case UnqualifiedId::IK_ImplicitSelfParam:
5844   case UnqualifiedId::IK_Identifier:
5845   case UnqualifiedId::IK_OperatorFunctionId:
5846   case UnqualifiedId::IK_LiteralOperatorId:
5847   case UnqualifiedId::IK_ConversionFunctionId:
5848     break;
5849 
5850   case UnqualifiedId::IK_ConstructorName:
5851   case UnqualifiedId::IK_ConstructorTemplateId:
5852     // C++11 inheriting constructors.
5853     Diag(Name.getLocStart(),
5854          getLangOpts().CPlusPlus0x ?
5855            // FIXME: Produce warn_cxx98_compat_using_decl_constructor
5856            //        instead once inheriting constructors work.
5857            diag::err_using_decl_constructor_unsupported :
5858            diag::err_using_decl_constructor)
5859       << SS.getRange();
5860 
5861     if (getLangOpts().CPlusPlus0x) break;
5862 
5863     return 0;
5864 
5865   case UnqualifiedId::IK_DestructorName:
5866     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
5867       << SS.getRange();
5868     return 0;
5869 
5870   case UnqualifiedId::IK_TemplateId:
5871     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
5872       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
5873     return 0;
5874   }
5875 
5876   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5877   DeclarationName TargetName = TargetNameInfo.getName();
5878   if (!TargetName)
5879     return 0;
5880 
5881   // Warn about using declarations.
5882   // TODO: store that the declaration was written without 'using' and
5883   // talk about access decls instead of using decls in the
5884   // diagnostics.
5885   if (!HasUsingKeyword) {
5886     UsingLoc = Name.getLocStart();
5887 
5888     Diag(UsingLoc, diag::warn_access_decl_deprecated)
5889       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
5890   }
5891 
5892   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5893       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5894     return 0;
5895 
5896   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
5897                                         TargetNameInfo, AttrList,
5898                                         /* IsInstantiation */ false,
5899                                         IsTypeName, TypenameLoc);
5900   if (UD)
5901     PushOnScopeChains(UD, S, /*AddToContext*/ false);
5902 
5903   return UD;
5904 }
5905 
5906 /// \brief Determine whether a using declaration considers the given
5907 /// declarations as "equivalent", e.g., if they are redeclarations of
5908 /// the same entity or are both typedefs of the same type.
5909 static bool
5910 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5911                          bool &SuppressRedeclaration) {
5912   if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5913     SuppressRedeclaration = false;
5914     return true;
5915   }
5916 
5917   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5918     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
5919       SuppressRedeclaration = true;
5920       return Context.hasSameType(TD1->getUnderlyingType(),
5921                                  TD2->getUnderlyingType());
5922     }
5923 
5924   return false;
5925 }
5926 
5927 
5928 /// Determines whether to create a using shadow decl for a particular
5929 /// decl, given the set of decls existing prior to this using lookup.
5930 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5931                                 const LookupResult &Previous) {
5932   // Diagnose finding a decl which is not from a base class of the
5933   // current class.  We do this now because there are cases where this
5934   // function will silently decide not to build a shadow decl, which
5935   // will pre-empt further diagnostics.
5936   //
5937   // We don't need to do this in C++0x because we do the check once on
5938   // the qualifier.
5939   //
5940   // FIXME: diagnose the following if we care enough:
5941   //   struct A { int foo; };
5942   //   struct B : A { using A::foo; };
5943   //   template <class T> struct C : A {};
5944   //   template <class T> struct D : C<T> { using B::foo; } // <---
5945   // This is invalid (during instantiation) in C++03 because B::foo
5946   // resolves to the using decl in B, which is not a base class of D<T>.
5947   // We can't diagnose it immediately because C<T> is an unknown
5948   // specialization.  The UsingShadowDecl in D<T> then points directly
5949   // to A::foo, which will look well-formed when we instantiate.
5950   // The right solution is to not collapse the shadow-decl chain.
5951   if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
5952     DeclContext *OrigDC = Orig->getDeclContext();
5953 
5954     // Handle enums and anonymous structs.
5955     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5956     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5957     while (OrigRec->isAnonymousStructOrUnion())
5958       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5959 
5960     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5961       if (OrigDC == CurContext) {
5962         Diag(Using->getLocation(),
5963              diag::err_using_decl_nested_name_specifier_is_current_class)
5964           << Using->getQualifierLoc().getSourceRange();
5965         Diag(Orig->getLocation(), diag::note_using_decl_target);
5966         return true;
5967       }
5968 
5969       Diag(Using->getQualifierLoc().getBeginLoc(),
5970            diag::err_using_decl_nested_name_specifier_is_not_base_class)
5971         << Using->getQualifier()
5972         << cast<CXXRecordDecl>(CurContext)
5973         << Using->getQualifierLoc().getSourceRange();
5974       Diag(Orig->getLocation(), diag::note_using_decl_target);
5975       return true;
5976     }
5977   }
5978 
5979   if (Previous.empty()) return false;
5980 
5981   NamedDecl *Target = Orig;
5982   if (isa<UsingShadowDecl>(Target))
5983     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5984 
5985   // If the target happens to be one of the previous declarations, we
5986   // don't have a conflict.
5987   //
5988   // FIXME: but we might be increasing its access, in which case we
5989   // should redeclare it.
5990   NamedDecl *NonTag = 0, *Tag = 0;
5991   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5992          I != E; ++I) {
5993     NamedDecl *D = (*I)->getUnderlyingDecl();
5994     bool Result;
5995     if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5996       return Result;
5997 
5998     (isa<TagDecl>(D) ? Tag : NonTag) = D;
5999   }
6000 
6001   if (Target->isFunctionOrFunctionTemplate()) {
6002     FunctionDecl *FD;
6003     if (isa<FunctionTemplateDecl>(Target))
6004       FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6005     else
6006       FD = cast<FunctionDecl>(Target);
6007 
6008     NamedDecl *OldDecl = 0;
6009     switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6010     case Ovl_Overload:
6011       return false;
6012 
6013     case Ovl_NonFunction:
6014       Diag(Using->getLocation(), diag::err_using_decl_conflict);
6015       break;
6016 
6017     // We found a decl with the exact signature.
6018     case Ovl_Match:
6019       // If we're in a record, we want to hide the target, so we
6020       // return true (without a diagnostic) to tell the caller not to
6021       // build a shadow decl.
6022       if (CurContext->isRecord())
6023         return true;
6024 
6025       // If we're not in a record, this is an error.
6026       Diag(Using->getLocation(), diag::err_using_decl_conflict);
6027       break;
6028     }
6029 
6030     Diag(Target->getLocation(), diag::note_using_decl_target);
6031     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6032     return true;
6033   }
6034 
6035   // Target is not a function.
6036 
6037   if (isa<TagDecl>(Target)) {
6038     // No conflict between a tag and a non-tag.
6039     if (!Tag) return false;
6040 
6041     Diag(Using->getLocation(), diag::err_using_decl_conflict);
6042     Diag(Target->getLocation(), diag::note_using_decl_target);
6043     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6044     return true;
6045   }
6046 
6047   // No conflict between a tag and a non-tag.
6048   if (!NonTag) return false;
6049 
6050   Diag(Using->getLocation(), diag::err_using_decl_conflict);
6051   Diag(Target->getLocation(), diag::note_using_decl_target);
6052   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6053   return true;
6054 }
6055 
6056 /// Builds a shadow declaration corresponding to a 'using' declaration.
6057 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6058                                             UsingDecl *UD,
6059                                             NamedDecl *Orig) {
6060 
6061   // If we resolved to another shadow declaration, just coalesce them.
6062   NamedDecl *Target = Orig;
6063   if (isa<UsingShadowDecl>(Target)) {
6064     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6065     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6066   }
6067 
6068   UsingShadowDecl *Shadow
6069     = UsingShadowDecl::Create(Context, CurContext,
6070                               UD->getLocation(), UD, Target);
6071   UD->addShadowDecl(Shadow);
6072 
6073   Shadow->setAccess(UD->getAccess());
6074   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6075     Shadow->setInvalidDecl();
6076 
6077   if (S)
6078     PushOnScopeChains(Shadow, S);
6079   else
6080     CurContext->addDecl(Shadow);
6081 
6082 
6083   return Shadow;
6084 }
6085 
6086 /// Hides a using shadow declaration.  This is required by the current
6087 /// using-decl implementation when a resolvable using declaration in a
6088 /// class is followed by a declaration which would hide or override
6089 /// one or more of the using decl's targets; for example:
6090 ///
6091 ///   struct Base { void foo(int); };
6092 ///   struct Derived : Base {
6093 ///     using Base::foo;
6094 ///     void foo(int);
6095 ///   };
6096 ///
6097 /// The governing language is C++03 [namespace.udecl]p12:
6098 ///
6099 ///   When a using-declaration brings names from a base class into a
6100 ///   derived class scope, member functions in the derived class
6101 ///   override and/or hide member functions with the same name and
6102 ///   parameter types in a base class (rather than conflicting).
6103 ///
6104 /// There are two ways to implement this:
6105 ///   (1) optimistically create shadow decls when they're not hidden
6106 ///       by existing declarations, or
6107 ///   (2) don't create any shadow decls (or at least don't make them
6108 ///       visible) until we've fully parsed/instantiated the class.
6109 /// The problem with (1) is that we might have to retroactively remove
6110 /// a shadow decl, which requires several O(n) operations because the
6111 /// decl structures are (very reasonably) not designed for removal.
6112 /// (2) avoids this but is very fiddly and phase-dependent.
6113 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6114   if (Shadow->getDeclName().getNameKind() ==
6115         DeclarationName::CXXConversionFunctionName)
6116     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6117 
6118   // Remove it from the DeclContext...
6119   Shadow->getDeclContext()->removeDecl(Shadow);
6120 
6121   // ...and the scope, if applicable...
6122   if (S) {
6123     S->RemoveDecl(Shadow);
6124     IdResolver.RemoveDecl(Shadow);
6125   }
6126 
6127   // ...and the using decl.
6128   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6129 
6130   // TODO: complain somehow if Shadow was used.  It shouldn't
6131   // be possible for this to happen, because...?
6132 }
6133 
6134 /// Builds a using declaration.
6135 ///
6136 /// \param IsInstantiation - Whether this call arises from an
6137 ///   instantiation of an unresolved using declaration.  We treat
6138 ///   the lookup differently for these declarations.
6139 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6140                                        SourceLocation UsingLoc,
6141                                        CXXScopeSpec &SS,
6142                                        const DeclarationNameInfo &NameInfo,
6143                                        AttributeList *AttrList,
6144                                        bool IsInstantiation,
6145                                        bool IsTypeName,
6146                                        SourceLocation TypenameLoc) {
6147   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6148   SourceLocation IdentLoc = NameInfo.getLoc();
6149   assert(IdentLoc.isValid() && "Invalid TargetName location.");
6150 
6151   // FIXME: We ignore attributes for now.
6152 
6153   if (SS.isEmpty()) {
6154     Diag(IdentLoc, diag::err_using_requires_qualname);
6155     return 0;
6156   }
6157 
6158   // Do the redeclaration lookup in the current scope.
6159   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
6160                         ForRedeclaration);
6161   Previous.setHideTags(false);
6162   if (S) {
6163     LookupName(Previous, S);
6164 
6165     // It is really dumb that we have to do this.
6166     LookupResult::Filter F = Previous.makeFilter();
6167     while (F.hasNext()) {
6168       NamedDecl *D = F.next();
6169       if (!isDeclInScope(D, CurContext, S))
6170         F.erase();
6171     }
6172     F.done();
6173   } else {
6174     assert(IsInstantiation && "no scope in non-instantiation");
6175     assert(CurContext->isRecord() && "scope not record in instantiation");
6176     LookupQualifiedName(Previous, CurContext);
6177   }
6178 
6179   // Check for invalid redeclarations.
6180   if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6181     return 0;
6182 
6183   // Check for bad qualifiers.
6184   if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6185     return 0;
6186 
6187   DeclContext *LookupContext = computeDeclContext(SS);
6188   NamedDecl *D;
6189   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6190   if (!LookupContext) {
6191     if (IsTypeName) {
6192       // FIXME: not all declaration name kinds are legal here
6193       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6194                                               UsingLoc, TypenameLoc,
6195                                               QualifierLoc,
6196                                               IdentLoc, NameInfo.getName());
6197     } else {
6198       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6199                                            QualifierLoc, NameInfo);
6200     }
6201   } else {
6202     D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6203                           NameInfo, IsTypeName);
6204   }
6205   D->setAccess(AS);
6206   CurContext->addDecl(D);
6207 
6208   if (!LookupContext) return D;
6209   UsingDecl *UD = cast<UsingDecl>(D);
6210 
6211   if (RequireCompleteDeclContext(SS, LookupContext)) {
6212     UD->setInvalidDecl();
6213     return UD;
6214   }
6215 
6216   // The normal rules do not apply to inheriting constructor declarations.
6217   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
6218     if (CheckInheritingConstructorUsingDecl(UD))
6219       UD->setInvalidDecl();
6220     return UD;
6221   }
6222 
6223   // Otherwise, look up the target name.
6224 
6225   LookupResult R(*this, NameInfo, LookupOrdinaryName);
6226 
6227   // Unlike most lookups, we don't always want to hide tag
6228   // declarations: tag names are visible through the using declaration
6229   // even if hidden by ordinary names, *except* in a dependent context
6230   // where it's important for the sanity of two-phase lookup.
6231   if (!IsInstantiation)
6232     R.setHideTags(false);
6233 
6234   // For the purposes of this lookup, we have a base object type
6235   // equal to that of the current context.
6236   if (CurContext->isRecord()) {
6237     R.setBaseObjectType(
6238                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6239   }
6240 
6241   LookupQualifiedName(R, LookupContext);
6242 
6243   if (R.empty()) {
6244     Diag(IdentLoc, diag::err_no_member)
6245       << NameInfo.getName() << LookupContext << SS.getRange();
6246     UD->setInvalidDecl();
6247     return UD;
6248   }
6249 
6250   if (R.isAmbiguous()) {
6251     UD->setInvalidDecl();
6252     return UD;
6253   }
6254 
6255   if (IsTypeName) {
6256     // If we asked for a typename and got a non-type decl, error out.
6257     if (!R.getAsSingle<TypeDecl>()) {
6258       Diag(IdentLoc, diag::err_using_typename_non_type);
6259       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6260         Diag((*I)->getUnderlyingDecl()->getLocation(),
6261              diag::note_using_decl_target);
6262       UD->setInvalidDecl();
6263       return UD;
6264     }
6265   } else {
6266     // If we asked for a non-typename and we got a type, error out,
6267     // but only if this is an instantiation of an unresolved using
6268     // decl.  Otherwise just silently find the type name.
6269     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
6270       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6271       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
6272       UD->setInvalidDecl();
6273       return UD;
6274     }
6275   }
6276 
6277   // C++0x N2914 [namespace.udecl]p6:
6278   // A using-declaration shall not name a namespace.
6279   if (R.getAsSingle<NamespaceDecl>()) {
6280     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6281       << SS.getRange();
6282     UD->setInvalidDecl();
6283     return UD;
6284   }
6285 
6286   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6287     if (!CheckUsingShadowDecl(UD, *I, Previous))
6288       BuildUsingShadowDecl(S, UD, *I);
6289   }
6290 
6291   return UD;
6292 }
6293 
6294 /// Additional checks for a using declaration referring to a constructor name.
6295 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6296   assert(!UD->isTypeName() && "expecting a constructor name");
6297 
6298   const Type *SourceType = UD->getQualifier()->getAsType();
6299   assert(SourceType &&
6300          "Using decl naming constructor doesn't have type in scope spec.");
6301   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6302 
6303   // Check whether the named type is a direct base class.
6304   CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6305   CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6306   for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6307        BaseIt != BaseE; ++BaseIt) {
6308     CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6309     if (CanonicalSourceType == BaseType)
6310       break;
6311     if (BaseIt->getType()->isDependentType())
6312       break;
6313   }
6314 
6315   if (BaseIt == BaseE) {
6316     // Did not find SourceType in the bases.
6317     Diag(UD->getUsingLocation(),
6318          diag::err_using_decl_constructor_not_in_direct_base)
6319       << UD->getNameInfo().getSourceRange()
6320       << QualType(SourceType, 0) << TargetClass;
6321     return true;
6322   }
6323 
6324   if (!CurContext->isDependentContext())
6325     BaseIt->setInheritConstructors();
6326 
6327   return false;
6328 }
6329 
6330 /// Checks that the given using declaration is not an invalid
6331 /// redeclaration.  Note that this is checking only for the using decl
6332 /// itself, not for any ill-formedness among the UsingShadowDecls.
6333 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6334                                        bool isTypeName,
6335                                        const CXXScopeSpec &SS,
6336                                        SourceLocation NameLoc,
6337                                        const LookupResult &Prev) {
6338   // C++03 [namespace.udecl]p8:
6339   // C++0x [namespace.udecl]p10:
6340   //   A using-declaration is a declaration and can therefore be used
6341   //   repeatedly where (and only where) multiple declarations are
6342   //   allowed.
6343   //
6344   // That's in non-member contexts.
6345   if (!CurContext->getRedeclContext()->isRecord())
6346     return false;
6347 
6348   NestedNameSpecifier *Qual
6349     = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6350 
6351   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6352     NamedDecl *D = *I;
6353 
6354     bool DTypename;
6355     NestedNameSpecifier *DQual;
6356     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6357       DTypename = UD->isTypeName();
6358       DQual = UD->getQualifier();
6359     } else if (UnresolvedUsingValueDecl *UD
6360                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6361       DTypename = false;
6362       DQual = UD->getQualifier();
6363     } else if (UnresolvedUsingTypenameDecl *UD
6364                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6365       DTypename = true;
6366       DQual = UD->getQualifier();
6367     } else continue;
6368 
6369     // using decls differ if one says 'typename' and the other doesn't.
6370     // FIXME: non-dependent using decls?
6371     if (isTypeName != DTypename) continue;
6372 
6373     // using decls differ if they name different scopes (but note that
6374     // template instantiation can cause this check to trigger when it
6375     // didn't before instantiation).
6376     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6377         Context.getCanonicalNestedNameSpecifier(DQual))
6378       continue;
6379 
6380     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
6381     Diag(D->getLocation(), diag::note_using_decl) << 1;
6382     return true;
6383   }
6384 
6385   return false;
6386 }
6387 
6388 
6389 /// Checks that the given nested-name qualifier used in a using decl
6390 /// in the current context is appropriately related to the current
6391 /// scope.  If an error is found, diagnoses it and returns true.
6392 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6393                                    const CXXScopeSpec &SS,
6394                                    SourceLocation NameLoc) {
6395   DeclContext *NamedContext = computeDeclContext(SS);
6396 
6397   if (!CurContext->isRecord()) {
6398     // C++03 [namespace.udecl]p3:
6399     // C++0x [namespace.udecl]p8:
6400     //   A using-declaration for a class member shall be a member-declaration.
6401 
6402     // If we weren't able to compute a valid scope, it must be a
6403     // dependent class scope.
6404     if (!NamedContext || NamedContext->isRecord()) {
6405       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6406         << SS.getRange();
6407       return true;
6408     }
6409 
6410     // Otherwise, everything is known to be fine.
6411     return false;
6412   }
6413 
6414   // The current scope is a record.
6415 
6416   // If the named context is dependent, we can't decide much.
6417   if (!NamedContext) {
6418     // FIXME: in C++0x, we can diagnose if we can prove that the
6419     // nested-name-specifier does not refer to a base class, which is
6420     // still possible in some cases.
6421 
6422     // Otherwise we have to conservatively report that things might be
6423     // okay.
6424     return false;
6425   }
6426 
6427   if (!NamedContext->isRecord()) {
6428     // Ideally this would point at the last name in the specifier,
6429     // but we don't have that level of source info.
6430     Diag(SS.getRange().getBegin(),
6431          diag::err_using_decl_nested_name_specifier_is_not_class)
6432       << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6433     return true;
6434   }
6435 
6436   if (!NamedContext->isDependentContext() &&
6437       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6438     return true;
6439 
6440   if (getLangOpts().CPlusPlus0x) {
6441     // C++0x [namespace.udecl]p3:
6442     //   In a using-declaration used as a member-declaration, the
6443     //   nested-name-specifier shall name a base class of the class
6444     //   being defined.
6445 
6446     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6447                                  cast<CXXRecordDecl>(NamedContext))) {
6448       if (CurContext == NamedContext) {
6449         Diag(NameLoc,
6450              diag::err_using_decl_nested_name_specifier_is_current_class)
6451           << SS.getRange();
6452         return true;
6453       }
6454 
6455       Diag(SS.getRange().getBegin(),
6456            diag::err_using_decl_nested_name_specifier_is_not_base_class)
6457         << (NestedNameSpecifier*) SS.getScopeRep()
6458         << cast<CXXRecordDecl>(CurContext)
6459         << SS.getRange();
6460       return true;
6461     }
6462 
6463     return false;
6464   }
6465 
6466   // C++03 [namespace.udecl]p4:
6467   //   A using-declaration used as a member-declaration shall refer
6468   //   to a member of a base class of the class being defined [etc.].
6469 
6470   // Salient point: SS doesn't have to name a base class as long as
6471   // lookup only finds members from base classes.  Therefore we can
6472   // diagnose here only if we can prove that that can't happen,
6473   // i.e. if the class hierarchies provably don't intersect.
6474 
6475   // TODO: it would be nice if "definitely valid" results were cached
6476   // in the UsingDecl and UsingShadowDecl so that these checks didn't
6477   // need to be repeated.
6478 
6479   struct UserData {
6480     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
6481 
6482     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6483       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6484       Data->Bases.insert(Base);
6485       return true;
6486     }
6487 
6488     bool hasDependentBases(const CXXRecordDecl *Class) {
6489       return !Class->forallBases(collect, this);
6490     }
6491 
6492     /// Returns true if the base is dependent or is one of the
6493     /// accumulated base classes.
6494     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6495       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6496       return !Data->Bases.count(Base);
6497     }
6498 
6499     bool mightShareBases(const CXXRecordDecl *Class) {
6500       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6501     }
6502   };
6503 
6504   UserData Data;
6505 
6506   // Returns false if we find a dependent base.
6507   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6508     return false;
6509 
6510   // Returns false if the class has a dependent base or if it or one
6511   // of its bases is present in the base set of the current context.
6512   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6513     return false;
6514 
6515   Diag(SS.getRange().getBegin(),
6516        diag::err_using_decl_nested_name_specifier_is_not_base_class)
6517     << (NestedNameSpecifier*) SS.getScopeRep()
6518     << cast<CXXRecordDecl>(CurContext)
6519     << SS.getRange();
6520 
6521   return true;
6522 }
6523 
6524 Decl *Sema::ActOnAliasDeclaration(Scope *S,
6525                                   AccessSpecifier AS,
6526                                   MultiTemplateParamsArg TemplateParamLists,
6527                                   SourceLocation UsingLoc,
6528                                   UnqualifiedId &Name,
6529                                   TypeResult Type) {
6530   // Skip up to the relevant declaration scope.
6531   while (S->getFlags() & Scope::TemplateParamScope)
6532     S = S->getParent();
6533   assert((S->getFlags() & Scope::DeclScope) &&
6534          "got alias-declaration outside of declaration scope");
6535 
6536   if (Type.isInvalid())
6537     return 0;
6538 
6539   bool Invalid = false;
6540   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6541   TypeSourceInfo *TInfo = 0;
6542   GetTypeFromParser(Type.get(), &TInfo);
6543 
6544   if (DiagnoseClassNameShadow(CurContext, NameInfo))
6545     return 0;
6546 
6547   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
6548                                       UPPC_DeclarationType)) {
6549     Invalid = true;
6550     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6551                                              TInfo->getTypeLoc().getBeginLoc());
6552   }
6553 
6554   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6555   LookupName(Previous, S);
6556 
6557   // Warn about shadowing the name of a template parameter.
6558   if (Previous.isSingleResult() &&
6559       Previous.getFoundDecl()->isTemplateParameter()) {
6560     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
6561     Previous.clear();
6562   }
6563 
6564   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6565          "name in alias declaration must be an identifier");
6566   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6567                                                Name.StartLocation,
6568                                                Name.Identifier, TInfo);
6569 
6570   NewTD->setAccess(AS);
6571 
6572   if (Invalid)
6573     NewTD->setInvalidDecl();
6574 
6575   CheckTypedefForVariablyModifiedType(S, NewTD);
6576   Invalid |= NewTD->isInvalidDecl();
6577 
6578   bool Redeclaration = false;
6579 
6580   NamedDecl *NewND;
6581   if (TemplateParamLists.size()) {
6582     TypeAliasTemplateDecl *OldDecl = 0;
6583     TemplateParameterList *OldTemplateParams = 0;
6584 
6585     if (TemplateParamLists.size() != 1) {
6586       Diag(UsingLoc, diag::err_alias_template_extra_headers)
6587         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
6588          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
6589     }
6590     TemplateParameterList *TemplateParams = TemplateParamLists[0];
6591 
6592     // Only consider previous declarations in the same scope.
6593     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6594                          /*ExplicitInstantiationOrSpecialization*/false);
6595     if (!Previous.empty()) {
6596       Redeclaration = true;
6597 
6598       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6599       if (!OldDecl && !Invalid) {
6600         Diag(UsingLoc, diag::err_redefinition_different_kind)
6601           << Name.Identifier;
6602 
6603         NamedDecl *OldD = Previous.getRepresentativeDecl();
6604         if (OldD->getLocation().isValid())
6605           Diag(OldD->getLocation(), diag::note_previous_definition);
6606 
6607         Invalid = true;
6608       }
6609 
6610       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6611         if (TemplateParameterListsAreEqual(TemplateParams,
6612                                            OldDecl->getTemplateParameters(),
6613                                            /*Complain=*/true,
6614                                            TPL_TemplateMatch))
6615           OldTemplateParams = OldDecl->getTemplateParameters();
6616         else
6617           Invalid = true;
6618 
6619         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6620         if (!Invalid &&
6621             !Context.hasSameType(OldTD->getUnderlyingType(),
6622                                  NewTD->getUnderlyingType())) {
6623           // FIXME: The C++0x standard does not clearly say this is ill-formed,
6624           // but we can't reasonably accept it.
6625           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6626             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6627           if (OldTD->getLocation().isValid())
6628             Diag(OldTD->getLocation(), diag::note_previous_definition);
6629           Invalid = true;
6630         }
6631       }
6632     }
6633 
6634     // Merge any previous default template arguments into our parameters,
6635     // and check the parameter list.
6636     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6637                                    TPC_TypeAliasTemplate))
6638       return 0;
6639 
6640     TypeAliasTemplateDecl *NewDecl =
6641       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6642                                     Name.Identifier, TemplateParams,
6643                                     NewTD);
6644 
6645     NewDecl->setAccess(AS);
6646 
6647     if (Invalid)
6648       NewDecl->setInvalidDecl();
6649     else if (OldDecl)
6650       NewDecl->setPreviousDeclaration(OldDecl);
6651 
6652     NewND = NewDecl;
6653   } else {
6654     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6655     NewND = NewTD;
6656   }
6657 
6658   if (!Redeclaration)
6659     PushOnScopeChains(NewND, S);
6660 
6661   ActOnDocumentableDecl(NewND);
6662   return NewND;
6663 }
6664 
6665 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
6666                                              SourceLocation NamespaceLoc,
6667                                              SourceLocation AliasLoc,
6668                                              IdentifierInfo *Alias,
6669                                              CXXScopeSpec &SS,
6670                                              SourceLocation IdentLoc,
6671                                              IdentifierInfo *Ident) {
6672 
6673   // Lookup the namespace name.
6674   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6675   LookupParsedName(R, S, &SS);
6676 
6677   // Check if we have a previous declaration with the same name.
6678   NamedDecl *PrevDecl
6679     = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6680                        ForRedeclaration);
6681   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6682     PrevDecl = 0;
6683 
6684   if (PrevDecl) {
6685     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
6686       // We already have an alias with the same name that points to the same
6687       // namespace, so don't create a new one.
6688       // FIXME: At some point, we'll want to create the (redundant)
6689       // declaration to maintain better source information.
6690       if (!R.isAmbiguous() && !R.empty() &&
6691           AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
6692         return 0;
6693     }
6694 
6695     unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6696       diag::err_redefinition_different_kind;
6697     Diag(AliasLoc, DiagID) << Alias;
6698     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6699     return 0;
6700   }
6701 
6702   if (R.isAmbiguous())
6703     return 0;
6704 
6705   if (R.empty()) {
6706     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
6707       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6708       return 0;
6709     }
6710   }
6711 
6712   NamespaceAliasDecl *AliasDecl =
6713     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
6714                                Alias, SS.getWithLocInContext(Context),
6715                                IdentLoc, R.getFoundDecl());
6716 
6717   PushOnScopeChains(AliasDecl, S);
6718   return AliasDecl;
6719 }
6720 
6721 namespace {
6722   /// \brief Scoped object used to handle the state changes required in Sema
6723   /// to implicitly define the body of a C++ member function;
6724   class ImplicitlyDefinedFunctionScope {
6725     Sema &S;
6726     Sema::ContextRAII SavedContext;
6727 
6728   public:
6729     ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
6730       : S(S), SavedContext(S, Method)
6731     {
6732       S.PushFunctionScope();
6733       S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6734     }
6735 
6736     ~ImplicitlyDefinedFunctionScope() {
6737       S.PopExpressionEvaluationContext();
6738       S.PopFunctionScopeInfo();
6739     }
6740   };
6741 }
6742 
6743 Sema::ImplicitExceptionSpecification
6744 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
6745                                                CXXMethodDecl *MD) {
6746   CXXRecordDecl *ClassDecl = MD->getParent();
6747 
6748   // C++ [except.spec]p14:
6749   //   An implicitly declared special member function (Clause 12) shall have an
6750   //   exception-specification. [...]
6751   ImplicitExceptionSpecification ExceptSpec(*this);
6752   if (ClassDecl->isInvalidDecl())
6753     return ExceptSpec;
6754 
6755   // Direct base-class constructors.
6756   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6757                                        BEnd = ClassDecl->bases_end();
6758        B != BEnd; ++B) {
6759     if (B->isVirtual()) // Handled below.
6760       continue;
6761 
6762     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6763       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6764       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6765       // If this is a deleted function, add it anyway. This might be conformant
6766       // with the standard. This might not. I'm not sure. It might not matter.
6767       if (Constructor)
6768         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
6769     }
6770   }
6771 
6772   // Virtual base-class constructors.
6773   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6774                                        BEnd = ClassDecl->vbases_end();
6775        B != BEnd; ++B) {
6776     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6777       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6778       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6779       // If this is a deleted function, add it anyway. This might be conformant
6780       // with the standard. This might not. I'm not sure. It might not matter.
6781       if (Constructor)
6782         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
6783     }
6784   }
6785 
6786   // Field constructors.
6787   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6788                                FEnd = ClassDecl->field_end();
6789        F != FEnd; ++F) {
6790     if (F->hasInClassInitializer()) {
6791       if (Expr *E = F->getInClassInitializer())
6792         ExceptSpec.CalledExpr(E);
6793       else if (!F->isInvalidDecl())
6794         // DR1351:
6795         //   If the brace-or-equal-initializer of a non-static data member
6796         //   invokes a defaulted default constructor of its class or of an
6797         //   enclosing class in a potentially evaluated subexpression, the
6798         //   program is ill-formed.
6799         //
6800         // This resolution is unworkable: the exception specification of the
6801         // default constructor can be needed in an unevaluated context, in
6802         // particular, in the operand of a noexcept-expression, and we can be
6803         // unable to compute an exception specification for an enclosed class.
6804         //
6805         // We do not allow an in-class initializer to require the evaluation
6806         // of the exception specification for any in-class initializer whose
6807         // definition is not lexically complete.
6808         Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
6809     } else if (const RecordType *RecordTy
6810               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
6811       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6812       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6813       // If this is a deleted function, add it anyway. This might be conformant
6814       // with the standard. This might not. I'm not sure. It might not matter.
6815       // In particular, the problem is that this function never gets called. It
6816       // might just be ill-formed because this function attempts to refer to
6817       // a deleted function here.
6818       if (Constructor)
6819         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
6820     }
6821   }
6822 
6823   return ExceptSpec;
6824 }
6825 
6826 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6827                                                      CXXRecordDecl *ClassDecl) {
6828   // C++ [class.ctor]p5:
6829   //   A default constructor for a class X is a constructor of class X
6830   //   that can be called without an argument. If there is no
6831   //   user-declared constructor for class X, a default constructor is
6832   //   implicitly declared. An implicitly-declared default constructor
6833   //   is an inline public member of its class.
6834   assert(!ClassDecl->hasUserDeclaredConstructor() &&
6835          "Should not build implicit default constructor!");
6836 
6837   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
6838                                                      CXXDefaultConstructor,
6839                                                      false);
6840 
6841   // Create the actual constructor declaration.
6842   CanQualType ClassType
6843     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6844   SourceLocation ClassLoc = ClassDecl->getLocation();
6845   DeclarationName Name
6846     = Context.DeclarationNames.getCXXConstructorName(ClassType);
6847   DeclarationNameInfo NameInfo(Name, ClassLoc);
6848   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6849       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
6850       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
6851       Constexpr);
6852   DefaultCon->setAccess(AS_public);
6853   DefaultCon->setDefaulted();
6854   DefaultCon->setImplicit();
6855   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
6856 
6857   // Build an exception specification pointing back at this constructor.
6858   FunctionProtoType::ExtProtoInfo EPI;
6859   EPI.ExceptionSpecType = EST_Unevaluated;
6860   EPI.ExceptionSpecDecl = DefaultCon;
6861   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6862 
6863   // Note that we have declared this constructor.
6864   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6865 
6866   if (Scope *S = getScopeForContext(ClassDecl))
6867     PushOnScopeChains(DefaultCon, S, false);
6868   ClassDecl->addDecl(DefaultCon);
6869 
6870   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
6871     DefaultCon->setDeletedAsWritten();
6872 
6873   return DefaultCon;
6874 }
6875 
6876 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6877                                             CXXConstructorDecl *Constructor) {
6878   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6879           !Constructor->doesThisDeclarationHaveABody() &&
6880           !Constructor->isDeleted()) &&
6881     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
6882 
6883   CXXRecordDecl *ClassDecl = Constructor->getParent();
6884   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
6885 
6886   ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
6887   DiagnosticErrorTrap Trap(Diags);
6888   if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
6889       Trap.hasErrorOccurred()) {
6890     Diag(CurrentLocation, diag::note_member_synthesized_at)
6891       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
6892     Constructor->setInvalidDecl();
6893     return;
6894   }
6895 
6896   SourceLocation Loc = Constructor->getLocation();
6897   Constructor->setBody(new (Context) CompoundStmt(Loc));
6898 
6899   Constructor->setUsed();
6900   MarkVTableUsed(CurrentLocation, ClassDecl);
6901 
6902   if (ASTMutationListener *L = getASTMutationListener()) {
6903     L->CompletedImplicitDefinition(Constructor);
6904   }
6905 }
6906 
6907 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6908   if (!D) return;
6909   AdjustDeclIfTemplate(D);
6910 
6911   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6912 
6913   if (!ClassDecl->isDependentType())
6914     CheckExplicitlyDefaultedMethods(ClassDecl);
6915 }
6916 
6917 void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6918   // We start with an initial pass over the base classes to collect those that
6919   // inherit constructors from. If there are none, we can forgo all further
6920   // processing.
6921   typedef SmallVector<const RecordType *, 4> BasesVector;
6922   BasesVector BasesToInheritFrom;
6923   for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6924                                           BaseE = ClassDecl->bases_end();
6925          BaseIt != BaseE; ++BaseIt) {
6926     if (BaseIt->getInheritConstructors()) {
6927       QualType Base = BaseIt->getType();
6928       if (Base->isDependentType()) {
6929         // If we inherit constructors from anything that is dependent, just
6930         // abort processing altogether. We'll get another chance for the
6931         // instantiations.
6932         return;
6933       }
6934       BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6935     }
6936   }
6937   if (BasesToInheritFrom.empty())
6938     return;
6939 
6940   // Now collect the constructors that we already have in the current class.
6941   // Those take precedence over inherited constructors.
6942   // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6943   //   unless there is a user-declared constructor with the same signature in
6944   //   the class where the using-declaration appears.
6945   llvm::SmallSet<const Type *, 8> ExistingConstructors;
6946   for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6947                                     CtorE = ClassDecl->ctor_end();
6948        CtorIt != CtorE; ++CtorIt) {
6949     ExistingConstructors.insert(
6950         Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6951   }
6952 
6953   DeclarationName CreatedCtorName =
6954       Context.DeclarationNames.getCXXConstructorName(
6955           ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6956 
6957   // Now comes the true work.
6958   // First, we keep a map from constructor types to the base that introduced
6959   // them. Needed for finding conflicting constructors. We also keep the
6960   // actually inserted declarations in there, for pretty diagnostics.
6961   typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6962   typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6963   ConstructorToSourceMap InheritedConstructors;
6964   for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6965                              BaseE = BasesToInheritFrom.end();
6966        BaseIt != BaseE; ++BaseIt) {
6967     const RecordType *Base = *BaseIt;
6968     CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6969     CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6970     for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6971                                       CtorE = BaseDecl->ctor_end();
6972          CtorIt != CtorE; ++CtorIt) {
6973       // Find the using declaration for inheriting this base's constructors.
6974       // FIXME: Don't perform name lookup just to obtain a source location!
6975       DeclarationName Name =
6976           Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6977       LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
6978       LookupQualifiedName(Result, CurContext);
6979       UsingDecl *UD = Result.getAsSingle<UsingDecl>();
6980       SourceLocation UsingLoc = UD ? UD->getLocation() :
6981                                      ClassDecl->getLocation();
6982 
6983       // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6984       //   from the class X named in the using-declaration consists of actual
6985       //   constructors and notional constructors that result from the
6986       //   transformation of defaulted parameters as follows:
6987       //   - all non-template default constructors of X, and
6988       //   - for each non-template constructor of X that has at least one
6989       //     parameter with a default argument, the set of constructors that
6990       //     results from omitting any ellipsis parameter specification and
6991       //     successively omitting parameters with a default argument from the
6992       //     end of the parameter-type-list.
6993       CXXConstructorDecl *BaseCtor = *CtorIt;
6994       bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6995       const FunctionProtoType *BaseCtorType =
6996           BaseCtor->getType()->getAs<FunctionProtoType>();
6997 
6998       for (unsigned params = BaseCtor->getMinRequiredArguments(),
6999                     maxParams = BaseCtor->getNumParams();
7000            params <= maxParams; ++params) {
7001         // Skip default constructors. They're never inherited.
7002         if (params == 0)
7003           continue;
7004         // Skip copy and move constructors for the same reason.
7005         if (CanBeCopyOrMove && params == 1)
7006           continue;
7007 
7008         // Build up a function type for this particular constructor.
7009         // FIXME: The working paper does not consider that the exception spec
7010         // for the inheriting constructor might be larger than that of the
7011         // source. This code doesn't yet, either. When it does, this code will
7012         // need to be delayed until after exception specifications and in-class
7013         // member initializers are attached.
7014         const Type *NewCtorType;
7015         if (params == maxParams)
7016           NewCtorType = BaseCtorType;
7017         else {
7018           SmallVector<QualType, 16> Args;
7019           for (unsigned i = 0; i < params; ++i) {
7020             Args.push_back(BaseCtorType->getArgType(i));
7021           }
7022           FunctionProtoType::ExtProtoInfo ExtInfo =
7023               BaseCtorType->getExtProtoInfo();
7024           ExtInfo.Variadic = false;
7025           NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7026                                                 Args.data(), params, ExtInfo)
7027                        .getTypePtr();
7028         }
7029         const Type *CanonicalNewCtorType =
7030             Context.getCanonicalType(NewCtorType);
7031 
7032         // Now that we have the type, first check if the class already has a
7033         // constructor with this signature.
7034         if (ExistingConstructors.count(CanonicalNewCtorType))
7035           continue;
7036 
7037         // Then we check if we have already declared an inherited constructor
7038         // with this signature.
7039         std::pair<ConstructorToSourceMap::iterator, bool> result =
7040             InheritedConstructors.insert(std::make_pair(
7041                 CanonicalNewCtorType,
7042                 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7043         if (!result.second) {
7044           // Already in the map. If it came from a different class, that's an
7045           // error. Not if it's from the same.
7046           CanQualType PreviousBase = result.first->second.first;
7047           if (CanonicalBase != PreviousBase) {
7048             const CXXConstructorDecl *PrevCtor = result.first->second.second;
7049             const CXXConstructorDecl *PrevBaseCtor =
7050                 PrevCtor->getInheritedConstructor();
7051             assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7052 
7053             Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7054             Diag(BaseCtor->getLocation(),
7055                  diag::note_using_decl_constructor_conflict_current_ctor);
7056             Diag(PrevBaseCtor->getLocation(),
7057                  diag::note_using_decl_constructor_conflict_previous_ctor);
7058             Diag(PrevCtor->getLocation(),
7059                  diag::note_using_decl_constructor_conflict_previous_using);
7060           }
7061           continue;
7062         }
7063 
7064         // OK, we're there, now add the constructor.
7065         // C++0x [class.inhctor]p8: [...] that would be performed by a
7066         //   user-written inline constructor [...]
7067         DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7068         CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
7069             Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7070             /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
7071             /*ImplicitlyDeclared=*/true,
7072             // FIXME: Due to a defect in the standard, we treat inherited
7073             // constructors as constexpr even if that makes them ill-formed.
7074             /*Constexpr=*/BaseCtor->isConstexpr());
7075         NewCtor->setAccess(BaseCtor->getAccess());
7076 
7077         // Build up the parameter decls and add them.
7078         SmallVector<ParmVarDecl *, 16> ParamDecls;
7079         for (unsigned i = 0; i < params; ++i) {
7080           ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7081                                                    UsingLoc, UsingLoc,
7082                                                    /*IdentifierInfo=*/0,
7083                                                    BaseCtorType->getArgType(i),
7084                                                    /*TInfo=*/0, SC_None,
7085                                                    SC_None, /*DefaultArg=*/0));
7086         }
7087         NewCtor->setParams(ParamDecls);
7088         NewCtor->setInheritedConstructor(BaseCtor);
7089 
7090         ClassDecl->addDecl(NewCtor);
7091         result.first->second.second = NewCtor;
7092       }
7093     }
7094   }
7095 }
7096 
7097 Sema::ImplicitExceptionSpecification
7098 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7099   CXXRecordDecl *ClassDecl = MD->getParent();
7100 
7101   // C++ [except.spec]p14:
7102   //   An implicitly declared special member function (Clause 12) shall have
7103   //   an exception-specification.
7104   ImplicitExceptionSpecification ExceptSpec(*this);
7105   if (ClassDecl->isInvalidDecl())
7106     return ExceptSpec;
7107 
7108   // Direct base-class destructors.
7109   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7110                                        BEnd = ClassDecl->bases_end();
7111        B != BEnd; ++B) {
7112     if (B->isVirtual()) // Handled below.
7113       continue;
7114 
7115     if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7116       ExceptSpec.CalledDecl(B->getLocStart(),
7117                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7118   }
7119 
7120   // Virtual base-class destructors.
7121   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7122                                        BEnd = ClassDecl->vbases_end();
7123        B != BEnd; ++B) {
7124     if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7125       ExceptSpec.CalledDecl(B->getLocStart(),
7126                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7127   }
7128 
7129   // Field destructors.
7130   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7131                                FEnd = ClassDecl->field_end();
7132        F != FEnd; ++F) {
7133     if (const RecordType *RecordTy
7134         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7135       ExceptSpec.CalledDecl(F->getLocation(),
7136                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
7137   }
7138 
7139   return ExceptSpec;
7140 }
7141 
7142 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7143   // C++ [class.dtor]p2:
7144   //   If a class has no user-declared destructor, a destructor is
7145   //   declared implicitly. An implicitly-declared destructor is an
7146   //   inline public member of its class.
7147 
7148   // Create the actual destructor declaration.
7149   CanQualType ClassType
7150     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7151   SourceLocation ClassLoc = ClassDecl->getLocation();
7152   DeclarationName Name
7153     = Context.DeclarationNames.getCXXDestructorName(ClassType);
7154   DeclarationNameInfo NameInfo(Name, ClassLoc);
7155   CXXDestructorDecl *Destructor
7156       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7157                                   QualType(), 0, /*isInline=*/true,
7158                                   /*isImplicitlyDeclared=*/true);
7159   Destructor->setAccess(AS_public);
7160   Destructor->setDefaulted();
7161   Destructor->setImplicit();
7162   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7163 
7164   // Build an exception specification pointing back at this destructor.
7165   FunctionProtoType::ExtProtoInfo EPI;
7166   EPI.ExceptionSpecType = EST_Unevaluated;
7167   EPI.ExceptionSpecDecl = Destructor;
7168   Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7169 
7170   // Note that we have declared this destructor.
7171   ++ASTContext::NumImplicitDestructorsDeclared;
7172 
7173   // Introduce this destructor into its scope.
7174   if (Scope *S = getScopeForContext(ClassDecl))
7175     PushOnScopeChains(Destructor, S, false);
7176   ClassDecl->addDecl(Destructor);
7177 
7178   AddOverriddenMethods(ClassDecl, Destructor);
7179 
7180   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7181     Destructor->setDeletedAsWritten();
7182 
7183   return Destructor;
7184 }
7185 
7186 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
7187                                     CXXDestructorDecl *Destructor) {
7188   assert((Destructor->isDefaulted() &&
7189           !Destructor->doesThisDeclarationHaveABody() &&
7190           !Destructor->isDeleted()) &&
7191          "DefineImplicitDestructor - call it for implicit default dtor");
7192   CXXRecordDecl *ClassDecl = Destructor->getParent();
7193   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
7194 
7195   if (Destructor->isInvalidDecl())
7196     return;
7197 
7198   ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
7199 
7200   DiagnosticErrorTrap Trap(Diags);
7201   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7202                                          Destructor->getParent());
7203 
7204   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
7205     Diag(CurrentLocation, diag::note_member_synthesized_at)
7206       << CXXDestructor << Context.getTagDeclType(ClassDecl);
7207 
7208     Destructor->setInvalidDecl();
7209     return;
7210   }
7211 
7212   SourceLocation Loc = Destructor->getLocation();
7213   Destructor->setBody(new (Context) CompoundStmt(Loc));
7214   Destructor->setImplicitlyDefined(true);
7215   Destructor->setUsed();
7216   MarkVTableUsed(CurrentLocation, ClassDecl);
7217 
7218   if (ASTMutationListener *L = getASTMutationListener()) {
7219     L->CompletedImplicitDefinition(Destructor);
7220   }
7221 }
7222 
7223 /// \brief Perform any semantic analysis which needs to be delayed until all
7224 /// pending class member declarations have been parsed.
7225 void Sema::ActOnFinishCXXMemberDecls() {
7226   // Perform any deferred checking of exception specifications for virtual
7227   // destructors.
7228   for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7229        i != e; ++i) {
7230     const CXXDestructorDecl *Dtor =
7231         DelayedDestructorExceptionSpecChecks[i].first;
7232     assert(!Dtor->getParent()->isDependentType() &&
7233            "Should not ever add destructors of templates into the list.");
7234     CheckOverridingFunctionExceptionSpec(Dtor,
7235         DelayedDestructorExceptionSpecChecks[i].second);
7236   }
7237   DelayedDestructorExceptionSpecChecks.clear();
7238 }
7239 
7240 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7241                                          CXXDestructorDecl *Destructor) {
7242   assert(getLangOpts().CPlusPlus0x &&
7243          "adjusting dtor exception specs was introduced in c++11");
7244 
7245   // C++11 [class.dtor]p3:
7246   //   A declaration of a destructor that does not have an exception-
7247   //   specification is implicitly considered to have the same exception-
7248   //   specification as an implicit declaration.
7249   const FunctionProtoType *DtorType = Destructor->getType()->
7250                                         getAs<FunctionProtoType>();
7251   if (DtorType->hasExceptionSpec())
7252     return;
7253 
7254   // Replace the destructor's type, building off the existing one. Fortunately,
7255   // the only thing of interest in the destructor type is its extended info.
7256   // The return and arguments are fixed.
7257   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7258   EPI.ExceptionSpecType = EST_Unevaluated;
7259   EPI.ExceptionSpecDecl = Destructor;
7260   Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7261 
7262   // FIXME: If the destructor has a body that could throw, and the newly created
7263   // spec doesn't allow exceptions, we should emit a warning, because this
7264   // change in behavior can break conforming C++03 programs at runtime.
7265   // However, we don't have a body or an exception specification yet, so it
7266   // needs to be done somewhere else.
7267 }
7268 
7269 /// \brief Builds a statement that copies/moves the given entity from \p From to
7270 /// \c To.
7271 ///
7272 /// This routine is used to copy/move the members of a class with an
7273 /// implicitly-declared copy/move assignment operator. When the entities being
7274 /// copied are arrays, this routine builds for loops to copy them.
7275 ///
7276 /// \param S The Sema object used for type-checking.
7277 ///
7278 /// \param Loc The location where the implicit copy/move is being generated.
7279 ///
7280 /// \param T The type of the expressions being copied/moved. Both expressions
7281 /// must have this type.
7282 ///
7283 /// \param To The expression we are copying/moving to.
7284 ///
7285 /// \param From The expression we are copying/moving from.
7286 ///
7287 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
7288 /// Otherwise, it's a non-static member subobject.
7289 ///
7290 /// \param Copying Whether we're copying or moving.
7291 ///
7292 /// \param Depth Internal parameter recording the depth of the recursion.
7293 ///
7294 /// \returns A statement or a loop that copies the expressions.
7295 static StmtResult
7296 BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
7297                       Expr *To, Expr *From,
7298                       bool CopyingBaseSubobject, bool Copying,
7299                       unsigned Depth = 0) {
7300   // C++0x [class.copy]p28:
7301   //   Each subobject is assigned in the manner appropriate to its type:
7302   //
7303   //     - if the subobject is of class type, as if by a call to operator= with
7304   //       the subobject as the object expression and the corresponding
7305   //       subobject of x as a single function argument (as if by explicit
7306   //       qualification; that is, ignoring any possible virtual overriding
7307   //       functions in more derived classes);
7308   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7309     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7310 
7311     // Look for operator=.
7312     DeclarationName Name
7313       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7314     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7315     S.LookupQualifiedName(OpLookup, ClassDecl, false);
7316 
7317     // Filter out any result that isn't a copy/move-assignment operator.
7318     LookupResult::Filter F = OpLookup.makeFilter();
7319     while (F.hasNext()) {
7320       NamedDecl *D = F.next();
7321       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
7322         if (Method->isCopyAssignmentOperator() ||
7323             (!Copying && Method->isMoveAssignmentOperator()))
7324           continue;
7325 
7326       F.erase();
7327     }
7328     F.done();
7329 
7330     // Suppress the protected check (C++ [class.protected]) for each of the
7331     // assignment operators we found. This strange dance is required when
7332     // we're assigning via a base classes's copy-assignment operator. To
7333     // ensure that we're getting the right base class subobject (without
7334     // ambiguities), we need to cast "this" to that subobject type; to
7335     // ensure that we don't go through the virtual call mechanism, we need
7336     // to qualify the operator= name with the base class (see below). However,
7337     // this means that if the base class has a protected copy assignment
7338     // operator, the protected member access check will fail. So, we
7339     // rewrite "protected" access to "public" access in this case, since we
7340     // know by construction that we're calling from a derived class.
7341     if (CopyingBaseSubobject) {
7342       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7343            L != LEnd; ++L) {
7344         if (L.getAccess() == AS_protected)
7345           L.setAccess(AS_public);
7346       }
7347     }
7348 
7349     // Create the nested-name-specifier that will be used to qualify the
7350     // reference to operator=; this is required to suppress the virtual
7351     // call mechanism.
7352     CXXScopeSpec SS;
7353     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
7354     SS.MakeTrivial(S.Context,
7355                    NestedNameSpecifier::Create(S.Context, 0, false,
7356                                                CanonicalT),
7357                    Loc);
7358 
7359     // Create the reference to operator=.
7360     ExprResult OpEqualRef
7361       = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
7362                                    /*TemplateKWLoc=*/SourceLocation(),
7363                                    /*FirstQualifierInScope=*/0,
7364                                    OpLookup,
7365                                    /*TemplateArgs=*/0,
7366                                    /*SuppressQualifierCheck=*/true);
7367     if (OpEqualRef.isInvalid())
7368       return StmtError();
7369 
7370     // Build the call to the assignment operator.
7371 
7372     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
7373                                                   OpEqualRef.takeAs<Expr>(),
7374                                                   Loc, &From, 1, Loc);
7375     if (Call.isInvalid())
7376       return StmtError();
7377 
7378     return S.Owned(Call.takeAs<Stmt>());
7379   }
7380 
7381   //     - if the subobject is of scalar type, the built-in assignment
7382   //       operator is used.
7383   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7384   if (!ArrayTy) {
7385     ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
7386     if (Assignment.isInvalid())
7387       return StmtError();
7388 
7389     return S.Owned(Assignment.takeAs<Stmt>());
7390   }
7391 
7392   //     - if the subobject is an array, each element is assigned, in the
7393   //       manner appropriate to the element type;
7394 
7395   // Construct a loop over the array bounds, e.g.,
7396   //
7397   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7398   //
7399   // that will copy each of the array elements.
7400   QualType SizeType = S.Context.getSizeType();
7401 
7402   // Create the iteration variable.
7403   IdentifierInfo *IterationVarName = 0;
7404   {
7405     SmallString<8> Str;
7406     llvm::raw_svector_ostream OS(Str);
7407     OS << "__i" << Depth;
7408     IterationVarName = &S.Context.Idents.get(OS.str());
7409   }
7410   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
7411                                           IterationVarName, SizeType,
7412                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
7413                                           SC_None, SC_None);
7414 
7415   // Initialize the iteration variable to zero.
7416   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
7417   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
7418 
7419   // Create a reference to the iteration variable; we'll use this several
7420   // times throughout.
7421   Expr *IterationVarRef
7422     = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
7423   assert(IterationVarRef && "Reference to invented variable cannot fail!");
7424   Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7425   assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7426 
7427   // Create the DeclStmt that holds the iteration variable.
7428   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7429 
7430   // Create the comparison against the array bound.
7431   llvm::APInt Upper
7432     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
7433   Expr *Comparison
7434     = new (S.Context) BinaryOperator(IterationVarRefRVal,
7435                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7436                                      BO_NE, S.Context.BoolTy,
7437                                      VK_RValue, OK_Ordinary, Loc);
7438 
7439   // Create the pre-increment of the iteration variable.
7440   Expr *Increment
7441     = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7442                                     VK_LValue, OK_Ordinary, Loc);
7443 
7444   // Subscript the "from" and "to" expressions with the iteration variable.
7445   From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7446                                                          IterationVarRefRVal,
7447                                                          Loc));
7448   To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7449                                                        IterationVarRefRVal,
7450                                                        Loc));
7451   if (!Copying) // Cast to rvalue
7452     From = CastForMoving(S, From);
7453 
7454   // Build the copy/move for an individual element of the array.
7455   StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7456                                           To, From, CopyingBaseSubobject,
7457                                           Copying, Depth + 1);
7458   if (Copy.isInvalid())
7459     return StmtError();
7460 
7461   // Construct the loop that copies all elements of this array.
7462   return S.ActOnForStmt(Loc, Loc, InitStmt,
7463                         S.MakeFullExpr(Comparison),
7464                         0, S.MakeFullExpr(Increment),
7465                         Loc, Copy.take());
7466 }
7467 
7468 /// Determine whether an implicit copy assignment operator for ClassDecl has a
7469 /// const argument.
7470 /// FIXME: It ought to be possible to store this on the record.
7471 static bool isImplicitCopyAssignmentArgConst(Sema &S,
7472                                              CXXRecordDecl *ClassDecl) {
7473   if (ClassDecl->isInvalidDecl())
7474     return true;
7475 
7476   // C++ [class.copy]p10:
7477   //   If the class definition does not explicitly declare a copy
7478   //   assignment operator, one is declared implicitly.
7479   //   The implicitly-defined copy assignment operator for a class X
7480   //   will have the form
7481   //
7482   //       X& X::operator=(const X&)
7483   //
7484   //   if
7485   //       -- each direct base class B of X has a copy assignment operator
7486   //          whose parameter is of type const B&, const volatile B& or B,
7487   //          and
7488   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7489                                        BaseEnd = ClassDecl->bases_end();
7490        Base != BaseEnd; ++Base) {
7491     // We'll handle this below
7492     if (S.getLangOpts().CPlusPlus0x && Base->isVirtual())
7493       continue;
7494 
7495     assert(!Base->getType()->isDependentType() &&
7496            "Cannot generate implicit members for class with dependent bases.");
7497     CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7498     if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0))
7499       return false;
7500   }
7501 
7502   // In C++11, the above citation has "or virtual" added
7503   if (S.getLangOpts().CPlusPlus0x) {
7504     for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7505                                          BaseEnd = ClassDecl->vbases_end();
7506          Base != BaseEnd; ++Base) {
7507       assert(!Base->getType()->isDependentType() &&
7508              "Cannot generate implicit members for class with dependent bases.");
7509       CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7510       if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7511                                      false, 0))
7512         return false;
7513     }
7514   }
7515 
7516   //       -- for all the nonstatic data members of X that are of a class
7517   //          type M (or array thereof), each such class type has a copy
7518   //          assignment operator whose parameter is of type const M&,
7519   //          const volatile M& or M.
7520   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7521                                   FieldEnd = ClassDecl->field_end();
7522        Field != FieldEnd; ++Field) {
7523     QualType FieldType = S.Context.getBaseElementType(Field->getType());
7524     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl())
7525       if (!S.LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const,
7526                                      false, 0))
7527         return false;
7528   }
7529 
7530   //   Otherwise, the implicitly declared copy assignment operator will
7531   //   have the form
7532   //
7533   //       X& X::operator=(X&)
7534 
7535   return true;
7536 }
7537 
7538 Sema::ImplicitExceptionSpecification
7539 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
7540   CXXRecordDecl *ClassDecl = MD->getParent();
7541 
7542   ImplicitExceptionSpecification ExceptSpec(*this);
7543   if (ClassDecl->isInvalidDecl())
7544     return ExceptSpec;
7545 
7546   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
7547   assert(T->getNumArgs() == 1 && "not a copy assignment op");
7548   unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
7549 
7550   // C++ [except.spec]p14:
7551   //   An implicitly declared special member function (Clause 12) shall have an
7552   //   exception-specification. [...]
7553 
7554   // It is unspecified whether or not an implicit copy assignment operator
7555   // attempts to deduplicate calls to assignment operators of virtual bases are
7556   // made. As such, this exception specification is effectively unspecified.
7557   // Based on a similar decision made for constness in C++0x, we're erring on
7558   // the side of assuming such calls to be made regardless of whether they
7559   // actually happen.
7560   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7561                                        BaseEnd = ClassDecl->bases_end();
7562        Base != BaseEnd; ++Base) {
7563     if (Base->isVirtual())
7564       continue;
7565 
7566     CXXRecordDecl *BaseClassDecl
7567       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7568     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7569                                                             ArgQuals, false, 0))
7570       ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
7571   }
7572 
7573   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7574                                        BaseEnd = ClassDecl->vbases_end();
7575        Base != BaseEnd; ++Base) {
7576     CXXRecordDecl *BaseClassDecl
7577       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7578     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7579                                                             ArgQuals, false, 0))
7580       ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
7581   }
7582 
7583   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7584                                   FieldEnd = ClassDecl->field_end();
7585        Field != FieldEnd;
7586        ++Field) {
7587     QualType FieldType = Context.getBaseElementType(Field->getType());
7588     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7589       if (CXXMethodDecl *CopyAssign =
7590           LookupCopyingAssignment(FieldClassDecl,
7591                                   ArgQuals | FieldType.getCVRQualifiers(),
7592                                   false, 0))
7593         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
7594     }
7595   }
7596 
7597   return ExceptSpec;
7598 }
7599 
7600 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7601   // Note: The following rules are largely analoguous to the copy
7602   // constructor rules. Note that virtual bases are not taken into account
7603   // for determining the argument type of the operator. Note also that
7604   // operators taking an object instead of a reference are allowed.
7605 
7606   QualType ArgType = Context.getTypeDeclType(ClassDecl);
7607   QualType RetType = Context.getLValueReferenceType(ArgType);
7608   if (isImplicitCopyAssignmentArgConst(*this, ClassDecl))
7609     ArgType = ArgType.withConst();
7610   ArgType = Context.getLValueReferenceType(ArgType);
7611 
7612   //   An implicitly-declared copy assignment operator is an inline public
7613   //   member of its class.
7614   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7615   SourceLocation ClassLoc = ClassDecl->getLocation();
7616   DeclarationNameInfo NameInfo(Name, ClassLoc);
7617   CXXMethodDecl *CopyAssignment
7618     = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
7619                             /*TInfo=*/0, /*isStatic=*/false,
7620                             /*StorageClassAsWritten=*/SC_None,
7621                             /*isInline=*/true, /*isConstexpr=*/false,
7622                             SourceLocation());
7623   CopyAssignment->setAccess(AS_public);
7624   CopyAssignment->setDefaulted();
7625   CopyAssignment->setImplicit();
7626   CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
7627 
7628   // Build an exception specification pointing back at this member.
7629   FunctionProtoType::ExtProtoInfo EPI;
7630   EPI.ExceptionSpecType = EST_Unevaluated;
7631   EPI.ExceptionSpecDecl = CopyAssignment;
7632   CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
7633 
7634   // Add the parameter to the operator.
7635   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
7636                                                ClassLoc, ClassLoc, /*Id=*/0,
7637                                                ArgType, /*TInfo=*/0,
7638                                                SC_None,
7639                                                SC_None, 0);
7640   CopyAssignment->setParams(FromParam);
7641 
7642   // Note that we have added this copy-assignment operator.
7643   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
7644 
7645   if (Scope *S = getScopeForContext(ClassDecl))
7646     PushOnScopeChains(CopyAssignment, S, false);
7647   ClassDecl->addDecl(CopyAssignment);
7648 
7649   // C++0x [class.copy]p19:
7650   //   ....  If the class definition does not explicitly declare a copy
7651   //   assignment operator, there is no user-declared move constructor, and
7652   //   there is no user-declared move assignment operator, a copy assignment
7653   //   operator is implicitly declared as defaulted.
7654   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
7655     CopyAssignment->setDeletedAsWritten();
7656 
7657   AddOverriddenMethods(ClassDecl, CopyAssignment);
7658   return CopyAssignment;
7659 }
7660 
7661 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7662                                         CXXMethodDecl *CopyAssignOperator) {
7663   assert((CopyAssignOperator->isDefaulted() &&
7664           CopyAssignOperator->isOverloadedOperator() &&
7665           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
7666           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7667           !CopyAssignOperator->isDeleted()) &&
7668          "DefineImplicitCopyAssignment called for wrong function");
7669 
7670   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7671 
7672   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7673     CopyAssignOperator->setInvalidDecl();
7674     return;
7675   }
7676 
7677   CopyAssignOperator->setUsed();
7678 
7679   ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
7680   DiagnosticErrorTrap Trap(Diags);
7681 
7682   // C++0x [class.copy]p30:
7683   //   The implicitly-defined or explicitly-defaulted copy assignment operator
7684   //   for a non-union class X performs memberwise copy assignment of its
7685   //   subobjects. The direct base classes of X are assigned first, in the
7686   //   order of their declaration in the base-specifier-list, and then the
7687   //   immediate non-static data members of X are assigned, in the order in
7688   //   which they were declared in the class definition.
7689 
7690   // The statements that form the synthesized function body.
7691   SmallVector<Stmt*, 8> Statements;
7692 
7693   // The parameter for the "other" object, which we are copying from.
7694   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7695   Qualifiers OtherQuals = Other->getType().getQualifiers();
7696   QualType OtherRefType = Other->getType();
7697   if (const LValueReferenceType *OtherRef
7698                                 = OtherRefType->getAs<LValueReferenceType>()) {
7699     OtherRefType = OtherRef->getPointeeType();
7700     OtherQuals = OtherRefType.getQualifiers();
7701   }
7702 
7703   // Our location for everything implicitly-generated.
7704   SourceLocation Loc = CopyAssignOperator->getLocation();
7705 
7706   // Construct a reference to the "other" object. We'll be using this
7707   // throughout the generated ASTs.
7708   Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7709   assert(OtherRef && "Reference to parameter cannot fail!");
7710 
7711   // Construct the "this" pointer. We'll be using this throughout the generated
7712   // ASTs.
7713   Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7714   assert(This && "Reference to this cannot fail!");
7715 
7716   // Assign base classes.
7717   bool Invalid = false;
7718   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7719        E = ClassDecl->bases_end(); Base != E; ++Base) {
7720     // Form the assignment:
7721     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7722     QualType BaseType = Base->getType().getUnqualifiedType();
7723     if (!BaseType->isRecordType()) {
7724       Invalid = true;
7725       continue;
7726     }
7727 
7728     CXXCastPath BasePath;
7729     BasePath.push_back(Base);
7730 
7731     // Construct the "from" expression, which is an implicit cast to the
7732     // appropriately-qualified base type.
7733     Expr *From = OtherRef;
7734     From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7735                              CK_UncheckedDerivedToBase,
7736                              VK_LValue, &BasePath).take();
7737 
7738     // Dereference "this".
7739     ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7740 
7741     // Implicitly cast "this" to the appropriately-qualified base type.
7742     To = ImpCastExprToType(To.take(),
7743                            Context.getCVRQualifiedType(BaseType,
7744                                      CopyAssignOperator->getTypeQualifiers()),
7745                            CK_UncheckedDerivedToBase,
7746                            VK_LValue, &BasePath);
7747 
7748     // Build the copy.
7749     StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
7750                                             To.get(), From,
7751                                             /*CopyingBaseSubobject=*/true,
7752                                             /*Copying=*/true);
7753     if (Copy.isInvalid()) {
7754       Diag(CurrentLocation, diag::note_member_synthesized_at)
7755         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7756       CopyAssignOperator->setInvalidDecl();
7757       return;
7758     }
7759 
7760     // Success! Record the copy.
7761     Statements.push_back(Copy.takeAs<Expr>());
7762   }
7763 
7764   // \brief Reference to the __builtin_memcpy function.
7765   Expr *BuiltinMemCpyRef = 0;
7766   // \brief Reference to the __builtin_objc_memmove_collectable function.
7767   Expr *CollectableMemCpyRef = 0;
7768 
7769   // Assign non-static members.
7770   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7771                                   FieldEnd = ClassDecl->field_end();
7772        Field != FieldEnd; ++Field) {
7773     if (Field->isUnnamedBitfield())
7774       continue;
7775 
7776     // Check for members of reference type; we can't copy those.
7777     if (Field->getType()->isReferenceType()) {
7778       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7779         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7780       Diag(Field->getLocation(), diag::note_declared_at);
7781       Diag(CurrentLocation, diag::note_member_synthesized_at)
7782         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7783       Invalid = true;
7784       continue;
7785     }
7786 
7787     // Check for members of const-qualified, non-class type.
7788     QualType BaseType = Context.getBaseElementType(Field->getType());
7789     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7790       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7791         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7792       Diag(Field->getLocation(), diag::note_declared_at);
7793       Diag(CurrentLocation, diag::note_member_synthesized_at)
7794         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7795       Invalid = true;
7796       continue;
7797     }
7798 
7799     // Suppress assigning zero-width bitfields.
7800     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7801       continue;
7802 
7803     QualType FieldType = Field->getType().getNonReferenceType();
7804     if (FieldType->isIncompleteArrayType()) {
7805       assert(ClassDecl->hasFlexibleArrayMember() &&
7806              "Incomplete array type is not valid");
7807       continue;
7808     }
7809 
7810     // Build references to the field in the object we're copying from and to.
7811     CXXScopeSpec SS; // Intentionally empty
7812     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7813                               LookupMemberName);
7814     MemberLookup.addDecl(*Field);
7815     MemberLookup.resolveKind();
7816     ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7817                                                Loc, /*IsArrow=*/false,
7818                                                SS, SourceLocation(), 0,
7819                                                MemberLookup, 0);
7820     ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7821                                              Loc, /*IsArrow=*/true,
7822                                              SS, SourceLocation(), 0,
7823                                              MemberLookup, 0);
7824     assert(!From.isInvalid() && "Implicit field reference cannot fail");
7825     assert(!To.isInvalid() && "Implicit field reference cannot fail");
7826 
7827     // If the field should be copied with __builtin_memcpy rather than via
7828     // explicit assignments, do so. This optimization only applies for arrays
7829     // of scalars and arrays of class type with trivial copy-assignment
7830     // operators.
7831     if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7832         && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
7833       // Compute the size of the memory buffer to be copied.
7834       QualType SizeType = Context.getSizeType();
7835       llvm::APInt Size(Context.getTypeSize(SizeType),
7836                        Context.getTypeSizeInChars(BaseType).getQuantity());
7837       for (const ConstantArrayType *Array
7838               = Context.getAsConstantArrayType(FieldType);
7839            Array;
7840            Array = Context.getAsConstantArrayType(Array->getElementType())) {
7841         llvm::APInt ArraySize
7842           = Array->getSize().zextOrTrunc(Size.getBitWidth());
7843         Size *= ArraySize;
7844       }
7845 
7846       // Take the address of the field references for "from" and "to".
7847       From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7848       To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
7849 
7850       bool NeedsCollectableMemCpy =
7851           (BaseType->isRecordType() &&
7852            BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7853 
7854       if (NeedsCollectableMemCpy) {
7855         if (!CollectableMemCpyRef) {
7856           // Create a reference to the __builtin_objc_memmove_collectable function.
7857           LookupResult R(*this,
7858                          &Context.Idents.get("__builtin_objc_memmove_collectable"),
7859                          Loc, LookupOrdinaryName);
7860           LookupName(R, TUScope, true);
7861 
7862           FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7863           if (!CollectableMemCpy) {
7864             // Something went horribly wrong earlier, and we will have
7865             // complained about it.
7866             Invalid = true;
7867             continue;
7868           }
7869 
7870           CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7871                                                   Context.BuiltinFnTy,
7872                                                   VK_RValue, Loc, 0).take();
7873           assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7874         }
7875       }
7876       // Create a reference to the __builtin_memcpy builtin function.
7877       else if (!BuiltinMemCpyRef) {
7878         LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7879                        LookupOrdinaryName);
7880         LookupName(R, TUScope, true);
7881 
7882         FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7883         if (!BuiltinMemCpy) {
7884           // Something went horribly wrong earlier, and we will have complained
7885           // about it.
7886           Invalid = true;
7887           continue;
7888         }
7889 
7890         BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7891                                             Context.BuiltinFnTy,
7892                                             VK_RValue, Loc, 0).take();
7893         assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7894       }
7895 
7896       SmallVector<Expr*, 8> CallArgs;
7897       CallArgs.push_back(To.takeAs<Expr>());
7898       CallArgs.push_back(From.takeAs<Expr>());
7899       CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
7900       ExprResult Call = ExprError();
7901       if (NeedsCollectableMemCpy)
7902         Call = ActOnCallExpr(/*Scope=*/0,
7903                              CollectableMemCpyRef,
7904                              Loc, CallArgs,
7905                              Loc);
7906       else
7907         Call = ActOnCallExpr(/*Scope=*/0,
7908                              BuiltinMemCpyRef,
7909                              Loc, CallArgs,
7910                              Loc);
7911 
7912       assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7913       Statements.push_back(Call.takeAs<Expr>());
7914       continue;
7915     }
7916 
7917     // Build the copy of this field.
7918     StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
7919                                             To.get(), From.get(),
7920                                             /*CopyingBaseSubobject=*/false,
7921                                             /*Copying=*/true);
7922     if (Copy.isInvalid()) {
7923       Diag(CurrentLocation, diag::note_member_synthesized_at)
7924         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7925       CopyAssignOperator->setInvalidDecl();
7926       return;
7927     }
7928 
7929     // Success! Record the copy.
7930     Statements.push_back(Copy.takeAs<Stmt>());
7931   }
7932 
7933   if (!Invalid) {
7934     // Add a "return *this;"
7935     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7936 
7937     StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
7938     if (Return.isInvalid())
7939       Invalid = true;
7940     else {
7941       Statements.push_back(Return.takeAs<Stmt>());
7942 
7943       if (Trap.hasErrorOccurred()) {
7944         Diag(CurrentLocation, diag::note_member_synthesized_at)
7945           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7946         Invalid = true;
7947       }
7948     }
7949   }
7950 
7951   if (Invalid) {
7952     CopyAssignOperator->setInvalidDecl();
7953     return;
7954   }
7955 
7956   StmtResult Body;
7957   {
7958     CompoundScopeRAII CompoundScope(*this);
7959     Body = ActOnCompoundStmt(Loc, Loc, Statements,
7960                              /*isStmtExpr=*/false);
7961     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7962   }
7963   CopyAssignOperator->setBody(Body.takeAs<Stmt>());
7964 
7965   if (ASTMutationListener *L = getASTMutationListener()) {
7966     L->CompletedImplicitDefinition(CopyAssignOperator);
7967   }
7968 }
7969 
7970 Sema::ImplicitExceptionSpecification
7971 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
7972   CXXRecordDecl *ClassDecl = MD->getParent();
7973 
7974   ImplicitExceptionSpecification ExceptSpec(*this);
7975   if (ClassDecl->isInvalidDecl())
7976     return ExceptSpec;
7977 
7978   // C++0x [except.spec]p14:
7979   //   An implicitly declared special member function (Clause 12) shall have an
7980   //   exception-specification. [...]
7981 
7982   // It is unspecified whether or not an implicit move assignment operator
7983   // attempts to deduplicate calls to assignment operators of virtual bases are
7984   // made. As such, this exception specification is effectively unspecified.
7985   // Based on a similar decision made for constness in C++0x, we're erring on
7986   // the side of assuming such calls to be made regardless of whether they
7987   // actually happen.
7988   // Note that a move constructor is not implicitly declared when there are
7989   // virtual bases, but it can still be user-declared and explicitly defaulted.
7990   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7991                                        BaseEnd = ClassDecl->bases_end();
7992        Base != BaseEnd; ++Base) {
7993     if (Base->isVirtual())
7994       continue;
7995 
7996     CXXRecordDecl *BaseClassDecl
7997       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7998     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7999                                                            0, false, 0))
8000       ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8001   }
8002 
8003   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8004                                        BaseEnd = ClassDecl->vbases_end();
8005        Base != BaseEnd; ++Base) {
8006     CXXRecordDecl *BaseClassDecl
8007       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8008     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8009                                                            0, false, 0))
8010       ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8011   }
8012 
8013   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8014                                   FieldEnd = ClassDecl->field_end();
8015        Field != FieldEnd;
8016        ++Field) {
8017     QualType FieldType = Context.getBaseElementType(Field->getType());
8018     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8019       if (CXXMethodDecl *MoveAssign =
8020               LookupMovingAssignment(FieldClassDecl,
8021                                      FieldType.getCVRQualifiers(),
8022                                      false, 0))
8023         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
8024     }
8025   }
8026 
8027   return ExceptSpec;
8028 }
8029 
8030 /// Determine whether the class type has any direct or indirect virtual base
8031 /// classes which have a non-trivial move assignment operator.
8032 static bool
8033 hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8034   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8035                                           BaseEnd = ClassDecl->vbases_end();
8036        Base != BaseEnd; ++Base) {
8037     CXXRecordDecl *BaseClass =
8038         cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8039 
8040     // Try to declare the move assignment. If it would be deleted, then the
8041     // class does not have a non-trivial move assignment.
8042     if (BaseClass->needsImplicitMoveAssignment())
8043       S.DeclareImplicitMoveAssignment(BaseClass);
8044 
8045     // If the class has both a trivial move assignment and a non-trivial move
8046     // assignment, hasTrivialMoveAssignment() is false.
8047     if (BaseClass->hasDeclaredMoveAssignment() &&
8048         !BaseClass->hasTrivialMoveAssignment())
8049       return true;
8050   }
8051 
8052   return false;
8053 }
8054 
8055 /// Determine whether the given type either has a move constructor or is
8056 /// trivially copyable.
8057 static bool
8058 hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8059   Type = S.Context.getBaseElementType(Type);
8060 
8061   // FIXME: Technically, non-trivially-copyable non-class types, such as
8062   // reference types, are supposed to return false here, but that appears
8063   // to be a standard defect.
8064   CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
8065   if (!ClassDecl || !ClassDecl->getDefinition())
8066     return true;
8067 
8068   if (Type.isTriviallyCopyableType(S.Context))
8069     return true;
8070 
8071   if (IsConstructor) {
8072     if (ClassDecl->needsImplicitMoveConstructor())
8073       S.DeclareImplicitMoveConstructor(ClassDecl);
8074     return ClassDecl->hasDeclaredMoveConstructor();
8075   }
8076 
8077   if (ClassDecl->needsImplicitMoveAssignment())
8078     S.DeclareImplicitMoveAssignment(ClassDecl);
8079   return ClassDecl->hasDeclaredMoveAssignment();
8080 }
8081 
8082 /// Determine whether all non-static data members and direct or virtual bases
8083 /// of class \p ClassDecl have either a move operation, or are trivially
8084 /// copyable.
8085 static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8086                                             bool IsConstructor) {
8087   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8088                                           BaseEnd = ClassDecl->bases_end();
8089        Base != BaseEnd; ++Base) {
8090     if (Base->isVirtual())
8091       continue;
8092 
8093     if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8094       return false;
8095   }
8096 
8097   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8098                                           BaseEnd = ClassDecl->vbases_end();
8099        Base != BaseEnd; ++Base) {
8100     if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8101       return false;
8102   }
8103 
8104   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8105                                      FieldEnd = ClassDecl->field_end();
8106        Field != FieldEnd; ++Field) {
8107     if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
8108       return false;
8109   }
8110 
8111   return true;
8112 }
8113 
8114 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8115   // C++11 [class.copy]p20:
8116   //   If the definition of a class X does not explicitly declare a move
8117   //   assignment operator, one will be implicitly declared as defaulted
8118   //   if and only if:
8119   //
8120   //   - [first 4 bullets]
8121   assert(ClassDecl->needsImplicitMoveAssignment());
8122 
8123   // [Checked after we build the declaration]
8124   //   - the move assignment operator would not be implicitly defined as
8125   //     deleted,
8126 
8127   // [DR1402]:
8128   //   - X has no direct or indirect virtual base class with a non-trivial
8129   //     move assignment operator, and
8130   //   - each of X's non-static data members and direct or virtual base classes
8131   //     has a type that either has a move assignment operator or is trivially
8132   //     copyable.
8133   if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8134       !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8135     ClassDecl->setFailedImplicitMoveAssignment();
8136     return 0;
8137   }
8138 
8139   // Note: The following rules are largely analoguous to the move
8140   // constructor rules.
8141 
8142   QualType ArgType = Context.getTypeDeclType(ClassDecl);
8143   QualType RetType = Context.getLValueReferenceType(ArgType);
8144   ArgType = Context.getRValueReferenceType(ArgType);
8145 
8146   //   An implicitly-declared move assignment operator is an inline public
8147   //   member of its class.
8148   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8149   SourceLocation ClassLoc = ClassDecl->getLocation();
8150   DeclarationNameInfo NameInfo(Name, ClassLoc);
8151   CXXMethodDecl *MoveAssignment
8152     = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8153                             /*TInfo=*/0, /*isStatic=*/false,
8154                             /*StorageClassAsWritten=*/SC_None,
8155                             /*isInline=*/true,
8156                             /*isConstexpr=*/false,
8157                             SourceLocation());
8158   MoveAssignment->setAccess(AS_public);
8159   MoveAssignment->setDefaulted();
8160   MoveAssignment->setImplicit();
8161   MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8162 
8163   // Build an exception specification pointing back at this member.
8164   FunctionProtoType::ExtProtoInfo EPI;
8165   EPI.ExceptionSpecType = EST_Unevaluated;
8166   EPI.ExceptionSpecDecl = MoveAssignment;
8167   MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8168 
8169   // Add the parameter to the operator.
8170   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8171                                                ClassLoc, ClassLoc, /*Id=*/0,
8172                                                ArgType, /*TInfo=*/0,
8173                                                SC_None,
8174                                                SC_None, 0);
8175   MoveAssignment->setParams(FromParam);
8176 
8177   // Note that we have added this copy-assignment operator.
8178   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8179 
8180   // C++0x [class.copy]p9:
8181   //   If the definition of a class X does not explicitly declare a move
8182   //   assignment operator, one will be implicitly declared as defaulted if and
8183   //   only if:
8184   //   [...]
8185   //   - the move assignment operator would not be implicitly defined as
8186   //     deleted.
8187   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
8188     // Cache this result so that we don't try to generate this over and over
8189     // on every lookup, leaking memory and wasting time.
8190     ClassDecl->setFailedImplicitMoveAssignment();
8191     return 0;
8192   }
8193 
8194   if (Scope *S = getScopeForContext(ClassDecl))
8195     PushOnScopeChains(MoveAssignment, S, false);
8196   ClassDecl->addDecl(MoveAssignment);
8197 
8198   AddOverriddenMethods(ClassDecl, MoveAssignment);
8199   return MoveAssignment;
8200 }
8201 
8202 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8203                                         CXXMethodDecl *MoveAssignOperator) {
8204   assert((MoveAssignOperator->isDefaulted() &&
8205           MoveAssignOperator->isOverloadedOperator() &&
8206           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8207           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8208           !MoveAssignOperator->isDeleted()) &&
8209          "DefineImplicitMoveAssignment called for wrong function");
8210 
8211   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8212 
8213   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8214     MoveAssignOperator->setInvalidDecl();
8215     return;
8216   }
8217 
8218   MoveAssignOperator->setUsed();
8219 
8220   ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8221   DiagnosticErrorTrap Trap(Diags);
8222 
8223   // C++0x [class.copy]p28:
8224   //   The implicitly-defined or move assignment operator for a non-union class
8225   //   X performs memberwise move assignment of its subobjects. The direct base
8226   //   classes of X are assigned first, in the order of their declaration in the
8227   //   base-specifier-list, and then the immediate non-static data members of X
8228   //   are assigned, in the order in which they were declared in the class
8229   //   definition.
8230 
8231   // The statements that form the synthesized function body.
8232   SmallVector<Stmt*, 8> Statements;
8233 
8234   // The parameter for the "other" object, which we are move from.
8235   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8236   QualType OtherRefType = Other->getType()->
8237       getAs<RValueReferenceType>()->getPointeeType();
8238   assert(OtherRefType.getQualifiers() == 0 &&
8239          "Bad argument type of defaulted move assignment");
8240 
8241   // Our location for everything implicitly-generated.
8242   SourceLocation Loc = MoveAssignOperator->getLocation();
8243 
8244   // Construct a reference to the "other" object. We'll be using this
8245   // throughout the generated ASTs.
8246   Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8247   assert(OtherRef && "Reference to parameter cannot fail!");
8248   // Cast to rvalue.
8249   OtherRef = CastForMoving(*this, OtherRef);
8250 
8251   // Construct the "this" pointer. We'll be using this throughout the generated
8252   // ASTs.
8253   Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8254   assert(This && "Reference to this cannot fail!");
8255 
8256   // Assign base classes.
8257   bool Invalid = false;
8258   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8259        E = ClassDecl->bases_end(); Base != E; ++Base) {
8260     // Form the assignment:
8261     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8262     QualType BaseType = Base->getType().getUnqualifiedType();
8263     if (!BaseType->isRecordType()) {
8264       Invalid = true;
8265       continue;
8266     }
8267 
8268     CXXCastPath BasePath;
8269     BasePath.push_back(Base);
8270 
8271     // Construct the "from" expression, which is an implicit cast to the
8272     // appropriately-qualified base type.
8273     Expr *From = OtherRef;
8274     From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
8275                              VK_XValue, &BasePath).take();
8276 
8277     // Dereference "this".
8278     ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8279 
8280     // Implicitly cast "this" to the appropriately-qualified base type.
8281     To = ImpCastExprToType(To.take(),
8282                            Context.getCVRQualifiedType(BaseType,
8283                                      MoveAssignOperator->getTypeQualifiers()),
8284                            CK_UncheckedDerivedToBase,
8285                            VK_LValue, &BasePath);
8286 
8287     // Build the move.
8288     StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8289                                             To.get(), From,
8290                                             /*CopyingBaseSubobject=*/true,
8291                                             /*Copying=*/false);
8292     if (Move.isInvalid()) {
8293       Diag(CurrentLocation, diag::note_member_synthesized_at)
8294         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8295       MoveAssignOperator->setInvalidDecl();
8296       return;
8297     }
8298 
8299     // Success! Record the move.
8300     Statements.push_back(Move.takeAs<Expr>());
8301   }
8302 
8303   // \brief Reference to the __builtin_memcpy function.
8304   Expr *BuiltinMemCpyRef = 0;
8305   // \brief Reference to the __builtin_objc_memmove_collectable function.
8306   Expr *CollectableMemCpyRef = 0;
8307 
8308   // Assign non-static members.
8309   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8310                                   FieldEnd = ClassDecl->field_end();
8311        Field != FieldEnd; ++Field) {
8312     if (Field->isUnnamedBitfield())
8313       continue;
8314 
8315     // Check for members of reference type; we can't move those.
8316     if (Field->getType()->isReferenceType()) {
8317       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8318         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8319       Diag(Field->getLocation(), diag::note_declared_at);
8320       Diag(CurrentLocation, diag::note_member_synthesized_at)
8321         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8322       Invalid = true;
8323       continue;
8324     }
8325 
8326     // Check for members of const-qualified, non-class type.
8327     QualType BaseType = Context.getBaseElementType(Field->getType());
8328     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8329       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8330         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8331       Diag(Field->getLocation(), diag::note_declared_at);
8332       Diag(CurrentLocation, diag::note_member_synthesized_at)
8333         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8334       Invalid = true;
8335       continue;
8336     }
8337 
8338     // Suppress assigning zero-width bitfields.
8339     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8340       continue;
8341 
8342     QualType FieldType = Field->getType().getNonReferenceType();
8343     if (FieldType->isIncompleteArrayType()) {
8344       assert(ClassDecl->hasFlexibleArrayMember() &&
8345              "Incomplete array type is not valid");
8346       continue;
8347     }
8348 
8349     // Build references to the field in the object we're copying from and to.
8350     CXXScopeSpec SS; // Intentionally empty
8351     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8352                               LookupMemberName);
8353     MemberLookup.addDecl(*Field);
8354     MemberLookup.resolveKind();
8355     ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8356                                                Loc, /*IsArrow=*/false,
8357                                                SS, SourceLocation(), 0,
8358                                                MemberLookup, 0);
8359     ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8360                                              Loc, /*IsArrow=*/true,
8361                                              SS, SourceLocation(), 0,
8362                                              MemberLookup, 0);
8363     assert(!From.isInvalid() && "Implicit field reference cannot fail");
8364     assert(!To.isInvalid() && "Implicit field reference cannot fail");
8365 
8366     assert(!From.get()->isLValue() && // could be xvalue or prvalue
8367         "Member reference with rvalue base must be rvalue except for reference "
8368         "members, which aren't allowed for move assignment.");
8369 
8370     // If the field should be copied with __builtin_memcpy rather than via
8371     // explicit assignments, do so. This optimization only applies for arrays
8372     // of scalars and arrays of class type with trivial move-assignment
8373     // operators.
8374     if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8375         && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8376       // Compute the size of the memory buffer to be copied.
8377       QualType SizeType = Context.getSizeType();
8378       llvm::APInt Size(Context.getTypeSize(SizeType),
8379                        Context.getTypeSizeInChars(BaseType).getQuantity());
8380       for (const ConstantArrayType *Array
8381               = Context.getAsConstantArrayType(FieldType);
8382            Array;
8383            Array = Context.getAsConstantArrayType(Array->getElementType())) {
8384         llvm::APInt ArraySize
8385           = Array->getSize().zextOrTrunc(Size.getBitWidth());
8386         Size *= ArraySize;
8387       }
8388 
8389       // Take the address of the field references for "from" and "to". We
8390       // directly construct UnaryOperators here because semantic analysis
8391       // does not permit us to take the address of an xvalue.
8392       From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8393                              Context.getPointerType(From.get()->getType()),
8394                              VK_RValue, OK_Ordinary, Loc);
8395       To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8396                            Context.getPointerType(To.get()->getType()),
8397                            VK_RValue, OK_Ordinary, Loc);
8398 
8399       bool NeedsCollectableMemCpy =
8400           (BaseType->isRecordType() &&
8401            BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8402 
8403       if (NeedsCollectableMemCpy) {
8404         if (!CollectableMemCpyRef) {
8405           // Create a reference to the __builtin_objc_memmove_collectable function.
8406           LookupResult R(*this,
8407                          &Context.Idents.get("__builtin_objc_memmove_collectable"),
8408                          Loc, LookupOrdinaryName);
8409           LookupName(R, TUScope, true);
8410 
8411           FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8412           if (!CollectableMemCpy) {
8413             // Something went horribly wrong earlier, and we will have
8414             // complained about it.
8415             Invalid = true;
8416             continue;
8417           }
8418 
8419           CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8420                                                   Context.BuiltinFnTy,
8421                                                   VK_RValue, Loc, 0).take();
8422           assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8423         }
8424       }
8425       // Create a reference to the __builtin_memcpy builtin function.
8426       else if (!BuiltinMemCpyRef) {
8427         LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8428                        LookupOrdinaryName);
8429         LookupName(R, TUScope, true);
8430 
8431         FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8432         if (!BuiltinMemCpy) {
8433           // Something went horribly wrong earlier, and we will have complained
8434           // about it.
8435           Invalid = true;
8436           continue;
8437         }
8438 
8439         BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8440                                             Context.BuiltinFnTy,
8441                                             VK_RValue, Loc, 0).take();
8442         assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8443       }
8444 
8445       SmallVector<Expr*, 8> CallArgs;
8446       CallArgs.push_back(To.takeAs<Expr>());
8447       CallArgs.push_back(From.takeAs<Expr>());
8448       CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8449       ExprResult Call = ExprError();
8450       if (NeedsCollectableMemCpy)
8451         Call = ActOnCallExpr(/*Scope=*/0,
8452                              CollectableMemCpyRef,
8453                              Loc, CallArgs,
8454                              Loc);
8455       else
8456         Call = ActOnCallExpr(/*Scope=*/0,
8457                              BuiltinMemCpyRef,
8458                              Loc, CallArgs,
8459                              Loc);
8460 
8461       assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8462       Statements.push_back(Call.takeAs<Expr>());
8463       continue;
8464     }
8465 
8466     // Build the move of this field.
8467     StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8468                                             To.get(), From.get(),
8469                                             /*CopyingBaseSubobject=*/false,
8470                                             /*Copying=*/false);
8471     if (Move.isInvalid()) {
8472       Diag(CurrentLocation, diag::note_member_synthesized_at)
8473         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8474       MoveAssignOperator->setInvalidDecl();
8475       return;
8476     }
8477 
8478     // Success! Record the copy.
8479     Statements.push_back(Move.takeAs<Stmt>());
8480   }
8481 
8482   if (!Invalid) {
8483     // Add a "return *this;"
8484     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8485 
8486     StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8487     if (Return.isInvalid())
8488       Invalid = true;
8489     else {
8490       Statements.push_back(Return.takeAs<Stmt>());
8491 
8492       if (Trap.hasErrorOccurred()) {
8493         Diag(CurrentLocation, diag::note_member_synthesized_at)
8494           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8495         Invalid = true;
8496       }
8497     }
8498   }
8499 
8500   if (Invalid) {
8501     MoveAssignOperator->setInvalidDecl();
8502     return;
8503   }
8504 
8505   StmtResult Body;
8506   {
8507     CompoundScopeRAII CompoundScope(*this);
8508     Body = ActOnCompoundStmt(Loc, Loc, Statements,
8509                              /*isStmtExpr=*/false);
8510     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8511   }
8512   MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8513 
8514   if (ASTMutationListener *L = getASTMutationListener()) {
8515     L->CompletedImplicitDefinition(MoveAssignOperator);
8516   }
8517 }
8518 
8519 /// Determine whether an implicit copy constructor for ClassDecl has a const
8520 /// argument.
8521 /// FIXME: It ought to be possible to store this on the record.
8522 static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl) {
8523   if (ClassDecl->isInvalidDecl())
8524     return true;
8525 
8526   // C++ [class.copy]p5:
8527   //   The implicitly-declared copy constructor for a class X will
8528   //   have the form
8529   //
8530   //       X::X(const X&)
8531   //
8532   //   if
8533   //     -- each direct or virtual base class B of X has a copy
8534   //        constructor whose first parameter is of type const B& or
8535   //        const volatile B&, and
8536   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8537                                        BaseEnd = ClassDecl->bases_end();
8538        Base != BaseEnd; ++Base) {
8539     // Virtual bases are handled below.
8540     if (Base->isVirtual())
8541       continue;
8542 
8543     CXXRecordDecl *BaseClassDecl
8544       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8545     // FIXME: This lookup is wrong. If the copy ctor for a member or base is
8546     // ambiguous, we should still produce a constructor with a const-qualified
8547     // parameter.
8548     if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8549       return false;
8550   }
8551 
8552   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8553                                        BaseEnd = ClassDecl->vbases_end();
8554        Base != BaseEnd; ++Base) {
8555     CXXRecordDecl *BaseClassDecl
8556       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8557     if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8558       return false;
8559   }
8560 
8561   //     -- for all the nonstatic data members of X that are of a
8562   //        class type M (or array thereof), each such class type
8563   //        has a copy constructor whose first parameter is of type
8564   //        const M& or const volatile M&.
8565   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8566                                   FieldEnd = ClassDecl->field_end();
8567        Field != FieldEnd; ++Field) {
8568     QualType FieldType = S.Context.getBaseElementType(Field->getType());
8569     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8570       if (!S.LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const))
8571         return false;
8572     }
8573   }
8574 
8575   //   Otherwise, the implicitly declared copy constructor will have
8576   //   the form
8577   //
8578   //       X::X(X&)
8579 
8580   return true;
8581 }
8582 
8583 Sema::ImplicitExceptionSpecification
8584 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
8585   CXXRecordDecl *ClassDecl = MD->getParent();
8586 
8587   ImplicitExceptionSpecification ExceptSpec(*this);
8588   if (ClassDecl->isInvalidDecl())
8589     return ExceptSpec;
8590 
8591   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8592   assert(T->getNumArgs() >= 1 && "not a copy ctor");
8593   unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8594 
8595   // C++ [except.spec]p14:
8596   //   An implicitly declared special member function (Clause 12) shall have an
8597   //   exception-specification. [...]
8598   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8599                                        BaseEnd = ClassDecl->bases_end();
8600        Base != BaseEnd;
8601        ++Base) {
8602     // Virtual bases are handled below.
8603     if (Base->isVirtual())
8604       continue;
8605 
8606     CXXRecordDecl *BaseClassDecl
8607       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8608     if (CXXConstructorDecl *CopyConstructor =
8609           LookupCopyingConstructor(BaseClassDecl, Quals))
8610       ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
8611   }
8612   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8613                                        BaseEnd = ClassDecl->vbases_end();
8614        Base != BaseEnd;
8615        ++Base) {
8616     CXXRecordDecl *BaseClassDecl
8617       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8618     if (CXXConstructorDecl *CopyConstructor =
8619           LookupCopyingConstructor(BaseClassDecl, Quals))
8620       ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
8621   }
8622   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8623                                   FieldEnd = ClassDecl->field_end();
8624        Field != FieldEnd;
8625        ++Field) {
8626     QualType FieldType = Context.getBaseElementType(Field->getType());
8627     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8628       if (CXXConstructorDecl *CopyConstructor =
8629               LookupCopyingConstructor(FieldClassDecl,
8630                                        Quals | FieldType.getCVRQualifiers()))
8631       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
8632     }
8633   }
8634 
8635   return ExceptSpec;
8636 }
8637 
8638 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8639                                                     CXXRecordDecl *ClassDecl) {
8640   // C++ [class.copy]p4:
8641   //   If the class definition does not explicitly declare a copy
8642   //   constructor, one is declared implicitly.
8643 
8644   QualType ClassType = Context.getTypeDeclType(ClassDecl);
8645   QualType ArgType = ClassType;
8646   bool Const = isImplicitCopyCtorArgConst(*this, ClassDecl);
8647   if (Const)
8648     ArgType = ArgType.withConst();
8649   ArgType = Context.getLValueReferenceType(ArgType);
8650 
8651   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8652                                                      CXXCopyConstructor,
8653                                                      Const);
8654 
8655   DeclarationName Name
8656     = Context.DeclarationNames.getCXXConstructorName(
8657                                            Context.getCanonicalType(ClassType));
8658   SourceLocation ClassLoc = ClassDecl->getLocation();
8659   DeclarationNameInfo NameInfo(Name, ClassLoc);
8660 
8661   //   An implicitly-declared copy constructor is an inline public
8662   //   member of its class.
8663   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8664       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
8665       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8666       Constexpr);
8667   CopyConstructor->setAccess(AS_public);
8668   CopyConstructor->setDefaulted();
8669   CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8670 
8671   // Build an exception specification pointing back at this member.
8672   FunctionProtoType::ExtProtoInfo EPI;
8673   EPI.ExceptionSpecType = EST_Unevaluated;
8674   EPI.ExceptionSpecDecl = CopyConstructor;
8675   CopyConstructor->setType(
8676       Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8677 
8678   // Note that we have declared this constructor.
8679   ++ASTContext::NumImplicitCopyConstructorsDeclared;
8680 
8681   // Add the parameter to the constructor.
8682   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
8683                                                ClassLoc, ClassLoc,
8684                                                /*IdentifierInfo=*/0,
8685                                                ArgType, /*TInfo=*/0,
8686                                                SC_None,
8687                                                SC_None, 0);
8688   CopyConstructor->setParams(FromParam);
8689 
8690   if (Scope *S = getScopeForContext(ClassDecl))
8691     PushOnScopeChains(CopyConstructor, S, false);
8692   ClassDecl->addDecl(CopyConstructor);
8693 
8694   // C++11 [class.copy]p8:
8695   //   ... If the class definition does not explicitly declare a copy
8696   //   constructor, there is no user-declared move constructor, and there is no
8697   //   user-declared move assignment operator, a copy constructor is implicitly
8698   //   declared as defaulted.
8699   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
8700     CopyConstructor->setDeletedAsWritten();
8701 
8702   return CopyConstructor;
8703 }
8704 
8705 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
8706                                    CXXConstructorDecl *CopyConstructor) {
8707   assert((CopyConstructor->isDefaulted() &&
8708           CopyConstructor->isCopyConstructor() &&
8709           !CopyConstructor->doesThisDeclarationHaveABody() &&
8710           !CopyConstructor->isDeleted()) &&
8711          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
8712 
8713   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
8714   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
8715 
8716   ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
8717   DiagnosticErrorTrap Trap(Diags);
8718 
8719   if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
8720       Trap.hasErrorOccurred()) {
8721     Diag(CurrentLocation, diag::note_member_synthesized_at)
8722       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
8723     CopyConstructor->setInvalidDecl();
8724   }  else {
8725     Sema::CompoundScopeRAII CompoundScope(*this);
8726     CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8727                                                CopyConstructor->getLocation(),
8728                                                MultiStmtArg(),
8729                                                /*isStmtExpr=*/false)
8730                                                               .takeAs<Stmt>());
8731     CopyConstructor->setImplicitlyDefined(true);
8732   }
8733 
8734   CopyConstructor->setUsed();
8735   if (ASTMutationListener *L = getASTMutationListener()) {
8736     L->CompletedImplicitDefinition(CopyConstructor);
8737   }
8738 }
8739 
8740 Sema::ImplicitExceptionSpecification
8741 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
8742   CXXRecordDecl *ClassDecl = MD->getParent();
8743 
8744   // C++ [except.spec]p14:
8745   //   An implicitly declared special member function (Clause 12) shall have an
8746   //   exception-specification. [...]
8747   ImplicitExceptionSpecification ExceptSpec(*this);
8748   if (ClassDecl->isInvalidDecl())
8749     return ExceptSpec;
8750 
8751   // Direct base-class constructors.
8752   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8753                                        BEnd = ClassDecl->bases_end();
8754        B != BEnd; ++B) {
8755     if (B->isVirtual()) // Handled below.
8756       continue;
8757 
8758     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8759       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8760       CXXConstructorDecl *Constructor =
8761           LookupMovingConstructor(BaseClassDecl, 0);
8762       // If this is a deleted function, add it anyway. This might be conformant
8763       // with the standard. This might not. I'm not sure. It might not matter.
8764       if (Constructor)
8765         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8766     }
8767   }
8768 
8769   // Virtual base-class constructors.
8770   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8771                                        BEnd = ClassDecl->vbases_end();
8772        B != BEnd; ++B) {
8773     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8774       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8775       CXXConstructorDecl *Constructor =
8776           LookupMovingConstructor(BaseClassDecl, 0);
8777       // If this is a deleted function, add it anyway. This might be conformant
8778       // with the standard. This might not. I'm not sure. It might not matter.
8779       if (Constructor)
8780         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8781     }
8782   }
8783 
8784   // Field constructors.
8785   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8786                                FEnd = ClassDecl->field_end();
8787        F != FEnd; ++F) {
8788     QualType FieldType = Context.getBaseElementType(F->getType());
8789     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
8790       CXXConstructorDecl *Constructor =
8791           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
8792       // If this is a deleted function, add it anyway. This might be conformant
8793       // with the standard. This might not. I'm not sure. It might not matter.
8794       // In particular, the problem is that this function never gets called. It
8795       // might just be ill-formed because this function attempts to refer to
8796       // a deleted function here.
8797       if (Constructor)
8798         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8799     }
8800   }
8801 
8802   return ExceptSpec;
8803 }
8804 
8805 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8806                                                     CXXRecordDecl *ClassDecl) {
8807   // C++11 [class.copy]p9:
8808   //   If the definition of a class X does not explicitly declare a move
8809   //   constructor, one will be implicitly declared as defaulted if and only if:
8810   //
8811   //   - [first 4 bullets]
8812   assert(ClassDecl->needsImplicitMoveConstructor());
8813 
8814   // [Checked after we build the declaration]
8815   //   - the move assignment operator would not be implicitly defined as
8816   //     deleted,
8817 
8818   // [DR1402]:
8819   //   - each of X's non-static data members and direct or virtual base classes
8820   //     has a type that either has a move constructor or is trivially copyable.
8821   if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8822     ClassDecl->setFailedImplicitMoveConstructor();
8823     return 0;
8824   }
8825 
8826   QualType ClassType = Context.getTypeDeclType(ClassDecl);
8827   QualType ArgType = Context.getRValueReferenceType(ClassType);
8828 
8829   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8830                                                      CXXMoveConstructor,
8831                                                      false);
8832 
8833   DeclarationName Name
8834     = Context.DeclarationNames.getCXXConstructorName(
8835                                            Context.getCanonicalType(ClassType));
8836   SourceLocation ClassLoc = ClassDecl->getLocation();
8837   DeclarationNameInfo NameInfo(Name, ClassLoc);
8838 
8839   // C++0x [class.copy]p11:
8840   //   An implicitly-declared copy/move constructor is an inline public
8841   //   member of its class.
8842   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8843       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
8844       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8845       Constexpr);
8846   MoveConstructor->setAccess(AS_public);
8847   MoveConstructor->setDefaulted();
8848   MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8849 
8850   // Build an exception specification pointing back at this member.
8851   FunctionProtoType::ExtProtoInfo EPI;
8852   EPI.ExceptionSpecType = EST_Unevaluated;
8853   EPI.ExceptionSpecDecl = MoveConstructor;
8854   MoveConstructor->setType(
8855       Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8856 
8857   // Add the parameter to the constructor.
8858   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8859                                                ClassLoc, ClassLoc,
8860                                                /*IdentifierInfo=*/0,
8861                                                ArgType, /*TInfo=*/0,
8862                                                SC_None,
8863                                                SC_None, 0);
8864   MoveConstructor->setParams(FromParam);
8865 
8866   // C++0x [class.copy]p9:
8867   //   If the definition of a class X does not explicitly declare a move
8868   //   constructor, one will be implicitly declared as defaulted if and only if:
8869   //   [...]
8870   //   - the move constructor would not be implicitly defined as deleted.
8871   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
8872     // Cache this result so that we don't try to generate this over and over
8873     // on every lookup, leaking memory and wasting time.
8874     ClassDecl->setFailedImplicitMoveConstructor();
8875     return 0;
8876   }
8877 
8878   // Note that we have declared this constructor.
8879   ++ASTContext::NumImplicitMoveConstructorsDeclared;
8880 
8881   if (Scope *S = getScopeForContext(ClassDecl))
8882     PushOnScopeChains(MoveConstructor, S, false);
8883   ClassDecl->addDecl(MoveConstructor);
8884 
8885   return MoveConstructor;
8886 }
8887 
8888 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8889                                    CXXConstructorDecl *MoveConstructor) {
8890   assert((MoveConstructor->isDefaulted() &&
8891           MoveConstructor->isMoveConstructor() &&
8892           !MoveConstructor->doesThisDeclarationHaveABody() &&
8893           !MoveConstructor->isDeleted()) &&
8894          "DefineImplicitMoveConstructor - call it for implicit move ctor");
8895 
8896   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8897   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8898 
8899   ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8900   DiagnosticErrorTrap Trap(Diags);
8901 
8902   if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8903       Trap.hasErrorOccurred()) {
8904     Diag(CurrentLocation, diag::note_member_synthesized_at)
8905       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8906     MoveConstructor->setInvalidDecl();
8907   }  else {
8908     Sema::CompoundScopeRAII CompoundScope(*this);
8909     MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8910                                                MoveConstructor->getLocation(),
8911                                                MultiStmtArg(),
8912                                                /*isStmtExpr=*/false)
8913                                                               .takeAs<Stmt>());
8914     MoveConstructor->setImplicitlyDefined(true);
8915   }
8916 
8917   MoveConstructor->setUsed();
8918 
8919   if (ASTMutationListener *L = getASTMutationListener()) {
8920     L->CompletedImplicitDefinition(MoveConstructor);
8921   }
8922 }
8923 
8924 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8925   return FD->isDeleted() &&
8926          (FD->isDefaulted() || FD->isImplicit()) &&
8927          isa<CXXMethodDecl>(FD);
8928 }
8929 
8930 /// \brief Mark the call operator of the given lambda closure type as "used".
8931 static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8932   CXXMethodDecl *CallOperator
8933     = cast<CXXMethodDecl>(
8934         *Lambda->lookup(
8935           S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
8936   CallOperator->setReferenced();
8937   CallOperator->setUsed();
8938 }
8939 
8940 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8941        SourceLocation CurrentLocation,
8942        CXXConversionDecl *Conv)
8943 {
8944   CXXRecordDecl *Lambda = Conv->getParent();
8945 
8946   // Make sure that the lambda call operator is marked used.
8947   markLambdaCallOperatorUsed(*this, Lambda);
8948 
8949   Conv->setUsed();
8950 
8951   ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8952   DiagnosticErrorTrap Trap(Diags);
8953 
8954   // Return the address of the __invoke function.
8955   DeclarationName InvokeName = &Context.Idents.get("__invoke");
8956   CXXMethodDecl *Invoke
8957     = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8958   Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8959                                        VK_LValue, Conv->getLocation()).take();
8960   assert(FunctionRef && "Can't refer to __invoke function?");
8961   Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8962   Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8963                                            Conv->getLocation(),
8964                                            Conv->getLocation()));
8965 
8966   // Fill in the __invoke function with a dummy implementation. IR generation
8967   // will fill in the actual details.
8968   Invoke->setUsed();
8969   Invoke->setReferenced();
8970   Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
8971 
8972   if (ASTMutationListener *L = getASTMutationListener()) {
8973     L->CompletedImplicitDefinition(Conv);
8974     L->CompletedImplicitDefinition(Invoke);
8975   }
8976 }
8977 
8978 void Sema::DefineImplicitLambdaToBlockPointerConversion(
8979        SourceLocation CurrentLocation,
8980        CXXConversionDecl *Conv)
8981 {
8982   Conv->setUsed();
8983 
8984   ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8985   DiagnosticErrorTrap Trap(Diags);
8986 
8987   // Copy-initialize the lambda object as needed to capture it.
8988   Expr *This = ActOnCXXThis(CurrentLocation).take();
8989   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
8990 
8991   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8992                                                         Conv->getLocation(),
8993                                                         Conv, DerefThis);
8994 
8995   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8996   // behavior.  Note that only the general conversion function does this
8997   // (since it's unusable otherwise); in the case where we inline the
8998   // block literal, it has block literal lifetime semantics.
8999   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
9000     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9001                                           CK_CopyAndAutoreleaseBlockObject,
9002                                           BuildBlock.get(), 0, VK_RValue);
9003 
9004   if (BuildBlock.isInvalid()) {
9005     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9006     Conv->setInvalidDecl();
9007     return;
9008   }
9009 
9010   // Create the return statement that returns the block from the conversion
9011   // function.
9012   StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
9013   if (Return.isInvalid()) {
9014     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9015     Conv->setInvalidDecl();
9016     return;
9017   }
9018 
9019   // Set the body of the conversion function.
9020   Stmt *ReturnS = Return.take();
9021   Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9022                                            Conv->getLocation(),
9023                                            Conv->getLocation()));
9024 
9025   // We're done; notify the mutation listener, if any.
9026   if (ASTMutationListener *L = getASTMutationListener()) {
9027     L->CompletedImplicitDefinition(Conv);
9028   }
9029 }
9030 
9031 /// \brief Determine whether the given list arguments contains exactly one
9032 /// "real" (non-default) argument.
9033 static bool hasOneRealArgument(MultiExprArg Args) {
9034   switch (Args.size()) {
9035   case 0:
9036     return false;
9037 
9038   default:
9039     if (!Args[1]->isDefaultArgument())
9040       return false;
9041 
9042     // fall through
9043   case 1:
9044     return !Args[0]->isDefaultArgument();
9045   }
9046 
9047   return false;
9048 }
9049 
9050 ExprResult
9051 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9052                             CXXConstructorDecl *Constructor,
9053                             MultiExprArg ExprArgs,
9054                             bool HadMultipleCandidates,
9055                             bool RequiresZeroInit,
9056                             unsigned ConstructKind,
9057                             SourceRange ParenRange) {
9058   bool Elidable = false;
9059 
9060   // C++0x [class.copy]p34:
9061   //   When certain criteria are met, an implementation is allowed to
9062   //   omit the copy/move construction of a class object, even if the
9063   //   copy/move constructor and/or destructor for the object have
9064   //   side effects. [...]
9065   //     - when a temporary class object that has not been bound to a
9066   //       reference (12.2) would be copied/moved to a class object
9067   //       with the same cv-unqualified type, the copy/move operation
9068   //       can be omitted by constructing the temporary object
9069   //       directly into the target of the omitted copy/move
9070   if (ConstructKind == CXXConstructExpr::CK_Complete &&
9071       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
9072     Expr *SubExpr = ExprArgs[0];
9073     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
9074   }
9075 
9076   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
9077                                Elidable, ExprArgs, HadMultipleCandidates,
9078                                RequiresZeroInit, ConstructKind, ParenRange);
9079 }
9080 
9081 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
9082 /// including handling of its default argument expressions.
9083 ExprResult
9084 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9085                             CXXConstructorDecl *Constructor, bool Elidable,
9086                             MultiExprArg ExprArgs,
9087                             bool HadMultipleCandidates,
9088                             bool RequiresZeroInit,
9089                             unsigned ConstructKind,
9090                             SourceRange ParenRange) {
9091   MarkFunctionReferenced(ConstructLoc, Constructor);
9092   return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
9093                                         Constructor, Elidable, ExprArgs,
9094                                         HadMultipleCandidates, /*FIXME*/false,
9095                                         RequiresZeroInit,
9096               static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9097                                         ParenRange));
9098 }
9099 
9100 bool Sema::InitializeVarWithConstructor(VarDecl *VD,
9101                                         CXXConstructorDecl *Constructor,
9102                                         MultiExprArg Exprs,
9103                                         bool HadMultipleCandidates) {
9104   // FIXME: Provide the correct paren SourceRange when available.
9105   ExprResult TempResult =
9106     BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
9107                           Exprs, HadMultipleCandidates, false,
9108                           CXXConstructExpr::CK_Complete, SourceRange());
9109   if (TempResult.isInvalid())
9110     return true;
9111 
9112   Expr *Temp = TempResult.takeAs<Expr>();
9113   CheckImplicitConversions(Temp, VD->getLocation());
9114   MarkFunctionReferenced(VD->getLocation(), Constructor);
9115   Temp = MaybeCreateExprWithCleanups(Temp);
9116   VD->setInit(Temp);
9117 
9118   return false;
9119 }
9120 
9121 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
9122   if (VD->isInvalidDecl()) return;
9123 
9124   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
9125   if (ClassDecl->isInvalidDecl()) return;
9126   if (ClassDecl->hasIrrelevantDestructor()) return;
9127   if (ClassDecl->isDependentContext()) return;
9128 
9129   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9130   MarkFunctionReferenced(VD->getLocation(), Destructor);
9131   CheckDestructorAccess(VD->getLocation(), Destructor,
9132                         PDiag(diag::err_access_dtor_var)
9133                         << VD->getDeclName()
9134                         << VD->getType());
9135   DiagnoseUseOfDecl(Destructor, VD->getLocation());
9136 
9137   if (!VD->hasGlobalStorage()) return;
9138 
9139   // Emit warning for non-trivial dtor in global scope (a real global,
9140   // class-static, function-static).
9141   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9142 
9143   // TODO: this should be re-enabled for static locals by !CXAAtExit
9144   if (!VD->isStaticLocal())
9145     Diag(VD->getLocation(), diag::warn_global_destructor);
9146 }
9147 
9148 /// \brief Given a constructor and the set of arguments provided for the
9149 /// constructor, convert the arguments and add any required default arguments
9150 /// to form a proper call to this constructor.
9151 ///
9152 /// \returns true if an error occurred, false otherwise.
9153 bool
9154 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9155                               MultiExprArg ArgsPtr,
9156                               SourceLocation Loc,
9157                               SmallVectorImpl<Expr*> &ConvertedArgs,
9158                               bool AllowExplicit) {
9159   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9160   unsigned NumArgs = ArgsPtr.size();
9161   Expr **Args = ArgsPtr.data();
9162 
9163   const FunctionProtoType *Proto
9164     = Constructor->getType()->getAs<FunctionProtoType>();
9165   assert(Proto && "Constructor without a prototype?");
9166   unsigned NumArgsInProto = Proto->getNumArgs();
9167 
9168   // If too few arguments are available, we'll fill in the rest with defaults.
9169   if (NumArgs < NumArgsInProto)
9170     ConvertedArgs.reserve(NumArgsInProto);
9171   else
9172     ConvertedArgs.reserve(NumArgs);
9173 
9174   VariadicCallType CallType =
9175     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
9176   SmallVector<Expr *, 8> AllArgs;
9177   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9178                                         Proto, 0, Args, NumArgs, AllArgs,
9179                                         CallType, AllowExplicit);
9180   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
9181 
9182   DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9183 
9184   CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9185                        Proto, Loc);
9186 
9187   return Invalid;
9188 }
9189 
9190 static inline bool
9191 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9192                                        const FunctionDecl *FnDecl) {
9193   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
9194   if (isa<NamespaceDecl>(DC)) {
9195     return SemaRef.Diag(FnDecl->getLocation(),
9196                         diag::err_operator_new_delete_declared_in_namespace)
9197       << FnDecl->getDeclName();
9198   }
9199 
9200   if (isa<TranslationUnitDecl>(DC) &&
9201       FnDecl->getStorageClass() == SC_Static) {
9202     return SemaRef.Diag(FnDecl->getLocation(),
9203                         diag::err_operator_new_delete_declared_static)
9204       << FnDecl->getDeclName();
9205   }
9206 
9207   return false;
9208 }
9209 
9210 static inline bool
9211 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9212                             CanQualType ExpectedResultType,
9213                             CanQualType ExpectedFirstParamType,
9214                             unsigned DependentParamTypeDiag,
9215                             unsigned InvalidParamTypeDiag) {
9216   QualType ResultType =
9217     FnDecl->getType()->getAs<FunctionType>()->getResultType();
9218 
9219   // Check that the result type is not dependent.
9220   if (ResultType->isDependentType())
9221     return SemaRef.Diag(FnDecl->getLocation(),
9222                         diag::err_operator_new_delete_dependent_result_type)
9223     << FnDecl->getDeclName() << ExpectedResultType;
9224 
9225   // Check that the result type is what we expect.
9226   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9227     return SemaRef.Diag(FnDecl->getLocation(),
9228                         diag::err_operator_new_delete_invalid_result_type)
9229     << FnDecl->getDeclName() << ExpectedResultType;
9230 
9231   // A function template must have at least 2 parameters.
9232   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9233     return SemaRef.Diag(FnDecl->getLocation(),
9234                       diag::err_operator_new_delete_template_too_few_parameters)
9235         << FnDecl->getDeclName();
9236 
9237   // The function decl must have at least 1 parameter.
9238   if (FnDecl->getNumParams() == 0)
9239     return SemaRef.Diag(FnDecl->getLocation(),
9240                         diag::err_operator_new_delete_too_few_parameters)
9241       << FnDecl->getDeclName();
9242 
9243   // Check the first parameter type is not dependent.
9244   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9245   if (FirstParamType->isDependentType())
9246     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9247       << FnDecl->getDeclName() << ExpectedFirstParamType;
9248 
9249   // Check that the first parameter type is what we expect.
9250   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
9251       ExpectedFirstParamType)
9252     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9253     << FnDecl->getDeclName() << ExpectedFirstParamType;
9254 
9255   return false;
9256 }
9257 
9258 static bool
9259 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9260   // C++ [basic.stc.dynamic.allocation]p1:
9261   //   A program is ill-formed if an allocation function is declared in a
9262   //   namespace scope other than global scope or declared static in global
9263   //   scope.
9264   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9265     return true;
9266 
9267   CanQualType SizeTy =
9268     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9269 
9270   // C++ [basic.stc.dynamic.allocation]p1:
9271   //  The return type shall be void*. The first parameter shall have type
9272   //  std::size_t.
9273   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9274                                   SizeTy,
9275                                   diag::err_operator_new_dependent_param_type,
9276                                   diag::err_operator_new_param_type))
9277     return true;
9278 
9279   // C++ [basic.stc.dynamic.allocation]p1:
9280   //  The first parameter shall not have an associated default argument.
9281   if (FnDecl->getParamDecl(0)->hasDefaultArg())
9282     return SemaRef.Diag(FnDecl->getLocation(),
9283                         diag::err_operator_new_default_arg)
9284       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9285 
9286   return false;
9287 }
9288 
9289 static bool
9290 CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9291   // C++ [basic.stc.dynamic.deallocation]p1:
9292   //   A program is ill-formed if deallocation functions are declared in a
9293   //   namespace scope other than global scope or declared static in global
9294   //   scope.
9295   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9296     return true;
9297 
9298   // C++ [basic.stc.dynamic.deallocation]p2:
9299   //   Each deallocation function shall return void and its first parameter
9300   //   shall be void*.
9301   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9302                                   SemaRef.Context.VoidPtrTy,
9303                                  diag::err_operator_delete_dependent_param_type,
9304                                  diag::err_operator_delete_param_type))
9305     return true;
9306 
9307   return false;
9308 }
9309 
9310 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
9311 /// of this overloaded operator is well-formed. If so, returns false;
9312 /// otherwise, emits appropriate diagnostics and returns true.
9313 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
9314   assert(FnDecl && FnDecl->isOverloadedOperator() &&
9315          "Expected an overloaded operator declaration");
9316 
9317   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9318 
9319   // C++ [over.oper]p5:
9320   //   The allocation and deallocation functions, operator new,
9321   //   operator new[], operator delete and operator delete[], are
9322   //   described completely in 3.7.3. The attributes and restrictions
9323   //   found in the rest of this subclause do not apply to them unless
9324   //   explicitly stated in 3.7.3.
9325   if (Op == OO_Delete || Op == OO_Array_Delete)
9326     return CheckOperatorDeleteDeclaration(*this, FnDecl);
9327 
9328   if (Op == OO_New || Op == OO_Array_New)
9329     return CheckOperatorNewDeclaration(*this, FnDecl);
9330 
9331   // C++ [over.oper]p6:
9332   //   An operator function shall either be a non-static member
9333   //   function or be a non-member function and have at least one
9334   //   parameter whose type is a class, a reference to a class, an
9335   //   enumeration, or a reference to an enumeration.
9336   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9337     if (MethodDecl->isStatic())
9338       return Diag(FnDecl->getLocation(),
9339                   diag::err_operator_overload_static) << FnDecl->getDeclName();
9340   } else {
9341     bool ClassOrEnumParam = false;
9342     for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9343                                    ParamEnd = FnDecl->param_end();
9344          Param != ParamEnd; ++Param) {
9345       QualType ParamType = (*Param)->getType().getNonReferenceType();
9346       if (ParamType->isDependentType() || ParamType->isRecordType() ||
9347           ParamType->isEnumeralType()) {
9348         ClassOrEnumParam = true;
9349         break;
9350       }
9351     }
9352 
9353     if (!ClassOrEnumParam)
9354       return Diag(FnDecl->getLocation(),
9355                   diag::err_operator_overload_needs_class_or_enum)
9356         << FnDecl->getDeclName();
9357   }
9358 
9359   // C++ [over.oper]p8:
9360   //   An operator function cannot have default arguments (8.3.6),
9361   //   except where explicitly stated below.
9362   //
9363   // Only the function-call operator allows default arguments
9364   // (C++ [over.call]p1).
9365   if (Op != OO_Call) {
9366     for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9367          Param != FnDecl->param_end(); ++Param) {
9368       if ((*Param)->hasDefaultArg())
9369         return Diag((*Param)->getLocation(),
9370                     diag::err_operator_overload_default_arg)
9371           << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
9372     }
9373   }
9374 
9375   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9376     { false, false, false }
9377 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9378     , { Unary, Binary, MemberOnly }
9379 #include "clang/Basic/OperatorKinds.def"
9380   };
9381 
9382   bool CanBeUnaryOperator = OperatorUses[Op][0];
9383   bool CanBeBinaryOperator = OperatorUses[Op][1];
9384   bool MustBeMemberOperator = OperatorUses[Op][2];
9385 
9386   // C++ [over.oper]p8:
9387   //   [...] Operator functions cannot have more or fewer parameters
9388   //   than the number required for the corresponding operator, as
9389   //   described in the rest of this subclause.
9390   unsigned NumParams = FnDecl->getNumParams()
9391                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
9392   if (Op != OO_Call &&
9393       ((NumParams == 1 && !CanBeUnaryOperator) ||
9394        (NumParams == 2 && !CanBeBinaryOperator) ||
9395        (NumParams < 1) || (NumParams > 2))) {
9396     // We have the wrong number of parameters.
9397     unsigned ErrorKind;
9398     if (CanBeUnaryOperator && CanBeBinaryOperator) {
9399       ErrorKind = 2;  // 2 -> unary or binary.
9400     } else if (CanBeUnaryOperator) {
9401       ErrorKind = 0;  // 0 -> unary
9402     } else {
9403       assert(CanBeBinaryOperator &&
9404              "All non-call overloaded operators are unary or binary!");
9405       ErrorKind = 1;  // 1 -> binary
9406     }
9407 
9408     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
9409       << FnDecl->getDeclName() << NumParams << ErrorKind;
9410   }
9411 
9412   // Overloaded operators other than operator() cannot be variadic.
9413   if (Op != OO_Call &&
9414       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
9415     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
9416       << FnDecl->getDeclName();
9417   }
9418 
9419   // Some operators must be non-static member functions.
9420   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9421     return Diag(FnDecl->getLocation(),
9422                 diag::err_operator_overload_must_be_member)
9423       << FnDecl->getDeclName();
9424   }
9425 
9426   // C++ [over.inc]p1:
9427   //   The user-defined function called operator++ implements the
9428   //   prefix and postfix ++ operator. If this function is a member
9429   //   function with no parameters, or a non-member function with one
9430   //   parameter of class or enumeration type, it defines the prefix
9431   //   increment operator ++ for objects of that type. If the function
9432   //   is a member function with one parameter (which shall be of type
9433   //   int) or a non-member function with two parameters (the second
9434   //   of which shall be of type int), it defines the postfix
9435   //   increment operator ++ for objects of that type.
9436   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9437     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9438     bool ParamIsInt = false;
9439     if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
9440       ParamIsInt = BT->getKind() == BuiltinType::Int;
9441 
9442     if (!ParamIsInt)
9443       return Diag(LastParam->getLocation(),
9444                   diag::err_operator_overload_post_incdec_must_be_int)
9445         << LastParam->getType() << (Op == OO_MinusMinus);
9446   }
9447 
9448   return false;
9449 }
9450 
9451 /// CheckLiteralOperatorDeclaration - Check whether the declaration
9452 /// of this literal operator function is well-formed. If so, returns
9453 /// false; otherwise, emits appropriate diagnostics and returns true.
9454 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9455   if (isa<CXXMethodDecl>(FnDecl)) {
9456     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9457       << FnDecl->getDeclName();
9458     return true;
9459   }
9460 
9461   if (FnDecl->isExternC()) {
9462     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9463     return true;
9464   }
9465 
9466   bool Valid = false;
9467 
9468   // This might be the definition of a literal operator template.
9469   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9470   // This might be a specialization of a literal operator template.
9471   if (!TpDecl)
9472     TpDecl = FnDecl->getPrimaryTemplate();
9473 
9474   // template <char...> type operator "" name() is the only valid template
9475   // signature, and the only valid signature with no parameters.
9476   if (TpDecl) {
9477     if (FnDecl->param_size() == 0) {
9478       // Must have only one template parameter
9479       TemplateParameterList *Params = TpDecl->getTemplateParameters();
9480       if (Params->size() == 1) {
9481         NonTypeTemplateParmDecl *PmDecl =
9482           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
9483 
9484         // The template parameter must be a char parameter pack.
9485         if (PmDecl && PmDecl->isTemplateParameterPack() &&
9486             Context.hasSameType(PmDecl->getType(), Context.CharTy))
9487           Valid = true;
9488       }
9489     }
9490   } else if (FnDecl->param_size()) {
9491     // Check the first parameter
9492     FunctionDecl::param_iterator Param = FnDecl->param_begin();
9493 
9494     QualType T = (*Param)->getType().getUnqualifiedType();
9495 
9496     // unsigned long long int, long double, and any character type are allowed
9497     // as the only parameters.
9498     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9499         Context.hasSameType(T, Context.LongDoubleTy) ||
9500         Context.hasSameType(T, Context.CharTy) ||
9501         Context.hasSameType(T, Context.WCharTy) ||
9502         Context.hasSameType(T, Context.Char16Ty) ||
9503         Context.hasSameType(T, Context.Char32Ty)) {
9504       if (++Param == FnDecl->param_end())
9505         Valid = true;
9506       goto FinishedParams;
9507     }
9508 
9509     // Otherwise it must be a pointer to const; let's strip those qualifiers.
9510     const PointerType *PT = T->getAs<PointerType>();
9511     if (!PT)
9512       goto FinishedParams;
9513     T = PT->getPointeeType();
9514     if (!T.isConstQualified() || T.isVolatileQualified())
9515       goto FinishedParams;
9516     T = T.getUnqualifiedType();
9517 
9518     // Move on to the second parameter;
9519     ++Param;
9520 
9521     // If there is no second parameter, the first must be a const char *
9522     if (Param == FnDecl->param_end()) {
9523       if (Context.hasSameType(T, Context.CharTy))
9524         Valid = true;
9525       goto FinishedParams;
9526     }
9527 
9528     // const char *, const wchar_t*, const char16_t*, and const char32_t*
9529     // are allowed as the first parameter to a two-parameter function
9530     if (!(Context.hasSameType(T, Context.CharTy) ||
9531           Context.hasSameType(T, Context.WCharTy) ||
9532           Context.hasSameType(T, Context.Char16Ty) ||
9533           Context.hasSameType(T, Context.Char32Ty)))
9534       goto FinishedParams;
9535 
9536     // The second and final parameter must be an std::size_t
9537     T = (*Param)->getType().getUnqualifiedType();
9538     if (Context.hasSameType(T, Context.getSizeType()) &&
9539         ++Param == FnDecl->param_end())
9540       Valid = true;
9541   }
9542 
9543   // FIXME: This diagnostic is absolutely terrible.
9544 FinishedParams:
9545   if (!Valid) {
9546     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9547       << FnDecl->getDeclName();
9548     return true;
9549   }
9550 
9551   // A parameter-declaration-clause containing a default argument is not
9552   // equivalent to any of the permitted forms.
9553   for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9554                                     ParamEnd = FnDecl->param_end();
9555        Param != ParamEnd; ++Param) {
9556     if ((*Param)->hasDefaultArg()) {
9557       Diag((*Param)->getDefaultArgRange().getBegin(),
9558            diag::err_literal_operator_default_argument)
9559         << (*Param)->getDefaultArgRange();
9560       break;
9561     }
9562   }
9563 
9564   StringRef LiteralName
9565     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9566   if (LiteralName[0] != '_') {
9567     // C++11 [usrlit.suffix]p1:
9568     //   Literal suffix identifiers that do not start with an underscore
9569     //   are reserved for future standardization.
9570     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9571   }
9572 
9573   return false;
9574 }
9575 
9576 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9577 /// linkage specification, including the language and (if present)
9578 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9579 /// the location of the language string literal, which is provided
9580 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9581 /// the '{' brace. Otherwise, this linkage specification does not
9582 /// have any braces.
9583 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9584                                            SourceLocation LangLoc,
9585                                            StringRef Lang,
9586                                            SourceLocation LBraceLoc) {
9587   LinkageSpecDecl::LanguageIDs Language;
9588   if (Lang == "\"C\"")
9589     Language = LinkageSpecDecl::lang_c;
9590   else if (Lang == "\"C++\"")
9591     Language = LinkageSpecDecl::lang_cxx;
9592   else {
9593     Diag(LangLoc, diag::err_bad_language);
9594     return 0;
9595   }
9596 
9597   // FIXME: Add all the various semantics of linkage specifications
9598 
9599   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
9600                                                ExternLoc, LangLoc, Language);
9601   CurContext->addDecl(D);
9602   PushDeclContext(S, D);
9603   return D;
9604 }
9605 
9606 /// ActOnFinishLinkageSpecification - Complete the definition of
9607 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
9608 /// valid, it's the position of the closing '}' brace in a linkage
9609 /// specification that uses braces.
9610 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
9611                                             Decl *LinkageSpec,
9612                                             SourceLocation RBraceLoc) {
9613   if (LinkageSpec) {
9614     if (RBraceLoc.isValid()) {
9615       LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9616       LSDecl->setRBraceLoc(RBraceLoc);
9617     }
9618     PopDeclContext();
9619   }
9620   return LinkageSpec;
9621 }
9622 
9623 /// \brief Perform semantic analysis for the variable declaration that
9624 /// occurs within a C++ catch clause, returning the newly-created
9625 /// variable.
9626 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
9627                                          TypeSourceInfo *TInfo,
9628                                          SourceLocation StartLoc,
9629                                          SourceLocation Loc,
9630                                          IdentifierInfo *Name) {
9631   bool Invalid = false;
9632   QualType ExDeclType = TInfo->getType();
9633 
9634   // Arrays and functions decay.
9635   if (ExDeclType->isArrayType())
9636     ExDeclType = Context.getArrayDecayedType(ExDeclType);
9637   else if (ExDeclType->isFunctionType())
9638     ExDeclType = Context.getPointerType(ExDeclType);
9639 
9640   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9641   // The exception-declaration shall not denote a pointer or reference to an
9642   // incomplete type, other than [cv] void*.
9643   // N2844 forbids rvalue references.
9644   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
9645     Diag(Loc, diag::err_catch_rvalue_ref);
9646     Invalid = true;
9647   }
9648 
9649   QualType BaseType = ExDeclType;
9650   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
9651   unsigned DK = diag::err_catch_incomplete;
9652   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
9653     BaseType = Ptr->getPointeeType();
9654     Mode = 1;
9655     DK = diag::err_catch_incomplete_ptr;
9656   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
9657     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
9658     BaseType = Ref->getPointeeType();
9659     Mode = 2;
9660     DK = diag::err_catch_incomplete_ref;
9661   }
9662   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
9663       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
9664     Invalid = true;
9665 
9666   if (!Invalid && !ExDeclType->isDependentType() &&
9667       RequireNonAbstractType(Loc, ExDeclType,
9668                              diag::err_abstract_type_in_decl,
9669                              AbstractVariableType))
9670     Invalid = true;
9671 
9672   // Only the non-fragile NeXT runtime currently supports C++ catches
9673   // of ObjC types, and no runtime supports catching ObjC types by value.
9674   if (!Invalid && getLangOpts().ObjC1) {
9675     QualType T = ExDeclType;
9676     if (const ReferenceType *RT = T->getAs<ReferenceType>())
9677       T = RT->getPointeeType();
9678 
9679     if (T->isObjCObjectType()) {
9680       Diag(Loc, diag::err_objc_object_catch);
9681       Invalid = true;
9682     } else if (T->isObjCObjectPointerType()) {
9683       // FIXME: should this be a test for macosx-fragile specifically?
9684       if (getLangOpts().ObjCRuntime.isFragile())
9685         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
9686     }
9687   }
9688 
9689   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9690                                     ExDeclType, TInfo, SC_None, SC_None);
9691   ExDecl->setExceptionVariable(true);
9692 
9693   // In ARC, infer 'retaining' for variables of retainable type.
9694   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9695     Invalid = true;
9696 
9697   if (!Invalid && !ExDeclType->isDependentType()) {
9698     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
9699       // C++ [except.handle]p16:
9700       //   The object declared in an exception-declaration or, if the
9701       //   exception-declaration does not specify a name, a temporary (12.2) is
9702       //   copy-initialized (8.5) from the exception object. [...]
9703       //   The object is destroyed when the handler exits, after the destruction
9704       //   of any automatic objects initialized within the handler.
9705       //
9706       // We just pretend to initialize the object with itself, then make sure
9707       // it can be destroyed later.
9708       QualType initType = ExDeclType;
9709 
9710       InitializedEntity entity =
9711         InitializedEntity::InitializeVariable(ExDecl);
9712       InitializationKind initKind =
9713         InitializationKind::CreateCopy(Loc, SourceLocation());
9714 
9715       Expr *opaqueValue =
9716         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9717       InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9718       ExprResult result = sequence.Perform(*this, entity, initKind,
9719                                            MultiExprArg(&opaqueValue, 1));
9720       if (result.isInvalid())
9721         Invalid = true;
9722       else {
9723         // If the constructor used was non-trivial, set this as the
9724         // "initializer".
9725         CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9726         if (!construct->getConstructor()->isTrivial()) {
9727           Expr *init = MaybeCreateExprWithCleanups(construct);
9728           ExDecl->setInit(init);
9729         }
9730 
9731         // And make sure it's destructable.
9732         FinalizeVarWithDestructor(ExDecl, recordType);
9733       }
9734     }
9735   }
9736 
9737   if (Invalid)
9738     ExDecl->setInvalidDecl();
9739 
9740   return ExDecl;
9741 }
9742 
9743 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9744 /// handler.
9745 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
9746   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9747   bool Invalid = D.isInvalidType();
9748 
9749   // Check for unexpanded parameter packs.
9750   if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9751                                                UPPC_ExceptionType)) {
9752     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9753                                              D.getIdentifierLoc());
9754     Invalid = true;
9755   }
9756 
9757   IdentifierInfo *II = D.getIdentifier();
9758   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
9759                                              LookupOrdinaryName,
9760                                              ForRedeclaration)) {
9761     // The scope should be freshly made just for us. There is just no way
9762     // it contains any previous declaration.
9763     assert(!S->isDeclScope(PrevDecl));
9764     if (PrevDecl->isTemplateParameter()) {
9765       // Maybe we will complain about the shadowed template parameter.
9766       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9767       PrevDecl = 0;
9768     }
9769   }
9770 
9771   if (D.getCXXScopeSpec().isSet() && !Invalid) {
9772     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9773       << D.getCXXScopeSpec().getRange();
9774     Invalid = true;
9775   }
9776 
9777   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
9778                                               D.getLocStart(),
9779                                               D.getIdentifierLoc(),
9780                                               D.getIdentifier());
9781   if (Invalid)
9782     ExDecl->setInvalidDecl();
9783 
9784   // Add the exception declaration into this scope.
9785   if (II)
9786     PushOnScopeChains(ExDecl, S);
9787   else
9788     CurContext->addDecl(ExDecl);
9789 
9790   ProcessDeclAttributes(S, ExDecl, D);
9791   return ExDecl;
9792 }
9793 
9794 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9795                                          Expr *AssertExpr,
9796                                          Expr *AssertMessageExpr,
9797                                          SourceLocation RParenLoc) {
9798   StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
9799 
9800   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9801     return 0;
9802 
9803   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
9804                                       AssertMessage, RParenLoc, false);
9805 }
9806 
9807 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9808                                          Expr *AssertExpr,
9809                                          StringLiteral *AssertMessage,
9810                                          SourceLocation RParenLoc,
9811                                          bool Failed) {
9812   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
9813       !Failed) {
9814     // In a static_assert-declaration, the constant-expression shall be a
9815     // constant expression that can be contextually converted to bool.
9816     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9817     if (Converted.isInvalid())
9818       Failed = true;
9819 
9820     llvm::APSInt Cond;
9821     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
9822           diag::err_static_assert_expression_is_not_constant,
9823           /*AllowFold=*/false).isInvalid())
9824       Failed = true;
9825 
9826     if (!Failed && !Cond) {
9827       llvm::SmallString<256> MsgBuffer;
9828       llvm::raw_svector_ostream Msg(MsgBuffer);
9829       AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
9830       Diag(StaticAssertLoc, diag::err_static_assert_failed)
9831         << Msg.str() << AssertExpr->getSourceRange();
9832       Failed = true;
9833     }
9834   }
9835 
9836   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9837                                         AssertExpr, AssertMessage, RParenLoc,
9838                                         Failed);
9839 
9840   CurContext->addDecl(Decl);
9841   return Decl;
9842 }
9843 
9844 /// \brief Perform semantic analysis of the given friend type declaration.
9845 ///
9846 /// \returns A friend declaration that.
9847 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9848                                       SourceLocation FriendLoc,
9849                                       TypeSourceInfo *TSInfo) {
9850   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9851 
9852   QualType T = TSInfo->getType();
9853   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
9854 
9855   // C++03 [class.friend]p2:
9856   //   An elaborated-type-specifier shall be used in a friend declaration
9857   //   for a class.*
9858   //
9859   //   * The class-key of the elaborated-type-specifier is required.
9860   if (!ActiveTemplateInstantiations.empty()) {
9861     // Do not complain about the form of friend template types during
9862     // template instantiation; we will already have complained when the
9863     // template was declared.
9864   } else if (!T->isElaboratedTypeSpecifier()) {
9865     // If we evaluated the type to a record type, suggest putting
9866     // a tag in front.
9867     if (const RecordType *RT = T->getAs<RecordType>()) {
9868       RecordDecl *RD = RT->getDecl();
9869 
9870       std::string InsertionText = std::string(" ") + RD->getKindName();
9871 
9872       Diag(TypeRange.getBegin(),
9873            getLangOpts().CPlusPlus0x ?
9874              diag::warn_cxx98_compat_unelaborated_friend_type :
9875              diag::ext_unelaborated_friend_type)
9876         << (unsigned) RD->getTagKind()
9877         << T
9878         << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9879                                       InsertionText);
9880     } else {
9881       Diag(FriendLoc,
9882            getLangOpts().CPlusPlus0x ?
9883              diag::warn_cxx98_compat_nonclass_type_friend :
9884              diag::ext_nonclass_type_friend)
9885         << T
9886         << SourceRange(FriendLoc, TypeRange.getEnd());
9887     }
9888   } else if (T->getAs<EnumType>()) {
9889     Diag(FriendLoc,
9890          getLangOpts().CPlusPlus0x ?
9891            diag::warn_cxx98_compat_enum_friend :
9892            diag::ext_enum_friend)
9893       << T
9894       << SourceRange(FriendLoc, TypeRange.getEnd());
9895   }
9896 
9897   // C++0x [class.friend]p3:
9898   //   If the type specifier in a friend declaration designates a (possibly
9899   //   cv-qualified) class type, that class is declared as a friend; otherwise,
9900   //   the friend declaration is ignored.
9901 
9902   // FIXME: C++0x has some syntactic restrictions on friend type declarations
9903   // in [class.friend]p3 that we do not implement.
9904 
9905   return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
9906 }
9907 
9908 /// Handle a friend tag declaration where the scope specifier was
9909 /// templated.
9910 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9911                                     unsigned TagSpec, SourceLocation TagLoc,
9912                                     CXXScopeSpec &SS,
9913                                     IdentifierInfo *Name, SourceLocation NameLoc,
9914                                     AttributeList *Attr,
9915                                     MultiTemplateParamsArg TempParamLists) {
9916   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9917 
9918   bool isExplicitSpecialization = false;
9919   bool Invalid = false;
9920 
9921   if (TemplateParameterList *TemplateParams
9922         = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
9923                                                   TempParamLists.data(),
9924                                                   TempParamLists.size(),
9925                                                   /*friend*/ true,
9926                                                   isExplicitSpecialization,
9927                                                   Invalid)) {
9928     if (TemplateParams->size() > 0) {
9929       // This is a declaration of a class template.
9930       if (Invalid)
9931         return 0;
9932 
9933       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9934                                 SS, Name, NameLoc, Attr,
9935                                 TemplateParams, AS_public,
9936                                 /*ModulePrivateLoc=*/SourceLocation(),
9937                                 TempParamLists.size() - 1,
9938                                 TempParamLists.data()).take();
9939     } else {
9940       // The "template<>" header is extraneous.
9941       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9942         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9943       isExplicitSpecialization = true;
9944     }
9945   }
9946 
9947   if (Invalid) return 0;
9948 
9949   bool isAllExplicitSpecializations = true;
9950   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
9951     if (TempParamLists[I]->size()) {
9952       isAllExplicitSpecializations = false;
9953       break;
9954     }
9955   }
9956 
9957   // FIXME: don't ignore attributes.
9958 
9959   // If it's explicit specializations all the way down, just forget
9960   // about the template header and build an appropriate non-templated
9961   // friend.  TODO: for source fidelity, remember the headers.
9962   if (isAllExplicitSpecializations) {
9963     if (SS.isEmpty()) {
9964       bool Owned = false;
9965       bool IsDependent = false;
9966       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9967                       Attr, AS_public,
9968                       /*ModulePrivateLoc=*/SourceLocation(),
9969                       MultiTemplateParamsArg(), Owned, IsDependent,
9970                       /*ScopedEnumKWLoc=*/SourceLocation(),
9971                       /*ScopedEnumUsesClassTag=*/false,
9972                       /*UnderlyingType=*/TypeResult());
9973     }
9974 
9975     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9976     ElaboratedTypeKeyword Keyword
9977       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9978     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
9979                                    *Name, NameLoc);
9980     if (T.isNull())
9981       return 0;
9982 
9983     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9984     if (isa<DependentNameType>(T)) {
9985       DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9986       TL.setElaboratedKeywordLoc(TagLoc);
9987       TL.setQualifierLoc(QualifierLoc);
9988       TL.setNameLoc(NameLoc);
9989     } else {
9990       ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9991       TL.setElaboratedKeywordLoc(TagLoc);
9992       TL.setQualifierLoc(QualifierLoc);
9993       cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9994     }
9995 
9996     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9997                                             TSI, FriendLoc);
9998     Friend->setAccess(AS_public);
9999     CurContext->addDecl(Friend);
10000     return Friend;
10001   }
10002 
10003   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10004 
10005 
10006 
10007   // Handle the case of a templated-scope friend class.  e.g.
10008   //   template <class T> class A<T>::B;
10009   // FIXME: we don't support these right now.
10010   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10011   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10012   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10013   DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10014   TL.setElaboratedKeywordLoc(TagLoc);
10015   TL.setQualifierLoc(SS.getWithLocInContext(Context));
10016   TL.setNameLoc(NameLoc);
10017 
10018   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10019                                           TSI, FriendLoc);
10020   Friend->setAccess(AS_public);
10021   Friend->setUnsupportedFriend(true);
10022   CurContext->addDecl(Friend);
10023   return Friend;
10024 }
10025 
10026 
10027 /// Handle a friend type declaration.  This works in tandem with
10028 /// ActOnTag.
10029 ///
10030 /// Notes on friend class templates:
10031 ///
10032 /// We generally treat friend class declarations as if they were
10033 /// declaring a class.  So, for example, the elaborated type specifier
10034 /// in a friend declaration is required to obey the restrictions of a
10035 /// class-head (i.e. no typedefs in the scope chain), template
10036 /// parameters are required to match up with simple template-ids, &c.
10037 /// However, unlike when declaring a template specialization, it's
10038 /// okay to refer to a template specialization without an empty
10039 /// template parameter declaration, e.g.
10040 ///   friend class A<T>::B<unsigned>;
10041 /// We permit this as a special case; if there are any template
10042 /// parameters present at all, require proper matching, i.e.
10043 ///   template <> template \<class T> friend class A<int>::B;
10044 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
10045                                 MultiTemplateParamsArg TempParams) {
10046   SourceLocation Loc = DS.getLocStart();
10047 
10048   assert(DS.isFriendSpecified());
10049   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10050 
10051   // Try to convert the decl specifier to a type.  This works for
10052   // friend templates because ActOnTag never produces a ClassTemplateDecl
10053   // for a TUK_Friend.
10054   Declarator TheDeclarator(DS, Declarator::MemberContext);
10055   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10056   QualType T = TSI->getType();
10057   if (TheDeclarator.isInvalidType())
10058     return 0;
10059 
10060   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10061     return 0;
10062 
10063   // This is definitely an error in C++98.  It's probably meant to
10064   // be forbidden in C++0x, too, but the specification is just
10065   // poorly written.
10066   //
10067   // The problem is with declarations like the following:
10068   //   template <T> friend A<T>::foo;
10069   // where deciding whether a class C is a friend or not now hinges
10070   // on whether there exists an instantiation of A that causes
10071   // 'foo' to equal C.  There are restrictions on class-heads
10072   // (which we declare (by fiat) elaborated friend declarations to
10073   // be) that makes this tractable.
10074   //
10075   // FIXME: handle "template <> friend class A<T>;", which
10076   // is possibly well-formed?  Who even knows?
10077   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
10078     Diag(Loc, diag::err_tagless_friend_type_template)
10079       << DS.getSourceRange();
10080     return 0;
10081   }
10082 
10083   // C++98 [class.friend]p1: A friend of a class is a function
10084   //   or class that is not a member of the class . . .
10085   // This is fixed in DR77, which just barely didn't make the C++03
10086   // deadline.  It's also a very silly restriction that seriously
10087   // affects inner classes and which nobody else seems to implement;
10088   // thus we never diagnose it, not even in -pedantic.
10089   //
10090   // But note that we could warn about it: it's always useless to
10091   // friend one of your own members (it's not, however, worthless to
10092   // friend a member of an arbitrary specialization of your template).
10093 
10094   Decl *D;
10095   if (unsigned NumTempParamLists = TempParams.size())
10096     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
10097                                    NumTempParamLists,
10098                                    TempParams.data(),
10099                                    TSI,
10100                                    DS.getFriendSpecLoc());
10101   else
10102     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
10103 
10104   if (!D)
10105     return 0;
10106 
10107   D->setAccess(AS_public);
10108   CurContext->addDecl(D);
10109 
10110   return D;
10111 }
10112 
10113 Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10114                                     MultiTemplateParamsArg TemplateParams) {
10115   const DeclSpec &DS = D.getDeclSpec();
10116 
10117   assert(DS.isFriendSpecified());
10118   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10119 
10120   SourceLocation Loc = D.getIdentifierLoc();
10121   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10122 
10123   // C++ [class.friend]p1
10124   //   A friend of a class is a function or class....
10125   // Note that this sees through typedefs, which is intended.
10126   // It *doesn't* see through dependent types, which is correct
10127   // according to [temp.arg.type]p3:
10128   //   If a declaration acquires a function type through a
10129   //   type dependent on a template-parameter and this causes
10130   //   a declaration that does not use the syntactic form of a
10131   //   function declarator to have a function type, the program
10132   //   is ill-formed.
10133   if (!TInfo->getType()->isFunctionType()) {
10134     Diag(Loc, diag::err_unexpected_friend);
10135 
10136     // It might be worthwhile to try to recover by creating an
10137     // appropriate declaration.
10138     return 0;
10139   }
10140 
10141   // C++ [namespace.memdef]p3
10142   //  - If a friend declaration in a non-local class first declares a
10143   //    class or function, the friend class or function is a member
10144   //    of the innermost enclosing namespace.
10145   //  - The name of the friend is not found by simple name lookup
10146   //    until a matching declaration is provided in that namespace
10147   //    scope (either before or after the class declaration granting
10148   //    friendship).
10149   //  - If a friend function is called, its name may be found by the
10150   //    name lookup that considers functions from namespaces and
10151   //    classes associated with the types of the function arguments.
10152   //  - When looking for a prior declaration of a class or a function
10153   //    declared as a friend, scopes outside the innermost enclosing
10154   //    namespace scope are not considered.
10155 
10156   CXXScopeSpec &SS = D.getCXXScopeSpec();
10157   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10158   DeclarationName Name = NameInfo.getName();
10159   assert(Name);
10160 
10161   // Check for unexpanded parameter packs.
10162   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10163       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10164       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10165     return 0;
10166 
10167   // The context we found the declaration in, or in which we should
10168   // create the declaration.
10169   DeclContext *DC;
10170   Scope *DCScope = S;
10171   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10172                         ForRedeclaration);
10173 
10174   // FIXME: there are different rules in local classes
10175 
10176   // There are four cases here.
10177   //   - There's no scope specifier, in which case we just go to the
10178   //     appropriate scope and look for a function or function template
10179   //     there as appropriate.
10180   // Recover from invalid scope qualifiers as if they just weren't there.
10181   if (SS.isInvalid() || !SS.isSet()) {
10182     // C++0x [namespace.memdef]p3:
10183     //   If the name in a friend declaration is neither qualified nor
10184     //   a template-id and the declaration is a function or an
10185     //   elaborated-type-specifier, the lookup to determine whether
10186     //   the entity has been previously declared shall not consider
10187     //   any scopes outside the innermost enclosing namespace.
10188     // C++0x [class.friend]p11:
10189     //   If a friend declaration appears in a local class and the name
10190     //   specified is an unqualified name, a prior declaration is
10191     //   looked up without considering scopes that are outside the
10192     //   innermost enclosing non-class scope. For a friend function
10193     //   declaration, if there is no prior declaration, the program is
10194     //   ill-formed.
10195     bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
10196     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
10197 
10198     // Find the appropriate context according to the above.
10199     DC = CurContext;
10200     while (true) {
10201       // Skip class contexts.  If someone can cite chapter and verse
10202       // for this behavior, that would be nice --- it's what GCC and
10203       // EDG do, and it seems like a reasonable intent, but the spec
10204       // really only says that checks for unqualified existing
10205       // declarations should stop at the nearest enclosing namespace,
10206       // not that they should only consider the nearest enclosing
10207       // namespace.
10208       while (DC->isRecord() || DC->isTransparentContext())
10209         DC = DC->getParent();
10210 
10211       LookupQualifiedName(Previous, DC);
10212 
10213       // TODO: decide what we think about using declarations.
10214       if (isLocal || !Previous.empty())
10215         break;
10216 
10217       if (isTemplateId) {
10218         if (isa<TranslationUnitDecl>(DC)) break;
10219       } else {
10220         if (DC->isFileContext()) break;
10221       }
10222       DC = DC->getParent();
10223     }
10224 
10225     // C++ [class.friend]p1: A friend of a class is a function or
10226     //   class that is not a member of the class . . .
10227     // C++11 changes this for both friend types and functions.
10228     // Most C++ 98 compilers do seem to give an error here, so
10229     // we do, too.
10230     if (!Previous.empty() && DC->Equals(CurContext))
10231       Diag(DS.getFriendSpecLoc(),
10232            getLangOpts().CPlusPlus0x ?
10233              diag::warn_cxx98_compat_friend_is_member :
10234              diag::err_friend_is_member);
10235 
10236     DCScope = getScopeForDeclContext(S, DC);
10237 
10238     // C++ [class.friend]p6:
10239     //   A function can be defined in a friend declaration of a class if and
10240     //   only if the class is a non-local class (9.8), the function name is
10241     //   unqualified, and the function has namespace scope.
10242     if (isLocal && D.isFunctionDefinition()) {
10243       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10244     }
10245 
10246   //   - There's a non-dependent scope specifier, in which case we
10247   //     compute it and do a previous lookup there for a function
10248   //     or function template.
10249   } else if (!SS.getScopeRep()->isDependent()) {
10250     DC = computeDeclContext(SS);
10251     if (!DC) return 0;
10252 
10253     if (RequireCompleteDeclContext(SS, DC)) return 0;
10254 
10255     LookupQualifiedName(Previous, DC);
10256 
10257     // Ignore things found implicitly in the wrong scope.
10258     // TODO: better diagnostics for this case.  Suggesting the right
10259     // qualified scope would be nice...
10260     LookupResult::Filter F = Previous.makeFilter();
10261     while (F.hasNext()) {
10262       NamedDecl *D = F.next();
10263       if (!DC->InEnclosingNamespaceSetOf(
10264               D->getDeclContext()->getRedeclContext()))
10265         F.erase();
10266     }
10267     F.done();
10268 
10269     if (Previous.empty()) {
10270       D.setInvalidType();
10271       Diag(Loc, diag::err_qualified_friend_not_found)
10272           << Name << TInfo->getType();
10273       return 0;
10274     }
10275 
10276     // C++ [class.friend]p1: A friend of a class is a function or
10277     //   class that is not a member of the class . . .
10278     if (DC->Equals(CurContext))
10279       Diag(DS.getFriendSpecLoc(),
10280            getLangOpts().CPlusPlus0x ?
10281              diag::warn_cxx98_compat_friend_is_member :
10282              diag::err_friend_is_member);
10283 
10284     if (D.isFunctionDefinition()) {
10285       // C++ [class.friend]p6:
10286       //   A function can be defined in a friend declaration of a class if and
10287       //   only if the class is a non-local class (9.8), the function name is
10288       //   unqualified, and the function has namespace scope.
10289       SemaDiagnosticBuilder DB
10290         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10291 
10292       DB << SS.getScopeRep();
10293       if (DC->isFileContext())
10294         DB << FixItHint::CreateRemoval(SS.getRange());
10295       SS.clear();
10296     }
10297 
10298   //   - There's a scope specifier that does not match any template
10299   //     parameter lists, in which case we use some arbitrary context,
10300   //     create a method or method template, and wait for instantiation.
10301   //   - There's a scope specifier that does match some template
10302   //     parameter lists, which we don't handle right now.
10303   } else {
10304     if (D.isFunctionDefinition()) {
10305       // C++ [class.friend]p6:
10306       //   A function can be defined in a friend declaration of a class if and
10307       //   only if the class is a non-local class (9.8), the function name is
10308       //   unqualified, and the function has namespace scope.
10309       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10310         << SS.getScopeRep();
10311     }
10312 
10313     DC = CurContext;
10314     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
10315   }
10316 
10317   if (!DC->isRecord()) {
10318     // This implies that it has to be an operator or function.
10319     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10320         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10321         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
10322       Diag(Loc, diag::err_introducing_special_friend) <<
10323         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10324          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
10325       return 0;
10326     }
10327   }
10328 
10329   // FIXME: This is an egregious hack to cope with cases where the scope stack
10330   // does not contain the declaration context, i.e., in an out-of-line
10331   // definition of a class.
10332   Scope FakeDCScope(S, Scope::DeclScope, Diags);
10333   if (!DCScope) {
10334     FakeDCScope.setEntity(DC);
10335     DCScope = &FakeDCScope;
10336   }
10337 
10338   bool AddToScope = true;
10339   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10340                                           TemplateParams, AddToScope);
10341   if (!ND) return 0;
10342 
10343   assert(ND->getDeclContext() == DC);
10344   assert(ND->getLexicalDeclContext() == CurContext);
10345 
10346   // Add the function declaration to the appropriate lookup tables,
10347   // adjusting the redeclarations list as necessary.  We don't
10348   // want to do this yet if the friending class is dependent.
10349   //
10350   // Also update the scope-based lookup if the target context's
10351   // lookup context is in lexical scope.
10352   if (!CurContext->isDependentContext()) {
10353     DC = DC->getRedeclContext();
10354     DC->makeDeclVisibleInContext(ND);
10355     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10356       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
10357   }
10358 
10359   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
10360                                        D.getIdentifierLoc(), ND,
10361                                        DS.getFriendSpecLoc());
10362   FrD->setAccess(AS_public);
10363   CurContext->addDecl(FrD);
10364 
10365   if (ND->isInvalidDecl()) {
10366     FrD->setInvalidDecl();
10367   } else {
10368     if (DC->isRecord()) CheckFriendAccess(ND);
10369 
10370     FunctionDecl *FD;
10371     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10372       FD = FTD->getTemplatedDecl();
10373     else
10374       FD = cast<FunctionDecl>(ND);
10375 
10376     // Mark templated-scope function declarations as unsupported.
10377     if (FD->getNumTemplateParameterLists())
10378       FrD->setUnsupportedFriend(true);
10379   }
10380 
10381   return ND;
10382 }
10383 
10384 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10385   AdjustDeclIfTemplate(Dcl);
10386 
10387   FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10388   if (!Fn) {
10389     Diag(DelLoc, diag::err_deleted_non_function);
10390     return;
10391   }
10392   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
10393     // Don't consider the implicit declaration we generate for explicit
10394     // specializations. FIXME: Do not generate these implicit declarations.
10395     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10396         || Prev->getPreviousDecl()) && !Prev->isDefined()) {
10397       Diag(DelLoc, diag::err_deleted_decl_not_first);
10398       Diag(Prev->getLocation(), diag::note_previous_declaration);
10399     }
10400     // If the declaration wasn't the first, we delete the function anyway for
10401     // recovery.
10402   }
10403   Fn->setDeletedAsWritten();
10404 
10405   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10406   if (!MD)
10407     return;
10408 
10409   // A deleted special member function is trivial if the corresponding
10410   // implicitly-declared function would have been.
10411   switch (getSpecialMember(MD)) {
10412   case CXXInvalid:
10413     break;
10414   case CXXDefaultConstructor:
10415     MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10416     break;
10417   case CXXCopyConstructor:
10418     MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10419     break;
10420   case CXXMoveConstructor:
10421     MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10422     break;
10423   case CXXCopyAssignment:
10424     MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10425     break;
10426   case CXXMoveAssignment:
10427     MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10428     break;
10429   case CXXDestructor:
10430     MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10431     break;
10432   }
10433 }
10434 
10435 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10436   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10437 
10438   if (MD) {
10439     if (MD->getParent()->isDependentType()) {
10440       MD->setDefaulted();
10441       MD->setExplicitlyDefaulted();
10442       return;
10443     }
10444 
10445     CXXSpecialMember Member = getSpecialMember(MD);
10446     if (Member == CXXInvalid) {
10447       Diag(DefaultLoc, diag::err_default_special_members);
10448       return;
10449     }
10450 
10451     MD->setDefaulted();
10452     MD->setExplicitlyDefaulted();
10453 
10454     // If this definition appears within the record, do the checking when
10455     // the record is complete.
10456     const FunctionDecl *Primary = MD;
10457     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
10458       // Find the uninstantiated declaration that actually had the '= default'
10459       // on it.
10460       Pattern->isDefined(Primary);
10461 
10462     if (Primary == Primary->getCanonicalDecl())
10463       return;
10464 
10465     CheckExplicitlyDefaultedSpecialMember(MD);
10466 
10467     switch (Member) {
10468     case CXXDefaultConstructor: {
10469       CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10470       if (!CD->isInvalidDecl())
10471         DefineImplicitDefaultConstructor(DefaultLoc, CD);
10472       break;
10473     }
10474 
10475     case CXXCopyConstructor: {
10476       CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10477       if (!CD->isInvalidDecl())
10478         DefineImplicitCopyConstructor(DefaultLoc, CD);
10479       break;
10480     }
10481 
10482     case CXXCopyAssignment: {
10483       if (!MD->isInvalidDecl())
10484         DefineImplicitCopyAssignment(DefaultLoc, MD);
10485       break;
10486     }
10487 
10488     case CXXDestructor: {
10489       CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10490       if (!DD->isInvalidDecl())
10491         DefineImplicitDestructor(DefaultLoc, DD);
10492       break;
10493     }
10494 
10495     case CXXMoveConstructor: {
10496       CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10497       if (!CD->isInvalidDecl())
10498         DefineImplicitMoveConstructor(DefaultLoc, CD);
10499       break;
10500     }
10501 
10502     case CXXMoveAssignment: {
10503       if (!MD->isInvalidDecl())
10504         DefineImplicitMoveAssignment(DefaultLoc, MD);
10505       break;
10506     }
10507 
10508     case CXXInvalid:
10509       llvm_unreachable("Invalid special member.");
10510     }
10511   } else {
10512     Diag(DefaultLoc, diag::err_default_special_members);
10513   }
10514 }
10515 
10516 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
10517   for (Stmt::child_range CI = S->children(); CI; ++CI) {
10518     Stmt *SubStmt = *CI;
10519     if (!SubStmt)
10520       continue;
10521     if (isa<ReturnStmt>(SubStmt))
10522       Self.Diag(SubStmt->getLocStart(),
10523            diag::err_return_in_constructor_handler);
10524     if (!isa<Expr>(SubStmt))
10525       SearchForReturnInStmt(Self, SubStmt);
10526   }
10527 }
10528 
10529 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10530   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10531     CXXCatchStmt *Handler = TryBlock->getHandler(I);
10532     SearchForReturnInStmt(*this, Handler);
10533   }
10534 }
10535 
10536 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
10537                                              const CXXMethodDecl *Old) {
10538   QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10539   QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
10540 
10541   if (Context.hasSameType(NewTy, OldTy) ||
10542       NewTy->isDependentType() || OldTy->isDependentType())
10543     return false;
10544 
10545   // Check if the return types are covariant
10546   QualType NewClassTy, OldClassTy;
10547 
10548   /// Both types must be pointers or references to classes.
10549   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10550     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
10551       NewClassTy = NewPT->getPointeeType();
10552       OldClassTy = OldPT->getPointeeType();
10553     }
10554   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10555     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10556       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10557         NewClassTy = NewRT->getPointeeType();
10558         OldClassTy = OldRT->getPointeeType();
10559       }
10560     }
10561   }
10562 
10563   // The return types aren't either both pointers or references to a class type.
10564   if (NewClassTy.isNull()) {
10565     Diag(New->getLocation(),
10566          diag::err_different_return_type_for_overriding_virtual_function)
10567       << New->getDeclName() << NewTy << OldTy;
10568     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10569 
10570     return true;
10571   }
10572 
10573   // C++ [class.virtual]p6:
10574   //   If the return type of D::f differs from the return type of B::f, the
10575   //   class type in the return type of D::f shall be complete at the point of
10576   //   declaration of D::f or shall be the class type D.
10577   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10578     if (!RT->isBeingDefined() &&
10579         RequireCompleteType(New->getLocation(), NewClassTy,
10580                             diag::err_covariant_return_incomplete,
10581                             New->getDeclName()))
10582     return true;
10583   }
10584 
10585   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
10586     // Check if the new class derives from the old class.
10587     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10588       Diag(New->getLocation(),
10589            diag::err_covariant_return_not_derived)
10590       << New->getDeclName() << NewTy << OldTy;
10591       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10592       return true;
10593     }
10594 
10595     // Check if we the conversion from derived to base is valid.
10596     if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
10597                     diag::err_covariant_return_inaccessible_base,
10598                     diag::err_covariant_return_ambiguous_derived_to_base_conv,
10599                     // FIXME: Should this point to the return type?
10600                     New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
10601       // FIXME: this note won't trigger for delayed access control
10602       // diagnostics, and it's impossible to get an undelayed error
10603       // here from access control during the original parse because
10604       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
10605       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10606       return true;
10607     }
10608   }
10609 
10610   // The qualifiers of the return types must be the same.
10611   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
10612     Diag(New->getLocation(),
10613          diag::err_covariant_return_type_different_qualifications)
10614     << New->getDeclName() << NewTy << OldTy;
10615     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10616     return true;
10617   };
10618 
10619 
10620   // The new class type must have the same or less qualifiers as the old type.
10621   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10622     Diag(New->getLocation(),
10623          diag::err_covariant_return_type_class_type_more_qualified)
10624     << New->getDeclName() << NewTy << OldTy;
10625     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10626     return true;
10627   };
10628 
10629   return false;
10630 }
10631 
10632 /// \brief Mark the given method pure.
10633 ///
10634 /// \param Method the method to be marked pure.
10635 ///
10636 /// \param InitRange the source range that covers the "0" initializer.
10637 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
10638   SourceLocation EndLoc = InitRange.getEnd();
10639   if (EndLoc.isValid())
10640     Method->setRangeEnd(EndLoc);
10641 
10642   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10643     Method->setPure();
10644     return false;
10645   }
10646 
10647   if (!Method->isInvalidDecl())
10648     Diag(Method->getLocation(), diag::err_non_virtual_pure)
10649       << Method->getDeclName() << InitRange;
10650   return true;
10651 }
10652 
10653 /// \brief Determine whether the given declaration is a static data member.
10654 static bool isStaticDataMember(Decl *D) {
10655   VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10656   if (!Var)
10657     return false;
10658 
10659   return Var->isStaticDataMember();
10660 }
10661 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10662 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
10663 /// is a fresh scope pushed for just this purpose.
10664 ///
10665 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10666 /// static data member of class X, names should be looked up in the scope of
10667 /// class X.
10668 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
10669   // If there is no declaration, there was an error parsing it.
10670   if (D == 0 || D->isInvalidDecl()) return;
10671 
10672   // We should only get called for declarations with scope specifiers, like:
10673   //   int foo::bar;
10674   assert(D->isOutOfLine());
10675   EnterDeclaratorContext(S, D->getDeclContext());
10676 
10677   // If we are parsing the initializer for a static data member, push a
10678   // new expression evaluation context that is associated with this static
10679   // data member.
10680   if (isStaticDataMember(D))
10681     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
10682 }
10683 
10684 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
10685 /// initializer for the out-of-line declaration 'D'.
10686 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
10687   // If there is no declaration, there was an error parsing it.
10688   if (D == 0 || D->isInvalidDecl()) return;
10689 
10690   if (isStaticDataMember(D))
10691     PopExpressionEvaluationContext();
10692 
10693   assert(D->isOutOfLine());
10694   ExitDeclaratorContext(S);
10695 }
10696 
10697 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10698 /// C++ if/switch/while/for statement.
10699 /// e.g: "if (int x = f()) {...}"
10700 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
10701   // C++ 6.4p2:
10702   // The declarator shall not specify a function or an array.
10703   // The type-specifier-seq shall not contain typedef and shall not declare a
10704   // new class or enumeration.
10705   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10706          "Parser allowed 'typedef' as storage class of condition decl.");
10707 
10708   Decl *Dcl = ActOnDeclarator(S, D);
10709   if (!Dcl)
10710     return true;
10711 
10712   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10713     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
10714       << D.getSourceRange();
10715     return true;
10716   }
10717 
10718   return Dcl;
10719 }
10720 
10721 void Sema::LoadExternalVTableUses() {
10722   if (!ExternalSource)
10723     return;
10724 
10725   SmallVector<ExternalVTableUse, 4> VTables;
10726   ExternalSource->ReadUsedVTables(VTables);
10727   SmallVector<VTableUse, 4> NewUses;
10728   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10729     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10730       = VTablesUsed.find(VTables[I].Record);
10731     // Even if a definition wasn't required before, it may be required now.
10732     if (Pos != VTablesUsed.end()) {
10733       if (!Pos->second && VTables[I].DefinitionRequired)
10734         Pos->second = true;
10735       continue;
10736     }
10737 
10738     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10739     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10740   }
10741 
10742   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10743 }
10744 
10745 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10746                           bool DefinitionRequired) {
10747   // Ignore any vtable uses in unevaluated operands or for classes that do
10748   // not have a vtable.
10749   if (!Class->isDynamicClass() || Class->isDependentContext() ||
10750       CurContext->isDependentContext() ||
10751       ExprEvalContexts.back().Context == Unevaluated)
10752     return;
10753 
10754   // Try to insert this class into the map.
10755   LoadExternalVTableUses();
10756   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10757   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10758     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10759   if (!Pos.second) {
10760     // If we already had an entry, check to see if we are promoting this vtable
10761     // to required a definition. If so, we need to reappend to the VTableUses
10762     // list, since we may have already processed the first entry.
10763     if (DefinitionRequired && !Pos.first->second) {
10764       Pos.first->second = true;
10765     } else {
10766       // Otherwise, we can early exit.
10767       return;
10768     }
10769   }
10770 
10771   // Local classes need to have their virtual members marked
10772   // immediately. For all other classes, we mark their virtual members
10773   // at the end of the translation unit.
10774   if (Class->isLocalClass())
10775     MarkVirtualMembersReferenced(Loc, Class);
10776   else
10777     VTableUses.push_back(std::make_pair(Class, Loc));
10778 }
10779 
10780 bool Sema::DefineUsedVTables() {
10781   LoadExternalVTableUses();
10782   if (VTableUses.empty())
10783     return false;
10784 
10785   // Note: The VTableUses vector could grow as a result of marking
10786   // the members of a class as "used", so we check the size each
10787   // time through the loop and prefer indices (which are stable) to
10788   // iterators (which are not).
10789   bool DefinedAnything = false;
10790   for (unsigned I = 0; I != VTableUses.size(); ++I) {
10791     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
10792     if (!Class)
10793       continue;
10794 
10795     SourceLocation Loc = VTableUses[I].second;
10796 
10797     bool DefineVTable = true;
10798 
10799     // If this class has a key function, but that key function is
10800     // defined in another translation unit, we don't need to emit the
10801     // vtable even though we're using it.
10802     const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
10803     if (KeyFunction && !KeyFunction->hasBody()) {
10804       switch (KeyFunction->getTemplateSpecializationKind()) {
10805       case TSK_Undeclared:
10806       case TSK_ExplicitSpecialization:
10807       case TSK_ExplicitInstantiationDeclaration:
10808         // The key function is in another translation unit.
10809         DefineVTable = false;
10810         break;
10811 
10812       case TSK_ExplicitInstantiationDefinition:
10813       case TSK_ImplicitInstantiation:
10814         // We will be instantiating the key function.
10815         break;
10816       }
10817     } else if (!KeyFunction) {
10818       // If we have a class with no key function that is the subject
10819       // of an explicit instantiation declaration, suppress the
10820       // vtable; it will live with the explicit instantiation
10821       // definition.
10822       bool IsExplicitInstantiationDeclaration
10823         = Class->getTemplateSpecializationKind()
10824                                       == TSK_ExplicitInstantiationDeclaration;
10825       for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10826                                  REnd = Class->redecls_end();
10827            R != REnd; ++R) {
10828         TemplateSpecializationKind TSK
10829           = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10830         if (TSK == TSK_ExplicitInstantiationDeclaration)
10831           IsExplicitInstantiationDeclaration = true;
10832         else if (TSK == TSK_ExplicitInstantiationDefinition) {
10833           IsExplicitInstantiationDeclaration = false;
10834           break;
10835         }
10836       }
10837 
10838       if (IsExplicitInstantiationDeclaration)
10839         DefineVTable = false;
10840     }
10841 
10842     // The exception specifications for all virtual members may be needed even
10843     // if we are not providing an authoritative form of the vtable in this TU.
10844     // We may choose to emit it available_externally anyway.
10845     if (!DefineVTable) {
10846       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
10847       continue;
10848     }
10849 
10850     // Mark all of the virtual members of this class as referenced, so
10851     // that we can build a vtable. Then, tell the AST consumer that a
10852     // vtable for this class is required.
10853     DefinedAnything = true;
10854     MarkVirtualMembersReferenced(Loc, Class);
10855     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10856     Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10857 
10858     // Optionally warn if we're emitting a weak vtable.
10859     if (Class->getLinkage() == ExternalLinkage &&
10860         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
10861       const FunctionDecl *KeyFunctionDef = 0;
10862       if (!KeyFunction ||
10863           (KeyFunction->hasBody(KeyFunctionDef) &&
10864            KeyFunctionDef->isInlined()))
10865         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10866              TSK_ExplicitInstantiationDefinition
10867              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10868           << Class;
10869     }
10870   }
10871   VTableUses.clear();
10872 
10873   return DefinedAnything;
10874 }
10875 
10876 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
10877                                                  const CXXRecordDecl *RD) {
10878   for (CXXRecordDecl::method_iterator I = RD->method_begin(),
10879                                       E = RD->method_end(); I != E; ++I)
10880     if ((*I)->isVirtual() && !(*I)->isPure())
10881       ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
10882 }
10883 
10884 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10885                                         const CXXRecordDecl *RD) {
10886   // Mark all functions which will appear in RD's vtable as used.
10887   CXXFinalOverriderMap FinalOverriders;
10888   RD->getFinalOverriders(FinalOverriders);
10889   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
10890                                             E = FinalOverriders.end();
10891        I != E; ++I) {
10892     for (OverridingMethods::const_iterator OI = I->second.begin(),
10893                                            OE = I->second.end();
10894          OI != OE; ++OI) {
10895       assert(OI->second.size() > 0 && "no final overrider");
10896       CXXMethodDecl *Overrider = OI->second.front().Method;
10897 
10898       // C++ [basic.def.odr]p2:
10899       //   [...] A virtual member function is used if it is not pure. [...]
10900       if (!Overrider->isPure())
10901         MarkFunctionReferenced(Loc, Overrider);
10902     }
10903   }
10904 
10905   // Only classes that have virtual bases need a VTT.
10906   if (RD->getNumVBases() == 0)
10907     return;
10908 
10909   for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10910            e = RD->bases_end(); i != e; ++i) {
10911     const CXXRecordDecl *Base =
10912         cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
10913     if (Base->getNumVBases() == 0)
10914       continue;
10915     MarkVirtualMembersReferenced(Loc, Base);
10916   }
10917 }
10918 
10919 /// SetIvarInitializers - This routine builds initialization ASTs for the
10920 /// Objective-C implementation whose ivars need be initialized.
10921 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10922   if (!getLangOpts().CPlusPlus)
10923     return;
10924   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
10925     SmallVector<ObjCIvarDecl*, 8> ivars;
10926     CollectIvarsToConstructOrDestruct(OID, ivars);
10927     if (ivars.empty())
10928       return;
10929     SmallVector<CXXCtorInitializer*, 32> AllToInit;
10930     for (unsigned i = 0; i < ivars.size(); i++) {
10931       FieldDecl *Field = ivars[i];
10932       if (Field->isInvalidDecl())
10933         continue;
10934 
10935       CXXCtorInitializer *Member;
10936       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10937       InitializationKind InitKind =
10938         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10939 
10940       InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
10941       ExprResult MemberInit =
10942         InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
10943       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
10944       // Note, MemberInit could actually come back empty if no initialization
10945       // is required (e.g., because it would call a trivial default constructor)
10946       if (!MemberInit.get() || MemberInit.isInvalid())
10947         continue;
10948 
10949       Member =
10950         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10951                                          SourceLocation(),
10952                                          MemberInit.takeAs<Expr>(),
10953                                          SourceLocation());
10954       AllToInit.push_back(Member);
10955 
10956       // Be sure that the destructor is accessible and is marked as referenced.
10957       if (const RecordType *RecordTy
10958                   = Context.getBaseElementType(Field->getType())
10959                                                         ->getAs<RecordType>()) {
10960                     CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
10961         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
10962           MarkFunctionReferenced(Field->getLocation(), Destructor);
10963           CheckDestructorAccess(Field->getLocation(), Destructor,
10964                             PDiag(diag::err_access_dtor_ivar)
10965                               << Context.getBaseElementType(Field->getType()));
10966         }
10967       }
10968     }
10969     ObjCImplementation->setIvarInitializers(Context,
10970                                             AllToInit.data(), AllToInit.size());
10971   }
10972 }
10973 
10974 static
10975 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10976                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10977                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10978                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10979                            Sema &S) {
10980   llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10981                                                    CE = Current.end();
10982   if (Ctor->isInvalidDecl())
10983     return;
10984 
10985   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
10986 
10987   // Target may not be determinable yet, for instance if this is a dependent
10988   // call in an uninstantiated template.
10989   if (Target) {
10990     const FunctionDecl *FNTarget = 0;
10991     (void)Target->hasBody(FNTarget);
10992     Target = const_cast<CXXConstructorDecl*>(
10993       cast_or_null<CXXConstructorDecl>(FNTarget));
10994   }
10995 
10996   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10997                      // Avoid dereferencing a null pointer here.
10998                      *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10999 
11000   if (!Current.insert(Canonical))
11001     return;
11002 
11003   // We know that beyond here, we aren't chaining into a cycle.
11004   if (!Target || !Target->isDelegatingConstructor() ||
11005       Target->isInvalidDecl() || Valid.count(TCanonical)) {
11006     for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11007       Valid.insert(*CI);
11008     Current.clear();
11009   // We've hit a cycle.
11010   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11011              Current.count(TCanonical)) {
11012     // If we haven't diagnosed this cycle yet, do so now.
11013     if (!Invalid.count(TCanonical)) {
11014       S.Diag((*Ctor->init_begin())->getSourceLocation(),
11015              diag::warn_delegating_ctor_cycle)
11016         << Ctor;
11017 
11018       // Don't add a note for a function delegating directly to itself.
11019       if (TCanonical != Canonical)
11020         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11021 
11022       CXXConstructorDecl *C = Target;
11023       while (C->getCanonicalDecl() != Canonical) {
11024         const FunctionDecl *FNTarget = 0;
11025         (void)C->getTargetConstructor()->hasBody(FNTarget);
11026         assert(FNTarget && "Ctor cycle through bodiless function");
11027 
11028         C = const_cast<CXXConstructorDecl*>(
11029           cast<CXXConstructorDecl>(FNTarget));
11030         S.Diag(C->getLocation(), diag::note_which_delegates_to);
11031       }
11032     }
11033 
11034     for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11035       Invalid.insert(*CI);
11036     Current.clear();
11037   } else {
11038     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11039   }
11040 }
11041 
11042 
11043 void Sema::CheckDelegatingCtorCycles() {
11044   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11045 
11046   llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11047                                                    CE = Current.end();
11048 
11049   for (DelegatingCtorDeclsType::iterator
11050          I = DelegatingCtorDecls.begin(ExternalSource),
11051          E = DelegatingCtorDecls.end();
11052        I != E; ++I)
11053     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
11054 
11055   for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11056     (*CI)->setInvalidDecl();
11057 }
11058 
11059 namespace {
11060   /// \brief AST visitor that finds references to the 'this' expression.
11061   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11062     Sema &S;
11063 
11064   public:
11065     explicit FindCXXThisExpr(Sema &S) : S(S) { }
11066 
11067     bool VisitCXXThisExpr(CXXThisExpr *E) {
11068       S.Diag(E->getLocation(), diag::err_this_static_member_func)
11069         << E->isImplicit();
11070       return false;
11071     }
11072   };
11073 }
11074 
11075 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11076   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11077   if (!TSInfo)
11078     return false;
11079 
11080   TypeLoc TL = TSInfo->getTypeLoc();
11081   FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11082   if (!ProtoTL)
11083     return false;
11084 
11085   // C++11 [expr.prim.general]p3:
11086   //   [The expression this] shall not appear before the optional
11087   //   cv-qualifier-seq and it shall not appear within the declaration of a
11088   //   static member function (although its type and value category are defined
11089   //   within a static member function as they are within a non-static member
11090   //   function). [ Note: this is because declaration matching does not occur
11091   //  until the complete declarator is known. - end note ]
11092   const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11093   FindCXXThisExpr Finder(*this);
11094 
11095   // If the return type came after the cv-qualifier-seq, check it now.
11096   if (Proto->hasTrailingReturn() &&
11097       !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11098     return true;
11099 
11100   // Check the exception specification.
11101   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11102     return true;
11103 
11104   return checkThisInStaticMemberFunctionAttributes(Method);
11105 }
11106 
11107 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11108   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11109   if (!TSInfo)
11110     return false;
11111 
11112   TypeLoc TL = TSInfo->getTypeLoc();
11113   FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11114   if (!ProtoTL)
11115     return false;
11116 
11117   const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11118   FindCXXThisExpr Finder(*this);
11119 
11120   switch (Proto->getExceptionSpecType()) {
11121   case EST_Uninstantiated:
11122   case EST_Unevaluated:
11123   case EST_BasicNoexcept:
11124   case EST_DynamicNone:
11125   case EST_MSAny:
11126   case EST_None:
11127     break;
11128 
11129   case EST_ComputedNoexcept:
11130     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11131       return true;
11132 
11133   case EST_Dynamic:
11134     for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
11135          EEnd = Proto->exception_end();
11136          E != EEnd; ++E) {
11137       if (!Finder.TraverseType(*E))
11138         return true;
11139     }
11140     break;
11141   }
11142 
11143   return false;
11144 }
11145 
11146 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11147   FindCXXThisExpr Finder(*this);
11148 
11149   // Check attributes.
11150   for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11151        A != AEnd; ++A) {
11152     // FIXME: This should be emitted by tblgen.
11153     Expr *Arg = 0;
11154     ArrayRef<Expr *> Args;
11155     if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11156       Arg = G->getArg();
11157     else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11158       Arg = G->getArg();
11159     else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11160       Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11161     else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11162       Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11163     else if (ExclusiveLockFunctionAttr *ELF
11164                = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11165       Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11166     else if (SharedLockFunctionAttr *SLF
11167                = dyn_cast<SharedLockFunctionAttr>(*A))
11168       Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11169     else if (ExclusiveTrylockFunctionAttr *ETLF
11170                = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11171       Arg = ETLF->getSuccessValue();
11172       Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11173     } else if (SharedTrylockFunctionAttr *STLF
11174                  = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11175       Arg = STLF->getSuccessValue();
11176       Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11177     } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11178       Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11179     else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11180       Arg = LR->getArg();
11181     else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11182       Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11183     else if (ExclusiveLocksRequiredAttr *ELR
11184                = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11185       Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11186     else if (SharedLocksRequiredAttr *SLR
11187                = dyn_cast<SharedLocksRequiredAttr>(*A))
11188       Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11189 
11190     if (Arg && !Finder.TraverseStmt(Arg))
11191       return true;
11192 
11193     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11194       if (!Finder.TraverseStmt(Args[I]))
11195         return true;
11196     }
11197   }
11198 
11199   return false;
11200 }
11201 
11202 void
11203 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11204                                   ArrayRef<ParsedType> DynamicExceptions,
11205                                   ArrayRef<SourceRange> DynamicExceptionRanges,
11206                                   Expr *NoexceptExpr,
11207                                   llvm::SmallVectorImpl<QualType> &Exceptions,
11208                                   FunctionProtoType::ExtProtoInfo &EPI) {
11209   Exceptions.clear();
11210   EPI.ExceptionSpecType = EST;
11211   if (EST == EST_Dynamic) {
11212     Exceptions.reserve(DynamicExceptions.size());
11213     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11214       // FIXME: Preserve type source info.
11215       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11216 
11217       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11218       collectUnexpandedParameterPacks(ET, Unexpanded);
11219       if (!Unexpanded.empty()) {
11220         DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11221                                          UPPC_ExceptionType,
11222                                          Unexpanded);
11223         continue;
11224       }
11225 
11226       // Check that the type is valid for an exception spec, and
11227       // drop it if not.
11228       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11229         Exceptions.push_back(ET);
11230     }
11231     EPI.NumExceptions = Exceptions.size();
11232     EPI.Exceptions = Exceptions.data();
11233     return;
11234   }
11235 
11236   if (EST == EST_ComputedNoexcept) {
11237     // If an error occurred, there's no expression here.
11238     if (NoexceptExpr) {
11239       assert((NoexceptExpr->isTypeDependent() ||
11240               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11241               Context.BoolTy) &&
11242              "Parser should have made sure that the expression is boolean");
11243       if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11244         EPI.ExceptionSpecType = EST_BasicNoexcept;
11245         return;
11246       }
11247 
11248       if (!NoexceptExpr->isValueDependent())
11249         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
11250                          diag::err_noexcept_needs_constant_expression,
11251                          /*AllowFold*/ false).take();
11252       EPI.NoexceptExpr = NoexceptExpr;
11253     }
11254     return;
11255   }
11256 }
11257 
11258 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11259 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11260   // Implicitly declared functions (e.g. copy constructors) are
11261   // __host__ __device__
11262   if (D->isImplicit())
11263     return CFT_HostDevice;
11264 
11265   if (D->hasAttr<CUDAGlobalAttr>())
11266     return CFT_Global;
11267 
11268   if (D->hasAttr<CUDADeviceAttr>()) {
11269     if (D->hasAttr<CUDAHostAttr>())
11270       return CFT_HostDevice;
11271     else
11272       return CFT_Device;
11273   }
11274 
11275   return CFT_Host;
11276 }
11277 
11278 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11279                            CUDAFunctionTarget CalleeTarget) {
11280   // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11281   // Callable from the device only."
11282   if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11283     return true;
11284 
11285   // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11286   // Callable from the host only."
11287   // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11288   // Callable from the host only."
11289   if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11290       (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11291     return true;
11292 
11293   if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11294     return true;
11295 
11296   return false;
11297 }
11298