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/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/DeclVisitor.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/RecursiveASTVisitor.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/AST/TypeOrdering.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/LiteralSupport.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/CXXFieldCollector.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/Initialization.h"
36 #include "clang/Sema/Lookup.h"
37 #include "clang/Sema/ParsedTemplate.h"
38 #include "clang/Sema/Scope.h"
39 #include "clang/Sema/ScopeInfo.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include <map>
43 #include <set>
44 
45 using namespace clang;
46 
47 //===----------------------------------------------------------------------===//
48 // CheckDefaultArgumentVisitor
49 //===----------------------------------------------------------------------===//
50 
51 namespace {
52   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53   /// the default argument of a parameter to determine whether it
54   /// contains any ill-formed subexpressions. For example, this will
55   /// diagnose the use of local variables or parameters within the
56   /// default argument expression.
57   class CheckDefaultArgumentVisitor
58     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
59     Expr *DefaultArg;
60     Sema *S;
61 
62   public:
63     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
64       : DefaultArg(defarg), S(s) {}
65 
66     bool VisitExpr(Expr *Node);
67     bool VisitDeclRefExpr(DeclRefExpr *DRE);
68     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
69     bool VisitLambdaExpr(LambdaExpr *Lambda);
70     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
71   };
72 
73   /// VisitExpr - Visit all of the children of this expression.
74   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75     bool IsInvalid = false;
76     for (Stmt::child_range I = Node->children(); I; ++I)
77       IsInvalid |= Visit(*I);
78     return IsInvalid;
79   }
80 
81   /// VisitDeclRefExpr - Visit a reference to a declaration, to
82   /// determine whether this declaration can be used in the default
83   /// argument expression.
84   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
85     NamedDecl *Decl = DRE->getDecl();
86     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87       // C++ [dcl.fct.default]p9
88       //   Default arguments are evaluated each time the function is
89       //   called. The order of evaluation of function arguments is
90       //   unspecified. Consequently, parameters of a function shall not
91       //   be used in default argument expressions, even if they are not
92       //   evaluated. Parameters of a function declared before a default
93       //   argument expression are in scope and can hide namespace and
94       //   class member names.
95       return S->Diag(DRE->getLocStart(),
96                      diag::err_param_default_argument_references_param)
97          << Param->getDeclName() << DefaultArg->getSourceRange();
98     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
99       // C++ [dcl.fct.default]p7
100       //   Local variables shall not be used in default argument
101       //   expressions.
102       if (VDecl->isLocalVarDecl())
103         return S->Diag(DRE->getLocStart(),
104                        diag::err_param_default_argument_references_local)
105           << VDecl->getDeclName() << DefaultArg->getSourceRange();
106     }
107 
108     return false;
109   }
110 
111   /// VisitCXXThisExpr - Visit a C++ "this" expression.
112   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113     // C++ [dcl.fct.default]p8:
114     //   The keyword this shall not be used in a default argument of a
115     //   member function.
116     return S->Diag(ThisE->getLocStart(),
117                    diag::err_param_default_argument_references_this)
118                << ThisE->getSourceRange();
119   }
120 
121   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122     bool Invalid = false;
123     for (PseudoObjectExpr::semantics_iterator
124            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125       Expr *E = *i;
126 
127       // Look through bindings.
128       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129         E = OVE->getSourceExpr();
130         assert(E && "pseudo-object binding without source expression?");
131       }
132 
133       Invalid |= Visit(E);
134     }
135     return Invalid;
136   }
137 
138   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139     // C++11 [expr.lambda.prim]p13:
140     //   A lambda-expression appearing in a default argument shall not
141     //   implicitly or explicitly capture any entity.
142     if (Lambda->capture_begin() == Lambda->capture_end())
143       return false;
144 
145     return S->Diag(Lambda->getLocStart(),
146                    diag::err_lambda_capture_default_arg);
147   }
148 }
149 
150 void
151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152                                                  const CXXMethodDecl *Method) {
153   // If we have an MSAny spec already, don't bother.
154   if (!Method || ComputedEST == EST_MSAny)
155     return;
156 
157   const FunctionProtoType *Proto
158     = Method->getType()->getAs<FunctionProtoType>();
159   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160   if (!Proto)
161     return;
162 
163   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164 
165   // If this function can throw any exceptions, make a note of that.
166   if (EST == EST_MSAny || EST == EST_None) {
167     ClearExceptions();
168     ComputedEST = EST;
169     return;
170   }
171 
172   // FIXME: If the call to this decl is using any of its default arguments, we
173   // need to search them for potentially-throwing calls.
174 
175   // If this function has a basic noexcept, it doesn't affect the outcome.
176   if (EST == EST_BasicNoexcept)
177     return;
178 
179   // If we have a throw-all spec at this point, ignore the function.
180   if (ComputedEST == EST_None)
181     return;
182 
183   // If we're still at noexcept(true) and there's a nothrow() callee,
184   // change to that specification.
185   if (EST == EST_DynamicNone) {
186     if (ComputedEST == EST_BasicNoexcept)
187       ComputedEST = EST_DynamicNone;
188     return;
189   }
190 
191   // Check out noexcept specs.
192   if (EST == EST_ComputedNoexcept) {
193     FunctionProtoType::NoexceptResult NR =
194         Proto->getNoexceptSpec(Self->Context);
195     assert(NR != FunctionProtoType::NR_NoNoexcept &&
196            "Must have noexcept result for EST_ComputedNoexcept.");
197     assert(NR != FunctionProtoType::NR_Dependent &&
198            "Should not generate implicit declarations for dependent cases, "
199            "and don't know how to handle them anyway.");
200 
201     // noexcept(false) -> no spec on the new function
202     if (NR == FunctionProtoType::NR_Throw) {
203       ClearExceptions();
204       ComputedEST = EST_None;
205     }
206     // noexcept(true) won't change anything either.
207     return;
208   }
209 
210   assert(EST == EST_Dynamic && "EST case not considered earlier.");
211   assert(ComputedEST != EST_None &&
212          "Shouldn't collect exceptions when throw-all is guaranteed.");
213   ComputedEST = EST_Dynamic;
214   // Record the exceptions in this function's exception specification.
215   for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
216                                           EEnd = Proto->exception_end();
217        E != EEnd; ++E)
218     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
219       Exceptions.push_back(*E);
220 }
221 
222 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
223   if (!E || ComputedEST == EST_MSAny)
224     return;
225 
226   // FIXME:
227   //
228   // C++0x [except.spec]p14:
229   //   [An] implicit exception-specification specifies the type-id T if and
230   // only if T is allowed by the exception-specification of a function directly
231   // invoked by f's implicit definition; f shall allow all exceptions if any
232   // function it directly invokes allows all exceptions, and f shall allow no
233   // exceptions if every function it directly invokes allows no exceptions.
234   //
235   // Note in particular that if an implicit exception-specification is generated
236   // for a function containing a throw-expression, that specification can still
237   // be noexcept(true).
238   //
239   // Note also that 'directly invoked' is not defined in the standard, and there
240   // is no indication that we should only consider potentially-evaluated calls.
241   //
242   // Ultimately we should implement the intent of the standard: the exception
243   // specification should be the set of exceptions which can be thrown by the
244   // implicit definition. For now, we assume that any non-nothrow expression can
245   // throw any exception.
246 
247   if (Self->canThrow(E))
248     ComputedEST = EST_None;
249 }
250 
251 bool
252 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
253                               SourceLocation EqualLoc) {
254   if (RequireCompleteType(Param->getLocation(), Param->getType(),
255                           diag::err_typecheck_decl_incomplete_type)) {
256     Param->setInvalidDecl();
257     return true;
258   }
259 
260   // C++ [dcl.fct.default]p5
261   //   A default argument expression is implicitly converted (clause
262   //   4) to the parameter type. The default argument expression has
263   //   the same semantic constraints as the initializer expression in
264   //   a declaration of a variable of the parameter type, using the
265   //   copy-initialization semantics (8.5).
266   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
267                                                                     Param);
268   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
269                                                            EqualLoc);
270   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
271   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
272   if (Result.isInvalid())
273     return true;
274   Arg = Result.takeAs<Expr>();
275 
276   CheckCompletedExpr(Arg, EqualLoc);
277   Arg = MaybeCreateExprWithCleanups(Arg);
278 
279   // Okay: add the default argument to the parameter
280   Param->setDefaultArg(Arg);
281 
282   // We have already instantiated this parameter; provide each of the
283   // instantiations with the uninstantiated default argument.
284   UnparsedDefaultArgInstantiationsMap::iterator InstPos
285     = UnparsedDefaultArgInstantiations.find(Param);
286   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
287     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
288       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
289 
290     // We're done tracking this parameter's instantiations.
291     UnparsedDefaultArgInstantiations.erase(InstPos);
292   }
293 
294   return false;
295 }
296 
297 /// ActOnParamDefaultArgument - Check whether the default argument
298 /// provided for a function parameter is well-formed. If so, attach it
299 /// to the parameter declaration.
300 void
301 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
302                                 Expr *DefaultArg) {
303   if (!param || !DefaultArg)
304     return;
305 
306   ParmVarDecl *Param = cast<ParmVarDecl>(param);
307   UnparsedDefaultArgLocs.erase(Param);
308 
309   // Default arguments are only permitted in C++
310   if (!getLangOpts().CPlusPlus) {
311     Diag(EqualLoc, diag::err_param_default_argument)
312       << DefaultArg->getSourceRange();
313     Param->setInvalidDecl();
314     return;
315   }
316 
317   // Check for unexpanded parameter packs.
318   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
319     Param->setInvalidDecl();
320     return;
321   }
322 
323   // Check that the default argument is well-formed
324   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
325   if (DefaultArgChecker.Visit(DefaultArg)) {
326     Param->setInvalidDecl();
327     return;
328   }
329 
330   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
331 }
332 
333 /// ActOnParamUnparsedDefaultArgument - We've seen a default
334 /// argument for a function parameter, but we can't parse it yet
335 /// because we're inside a class definition. Note that this default
336 /// argument will be parsed later.
337 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
338                                              SourceLocation EqualLoc,
339                                              SourceLocation ArgLoc) {
340   if (!param)
341     return;
342 
343   ParmVarDecl *Param = cast<ParmVarDecl>(param);
344   Param->setUnparsedDefaultArg();
345   UnparsedDefaultArgLocs[Param] = ArgLoc;
346 }
347 
348 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349 /// the default argument for the parameter param failed.
350 void Sema::ActOnParamDefaultArgumentError(Decl *param) {
351   if (!param)
352     return;
353 
354   ParmVarDecl *Param = cast<ParmVarDecl>(param);
355   Param->setInvalidDecl();
356   UnparsedDefaultArgLocs.erase(Param);
357 }
358 
359 /// CheckExtraCXXDefaultArguments - Check for any extra default
360 /// arguments in the declarator, which is not a function declaration
361 /// or definition and therefore is not permitted to have default
362 /// arguments. This routine should be invoked for every declarator
363 /// that is not a function declaration or definition.
364 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
365   // C++ [dcl.fct.default]p3
366   //   A default argument expression shall be specified only in the
367   //   parameter-declaration-clause of a function declaration or in a
368   //   template-parameter (14.1). It shall not be specified for a
369   //   parameter pack. If it is specified in a
370   //   parameter-declaration-clause, it shall not occur within a
371   //   declarator or abstract-declarator of a parameter-declaration.
372   bool MightBeFunction = D.isFunctionDeclarationContext();
373   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
374     DeclaratorChunk &chunk = D.getTypeObject(i);
375     if (chunk.Kind == DeclaratorChunk::Function) {
376       if (MightBeFunction) {
377         // This is a function declaration. It can have default arguments, but
378         // keep looking in case its return type is a function type with default
379         // arguments.
380         MightBeFunction = false;
381         continue;
382       }
383       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
384            ++argIdx) {
385         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
386         if (Param->hasUnparsedDefaultArg()) {
387           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
388           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
389             << SourceRange((*Toks)[1].getLocation(),
390                            Toks->back().getLocation());
391           delete Toks;
392           chunk.Fun.Params[argIdx].DefaultArgTokens = 0;
393         } else if (Param->getDefaultArg()) {
394           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
395             << Param->getDefaultArg()->getSourceRange();
396           Param->setDefaultArg(0);
397         }
398       }
399     } else if (chunk.Kind != DeclaratorChunk::Paren) {
400       MightBeFunction = false;
401     }
402   }
403 }
404 
405 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
406   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
407     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
408     if (!PVD->hasDefaultArg())
409       return false;
410     if (!PVD->hasInheritedDefaultArg())
411       return true;
412   }
413   return false;
414 }
415 
416 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
417 /// function, once we already know that they have the same
418 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
419 /// error, false otherwise.
420 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
421                                 Scope *S) {
422   bool Invalid = false;
423 
424   // C++ [dcl.fct.default]p4:
425   //   For non-template functions, default arguments can be added in
426   //   later declarations of a function in the same
427   //   scope. Declarations in different scopes have completely
428   //   distinct sets of default arguments. That is, declarations in
429   //   inner scopes do not acquire default arguments from
430   //   declarations in outer scopes, and vice versa. In a given
431   //   function declaration, all parameters subsequent to a
432   //   parameter with a default argument shall have default
433   //   arguments supplied in this or previous declarations. A
434   //   default argument shall not be redefined by a later
435   //   declaration (not even to the same value).
436   //
437   // C++ [dcl.fct.default]p6:
438   //   Except for member functions of class templates, the default arguments
439   //   in a member function definition that appears outside of the class
440   //   definition are added to the set of default arguments provided by the
441   //   member function declaration in the class definition.
442   for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
443     ParmVarDecl *OldParam = Old->getParamDecl(p);
444     ParmVarDecl *NewParam = New->getParamDecl(p);
445 
446     bool OldParamHasDfl = OldParam->hasDefaultArg();
447     bool NewParamHasDfl = NewParam->hasDefaultArg();
448 
449     NamedDecl *ND = Old;
450 
451     // The declaration context corresponding to the scope is the semantic
452     // parent, unless this is a local function declaration, in which case
453     // it is that surrounding function.
454     DeclContext *ScopeDC = New->getLexicalDeclContext();
455     if (!ScopeDC->isFunctionOrMethod())
456       ScopeDC = New->getDeclContext();
457     if (S && !isDeclInScope(ND, ScopeDC, S) &&
458         !New->getDeclContext()->isRecord())
459       // Ignore default parameters of old decl if they are not in
460       // the same scope and this is not an out-of-line definition of
461       // a member function.
462       OldParamHasDfl = false;
463 
464     if (OldParamHasDfl && NewParamHasDfl) {
465 
466       unsigned DiagDefaultParamID =
467         diag::err_param_default_argument_redefinition;
468 
469       // MSVC accepts that default parameters be redefined for member functions
470       // of template class. The new default parameter's value is ignored.
471       Invalid = true;
472       if (getLangOpts().MicrosoftExt) {
473         CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
474         if (MD && MD->getParent()->getDescribedClassTemplate()) {
475           // Merge the old default argument into the new parameter.
476           NewParam->setHasInheritedDefaultArg();
477           if (OldParam->hasUninstantiatedDefaultArg())
478             NewParam->setUninstantiatedDefaultArg(
479                                       OldParam->getUninstantiatedDefaultArg());
480           else
481             NewParam->setDefaultArg(OldParam->getInit());
482           DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
483           Invalid = false;
484         }
485       }
486 
487       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
488       // hint here. Alternatively, we could walk the type-source information
489       // for NewParam to find the last source location in the type... but it
490       // isn't worth the effort right now. This is the kind of test case that
491       // is hard to get right:
492       //   int f(int);
493       //   void g(int (*fp)(int) = f);
494       //   void g(int (*fp)(int) = &f);
495       Diag(NewParam->getLocation(), DiagDefaultParamID)
496         << NewParam->getDefaultArgRange();
497 
498       // Look for the function declaration where the default argument was
499       // actually written, which may be a declaration prior to Old.
500       for (FunctionDecl *Older = Old->getPreviousDecl();
501            Older; Older = Older->getPreviousDecl()) {
502         if (!Older->getParamDecl(p)->hasDefaultArg())
503           break;
504 
505         OldParam = Older->getParamDecl(p);
506       }
507 
508       Diag(OldParam->getLocation(), diag::note_previous_definition)
509         << OldParam->getDefaultArgRange();
510     } else if (OldParamHasDfl) {
511       // Merge the old default argument into the new parameter.
512       // It's important to use getInit() here;  getDefaultArg()
513       // strips off any top-level ExprWithCleanups.
514       NewParam->setHasInheritedDefaultArg();
515       if (OldParam->hasUninstantiatedDefaultArg())
516         NewParam->setUninstantiatedDefaultArg(
517                                       OldParam->getUninstantiatedDefaultArg());
518       else
519         NewParam->setDefaultArg(OldParam->getInit());
520     } else if (NewParamHasDfl) {
521       if (New->getDescribedFunctionTemplate()) {
522         // Paragraph 4, quoted above, only applies to non-template functions.
523         Diag(NewParam->getLocation(),
524              diag::err_param_default_argument_template_redecl)
525           << NewParam->getDefaultArgRange();
526         Diag(Old->getLocation(), diag::note_template_prev_declaration)
527           << false;
528       } else if (New->getTemplateSpecializationKind()
529                    != TSK_ImplicitInstantiation &&
530                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
531         // C++ [temp.expr.spec]p21:
532         //   Default function arguments shall not be specified in a declaration
533         //   or a definition for one of the following explicit specializations:
534         //     - the explicit specialization of a function template;
535         //     - the explicit specialization of a member function template;
536         //     - the explicit specialization of a member function of a class
537         //       template where the class template specialization to which the
538         //       member function specialization belongs is implicitly
539         //       instantiated.
540         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
541           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
542           << New->getDeclName()
543           << NewParam->getDefaultArgRange();
544       } else if (New->getDeclContext()->isDependentContext()) {
545         // C++ [dcl.fct.default]p6 (DR217):
546         //   Default arguments for a member function of a class template shall
547         //   be specified on the initial declaration of the member function
548         //   within the class template.
549         //
550         // Reading the tea leaves a bit in DR217 and its reference to DR205
551         // leads me to the conclusion that one cannot add default function
552         // arguments for an out-of-line definition of a member function of a
553         // dependent type.
554         int WhichKind = 2;
555         if (CXXRecordDecl *Record
556               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
557           if (Record->getDescribedClassTemplate())
558             WhichKind = 0;
559           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
560             WhichKind = 1;
561           else
562             WhichKind = 2;
563         }
564 
565         Diag(NewParam->getLocation(),
566              diag::err_param_default_argument_member_template_redecl)
567           << WhichKind
568           << NewParam->getDefaultArgRange();
569       }
570     }
571   }
572 
573   // DR1344: If a default argument is added outside a class definition and that
574   // default argument makes the function a special member function, the program
575   // is ill-formed. This can only happen for constructors.
576   if (isa<CXXConstructorDecl>(New) &&
577       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
578     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
579                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
580     if (NewSM != OldSM) {
581       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
582       assert(NewParam->hasDefaultArg());
583       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
584         << NewParam->getDefaultArgRange() << NewSM;
585       Diag(Old->getLocation(), diag::note_previous_declaration);
586     }
587   }
588 
589   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
590   // template has a constexpr specifier then all its declarations shall
591   // contain the constexpr specifier.
592   if (New->isConstexpr() != Old->isConstexpr()) {
593     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
594       << New << New->isConstexpr();
595     Diag(Old->getLocation(), diag::note_previous_declaration);
596     Invalid = true;
597   }
598 
599   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
600   // argument expression, that declaration shall be a definition and shall be
601   // the only declaration of the function or function template in the
602   // translation unit.
603   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
604       functionDeclHasDefaultArgument(Old)) {
605     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
606     Diag(Old->getLocation(), diag::note_previous_declaration);
607     Invalid = true;
608   }
609 
610   if (CheckEquivalentExceptionSpec(Old, New))
611     Invalid = true;
612 
613   return Invalid;
614 }
615 
616 /// \brief Merge the exception specifications of two variable declarations.
617 ///
618 /// This is called when there's a redeclaration of a VarDecl. The function
619 /// checks if the redeclaration might have an exception specification and
620 /// validates compatibility and merges the specs if necessary.
621 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
622   // Shortcut if exceptions are disabled.
623   if (!getLangOpts().CXXExceptions)
624     return;
625 
626   assert(Context.hasSameType(New->getType(), Old->getType()) &&
627          "Should only be called if types are otherwise the same.");
628 
629   QualType NewType = New->getType();
630   QualType OldType = Old->getType();
631 
632   // We're only interested in pointers and references to functions, as well
633   // as pointers to member functions.
634   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
635     NewType = R->getPointeeType();
636     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
637   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
638     NewType = P->getPointeeType();
639     OldType = OldType->getAs<PointerType>()->getPointeeType();
640   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
641     NewType = M->getPointeeType();
642     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
643   }
644 
645   if (!NewType->isFunctionProtoType())
646     return;
647 
648   // There's lots of special cases for functions. For function pointers, system
649   // libraries are hopefully not as broken so that we don't need these
650   // workarounds.
651   if (CheckEquivalentExceptionSpec(
652         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
653         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
654     New->setInvalidDecl();
655   }
656 }
657 
658 /// CheckCXXDefaultArguments - Verify that the default arguments for a
659 /// function declaration are well-formed according to C++
660 /// [dcl.fct.default].
661 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
662   unsigned NumParams = FD->getNumParams();
663   unsigned p;
664 
665   // Find first parameter with a default argument
666   for (p = 0; p < NumParams; ++p) {
667     ParmVarDecl *Param = FD->getParamDecl(p);
668     if (Param->hasDefaultArg())
669       break;
670   }
671 
672   // C++ [dcl.fct.default]p4:
673   //   In a given function declaration, all parameters
674   //   subsequent to a parameter with a default argument shall
675   //   have default arguments supplied in this or previous
676   //   declarations. A default argument shall not be redefined
677   //   by a later declaration (not even to the same value).
678   unsigned LastMissingDefaultArg = 0;
679   for (; p < NumParams; ++p) {
680     ParmVarDecl *Param = FD->getParamDecl(p);
681     if (!Param->hasDefaultArg()) {
682       if (Param->isInvalidDecl())
683         /* We already complained about this parameter. */;
684       else if (Param->getIdentifier())
685         Diag(Param->getLocation(),
686              diag::err_param_default_argument_missing_name)
687           << Param->getIdentifier();
688       else
689         Diag(Param->getLocation(),
690              diag::err_param_default_argument_missing);
691 
692       LastMissingDefaultArg = p;
693     }
694   }
695 
696   if (LastMissingDefaultArg > 0) {
697     // Some default arguments were missing. Clear out all of the
698     // default arguments up to (and including) the last missing
699     // default argument, so that we leave the function parameters
700     // in a semantically valid state.
701     for (p = 0; p <= LastMissingDefaultArg; ++p) {
702       ParmVarDecl *Param = FD->getParamDecl(p);
703       if (Param->hasDefaultArg()) {
704         Param->setDefaultArg(0);
705       }
706     }
707   }
708 }
709 
710 // CheckConstexprParameterTypes - Check whether a function's parameter types
711 // are all literal types. If so, return true. If not, produce a suitable
712 // diagnostic and return false.
713 static bool CheckConstexprParameterTypes(Sema &SemaRef,
714                                          const FunctionDecl *FD) {
715   unsigned ArgIndex = 0;
716   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
717   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
718                                               e = FT->param_type_end();
719        i != e; ++i, ++ArgIndex) {
720     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
721     SourceLocation ParamLoc = PD->getLocation();
722     if (!(*i)->isDependentType() &&
723         SemaRef.RequireLiteralType(ParamLoc, *i,
724                                    diag::err_constexpr_non_literal_param,
725                                    ArgIndex+1, PD->getSourceRange(),
726                                    isa<CXXConstructorDecl>(FD)))
727       return false;
728   }
729   return true;
730 }
731 
732 /// \brief Get diagnostic %select index for tag kind for
733 /// record diagnostic message.
734 /// WARNING: Indexes apply to particular diagnostics only!
735 ///
736 /// \returns diagnostic %select index.
737 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
738   switch (Tag) {
739   case TTK_Struct: return 0;
740   case TTK_Interface: return 1;
741   case TTK_Class:  return 2;
742   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
743   }
744 }
745 
746 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
747 // the requirements of a constexpr function definition or a constexpr
748 // constructor definition. If so, return true. If not, produce appropriate
749 // diagnostics and return false.
750 //
751 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
752 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
753   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
754   if (MD && MD->isInstance()) {
755     // C++11 [dcl.constexpr]p4:
756     //  The definition of a constexpr constructor shall satisfy the following
757     //  constraints:
758     //  - the class shall not have any virtual base classes;
759     const CXXRecordDecl *RD = MD->getParent();
760     if (RD->getNumVBases()) {
761       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
762         << isa<CXXConstructorDecl>(NewFD)
763         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
764       for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
765              E = RD->vbases_end(); I != E; ++I)
766         Diag(I->getLocStart(),
767              diag::note_constexpr_virtual_base_here) << I->getSourceRange();
768       return false;
769     }
770   }
771 
772   if (!isa<CXXConstructorDecl>(NewFD)) {
773     // C++11 [dcl.constexpr]p3:
774     //  The definition of a constexpr function shall satisfy the following
775     //  constraints:
776     // - it shall not be virtual;
777     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
778     if (Method && Method->isVirtual()) {
779       Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
780 
781       // If it's not obvious why this function is virtual, find an overridden
782       // function which uses the 'virtual' keyword.
783       const CXXMethodDecl *WrittenVirtual = Method;
784       while (!WrittenVirtual->isVirtualAsWritten())
785         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
786       if (WrittenVirtual != Method)
787         Diag(WrittenVirtual->getLocation(),
788              diag::note_overridden_virtual_function);
789       return false;
790     }
791 
792     // - its return type shall be a literal type;
793     QualType RT = NewFD->getReturnType();
794     if (!RT->isDependentType() &&
795         RequireLiteralType(NewFD->getLocation(), RT,
796                            diag::err_constexpr_non_literal_return))
797       return false;
798   }
799 
800   // - each of its parameter types shall be a literal type;
801   if (!CheckConstexprParameterTypes(*this, NewFD))
802     return false;
803 
804   return true;
805 }
806 
807 /// Check the given declaration statement is legal within a constexpr function
808 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
809 ///
810 /// \return true if the body is OK (maybe only as an extension), false if we
811 ///         have diagnosed a problem.
812 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
813                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
814   // C++11 [dcl.constexpr]p3 and p4:
815   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
816   //  contain only
817   for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
818          DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
819     switch ((*DclIt)->getKind()) {
820     case Decl::StaticAssert:
821     case Decl::Using:
822     case Decl::UsingShadow:
823     case Decl::UsingDirective:
824     case Decl::UnresolvedUsingTypename:
825     case Decl::UnresolvedUsingValue:
826       //   - static_assert-declarations
827       //   - using-declarations,
828       //   - using-directives,
829       continue;
830 
831     case Decl::Typedef:
832     case Decl::TypeAlias: {
833       //   - typedef declarations and alias-declarations that do not define
834       //     classes or enumerations,
835       TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
836       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
837         // Don't allow variably-modified types in constexpr functions.
838         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
839         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
840           << TL.getSourceRange() << TL.getType()
841           << isa<CXXConstructorDecl>(Dcl);
842         return false;
843       }
844       continue;
845     }
846 
847     case Decl::Enum:
848     case Decl::CXXRecord:
849       // C++1y allows types to be defined, not just declared.
850       if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
851         SemaRef.Diag(DS->getLocStart(),
852                      SemaRef.getLangOpts().CPlusPlus1y
853                        ? diag::warn_cxx11_compat_constexpr_type_definition
854                        : diag::ext_constexpr_type_definition)
855           << isa<CXXConstructorDecl>(Dcl);
856       continue;
857 
858     case Decl::EnumConstant:
859     case Decl::IndirectField:
860     case Decl::ParmVar:
861       // These can only appear with other declarations which are banned in
862       // C++11 and permitted in C++1y, so ignore them.
863       continue;
864 
865     case Decl::Var: {
866       // C++1y [dcl.constexpr]p3 allows anything except:
867       //   a definition of a variable of non-literal type or of static or
868       //   thread storage duration or for which no initialization is performed.
869       VarDecl *VD = cast<VarDecl>(*DclIt);
870       if (VD->isThisDeclarationADefinition()) {
871         if (VD->isStaticLocal()) {
872           SemaRef.Diag(VD->getLocation(),
873                        diag::err_constexpr_local_var_static)
874             << isa<CXXConstructorDecl>(Dcl)
875             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
876           return false;
877         }
878         if (!VD->getType()->isDependentType() &&
879             SemaRef.RequireLiteralType(
880               VD->getLocation(), VD->getType(),
881               diag::err_constexpr_local_var_non_literal_type,
882               isa<CXXConstructorDecl>(Dcl)))
883           return false;
884         if (!VD->getType()->isDependentType() &&
885             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
886           SemaRef.Diag(VD->getLocation(),
887                        diag::err_constexpr_local_var_no_init)
888             << isa<CXXConstructorDecl>(Dcl);
889           return false;
890         }
891       }
892       SemaRef.Diag(VD->getLocation(),
893                    SemaRef.getLangOpts().CPlusPlus1y
894                     ? diag::warn_cxx11_compat_constexpr_local_var
895                     : diag::ext_constexpr_local_var)
896         << isa<CXXConstructorDecl>(Dcl);
897       continue;
898     }
899 
900     case Decl::NamespaceAlias:
901     case Decl::Function:
902       // These are disallowed in C++11 and permitted in C++1y. Allow them
903       // everywhere as an extension.
904       if (!Cxx1yLoc.isValid())
905         Cxx1yLoc = DS->getLocStart();
906       continue;
907 
908     default:
909       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
910         << isa<CXXConstructorDecl>(Dcl);
911       return false;
912     }
913   }
914 
915   return true;
916 }
917 
918 /// Check that the given field is initialized within a constexpr constructor.
919 ///
920 /// \param Dcl The constexpr constructor being checked.
921 /// \param Field The field being checked. This may be a member of an anonymous
922 ///        struct or union nested within the class being checked.
923 /// \param Inits All declarations, including anonymous struct/union members and
924 ///        indirect members, for which any initialization was provided.
925 /// \param Diagnosed Set to true if an error is produced.
926 static void CheckConstexprCtorInitializer(Sema &SemaRef,
927                                           const FunctionDecl *Dcl,
928                                           FieldDecl *Field,
929                                           llvm::SmallSet<Decl*, 16> &Inits,
930                                           bool &Diagnosed) {
931   if (Field->isInvalidDecl())
932     return;
933 
934   if (Field->isUnnamedBitfield())
935     return;
936 
937   // Anonymous unions with no variant members and empty anonymous structs do not
938   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
939   // indirect fields don't need initializing.
940   if (Field->isAnonymousStructOrUnion() &&
941       (Field->getType()->isUnionType()
942            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
943            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
944     return;
945 
946   if (!Inits.count(Field)) {
947     if (!Diagnosed) {
948       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
949       Diagnosed = true;
950     }
951     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
952   } else if (Field->isAnonymousStructOrUnion()) {
953     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
954     for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
955          I != E; ++I)
956       // If an anonymous union contains an anonymous struct of which any member
957       // is initialized, all members must be initialized.
958       if (!RD->isUnion() || Inits.count(*I))
959         CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
960   }
961 }
962 
963 /// Check the provided statement is allowed in a constexpr function
964 /// definition.
965 static bool
966 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
967                            SmallVectorImpl<SourceLocation> &ReturnStmts,
968                            SourceLocation &Cxx1yLoc) {
969   // - its function-body shall be [...] a compound-statement that contains only
970   switch (S->getStmtClass()) {
971   case Stmt::NullStmtClass:
972     //   - null statements,
973     return true;
974 
975   case Stmt::DeclStmtClass:
976     //   - static_assert-declarations
977     //   - using-declarations,
978     //   - using-directives,
979     //   - typedef declarations and alias-declarations that do not define
980     //     classes or enumerations,
981     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
982       return false;
983     return true;
984 
985   case Stmt::ReturnStmtClass:
986     //   - and exactly one return statement;
987     if (isa<CXXConstructorDecl>(Dcl)) {
988       // C++1y allows return statements in constexpr constructors.
989       if (!Cxx1yLoc.isValid())
990         Cxx1yLoc = S->getLocStart();
991       return true;
992     }
993 
994     ReturnStmts.push_back(S->getLocStart());
995     return true;
996 
997   case Stmt::CompoundStmtClass: {
998     // C++1y allows compound-statements.
999     if (!Cxx1yLoc.isValid())
1000       Cxx1yLoc = S->getLocStart();
1001 
1002     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1003     for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
1004            BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
1005       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
1006                                       Cxx1yLoc))
1007         return false;
1008     }
1009     return true;
1010   }
1011 
1012   case Stmt::AttributedStmtClass:
1013     if (!Cxx1yLoc.isValid())
1014       Cxx1yLoc = S->getLocStart();
1015     return true;
1016 
1017   case Stmt::IfStmtClass: {
1018     // C++1y allows if-statements.
1019     if (!Cxx1yLoc.isValid())
1020       Cxx1yLoc = S->getLocStart();
1021 
1022     IfStmt *If = cast<IfStmt>(S);
1023     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1024                                     Cxx1yLoc))
1025       return false;
1026     if (If->getElse() &&
1027         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1028                                     Cxx1yLoc))
1029       return false;
1030     return true;
1031   }
1032 
1033   case Stmt::WhileStmtClass:
1034   case Stmt::DoStmtClass:
1035   case Stmt::ForStmtClass:
1036   case Stmt::CXXForRangeStmtClass:
1037   case Stmt::ContinueStmtClass:
1038     // C++1y allows all of these. We don't allow them as extensions in C++11,
1039     // because they don't make sense without variable mutation.
1040     if (!SemaRef.getLangOpts().CPlusPlus1y)
1041       break;
1042     if (!Cxx1yLoc.isValid())
1043       Cxx1yLoc = S->getLocStart();
1044     for (Stmt::child_range Children = S->children(); Children; ++Children)
1045       if (*Children &&
1046           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1047                                       Cxx1yLoc))
1048         return false;
1049     return true;
1050 
1051   case Stmt::SwitchStmtClass:
1052   case Stmt::CaseStmtClass:
1053   case Stmt::DefaultStmtClass:
1054   case Stmt::BreakStmtClass:
1055     // C++1y allows switch-statements, and since they don't need variable
1056     // mutation, we can reasonably allow them in C++11 as an extension.
1057     if (!Cxx1yLoc.isValid())
1058       Cxx1yLoc = S->getLocStart();
1059     for (Stmt::child_range Children = S->children(); Children; ++Children)
1060       if (*Children &&
1061           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1062                                       Cxx1yLoc))
1063         return false;
1064     return true;
1065 
1066   default:
1067     if (!isa<Expr>(S))
1068       break;
1069 
1070     // C++1y allows expression-statements.
1071     if (!Cxx1yLoc.isValid())
1072       Cxx1yLoc = S->getLocStart();
1073     return true;
1074   }
1075 
1076   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1077     << isa<CXXConstructorDecl>(Dcl);
1078   return false;
1079 }
1080 
1081 /// Check the body for the given constexpr function declaration only contains
1082 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1083 ///
1084 /// \return true if the body is OK, false if we have diagnosed a problem.
1085 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1086   if (isa<CXXTryStmt>(Body)) {
1087     // C++11 [dcl.constexpr]p3:
1088     //  The definition of a constexpr function shall satisfy the following
1089     //  constraints: [...]
1090     // - its function-body shall be = delete, = default, or a
1091     //   compound-statement
1092     //
1093     // C++11 [dcl.constexpr]p4:
1094     //  In the definition of a constexpr constructor, [...]
1095     // - its function-body shall not be a function-try-block;
1096     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1097       << isa<CXXConstructorDecl>(Dcl);
1098     return false;
1099   }
1100 
1101   SmallVector<SourceLocation, 4> ReturnStmts;
1102 
1103   // - its function-body shall be [...] a compound-statement that contains only
1104   //   [... list of cases ...]
1105   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1106   SourceLocation Cxx1yLoc;
1107   for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1108          BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
1109     if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1110       return false;
1111   }
1112 
1113   if (Cxx1yLoc.isValid())
1114     Diag(Cxx1yLoc,
1115          getLangOpts().CPlusPlus1y
1116            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1117            : diag::ext_constexpr_body_invalid_stmt)
1118       << isa<CXXConstructorDecl>(Dcl);
1119 
1120   if (const CXXConstructorDecl *Constructor
1121         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1122     const CXXRecordDecl *RD = Constructor->getParent();
1123     // DR1359:
1124     // - every non-variant non-static data member and base class sub-object
1125     //   shall be initialized;
1126     // DR1460:
1127     // - if the class is a union having variant members, exactly one of them
1128     //   shall be initialized;
1129     if (RD->isUnion()) {
1130       if (Constructor->getNumCtorInitializers() == 0 &&
1131           RD->hasVariantMembers()) {
1132         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1133         return false;
1134       }
1135     } else if (!Constructor->isDependentContext() &&
1136                !Constructor->isDelegatingConstructor()) {
1137       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1138 
1139       // Skip detailed checking if we have enough initializers, and we would
1140       // allow at most one initializer per member.
1141       bool AnyAnonStructUnionMembers = false;
1142       unsigned Fields = 0;
1143       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1144            E = RD->field_end(); I != E; ++I, ++Fields) {
1145         if (I->isAnonymousStructOrUnion()) {
1146           AnyAnonStructUnionMembers = true;
1147           break;
1148         }
1149       }
1150       // DR1460:
1151       // - if the class is a union-like class, but is not a union, for each of
1152       //   its anonymous union members having variant members, exactly one of
1153       //   them shall be initialized;
1154       if (AnyAnonStructUnionMembers ||
1155           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1156         // Check initialization of non-static data members. Base classes are
1157         // always initialized so do not need to be checked. Dependent bases
1158         // might not have initializers in the member initializer list.
1159         llvm::SmallSet<Decl*, 16> Inits;
1160         for (CXXConstructorDecl::init_const_iterator
1161                I = Constructor->init_begin(), E = Constructor->init_end();
1162              I != E; ++I) {
1163           if (FieldDecl *FD = (*I)->getMember())
1164             Inits.insert(FD);
1165           else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1166             Inits.insert(ID->chain_begin(), ID->chain_end());
1167         }
1168 
1169         bool Diagnosed = false;
1170         for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1171              E = RD->field_end(); I != E; ++I)
1172           CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
1173         if (Diagnosed)
1174           return false;
1175       }
1176     }
1177   } else {
1178     if (ReturnStmts.empty()) {
1179       // C++1y doesn't require constexpr functions to contain a 'return'
1180       // statement. We still do, unless the return type is void, because
1181       // otherwise if there's no return statement, the function cannot
1182       // be used in a core constant expression.
1183       bool OK = getLangOpts().CPlusPlus1y && Dcl->getReturnType()->isVoidType();
1184       Diag(Dcl->getLocation(),
1185            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1186               : diag::err_constexpr_body_no_return);
1187       return OK;
1188     }
1189     if (ReturnStmts.size() > 1) {
1190       Diag(ReturnStmts.back(),
1191            getLangOpts().CPlusPlus1y
1192              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1193              : diag::ext_constexpr_body_multiple_return);
1194       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1195         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1196     }
1197   }
1198 
1199   // C++11 [dcl.constexpr]p5:
1200   //   if no function argument values exist such that the function invocation
1201   //   substitution would produce a constant expression, the program is
1202   //   ill-formed; no diagnostic required.
1203   // C++11 [dcl.constexpr]p3:
1204   //   - every constructor call and implicit conversion used in initializing the
1205   //     return value shall be one of those allowed in a constant expression.
1206   // C++11 [dcl.constexpr]p4:
1207   //   - every constructor involved in initializing non-static data members and
1208   //     base class sub-objects shall be a constexpr constructor.
1209   SmallVector<PartialDiagnosticAt, 8> Diags;
1210   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1211     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1212       << isa<CXXConstructorDecl>(Dcl);
1213     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1214       Diag(Diags[I].first, Diags[I].second);
1215     // Don't return false here: we allow this for compatibility in
1216     // system headers.
1217   }
1218 
1219   return true;
1220 }
1221 
1222 /// isCurrentClassName - Determine whether the identifier II is the
1223 /// name of the class type currently being defined. In the case of
1224 /// nested classes, this will only return true if II is the name of
1225 /// the innermost class.
1226 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1227                               const CXXScopeSpec *SS) {
1228   assert(getLangOpts().CPlusPlus && "No class names in C!");
1229 
1230   CXXRecordDecl *CurDecl;
1231   if (SS && SS->isSet() && !SS->isInvalid()) {
1232     DeclContext *DC = computeDeclContext(*SS, true);
1233     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1234   } else
1235     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1236 
1237   if (CurDecl && CurDecl->getIdentifier())
1238     return &II == CurDecl->getIdentifier();
1239   return false;
1240 }
1241 
1242 /// \brief Determine whether the identifier II is a typo for the name of
1243 /// the class type currently being defined. If so, update it to the identifier
1244 /// that should have been used.
1245 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1246   assert(getLangOpts().CPlusPlus && "No class names in C!");
1247 
1248   if (!getLangOpts().SpellChecking)
1249     return false;
1250 
1251   CXXRecordDecl *CurDecl;
1252   if (SS && SS->isSet() && !SS->isInvalid()) {
1253     DeclContext *DC = computeDeclContext(*SS, true);
1254     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1255   } else
1256     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1257 
1258   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1259       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1260           < II->getLength()) {
1261     II = CurDecl->getIdentifier();
1262     return true;
1263   }
1264 
1265   return false;
1266 }
1267 
1268 /// \brief Determine whether the given class is a base class of the given
1269 /// class, including looking at dependent bases.
1270 static bool findCircularInheritance(const CXXRecordDecl *Class,
1271                                     const CXXRecordDecl *Current) {
1272   SmallVector<const CXXRecordDecl*, 8> Queue;
1273 
1274   Class = Class->getCanonicalDecl();
1275   while (true) {
1276     for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1277                                                   E = Current->bases_end();
1278          I != E; ++I) {
1279       CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1280       if (!Base)
1281         continue;
1282 
1283       Base = Base->getDefinition();
1284       if (!Base)
1285         continue;
1286 
1287       if (Base->getCanonicalDecl() == Class)
1288         return true;
1289 
1290       Queue.push_back(Base);
1291     }
1292 
1293     if (Queue.empty())
1294       return false;
1295 
1296     Current = Queue.pop_back_val();
1297   }
1298 
1299   return false;
1300 }
1301 
1302 /// \brief Check the validity of a C++ base class specifier.
1303 ///
1304 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1305 /// and returns NULL otherwise.
1306 CXXBaseSpecifier *
1307 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1308                          SourceRange SpecifierRange,
1309                          bool Virtual, AccessSpecifier Access,
1310                          TypeSourceInfo *TInfo,
1311                          SourceLocation EllipsisLoc) {
1312   QualType BaseType = TInfo->getType();
1313 
1314   // C++ [class.union]p1:
1315   //   A union shall not have base classes.
1316   if (Class->isUnion()) {
1317     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1318       << SpecifierRange;
1319     return 0;
1320   }
1321 
1322   if (EllipsisLoc.isValid() &&
1323       !TInfo->getType()->containsUnexpandedParameterPack()) {
1324     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1325       << TInfo->getTypeLoc().getSourceRange();
1326     EllipsisLoc = SourceLocation();
1327   }
1328 
1329   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1330 
1331   if (BaseType->isDependentType()) {
1332     // Make sure that we don't have circular inheritance among our dependent
1333     // bases. For non-dependent bases, the check for completeness below handles
1334     // this.
1335     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1336       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1337           ((BaseDecl = BaseDecl->getDefinition()) &&
1338            findCircularInheritance(Class, BaseDecl))) {
1339         Diag(BaseLoc, diag::err_circular_inheritance)
1340           << BaseType << Context.getTypeDeclType(Class);
1341 
1342         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1343           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1344             << BaseType;
1345 
1346         return 0;
1347       }
1348     }
1349 
1350     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1351                                           Class->getTagKind() == TTK_Class,
1352                                           Access, TInfo, EllipsisLoc);
1353   }
1354 
1355   // Base specifiers must be record types.
1356   if (!BaseType->isRecordType()) {
1357     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1358     return 0;
1359   }
1360 
1361   // C++ [class.union]p1:
1362   //   A union shall not be used as a base class.
1363   if (BaseType->isUnionType()) {
1364     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1365     return 0;
1366   }
1367 
1368   // C++ [class.derived]p2:
1369   //   The class-name in a base-specifier shall not be an incompletely
1370   //   defined class.
1371   if (RequireCompleteType(BaseLoc, BaseType,
1372                           diag::err_incomplete_base_class, SpecifierRange)) {
1373     Class->setInvalidDecl();
1374     return 0;
1375   }
1376 
1377   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1378   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1379   assert(BaseDecl && "Record type has no declaration");
1380   BaseDecl = BaseDecl->getDefinition();
1381   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1382   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1383   assert(CXXBaseDecl && "Base type is not a C++ type");
1384 
1385   // A class which contains a flexible array member is not suitable for use as a
1386   // base class:
1387   //   - If the layout determines that a base comes before another base,
1388   //     the flexible array member would index into the subsequent base.
1389   //   - If the layout determines that base comes before the derived class,
1390   //     the flexible array member would index into the derived class.
1391   if (CXXBaseDecl->hasFlexibleArrayMember()) {
1392     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1393       << CXXBaseDecl->getDeclName();
1394     return 0;
1395   }
1396 
1397   // C++ [class]p3:
1398   //   If a class is marked final and it appears as a base-type-specifier in
1399   //   base-clause, the program is ill-formed.
1400   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1401     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1402       << CXXBaseDecl->getDeclName()
1403       << FA->isSpelledAsSealed();
1404     Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1405       << CXXBaseDecl->getDeclName();
1406     return 0;
1407   }
1408 
1409   if (BaseDecl->isInvalidDecl())
1410     Class->setInvalidDecl();
1411 
1412   // Create the base specifier.
1413   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1414                                         Class->getTagKind() == TTK_Class,
1415                                         Access, TInfo, EllipsisLoc);
1416 }
1417 
1418 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1419 /// one entry in the base class list of a class specifier, for
1420 /// example:
1421 ///    class foo : public bar, virtual private baz {
1422 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1423 BaseResult
1424 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1425                          ParsedAttributes &Attributes,
1426                          bool Virtual, AccessSpecifier Access,
1427                          ParsedType basetype, SourceLocation BaseLoc,
1428                          SourceLocation EllipsisLoc) {
1429   if (!classdecl)
1430     return true;
1431 
1432   AdjustDeclIfTemplate(classdecl);
1433   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1434   if (!Class)
1435     return true;
1436 
1437   // We do not support any C++11 attributes on base-specifiers yet.
1438   // Diagnose any attributes we see.
1439   if (!Attributes.empty()) {
1440     for (AttributeList *Attr = Attributes.getList(); Attr;
1441          Attr = Attr->getNext()) {
1442       if (Attr->isInvalid() ||
1443           Attr->getKind() == AttributeList::IgnoredAttribute)
1444         continue;
1445       Diag(Attr->getLoc(),
1446            Attr->getKind() == AttributeList::UnknownAttribute
1447              ? diag::warn_unknown_attribute_ignored
1448              : diag::err_base_specifier_attribute)
1449         << Attr->getName();
1450     }
1451   }
1452 
1453   TypeSourceInfo *TInfo = 0;
1454   GetTypeFromParser(basetype, &TInfo);
1455 
1456   if (EllipsisLoc.isInvalid() &&
1457       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1458                                       UPPC_BaseType))
1459     return true;
1460 
1461   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1462                                                       Virtual, Access, TInfo,
1463                                                       EllipsisLoc))
1464     return BaseSpec;
1465   else
1466     Class->setInvalidDecl();
1467 
1468   return true;
1469 }
1470 
1471 /// \brief Performs the actual work of attaching the given base class
1472 /// specifiers to a C++ class.
1473 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1474                                 unsigned NumBases) {
1475  if (NumBases == 0)
1476     return false;
1477 
1478   // Used to keep track of which base types we have already seen, so
1479   // that we can properly diagnose redundant direct base types. Note
1480   // that the key is always the unqualified canonical type of the base
1481   // class.
1482   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1483 
1484   // Copy non-redundant base specifiers into permanent storage.
1485   unsigned NumGoodBases = 0;
1486   bool Invalid = false;
1487   for (unsigned idx = 0; idx < NumBases; ++idx) {
1488     QualType NewBaseType
1489       = Context.getCanonicalType(Bases[idx]->getType());
1490     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1491 
1492     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1493     if (KnownBase) {
1494       // C++ [class.mi]p3:
1495       //   A class shall not be specified as a direct base class of a
1496       //   derived class more than once.
1497       Diag(Bases[idx]->getLocStart(),
1498            diag::err_duplicate_base_class)
1499         << KnownBase->getType()
1500         << Bases[idx]->getSourceRange();
1501 
1502       // Delete the duplicate base class specifier; we're going to
1503       // overwrite its pointer later.
1504       Context.Deallocate(Bases[idx]);
1505 
1506       Invalid = true;
1507     } else {
1508       // Okay, add this new base class.
1509       KnownBase = Bases[idx];
1510       Bases[NumGoodBases++] = Bases[idx];
1511       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1512         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1513         if (Class->isInterface() &&
1514               (!RD->isInterface() ||
1515                KnownBase->getAccessSpecifier() != AS_public)) {
1516           // The Microsoft extension __interface does not permit bases that
1517           // are not themselves public interfaces.
1518           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1519             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1520             << RD->getSourceRange();
1521           Invalid = true;
1522         }
1523         if (RD->hasAttr<WeakAttr>())
1524           Class->addAttr(WeakAttr::CreateImplicit(Context));
1525       }
1526     }
1527   }
1528 
1529   // Attach the remaining base class specifiers to the derived class.
1530   Class->setBases(Bases, NumGoodBases);
1531 
1532   // Delete the remaining (good) base class specifiers, since their
1533   // data has been copied into the CXXRecordDecl.
1534   for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1535     Context.Deallocate(Bases[idx]);
1536 
1537   return Invalid;
1538 }
1539 
1540 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1541 /// class, after checking whether there are any duplicate base
1542 /// classes.
1543 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1544                                unsigned NumBases) {
1545   if (!ClassDecl || !Bases || !NumBases)
1546     return;
1547 
1548   AdjustDeclIfTemplate(ClassDecl);
1549   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1550 }
1551 
1552 /// \brief Determine whether the type \p Derived is a C++ class that is
1553 /// derived from the type \p Base.
1554 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1555   if (!getLangOpts().CPlusPlus)
1556     return false;
1557 
1558   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1559   if (!DerivedRD)
1560     return false;
1561 
1562   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1563   if (!BaseRD)
1564     return false;
1565 
1566   // If either the base or the derived type is invalid, don't try to
1567   // check whether one is derived from the other.
1568   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1569     return false;
1570 
1571   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1572   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1573 }
1574 
1575 /// \brief Determine whether the type \p Derived is a C++ class that is
1576 /// derived from the type \p Base.
1577 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1578   if (!getLangOpts().CPlusPlus)
1579     return false;
1580 
1581   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1582   if (!DerivedRD)
1583     return false;
1584 
1585   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1586   if (!BaseRD)
1587     return false;
1588 
1589   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1590 }
1591 
1592 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1593                               CXXCastPath &BasePathArray) {
1594   assert(BasePathArray.empty() && "Base path array must be empty!");
1595   assert(Paths.isRecordingPaths() && "Must record paths!");
1596 
1597   const CXXBasePath &Path = Paths.front();
1598 
1599   // We first go backward and check if we have a virtual base.
1600   // FIXME: It would be better if CXXBasePath had the base specifier for
1601   // the nearest virtual base.
1602   unsigned Start = 0;
1603   for (unsigned I = Path.size(); I != 0; --I) {
1604     if (Path[I - 1].Base->isVirtual()) {
1605       Start = I - 1;
1606       break;
1607     }
1608   }
1609 
1610   // Now add all bases.
1611   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1612     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1613 }
1614 
1615 /// \brief Determine whether the given base path includes a virtual
1616 /// base class.
1617 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1618   for (CXXCastPath::const_iterator B = BasePath.begin(),
1619                                 BEnd = BasePath.end();
1620        B != BEnd; ++B)
1621     if ((*B)->isVirtual())
1622       return true;
1623 
1624   return false;
1625 }
1626 
1627 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1628 /// conversion (where Derived and Base are class types) is
1629 /// well-formed, meaning that the conversion is unambiguous (and
1630 /// that all of the base classes are accessible). Returns true
1631 /// and emits a diagnostic if the code is ill-formed, returns false
1632 /// otherwise. Loc is the location where this routine should point to
1633 /// if there is an error, and Range is the source range to highlight
1634 /// if there is an error.
1635 bool
1636 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1637                                    unsigned InaccessibleBaseID,
1638                                    unsigned AmbigiousBaseConvID,
1639                                    SourceLocation Loc, SourceRange Range,
1640                                    DeclarationName Name,
1641                                    CXXCastPath *BasePath) {
1642   // First, determine whether the path from Derived to Base is
1643   // ambiguous. This is slightly more expensive than checking whether
1644   // the Derived to Base conversion exists, because here we need to
1645   // explore multiple paths to determine if there is an ambiguity.
1646   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1647                      /*DetectVirtual=*/false);
1648   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1649   assert(DerivationOkay &&
1650          "Can only be used with a derived-to-base conversion");
1651   (void)DerivationOkay;
1652 
1653   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1654     if (InaccessibleBaseID) {
1655       // Check that the base class can be accessed.
1656       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1657                                    InaccessibleBaseID)) {
1658         case AR_inaccessible:
1659           return true;
1660         case AR_accessible:
1661         case AR_dependent:
1662         case AR_delayed:
1663           break;
1664       }
1665     }
1666 
1667     // Build a base path if necessary.
1668     if (BasePath)
1669       BuildBasePathArray(Paths, *BasePath);
1670     return false;
1671   }
1672 
1673   if (AmbigiousBaseConvID) {
1674     // We know that the derived-to-base conversion is ambiguous, and
1675     // we're going to produce a diagnostic. Perform the derived-to-base
1676     // search just one more time to compute all of the possible paths so
1677     // that we can print them out. This is more expensive than any of
1678     // the previous derived-to-base checks we've done, but at this point
1679     // performance isn't as much of an issue.
1680     Paths.clear();
1681     Paths.setRecordingPaths(true);
1682     bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1683     assert(StillOkay && "Can only be used with a derived-to-base conversion");
1684     (void)StillOkay;
1685 
1686     // Build up a textual representation of the ambiguous paths, e.g.,
1687     // D -> B -> A, that will be used to illustrate the ambiguous
1688     // conversions in the diagnostic. We only print one of the paths
1689     // to each base class subobject.
1690     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1691 
1692     Diag(Loc, AmbigiousBaseConvID)
1693     << Derived << Base << PathDisplayStr << Range << Name;
1694   }
1695   return true;
1696 }
1697 
1698 bool
1699 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1700                                    SourceLocation Loc, SourceRange Range,
1701                                    CXXCastPath *BasePath,
1702                                    bool IgnoreAccess) {
1703   return CheckDerivedToBaseConversion(Derived, Base,
1704                                       IgnoreAccess ? 0
1705                                        : diag::err_upcast_to_inaccessible_base,
1706                                       diag::err_ambiguous_derived_to_base_conv,
1707                                       Loc, Range, DeclarationName(),
1708                                       BasePath);
1709 }
1710 
1711 
1712 /// @brief Builds a string representing ambiguous paths from a
1713 /// specific derived class to different subobjects of the same base
1714 /// class.
1715 ///
1716 /// This function builds a string that can be used in error messages
1717 /// to show the different paths that one can take through the
1718 /// inheritance hierarchy to go from the derived class to different
1719 /// subobjects of a base class. The result looks something like this:
1720 /// @code
1721 /// struct D -> struct B -> struct A
1722 /// struct D -> struct C -> struct A
1723 /// @endcode
1724 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1725   std::string PathDisplayStr;
1726   std::set<unsigned> DisplayedPaths;
1727   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1728        Path != Paths.end(); ++Path) {
1729     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1730       // We haven't displayed a path to this particular base
1731       // class subobject yet.
1732       PathDisplayStr += "\n    ";
1733       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1734       for (CXXBasePath::const_iterator Element = Path->begin();
1735            Element != Path->end(); ++Element)
1736         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1737     }
1738   }
1739 
1740   return PathDisplayStr;
1741 }
1742 
1743 //===----------------------------------------------------------------------===//
1744 // C++ class member Handling
1745 //===----------------------------------------------------------------------===//
1746 
1747 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1748 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1749                                 SourceLocation ASLoc,
1750                                 SourceLocation ColonLoc,
1751                                 AttributeList *Attrs) {
1752   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1753   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1754                                                   ASLoc, ColonLoc);
1755   CurContext->addHiddenDecl(ASDecl);
1756   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1757 }
1758 
1759 /// CheckOverrideControl - Check C++11 override control semantics.
1760 void Sema::CheckOverrideControl(NamedDecl *D) {
1761   if (D->isInvalidDecl())
1762     return;
1763 
1764   // We only care about "override" and "final" declarations.
1765   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1766     return;
1767 
1768   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1769 
1770   // We can't check dependent instance methods.
1771   if (MD && MD->isInstance() &&
1772       (MD->getParent()->hasAnyDependentBases() ||
1773        MD->getType()->isDependentType()))
1774     return;
1775 
1776   if (MD && !MD->isVirtual()) {
1777     // If we have a non-virtual method, check if if hides a virtual method.
1778     // (In that case, it's most likely the method has the wrong type.)
1779     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1780     FindHiddenVirtualMethods(MD, OverloadedMethods);
1781 
1782     if (!OverloadedMethods.empty()) {
1783       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1784         Diag(OA->getLocation(),
1785              diag::override_keyword_hides_virtual_member_function)
1786           << "override" << (OverloadedMethods.size() > 1);
1787       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1788         Diag(FA->getLocation(),
1789              diag::override_keyword_hides_virtual_member_function)
1790           << (FA->isSpelledAsSealed() ? "sealed" : "final")
1791           << (OverloadedMethods.size() > 1);
1792       }
1793       NoteHiddenVirtualMethods(MD, OverloadedMethods);
1794       MD->setInvalidDecl();
1795       return;
1796     }
1797     // Fall through into the general case diagnostic.
1798     // FIXME: We might want to attempt typo correction here.
1799   }
1800 
1801   if (!MD || !MD->isVirtual()) {
1802     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1803       Diag(OA->getLocation(),
1804            diag::override_keyword_only_allowed_on_virtual_member_functions)
1805         << "override" << FixItHint::CreateRemoval(OA->getLocation());
1806       D->dropAttr<OverrideAttr>();
1807     }
1808     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1809       Diag(FA->getLocation(),
1810            diag::override_keyword_only_allowed_on_virtual_member_functions)
1811         << (FA->isSpelledAsSealed() ? "sealed" : "final")
1812         << FixItHint::CreateRemoval(FA->getLocation());
1813       D->dropAttr<FinalAttr>();
1814     }
1815     return;
1816   }
1817 
1818   // C++11 [class.virtual]p5:
1819   //   If a virtual function is marked with the virt-specifier override and
1820   //   does not override a member function of a base class, the program is
1821   //   ill-formed.
1822   bool HasOverriddenMethods =
1823     MD->begin_overridden_methods() != MD->end_overridden_methods();
1824   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1825     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1826       << MD->getDeclName();
1827 }
1828 
1829 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1830 /// function overrides a virtual member function marked 'final', according to
1831 /// C++11 [class.virtual]p4.
1832 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1833                                                   const CXXMethodDecl *Old) {
1834   FinalAttr *FA = Old->getAttr<FinalAttr>();
1835   if (!FA)
1836     return false;
1837 
1838   Diag(New->getLocation(), diag::err_final_function_overridden)
1839     << New->getDeclName()
1840     << FA->isSpelledAsSealed();
1841   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1842   return true;
1843 }
1844 
1845 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1846   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1847   // FIXME: Destruction of ObjC lifetime types has side-effects.
1848   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1849     return !RD->isCompleteDefinition() ||
1850            !RD->hasTrivialDefaultConstructor() ||
1851            !RD->hasTrivialDestructor();
1852   return false;
1853 }
1854 
1855 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1856   for (AttributeList* it = list; it != 0; it = it->getNext())
1857     if (it->isDeclspecPropertyAttribute())
1858       return it;
1859   return 0;
1860 }
1861 
1862 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1863 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1864 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1865 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1866 /// present (but parsing it has been deferred).
1867 NamedDecl *
1868 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1869                                MultiTemplateParamsArg TemplateParameterLists,
1870                                Expr *BW, const VirtSpecifiers &VS,
1871                                InClassInitStyle InitStyle) {
1872   const DeclSpec &DS = D.getDeclSpec();
1873   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1874   DeclarationName Name = NameInfo.getName();
1875   SourceLocation Loc = NameInfo.getLoc();
1876 
1877   // For anonymous bitfields, the location should point to the type.
1878   if (Loc.isInvalid())
1879     Loc = D.getLocStart();
1880 
1881   Expr *BitWidth = static_cast<Expr*>(BW);
1882 
1883   assert(isa<CXXRecordDecl>(CurContext));
1884   assert(!DS.isFriendSpecified());
1885 
1886   bool isFunc = D.isDeclarationOfFunction();
1887 
1888   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1889     // The Microsoft extension __interface only permits public member functions
1890     // and prohibits constructors, destructors, operators, non-public member
1891     // functions, static methods and data members.
1892     unsigned InvalidDecl;
1893     bool ShowDeclName = true;
1894     if (!isFunc)
1895       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1896     else if (AS != AS_public)
1897       InvalidDecl = 2;
1898     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1899       InvalidDecl = 3;
1900     else switch (Name.getNameKind()) {
1901       case DeclarationName::CXXConstructorName:
1902         InvalidDecl = 4;
1903         ShowDeclName = false;
1904         break;
1905 
1906       case DeclarationName::CXXDestructorName:
1907         InvalidDecl = 5;
1908         ShowDeclName = false;
1909         break;
1910 
1911       case DeclarationName::CXXOperatorName:
1912       case DeclarationName::CXXConversionFunctionName:
1913         InvalidDecl = 6;
1914         break;
1915 
1916       default:
1917         InvalidDecl = 0;
1918         break;
1919     }
1920 
1921     if (InvalidDecl) {
1922       if (ShowDeclName)
1923         Diag(Loc, diag::err_invalid_member_in_interface)
1924           << (InvalidDecl-1) << Name;
1925       else
1926         Diag(Loc, diag::err_invalid_member_in_interface)
1927           << (InvalidDecl-1) << "";
1928       return 0;
1929     }
1930   }
1931 
1932   // C++ 9.2p6: A member shall not be declared to have automatic storage
1933   // duration (auto, register) or with the extern storage-class-specifier.
1934   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1935   // data members and cannot be applied to names declared const or static,
1936   // and cannot be applied to reference members.
1937   switch (DS.getStorageClassSpec()) {
1938   case DeclSpec::SCS_unspecified:
1939   case DeclSpec::SCS_typedef:
1940   case DeclSpec::SCS_static:
1941     break;
1942   case DeclSpec::SCS_mutable:
1943     if (isFunc) {
1944       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1945 
1946       // FIXME: It would be nicer if the keyword was ignored only for this
1947       // declarator. Otherwise we could get follow-up errors.
1948       D.getMutableDeclSpec().ClearStorageClassSpecs();
1949     }
1950     break;
1951   default:
1952     Diag(DS.getStorageClassSpecLoc(),
1953          diag::err_storageclass_invalid_for_member);
1954     D.getMutableDeclSpec().ClearStorageClassSpecs();
1955     break;
1956   }
1957 
1958   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1959                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1960                       !isFunc);
1961 
1962   if (DS.isConstexprSpecified() && isInstField) {
1963     SemaDiagnosticBuilder B =
1964         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1965     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1966     if (InitStyle == ICIS_NoInit) {
1967       B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1968       D.getMutableDeclSpec().ClearConstexprSpec();
1969       const char *PrevSpec;
1970       unsigned DiagID;
1971       bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1972                                          PrevSpec, DiagID, getLangOpts());
1973       (void)Failed;
1974       assert(!Failed && "Making a constexpr member const shouldn't fail");
1975     } else {
1976       B << 1;
1977       const char *PrevSpec;
1978       unsigned DiagID;
1979       if (D.getMutableDeclSpec().SetStorageClassSpec(
1980           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
1981           Context.getPrintingPolicy())) {
1982         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
1983                "This is the only DeclSpec that should fail to be applied");
1984         B << 1;
1985       } else {
1986         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1987         isInstField = false;
1988       }
1989     }
1990   }
1991 
1992   NamedDecl *Member;
1993   if (isInstField) {
1994     CXXScopeSpec &SS = D.getCXXScopeSpec();
1995 
1996     // Data members must have identifiers for names.
1997     if (!Name.isIdentifier()) {
1998       Diag(Loc, diag::err_bad_variable_name)
1999         << Name;
2000       return 0;
2001     }
2002 
2003     IdentifierInfo *II = Name.getAsIdentifierInfo();
2004 
2005     // Member field could not be with "template" keyword.
2006     // So TemplateParameterLists should be empty in this case.
2007     if (TemplateParameterLists.size()) {
2008       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2009       if (TemplateParams->size()) {
2010         // There is no such thing as a member field template.
2011         Diag(D.getIdentifierLoc(), diag::err_template_member)
2012             << II
2013             << SourceRange(TemplateParams->getTemplateLoc(),
2014                 TemplateParams->getRAngleLoc());
2015       } else {
2016         // There is an extraneous 'template<>' for this member.
2017         Diag(TemplateParams->getTemplateLoc(),
2018             diag::err_template_member_noparams)
2019             << II
2020             << SourceRange(TemplateParams->getTemplateLoc(),
2021                 TemplateParams->getRAngleLoc());
2022       }
2023       return 0;
2024     }
2025 
2026     if (SS.isSet() && !SS.isInvalid()) {
2027       // The user provided a superfluous scope specifier inside a class
2028       // definition:
2029       //
2030       // class X {
2031       //   int X::member;
2032       // };
2033       if (DeclContext *DC = computeDeclContext(SS, false))
2034         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2035       else
2036         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2037           << Name << SS.getRange();
2038 
2039       SS.clear();
2040     }
2041 
2042     AttributeList *MSPropertyAttr =
2043       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2044     if (MSPropertyAttr) {
2045       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2046                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2047       if (!Member)
2048         return 0;
2049       isInstField = false;
2050     } else {
2051       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2052                                 BitWidth, InitStyle, AS);
2053       assert(Member && "HandleField never returns null");
2054     }
2055   } else {
2056     assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2057 
2058     Member = HandleDeclarator(S, D, TemplateParameterLists);
2059     if (!Member)
2060       return 0;
2061 
2062     // Non-instance-fields can't have a bitfield.
2063     if (BitWidth) {
2064       if (Member->isInvalidDecl()) {
2065         // don't emit another diagnostic.
2066       } else if (isa<VarDecl>(Member)) {
2067         // C++ 9.6p3: A bit-field shall not be a static member.
2068         // "static member 'A' cannot be a bit-field"
2069         Diag(Loc, diag::err_static_not_bitfield)
2070           << Name << BitWidth->getSourceRange();
2071       } else if (isa<TypedefDecl>(Member)) {
2072         // "typedef member 'x' cannot be a bit-field"
2073         Diag(Loc, diag::err_typedef_not_bitfield)
2074           << Name << BitWidth->getSourceRange();
2075       } else {
2076         // A function typedef ("typedef int f(); f a;").
2077         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2078         Diag(Loc, diag::err_not_integral_type_bitfield)
2079           << Name << cast<ValueDecl>(Member)->getType()
2080           << BitWidth->getSourceRange();
2081       }
2082 
2083       BitWidth = 0;
2084       Member->setInvalidDecl();
2085     }
2086 
2087     Member->setAccess(AS);
2088 
2089     // If we have declared a member function template or static data member
2090     // template, set the access of the templated declaration as well.
2091     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2092       FunTmpl->getTemplatedDecl()->setAccess(AS);
2093     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2094       VarTmpl->getTemplatedDecl()->setAccess(AS);
2095   }
2096 
2097   if (VS.isOverrideSpecified())
2098     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2099   if (VS.isFinalSpecified())
2100     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2101                                             VS.isFinalSpelledSealed()));
2102 
2103   if (VS.getLastLocation().isValid()) {
2104     // Update the end location of a method that has a virt-specifiers.
2105     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2106       MD->setRangeEnd(VS.getLastLocation());
2107   }
2108 
2109   CheckOverrideControl(Member);
2110 
2111   assert((Name || isInstField) && "No identifier for non-field ?");
2112 
2113   if (isInstField) {
2114     FieldDecl *FD = cast<FieldDecl>(Member);
2115     FieldCollector->Add(FD);
2116 
2117     if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2118                                  FD->getLocation())
2119           != DiagnosticsEngine::Ignored) {
2120       // Remember all explicit private FieldDecls that have a name, no side
2121       // effects and are not part of a dependent type declaration.
2122       if (!FD->isImplicit() && FD->getDeclName() &&
2123           FD->getAccess() == AS_private &&
2124           !FD->hasAttr<UnusedAttr>() &&
2125           !FD->getParent()->isDependentContext() &&
2126           !InitializationHasSideEffects(*FD))
2127         UnusedPrivateFields.insert(FD);
2128     }
2129   }
2130 
2131   return Member;
2132 }
2133 
2134 namespace {
2135   class UninitializedFieldVisitor
2136       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2137     Sema &S;
2138     // List of Decls to generate a warning on.  Also remove Decls that become
2139     // initialized.
2140     llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
2141     // If non-null, add a note to the warning pointing back to the constructor.
2142     const CXXConstructorDecl *Constructor;
2143   public:
2144     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2145     UninitializedFieldVisitor(Sema &S,
2146                               llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2147                               const CXXConstructorDecl *Constructor)
2148       : Inherited(S.Context), S(S), Decls(Decls),
2149         Constructor(Constructor) { }
2150 
2151     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
2152       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2153         return;
2154 
2155       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2156       // or union.
2157       MemberExpr *FieldME = ME;
2158 
2159       Expr *Base = ME;
2160       while (isa<MemberExpr>(Base)) {
2161         ME = cast<MemberExpr>(Base);
2162 
2163         if (isa<VarDecl>(ME->getMemberDecl()))
2164           return;
2165 
2166         if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2167           if (!FD->isAnonymousStructOrUnion())
2168             FieldME = ME;
2169 
2170         Base = ME->getBase();
2171       }
2172 
2173       if (!isa<CXXThisExpr>(Base))
2174         return;
2175 
2176       ValueDecl* FoundVD = FieldME->getMemberDecl();
2177 
2178       if (!Decls.count(FoundVD))
2179         return;
2180 
2181       const bool IsReference = FoundVD->getType()->isReferenceType();
2182 
2183       // Prevent double warnings on use of unbounded references.
2184       if (IsReference != CheckReferenceOnly)
2185         return;
2186 
2187       unsigned diag = IsReference
2188           ? diag::warn_reference_field_is_uninit
2189           : diag::warn_field_is_uninit;
2190       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2191       if (Constructor)
2192         S.Diag(Constructor->getLocation(),
2193                diag::note_uninit_in_this_constructor)
2194           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2195 
2196     }
2197 
2198     void HandleValue(Expr *E) {
2199       E = E->IgnoreParens();
2200 
2201       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2202         HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2203         return;
2204       }
2205 
2206       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2207         HandleValue(CO->getTrueExpr());
2208         HandleValue(CO->getFalseExpr());
2209         return;
2210       }
2211 
2212       if (BinaryConditionalOperator *BCO =
2213               dyn_cast<BinaryConditionalOperator>(E)) {
2214         HandleValue(BCO->getCommon());
2215         HandleValue(BCO->getFalseExpr());
2216         return;
2217       }
2218 
2219       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2220         switch (BO->getOpcode()) {
2221         default:
2222           return;
2223         case(BO_PtrMemD):
2224         case(BO_PtrMemI):
2225           HandleValue(BO->getLHS());
2226           return;
2227         case(BO_Comma):
2228           HandleValue(BO->getRHS());
2229           return;
2230         }
2231       }
2232     }
2233 
2234     void VisitMemberExpr(MemberExpr *ME) {
2235       // All uses of unbounded reference fields will warn.
2236       HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
2237 
2238       Inherited::VisitMemberExpr(ME);
2239     }
2240 
2241     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2242       if (E->getCastKind() == CK_LValueToRValue)
2243         HandleValue(E->getSubExpr());
2244 
2245       Inherited::VisitImplicitCastExpr(E);
2246     }
2247 
2248     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2249       if (E->getConstructor()->isCopyConstructor())
2250         if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2251           if (ICE->getCastKind() == CK_NoOp)
2252             if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
2253               HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2254 
2255       Inherited::VisitCXXConstructExpr(E);
2256     }
2257 
2258     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2259       Expr *Callee = E->getCallee();
2260       if (isa<MemberExpr>(Callee))
2261         HandleValue(Callee);
2262 
2263       Inherited::VisitCXXMemberCallExpr(E);
2264     }
2265 
2266     void VisitBinaryOperator(BinaryOperator *E) {
2267       // If a field assignment is detected, remove the field from the
2268       // uninitiailized field set.
2269       if (E->getOpcode() == BO_Assign)
2270         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2271           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2272             if (!FD->getType()->isReferenceType())
2273               Decls.erase(FD);
2274 
2275       Inherited::VisitBinaryOperator(E);
2276     }
2277   };
2278   static void CheckInitExprContainsUninitializedFields(
2279       Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2280       const CXXConstructorDecl *Constructor) {
2281     if (Decls.size() == 0)
2282       return;
2283 
2284     if (!E)
2285       return;
2286 
2287     if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2288       E = Default->getExpr();
2289       if (!E)
2290         return;
2291       // In class initializers will point to the constructor.
2292       UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2293     } else {
2294       UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2295     }
2296   }
2297 
2298   // Diagnose value-uses of fields to initialize themselves, e.g.
2299   //   foo(foo)
2300   // where foo is not also a parameter to the constructor.
2301   // Also diagnose across field uninitialized use such as
2302   //   x(y), y(x)
2303   // TODO: implement -Wuninitialized and fold this into that framework.
2304   static void DiagnoseUninitializedFields(
2305       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2306 
2307     if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2308                                                     Constructor->getLocation())
2309         == DiagnosticsEngine::Ignored) {
2310       return;
2311     }
2312 
2313     if (Constructor->isInvalidDecl())
2314       return;
2315 
2316     const CXXRecordDecl *RD = Constructor->getParent();
2317 
2318     // Holds fields that are uninitialized.
2319     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2320 
2321     // At the beginning, all fields are uninitialized.
2322     for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
2323          I != E; ++I) {
2324       if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) {
2325         UninitializedFields.insert(FD);
2326       } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) {
2327         UninitializedFields.insert(IFD->getAnonField());
2328       }
2329     }
2330 
2331     for (CXXConstructorDecl::init_const_iterator FieldInit =
2332              Constructor->init_begin(),
2333              FieldInitEnd = Constructor->init_end();
2334          FieldInit != FieldInitEnd; ++FieldInit) {
2335 
2336       Expr *InitExpr = (*FieldInit)->getInit();
2337 
2338       CheckInitExprContainsUninitializedFields(
2339           SemaRef, InitExpr, UninitializedFields, Constructor);
2340 
2341       if (FieldDecl *Field = (*FieldInit)->getAnyMember())
2342         UninitializedFields.erase(Field);
2343     }
2344   }
2345 } // namespace
2346 
2347 /// \brief Enter a new C++ default initializer scope. After calling this, the
2348 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2349 /// parsing or instantiating the initializer failed.
2350 void Sema::ActOnStartCXXInClassMemberInitializer() {
2351   // Create a synthetic function scope to represent the call to the constructor
2352   // that notionally surrounds a use of this initializer.
2353   PushFunctionScope();
2354 }
2355 
2356 /// \brief This is invoked after parsing an in-class initializer for a
2357 /// non-static C++ class member, and after instantiating an in-class initializer
2358 /// in a class template. Such actions are deferred until the class is complete.
2359 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2360                                                   SourceLocation InitLoc,
2361                                                   Expr *InitExpr) {
2362   // Pop the notional constructor scope we created earlier.
2363   PopFunctionScopeInfo(0, D);
2364 
2365   FieldDecl *FD = cast<FieldDecl>(D);
2366   assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2367          "must set init style when field is created");
2368 
2369   if (!InitExpr) {
2370     FD->setInvalidDecl();
2371     FD->removeInClassInitializer();
2372     return;
2373   }
2374 
2375   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2376     FD->setInvalidDecl();
2377     FD->removeInClassInitializer();
2378     return;
2379   }
2380 
2381   ExprResult Init = InitExpr;
2382   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2383     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2384     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2385         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2386         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2387     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2388     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2389     if (Init.isInvalid()) {
2390       FD->setInvalidDecl();
2391       return;
2392     }
2393   }
2394 
2395   // C++11 [class.base.init]p7:
2396   //   The initialization of each base and member constitutes a
2397   //   full-expression.
2398   Init = ActOnFinishFullExpr(Init.take(), InitLoc);
2399   if (Init.isInvalid()) {
2400     FD->setInvalidDecl();
2401     return;
2402   }
2403 
2404   InitExpr = Init.release();
2405 
2406   FD->setInClassInitializer(InitExpr);
2407 }
2408 
2409 /// \brief Find the direct and/or virtual base specifiers that
2410 /// correspond to the given base type, for use in base initialization
2411 /// within a constructor.
2412 static bool FindBaseInitializer(Sema &SemaRef,
2413                                 CXXRecordDecl *ClassDecl,
2414                                 QualType BaseType,
2415                                 const CXXBaseSpecifier *&DirectBaseSpec,
2416                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2417   // First, check for a direct base class.
2418   DirectBaseSpec = 0;
2419   for (CXXRecordDecl::base_class_const_iterator Base
2420          = ClassDecl->bases_begin();
2421        Base != ClassDecl->bases_end(); ++Base) {
2422     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2423       // We found a direct base of this type. That's what we're
2424       // initializing.
2425       DirectBaseSpec = &*Base;
2426       break;
2427     }
2428   }
2429 
2430   // Check for a virtual base class.
2431   // FIXME: We might be able to short-circuit this if we know in advance that
2432   // there are no virtual bases.
2433   VirtualBaseSpec = 0;
2434   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2435     // We haven't found a base yet; search the class hierarchy for a
2436     // virtual base class.
2437     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2438                        /*DetectVirtual=*/false);
2439     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2440                               BaseType, Paths)) {
2441       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2442            Path != Paths.end(); ++Path) {
2443         if (Path->back().Base->isVirtual()) {
2444           VirtualBaseSpec = Path->back().Base;
2445           break;
2446         }
2447       }
2448     }
2449   }
2450 
2451   return DirectBaseSpec || VirtualBaseSpec;
2452 }
2453 
2454 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2455 MemInitResult
2456 Sema::ActOnMemInitializer(Decl *ConstructorD,
2457                           Scope *S,
2458                           CXXScopeSpec &SS,
2459                           IdentifierInfo *MemberOrBase,
2460                           ParsedType TemplateTypeTy,
2461                           const DeclSpec &DS,
2462                           SourceLocation IdLoc,
2463                           Expr *InitList,
2464                           SourceLocation EllipsisLoc) {
2465   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2466                              DS, IdLoc, InitList,
2467                              EllipsisLoc);
2468 }
2469 
2470 /// \brief Handle a C++ member initializer using parentheses syntax.
2471 MemInitResult
2472 Sema::ActOnMemInitializer(Decl *ConstructorD,
2473                           Scope *S,
2474                           CXXScopeSpec &SS,
2475                           IdentifierInfo *MemberOrBase,
2476                           ParsedType TemplateTypeTy,
2477                           const DeclSpec &DS,
2478                           SourceLocation IdLoc,
2479                           SourceLocation LParenLoc,
2480                           ArrayRef<Expr *> Args,
2481                           SourceLocation RParenLoc,
2482                           SourceLocation EllipsisLoc) {
2483   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2484                                            Args, RParenLoc);
2485   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2486                              DS, IdLoc, List, EllipsisLoc);
2487 }
2488 
2489 namespace {
2490 
2491 // Callback to only accept typo corrections that can be a valid C++ member
2492 // intializer: either a non-static field member or a base class.
2493 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2494 public:
2495   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2496       : ClassDecl(ClassDecl) {}
2497 
2498   bool ValidateCandidate(const TypoCorrection &candidate) override {
2499     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2500       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2501         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2502       return isa<TypeDecl>(ND);
2503     }
2504     return false;
2505   }
2506 
2507 private:
2508   CXXRecordDecl *ClassDecl;
2509 };
2510 
2511 }
2512 
2513 /// \brief Handle a C++ member initializer.
2514 MemInitResult
2515 Sema::BuildMemInitializer(Decl *ConstructorD,
2516                           Scope *S,
2517                           CXXScopeSpec &SS,
2518                           IdentifierInfo *MemberOrBase,
2519                           ParsedType TemplateTypeTy,
2520                           const DeclSpec &DS,
2521                           SourceLocation IdLoc,
2522                           Expr *Init,
2523                           SourceLocation EllipsisLoc) {
2524   if (!ConstructorD)
2525     return true;
2526 
2527   AdjustDeclIfTemplate(ConstructorD);
2528 
2529   CXXConstructorDecl *Constructor
2530     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2531   if (!Constructor) {
2532     // The user wrote a constructor initializer on a function that is
2533     // not a C++ constructor. Ignore the error for now, because we may
2534     // have more member initializers coming; we'll diagnose it just
2535     // once in ActOnMemInitializers.
2536     return true;
2537   }
2538 
2539   CXXRecordDecl *ClassDecl = Constructor->getParent();
2540 
2541   // C++ [class.base.init]p2:
2542   //   Names in a mem-initializer-id are looked up in the scope of the
2543   //   constructor's class and, if not found in that scope, are looked
2544   //   up in the scope containing the constructor's definition.
2545   //   [Note: if the constructor's class contains a member with the
2546   //   same name as a direct or virtual base class of the class, a
2547   //   mem-initializer-id naming the member or base class and composed
2548   //   of a single identifier refers to the class member. A
2549   //   mem-initializer-id for the hidden base class may be specified
2550   //   using a qualified name. ]
2551   if (!SS.getScopeRep() && !TemplateTypeTy) {
2552     // Look for a member, first.
2553     DeclContext::lookup_result Result
2554       = ClassDecl->lookup(MemberOrBase);
2555     if (!Result.empty()) {
2556       ValueDecl *Member;
2557       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2558           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2559         if (EllipsisLoc.isValid())
2560           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2561             << MemberOrBase
2562             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2563 
2564         return BuildMemberInitializer(Member, Init, IdLoc);
2565       }
2566     }
2567   }
2568   // It didn't name a member, so see if it names a class.
2569   QualType BaseType;
2570   TypeSourceInfo *TInfo = 0;
2571 
2572   if (TemplateTypeTy) {
2573     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2574   } else if (DS.getTypeSpecType() == TST_decltype) {
2575     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2576   } else {
2577     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2578     LookupParsedName(R, S, &SS);
2579 
2580     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2581     if (!TyD) {
2582       if (R.isAmbiguous()) return true;
2583 
2584       // We don't want access-control diagnostics here.
2585       R.suppressDiagnostics();
2586 
2587       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2588         bool NotUnknownSpecialization = false;
2589         DeclContext *DC = computeDeclContext(SS, false);
2590         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2591           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2592 
2593         if (!NotUnknownSpecialization) {
2594           // When the scope specifier can refer to a member of an unknown
2595           // specialization, we take it as a type name.
2596           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2597                                        SS.getWithLocInContext(Context),
2598                                        *MemberOrBase, IdLoc);
2599           if (BaseType.isNull())
2600             return true;
2601 
2602           R.clear();
2603           R.setLookupName(MemberOrBase);
2604         }
2605       }
2606 
2607       // If no results were found, try to correct typos.
2608       TypoCorrection Corr;
2609       MemInitializerValidatorCCC Validator(ClassDecl);
2610       if (R.empty() && BaseType.isNull() &&
2611           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2612                               Validator, ClassDecl))) {
2613         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2614           // We have found a non-static data member with a similar
2615           // name to what was typed; complain and initialize that
2616           // member.
2617           diagnoseTypo(Corr,
2618                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2619                          << MemberOrBase << true);
2620           return BuildMemberInitializer(Member, Init, IdLoc);
2621         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2622           const CXXBaseSpecifier *DirectBaseSpec;
2623           const CXXBaseSpecifier *VirtualBaseSpec;
2624           if (FindBaseInitializer(*this, ClassDecl,
2625                                   Context.getTypeDeclType(Type),
2626                                   DirectBaseSpec, VirtualBaseSpec)) {
2627             // We have found a direct or virtual base class with a
2628             // similar name to what was typed; complain and initialize
2629             // that base class.
2630             diagnoseTypo(Corr,
2631                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2632                            << MemberOrBase << false,
2633                          PDiag() /*Suppress note, we provide our own.*/);
2634 
2635             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2636                                                               : VirtualBaseSpec;
2637             Diag(BaseSpec->getLocStart(),
2638                  diag::note_base_class_specified_here)
2639               << BaseSpec->getType()
2640               << BaseSpec->getSourceRange();
2641 
2642             TyD = Type;
2643           }
2644         }
2645       }
2646 
2647       if (!TyD && BaseType.isNull()) {
2648         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2649           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2650         return true;
2651       }
2652     }
2653 
2654     if (BaseType.isNull()) {
2655       BaseType = Context.getTypeDeclType(TyD);
2656       if (SS.isSet())
2657         // FIXME: preserve source range information
2658         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2659                                              BaseType);
2660     }
2661   }
2662 
2663   if (!TInfo)
2664     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2665 
2666   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2667 }
2668 
2669 /// Checks a member initializer expression for cases where reference (or
2670 /// pointer) members are bound to by-value parameters (or their addresses).
2671 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2672                                                Expr *Init,
2673                                                SourceLocation IdLoc) {
2674   QualType MemberTy = Member->getType();
2675 
2676   // We only handle pointers and references currently.
2677   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2678   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2679     return;
2680 
2681   const bool IsPointer = MemberTy->isPointerType();
2682   if (IsPointer) {
2683     if (const UnaryOperator *Op
2684           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2685       // The only case we're worried about with pointers requires taking the
2686       // address.
2687       if (Op->getOpcode() != UO_AddrOf)
2688         return;
2689 
2690       Init = Op->getSubExpr();
2691     } else {
2692       // We only handle address-of expression initializers for pointers.
2693       return;
2694     }
2695   }
2696 
2697   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2698     // We only warn when referring to a non-reference parameter declaration.
2699     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2700     if (!Parameter || Parameter->getType()->isReferenceType())
2701       return;
2702 
2703     S.Diag(Init->getExprLoc(),
2704            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2705                      : diag::warn_bind_ref_member_to_parameter)
2706       << Member << Parameter << Init->getSourceRange();
2707   } else {
2708     // Other initializers are fine.
2709     return;
2710   }
2711 
2712   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2713     << (unsigned)IsPointer;
2714 }
2715 
2716 MemInitResult
2717 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2718                              SourceLocation IdLoc) {
2719   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2720   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2721   assert((DirectMember || IndirectMember) &&
2722          "Member must be a FieldDecl or IndirectFieldDecl");
2723 
2724   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2725     return true;
2726 
2727   if (Member->isInvalidDecl())
2728     return true;
2729 
2730   MultiExprArg Args;
2731   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2732     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2733   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2734     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2735   } else {
2736     // Template instantiation doesn't reconstruct ParenListExprs for us.
2737     Args = Init;
2738   }
2739 
2740   SourceRange InitRange = Init->getSourceRange();
2741 
2742   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2743     // Can't check initialization for a member of dependent type or when
2744     // any of the arguments are type-dependent expressions.
2745     DiscardCleanupsInEvaluationContext();
2746   } else {
2747     bool InitList = false;
2748     if (isa<InitListExpr>(Init)) {
2749       InitList = true;
2750       Args = Init;
2751     }
2752 
2753     // Initialize the member.
2754     InitializedEntity MemberEntity =
2755       DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2756                    : InitializedEntity::InitializeMember(IndirectMember, 0);
2757     InitializationKind Kind =
2758       InitList ? InitializationKind::CreateDirectList(IdLoc)
2759                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2760                                                   InitRange.getEnd());
2761 
2762     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2763     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
2764     if (MemberInit.isInvalid())
2765       return true;
2766 
2767     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2768 
2769     // C++11 [class.base.init]p7:
2770     //   The initialization of each base and member constitutes a
2771     //   full-expression.
2772     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2773     if (MemberInit.isInvalid())
2774       return true;
2775 
2776     Init = MemberInit.get();
2777   }
2778 
2779   if (DirectMember) {
2780     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2781                                             InitRange.getBegin(), Init,
2782                                             InitRange.getEnd());
2783   } else {
2784     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2785                                             InitRange.getBegin(), Init,
2786                                             InitRange.getEnd());
2787   }
2788 }
2789 
2790 MemInitResult
2791 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2792                                  CXXRecordDecl *ClassDecl) {
2793   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2794   if (!LangOpts.CPlusPlus11)
2795     return Diag(NameLoc, diag::err_delegating_ctor)
2796       << TInfo->getTypeLoc().getLocalSourceRange();
2797   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2798 
2799   bool InitList = true;
2800   MultiExprArg Args = Init;
2801   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2802     InitList = false;
2803     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2804   }
2805 
2806   SourceRange InitRange = Init->getSourceRange();
2807   // Initialize the object.
2808   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2809                                      QualType(ClassDecl->getTypeForDecl(), 0));
2810   InitializationKind Kind =
2811     InitList ? InitializationKind::CreateDirectList(NameLoc)
2812              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2813                                                 InitRange.getEnd());
2814   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
2815   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2816                                               Args, 0);
2817   if (DelegationInit.isInvalid())
2818     return true;
2819 
2820   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2821          "Delegating constructor with no target?");
2822 
2823   // C++11 [class.base.init]p7:
2824   //   The initialization of each base and member constitutes a
2825   //   full-expression.
2826   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2827                                        InitRange.getBegin());
2828   if (DelegationInit.isInvalid())
2829     return true;
2830 
2831   // If we are in a dependent context, template instantiation will
2832   // perform this type-checking again. Just save the arguments that we
2833   // received in a ParenListExpr.
2834   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2835   // of the information that we have about the base
2836   // initializer. However, deconstructing the ASTs is a dicey process,
2837   // and this approach is far more likely to get the corner cases right.
2838   if (CurContext->isDependentContext())
2839     DelegationInit = Owned(Init);
2840 
2841   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2842                                           DelegationInit.takeAs<Expr>(),
2843                                           InitRange.getEnd());
2844 }
2845 
2846 MemInitResult
2847 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2848                            Expr *Init, CXXRecordDecl *ClassDecl,
2849                            SourceLocation EllipsisLoc) {
2850   SourceLocation BaseLoc
2851     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2852 
2853   if (!BaseType->isDependentType() && !BaseType->isRecordType())
2854     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2855              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2856 
2857   // C++ [class.base.init]p2:
2858   //   [...] Unless the mem-initializer-id names a nonstatic data
2859   //   member of the constructor's class or a direct or virtual base
2860   //   of that class, the mem-initializer is ill-formed. A
2861   //   mem-initializer-list can initialize a base class using any
2862   //   name that denotes that base class type.
2863   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2864 
2865   SourceRange InitRange = Init->getSourceRange();
2866   if (EllipsisLoc.isValid()) {
2867     // This is a pack expansion.
2868     if (!BaseType->containsUnexpandedParameterPack())  {
2869       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2870         << SourceRange(BaseLoc, InitRange.getEnd());
2871 
2872       EllipsisLoc = SourceLocation();
2873     }
2874   } else {
2875     // Check for any unexpanded parameter packs.
2876     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2877       return true;
2878 
2879     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2880       return true;
2881   }
2882 
2883   // Check for direct and virtual base classes.
2884   const CXXBaseSpecifier *DirectBaseSpec = 0;
2885   const CXXBaseSpecifier *VirtualBaseSpec = 0;
2886   if (!Dependent) {
2887     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2888                                        BaseType))
2889       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2890 
2891     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2892                         VirtualBaseSpec);
2893 
2894     // C++ [base.class.init]p2:
2895     // Unless the mem-initializer-id names a nonstatic data member of the
2896     // constructor's class or a direct or virtual base of that class, the
2897     // mem-initializer is ill-formed.
2898     if (!DirectBaseSpec && !VirtualBaseSpec) {
2899       // If the class has any dependent bases, then it's possible that
2900       // one of those types will resolve to the same type as
2901       // BaseType. Therefore, just treat this as a dependent base
2902       // class initialization.  FIXME: Should we try to check the
2903       // initialization anyway? It seems odd.
2904       if (ClassDecl->hasAnyDependentBases())
2905         Dependent = true;
2906       else
2907         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2908           << BaseType << Context.getTypeDeclType(ClassDecl)
2909           << BaseTInfo->getTypeLoc().getLocalSourceRange();
2910     }
2911   }
2912 
2913   if (Dependent) {
2914     DiscardCleanupsInEvaluationContext();
2915 
2916     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2917                                             /*IsVirtual=*/false,
2918                                             InitRange.getBegin(), Init,
2919                                             InitRange.getEnd(), EllipsisLoc);
2920   }
2921 
2922   // C++ [base.class.init]p2:
2923   //   If a mem-initializer-id is ambiguous because it designates both
2924   //   a direct non-virtual base class and an inherited virtual base
2925   //   class, the mem-initializer is ill-formed.
2926   if (DirectBaseSpec && VirtualBaseSpec)
2927     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2928       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2929 
2930   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
2931   if (!BaseSpec)
2932     BaseSpec = VirtualBaseSpec;
2933 
2934   // Initialize the base.
2935   bool InitList = true;
2936   MultiExprArg Args = Init;
2937   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2938     InitList = false;
2939     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2940   }
2941 
2942   InitializedEntity BaseEntity =
2943     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2944   InitializationKind Kind =
2945     InitList ? InitializationKind::CreateDirectList(BaseLoc)
2946              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2947                                                 InitRange.getEnd());
2948   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2949   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
2950   if (BaseInit.isInvalid())
2951     return true;
2952 
2953   // C++11 [class.base.init]p7:
2954   //   The initialization of each base and member constitutes a
2955   //   full-expression.
2956   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
2957   if (BaseInit.isInvalid())
2958     return true;
2959 
2960   // If we are in a dependent context, template instantiation will
2961   // perform this type-checking again. Just save the arguments that we
2962   // received in a ParenListExpr.
2963   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2964   // of the information that we have about the base
2965   // initializer. However, deconstructing the ASTs is a dicey process,
2966   // and this approach is far more likely to get the corner cases right.
2967   if (CurContext->isDependentContext())
2968     BaseInit = Owned(Init);
2969 
2970   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2971                                           BaseSpec->isVirtual(),
2972                                           InitRange.getBegin(),
2973                                           BaseInit.takeAs<Expr>(),
2974                                           InitRange.getEnd(), EllipsisLoc);
2975 }
2976 
2977 // Create a static_cast\<T&&>(expr).
2978 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2979   if (T.isNull()) T = E->getType();
2980   QualType TargetType = SemaRef.BuildReferenceType(
2981       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
2982   SourceLocation ExprLoc = E->getLocStart();
2983   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2984       TargetType, ExprLoc);
2985 
2986   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2987                                    SourceRange(ExprLoc, ExprLoc),
2988                                    E->getSourceRange()).take();
2989 }
2990 
2991 /// ImplicitInitializerKind - How an implicit base or member initializer should
2992 /// initialize its base or member.
2993 enum ImplicitInitializerKind {
2994   IIK_Default,
2995   IIK_Copy,
2996   IIK_Move,
2997   IIK_Inherit
2998 };
2999 
3000 static bool
3001 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3002                              ImplicitInitializerKind ImplicitInitKind,
3003                              CXXBaseSpecifier *BaseSpec,
3004                              bool IsInheritedVirtualBase,
3005                              CXXCtorInitializer *&CXXBaseInit) {
3006   InitializedEntity InitEntity
3007     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3008                                         IsInheritedVirtualBase);
3009 
3010   ExprResult BaseInit;
3011 
3012   switch (ImplicitInitKind) {
3013   case IIK_Inherit: {
3014     const CXXRecordDecl *Inherited =
3015         Constructor->getInheritedConstructor()->getParent();
3016     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3017     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3018       // C++11 [class.inhctor]p8:
3019       //   Each expression in the expression-list is of the form
3020       //   static_cast<T&&>(p), where p is the name of the corresponding
3021       //   constructor parameter and T is the declared type of p.
3022       SmallVector<Expr*, 16> Args;
3023       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3024         ParmVarDecl *PD = Constructor->getParamDecl(I);
3025         ExprResult ArgExpr =
3026             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3027                                      VK_LValue, SourceLocation());
3028         if (ArgExpr.isInvalid())
3029           return true;
3030         Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3031       }
3032 
3033       InitializationKind InitKind = InitializationKind::CreateDirect(
3034           Constructor->getLocation(), SourceLocation(), SourceLocation());
3035       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3036       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3037       break;
3038     }
3039   }
3040   // Fall through.
3041   case IIK_Default: {
3042     InitializationKind InitKind
3043       = InitializationKind::CreateDefault(Constructor->getLocation());
3044     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3045     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3046     break;
3047   }
3048 
3049   case IIK_Move:
3050   case IIK_Copy: {
3051     bool Moving = ImplicitInitKind == IIK_Move;
3052     ParmVarDecl *Param = Constructor->getParamDecl(0);
3053     QualType ParamType = Param->getType().getNonReferenceType();
3054 
3055     Expr *CopyCtorArg =
3056       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3057                           SourceLocation(), Param, false,
3058                           Constructor->getLocation(), ParamType,
3059                           VK_LValue, 0);
3060 
3061     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3062 
3063     // Cast to the base class to avoid ambiguities.
3064     QualType ArgTy =
3065       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3066                                        ParamType.getQualifiers());
3067 
3068     if (Moving) {
3069       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3070     }
3071 
3072     CXXCastPath BasePath;
3073     BasePath.push_back(BaseSpec);
3074     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3075                                             CK_UncheckedDerivedToBase,
3076                                             Moving ? VK_XValue : VK_LValue,
3077                                             &BasePath).take();
3078 
3079     InitializationKind InitKind
3080       = InitializationKind::CreateDirect(Constructor->getLocation(),
3081                                          SourceLocation(), SourceLocation());
3082     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3083     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3084     break;
3085   }
3086   }
3087 
3088   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3089   if (BaseInit.isInvalid())
3090     return true;
3091 
3092   CXXBaseInit =
3093     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3094                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3095                                                         SourceLocation()),
3096                                              BaseSpec->isVirtual(),
3097                                              SourceLocation(),
3098                                              BaseInit.takeAs<Expr>(),
3099                                              SourceLocation(),
3100                                              SourceLocation());
3101 
3102   return false;
3103 }
3104 
3105 static bool RefersToRValueRef(Expr *MemRef) {
3106   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3107   return Referenced->getType()->isRValueReferenceType();
3108 }
3109 
3110 static bool
3111 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3112                                ImplicitInitializerKind ImplicitInitKind,
3113                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3114                                CXXCtorInitializer *&CXXMemberInit) {
3115   if (Field->isInvalidDecl())
3116     return true;
3117 
3118   SourceLocation Loc = Constructor->getLocation();
3119 
3120   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3121     bool Moving = ImplicitInitKind == IIK_Move;
3122     ParmVarDecl *Param = Constructor->getParamDecl(0);
3123     QualType ParamType = Param->getType().getNonReferenceType();
3124 
3125     // Suppress copying zero-width bitfields.
3126     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3127       return false;
3128 
3129     Expr *MemberExprBase =
3130       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3131                           SourceLocation(), Param, false,
3132                           Loc, ParamType, VK_LValue, 0);
3133 
3134     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3135 
3136     if (Moving) {
3137       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3138     }
3139 
3140     // Build a reference to this field within the parameter.
3141     CXXScopeSpec SS;
3142     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3143                               Sema::LookupMemberName);
3144     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3145                                   : cast<ValueDecl>(Field), AS_public);
3146     MemberLookup.resolveKind();
3147     ExprResult CtorArg
3148       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3149                                          ParamType, Loc,
3150                                          /*IsArrow=*/false,
3151                                          SS,
3152                                          /*TemplateKWLoc=*/SourceLocation(),
3153                                          /*FirstQualifierInScope=*/0,
3154                                          MemberLookup,
3155                                          /*TemplateArgs=*/0);
3156     if (CtorArg.isInvalid())
3157       return true;
3158 
3159     // C++11 [class.copy]p15:
3160     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3161     //     with static_cast<T&&>(x.m);
3162     if (RefersToRValueRef(CtorArg.get())) {
3163       CtorArg = CastForMoving(SemaRef, CtorArg.take());
3164     }
3165 
3166     // When the field we are copying is an array, create index variables for
3167     // each dimension of the array. We use these index variables to subscript
3168     // the source array, and other clients (e.g., CodeGen) will perform the
3169     // necessary iteration with these index variables.
3170     SmallVector<VarDecl *, 4> IndexVariables;
3171     QualType BaseType = Field->getType();
3172     QualType SizeType = SemaRef.Context.getSizeType();
3173     bool InitializingArray = false;
3174     while (const ConstantArrayType *Array
3175                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3176       InitializingArray = true;
3177       // Create the iteration variable for this array index.
3178       IdentifierInfo *IterationVarName = 0;
3179       {
3180         SmallString<8> Str;
3181         llvm::raw_svector_ostream OS(Str);
3182         OS << "__i" << IndexVariables.size();
3183         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3184       }
3185       VarDecl *IterationVar
3186         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3187                           IterationVarName, SizeType,
3188                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3189                           SC_None);
3190       IndexVariables.push_back(IterationVar);
3191 
3192       // Create a reference to the iteration variable.
3193       ExprResult IterationVarRef
3194         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3195       assert(!IterationVarRef.isInvalid() &&
3196              "Reference to invented variable cannot fail!");
3197       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3198       assert(!IterationVarRef.isInvalid() &&
3199              "Conversion of invented variable cannot fail!");
3200 
3201       // Subscript the array with this iteration variable.
3202       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
3203                                                         IterationVarRef.take(),
3204                                                         Loc);
3205       if (CtorArg.isInvalid())
3206         return true;
3207 
3208       BaseType = Array->getElementType();
3209     }
3210 
3211     // The array subscript expression is an lvalue, which is wrong for moving.
3212     if (Moving && InitializingArray)
3213       CtorArg = CastForMoving(SemaRef, CtorArg.take());
3214 
3215     // Construct the entity that we will be initializing. For an array, this
3216     // will be first element in the array, which may require several levels
3217     // of array-subscript entities.
3218     SmallVector<InitializedEntity, 4> Entities;
3219     Entities.reserve(1 + IndexVariables.size());
3220     if (Indirect)
3221       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3222     else
3223       Entities.push_back(InitializedEntity::InitializeMember(Field));
3224     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3225       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3226                                                               0,
3227                                                               Entities.back()));
3228 
3229     // Direct-initialize to use the copy constructor.
3230     InitializationKind InitKind =
3231       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3232 
3233     Expr *CtorArgE = CtorArg.takeAs<Expr>();
3234     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3235 
3236     ExprResult MemberInit
3237       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3238                         MultiExprArg(&CtorArgE, 1));
3239     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3240     if (MemberInit.isInvalid())
3241       return true;
3242 
3243     if (Indirect) {
3244       assert(IndexVariables.size() == 0 &&
3245              "Indirect field improperly initialized");
3246       CXXMemberInit
3247         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3248                                                    Loc, Loc,
3249                                                    MemberInit.takeAs<Expr>(),
3250                                                    Loc);
3251     } else
3252       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3253                                                  Loc, MemberInit.takeAs<Expr>(),
3254                                                  Loc,
3255                                                  IndexVariables.data(),
3256                                                  IndexVariables.size());
3257     return false;
3258   }
3259 
3260   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3261          "Unhandled implicit init kind!");
3262 
3263   QualType FieldBaseElementType =
3264     SemaRef.Context.getBaseElementType(Field->getType());
3265 
3266   if (FieldBaseElementType->isRecordType()) {
3267     InitializedEntity InitEntity
3268       = Indirect? InitializedEntity::InitializeMember(Indirect)
3269                 : InitializedEntity::InitializeMember(Field);
3270     InitializationKind InitKind =
3271       InitializationKind::CreateDefault(Loc);
3272 
3273     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3274     ExprResult MemberInit =
3275       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3276 
3277     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3278     if (MemberInit.isInvalid())
3279       return true;
3280 
3281     if (Indirect)
3282       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3283                                                                Indirect, Loc,
3284                                                                Loc,
3285                                                                MemberInit.get(),
3286                                                                Loc);
3287     else
3288       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3289                                                                Field, Loc, Loc,
3290                                                                MemberInit.get(),
3291                                                                Loc);
3292     return false;
3293   }
3294 
3295   if (!Field->getParent()->isUnion()) {
3296     if (FieldBaseElementType->isReferenceType()) {
3297       SemaRef.Diag(Constructor->getLocation(),
3298                    diag::err_uninitialized_member_in_ctor)
3299       << (int)Constructor->isImplicit()
3300       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3301       << 0 << Field->getDeclName();
3302       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3303       return true;
3304     }
3305 
3306     if (FieldBaseElementType.isConstQualified()) {
3307       SemaRef.Diag(Constructor->getLocation(),
3308                    diag::err_uninitialized_member_in_ctor)
3309       << (int)Constructor->isImplicit()
3310       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3311       << 1 << Field->getDeclName();
3312       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3313       return true;
3314     }
3315   }
3316 
3317   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3318       FieldBaseElementType->isObjCRetainableType() &&
3319       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3320       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3321     // ARC:
3322     //   Default-initialize Objective-C pointers to NULL.
3323     CXXMemberInit
3324       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3325                                                  Loc, Loc,
3326                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3327                                                  Loc);
3328     return false;
3329   }
3330 
3331   // Nothing to initialize.
3332   CXXMemberInit = 0;
3333   return false;
3334 }
3335 
3336 namespace {
3337 struct BaseAndFieldInfo {
3338   Sema &S;
3339   CXXConstructorDecl *Ctor;
3340   bool AnyErrorsInInits;
3341   ImplicitInitializerKind IIK;
3342   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3343   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3344   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3345 
3346   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3347     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3348     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3349     if (Generated && Ctor->isCopyConstructor())
3350       IIK = IIK_Copy;
3351     else if (Generated && Ctor->isMoveConstructor())
3352       IIK = IIK_Move;
3353     else if (Ctor->getInheritedConstructor())
3354       IIK = IIK_Inherit;
3355     else
3356       IIK = IIK_Default;
3357   }
3358 
3359   bool isImplicitCopyOrMove() const {
3360     switch (IIK) {
3361     case IIK_Copy:
3362     case IIK_Move:
3363       return true;
3364 
3365     case IIK_Default:
3366     case IIK_Inherit:
3367       return false;
3368     }
3369 
3370     llvm_unreachable("Invalid ImplicitInitializerKind!");
3371   }
3372 
3373   bool addFieldInitializer(CXXCtorInitializer *Init) {
3374     AllToInit.push_back(Init);
3375 
3376     // Check whether this initializer makes the field "used".
3377     if (Init->getInit()->HasSideEffects(S.Context))
3378       S.UnusedPrivateFields.remove(Init->getAnyMember());
3379 
3380     return false;
3381   }
3382 
3383   bool isInactiveUnionMember(FieldDecl *Field) {
3384     RecordDecl *Record = Field->getParent();
3385     if (!Record->isUnion())
3386       return false;
3387 
3388     if (FieldDecl *Active =
3389             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3390       return Active != Field->getCanonicalDecl();
3391 
3392     // In an implicit copy or move constructor, ignore any in-class initializer.
3393     if (isImplicitCopyOrMove())
3394       return true;
3395 
3396     // If there's no explicit initialization, the field is active only if it
3397     // has an in-class initializer...
3398     if (Field->hasInClassInitializer())
3399       return false;
3400     // ... or it's an anonymous struct or union whose class has an in-class
3401     // initializer.
3402     if (!Field->isAnonymousStructOrUnion())
3403       return true;
3404     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3405     return !FieldRD->hasInClassInitializer();
3406   }
3407 
3408   /// \brief Determine whether the given field is, or is within, a union member
3409   /// that is inactive (because there was an initializer given for a different
3410   /// member of the union, or because the union was not initialized at all).
3411   bool isWithinInactiveUnionMember(FieldDecl *Field,
3412                                    IndirectFieldDecl *Indirect) {
3413     if (!Indirect)
3414       return isInactiveUnionMember(Field);
3415 
3416     for (IndirectFieldDecl::chain_iterator C = Indirect->chain_begin(),
3417                                            CEnd = Indirect->chain_end();
3418          C != CEnd; ++C) {
3419       FieldDecl *Field = dyn_cast<FieldDecl>(*C);
3420       if (Field && isInactiveUnionMember(Field))
3421         return true;
3422     }
3423     return false;
3424   }
3425 };
3426 }
3427 
3428 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3429 /// array type.
3430 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3431   if (T->isIncompleteArrayType())
3432     return true;
3433 
3434   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3435     if (!ArrayT->getSize())
3436       return true;
3437 
3438     T = ArrayT->getElementType();
3439   }
3440 
3441   return false;
3442 }
3443 
3444 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3445                                     FieldDecl *Field,
3446                                     IndirectFieldDecl *Indirect = 0) {
3447   if (Field->isInvalidDecl())
3448     return false;
3449 
3450   // Overwhelmingly common case: we have a direct initializer for this field.
3451   if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3452     return Info.addFieldInitializer(Init);
3453 
3454   // C++11 [class.base.init]p8:
3455   //   if the entity is a non-static data member that has a
3456   //   brace-or-equal-initializer and either
3457   //   -- the constructor's class is a union and no other variant member of that
3458   //      union is designated by a mem-initializer-id or
3459   //   -- the constructor's class is not a union, and, if the entity is a member
3460   //      of an anonymous union, no other member of that union is designated by
3461   //      a mem-initializer-id,
3462   //   the entity is initialized as specified in [dcl.init].
3463   //
3464   // We also apply the same rules to handle anonymous structs within anonymous
3465   // unions.
3466   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3467     return false;
3468 
3469   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3470     Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3471                                            Info.Ctor->getLocation(), Field);
3472     CXXCtorInitializer *Init;
3473     if (Indirect)
3474       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3475                                                       SourceLocation(),
3476                                                       SourceLocation(), DIE,
3477                                                       SourceLocation());
3478     else
3479       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3480                                                       SourceLocation(),
3481                                                       SourceLocation(), DIE,
3482                                                       SourceLocation());
3483     return Info.addFieldInitializer(Init);
3484   }
3485 
3486   // Don't initialize incomplete or zero-length arrays.
3487   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3488     return false;
3489 
3490   // Don't try to build an implicit initializer if there were semantic
3491   // errors in any of the initializers (and therefore we might be
3492   // missing some that the user actually wrote).
3493   if (Info.AnyErrorsInInits)
3494     return false;
3495 
3496   CXXCtorInitializer *Init = 0;
3497   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3498                                      Indirect, Init))
3499     return true;
3500 
3501   if (!Init)
3502     return false;
3503 
3504   return Info.addFieldInitializer(Init);
3505 }
3506 
3507 bool
3508 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3509                                CXXCtorInitializer *Initializer) {
3510   assert(Initializer->isDelegatingInitializer());
3511   Constructor->setNumCtorInitializers(1);
3512   CXXCtorInitializer **initializer =
3513     new (Context) CXXCtorInitializer*[1];
3514   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3515   Constructor->setCtorInitializers(initializer);
3516 
3517   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3518     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3519     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3520   }
3521 
3522   DelegatingCtorDecls.push_back(Constructor);
3523 
3524   return false;
3525 }
3526 
3527 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3528                                ArrayRef<CXXCtorInitializer *> Initializers) {
3529   if (Constructor->isDependentContext()) {
3530     // Just store the initializers as written, they will be checked during
3531     // instantiation.
3532     if (!Initializers.empty()) {
3533       Constructor->setNumCtorInitializers(Initializers.size());
3534       CXXCtorInitializer **baseOrMemberInitializers =
3535         new (Context) CXXCtorInitializer*[Initializers.size()];
3536       memcpy(baseOrMemberInitializers, Initializers.data(),
3537              Initializers.size() * sizeof(CXXCtorInitializer*));
3538       Constructor->setCtorInitializers(baseOrMemberInitializers);
3539     }
3540 
3541     // Let template instantiation know whether we had errors.
3542     if (AnyErrors)
3543       Constructor->setInvalidDecl();
3544 
3545     return false;
3546   }
3547 
3548   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3549 
3550   // We need to build the initializer AST according to order of construction
3551   // and not what user specified in the Initializers list.
3552   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3553   if (!ClassDecl)
3554     return true;
3555 
3556   bool HadError = false;
3557 
3558   for (unsigned i = 0; i < Initializers.size(); i++) {
3559     CXXCtorInitializer *Member = Initializers[i];
3560 
3561     if (Member->isBaseInitializer())
3562       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3563     else {
3564       Info.AllBaseFields[Member->getAnyMember()] = Member;
3565 
3566       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3567         for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3568                                             CEnd = F->chain_end();
3569              C != CEnd; ++C) {
3570           FieldDecl *FD = dyn_cast<FieldDecl>(*C);
3571           if (FD && FD->getParent()->isUnion())
3572             Info.ActiveUnionMember.insert(std::make_pair(
3573                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3574         }
3575       } else if (FieldDecl *FD = Member->getMember()) {
3576         if (FD->getParent()->isUnion())
3577           Info.ActiveUnionMember.insert(std::make_pair(
3578               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3579       }
3580     }
3581   }
3582 
3583   // Keep track of the direct virtual bases.
3584   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3585   for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3586        E = ClassDecl->bases_end(); I != E; ++I) {
3587     if (I->isVirtual())
3588       DirectVBases.insert(I);
3589   }
3590 
3591   // Push virtual bases before others.
3592   for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3593        E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3594 
3595     if (CXXCtorInitializer *Value
3596         = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3597       // [class.base.init]p7, per DR257:
3598       //   A mem-initializer where the mem-initializer-id names a virtual base
3599       //   class is ignored during execution of a constructor of any class that
3600       //   is not the most derived class.
3601       if (ClassDecl->isAbstract()) {
3602         // FIXME: Provide a fixit to remove the base specifier. This requires
3603         // tracking the location of the associated comma for a base specifier.
3604         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3605           << VBase->getType() << ClassDecl;
3606         DiagnoseAbstractType(ClassDecl);
3607       }
3608 
3609       Info.AllToInit.push_back(Value);
3610     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3611       // [class.base.init]p8, per DR257:
3612       //   If a given [...] base class is not named by a mem-initializer-id
3613       //   [...] and the entity is not a virtual base class of an abstract
3614       //   class, then [...] the entity is default-initialized.
3615       bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3616       CXXCtorInitializer *CXXBaseInit;
3617       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3618                                        VBase, IsInheritedVirtualBase,
3619                                        CXXBaseInit)) {
3620         HadError = true;
3621         continue;
3622       }
3623 
3624       Info.AllToInit.push_back(CXXBaseInit);
3625     }
3626   }
3627 
3628   // Non-virtual bases.
3629   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3630        E = ClassDecl->bases_end(); Base != E; ++Base) {
3631     // Virtuals are in the virtual base list and already constructed.
3632     if (Base->isVirtual())
3633       continue;
3634 
3635     if (CXXCtorInitializer *Value
3636           = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3637       Info.AllToInit.push_back(Value);
3638     } else if (!AnyErrors) {
3639       CXXCtorInitializer *CXXBaseInit;
3640       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3641                                        Base, /*IsInheritedVirtualBase=*/false,
3642                                        CXXBaseInit)) {
3643         HadError = true;
3644         continue;
3645       }
3646 
3647       Info.AllToInit.push_back(CXXBaseInit);
3648     }
3649   }
3650 
3651   // Fields.
3652   for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3653                                MemEnd = ClassDecl->decls_end();
3654        Mem != MemEnd; ++Mem) {
3655     if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3656       // C++ [class.bit]p2:
3657       //   A declaration for a bit-field that omits the identifier declares an
3658       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3659       //   initialized.
3660       if (F->isUnnamedBitfield())
3661         continue;
3662 
3663       // If we're not generating the implicit copy/move constructor, then we'll
3664       // handle anonymous struct/union fields based on their individual
3665       // indirect fields.
3666       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3667         continue;
3668 
3669       if (CollectFieldInitializer(*this, Info, F))
3670         HadError = true;
3671       continue;
3672     }
3673 
3674     // Beyond this point, we only consider default initialization.
3675     if (Info.isImplicitCopyOrMove())
3676       continue;
3677 
3678     if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3679       if (F->getType()->isIncompleteArrayType()) {
3680         assert(ClassDecl->hasFlexibleArrayMember() &&
3681                "Incomplete array type is not valid");
3682         continue;
3683       }
3684 
3685       // Initialize each field of an anonymous struct individually.
3686       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3687         HadError = true;
3688 
3689       continue;
3690     }
3691   }
3692 
3693   unsigned NumInitializers = Info.AllToInit.size();
3694   if (NumInitializers > 0) {
3695     Constructor->setNumCtorInitializers(NumInitializers);
3696     CXXCtorInitializer **baseOrMemberInitializers =
3697       new (Context) CXXCtorInitializer*[NumInitializers];
3698     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3699            NumInitializers * sizeof(CXXCtorInitializer*));
3700     Constructor->setCtorInitializers(baseOrMemberInitializers);
3701 
3702     // Constructors implicitly reference the base and member
3703     // destructors.
3704     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3705                                            Constructor->getParent());
3706   }
3707 
3708   return HadError;
3709 }
3710 
3711 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3712   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3713     const RecordDecl *RD = RT->getDecl();
3714     if (RD->isAnonymousStructOrUnion()) {
3715       for (RecordDecl::field_iterator Field = RD->field_begin(),
3716           E = RD->field_end(); Field != E; ++Field)
3717         PopulateKeysForFields(*Field, IdealInits);
3718       return;
3719     }
3720   }
3721   IdealInits.push_back(Field);
3722 }
3723 
3724 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3725   return Context.getCanonicalType(BaseType).getTypePtr();
3726 }
3727 
3728 static const void *GetKeyForMember(ASTContext &Context,
3729                                    CXXCtorInitializer *Member) {
3730   if (!Member->isAnyMemberInitializer())
3731     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3732 
3733   return Member->getAnyMember();
3734 }
3735 
3736 static void DiagnoseBaseOrMemInitializerOrder(
3737     Sema &SemaRef, const CXXConstructorDecl *Constructor,
3738     ArrayRef<CXXCtorInitializer *> Inits) {
3739   if (Constructor->getDeclContext()->isDependentContext())
3740     return;
3741 
3742   // Don't check initializers order unless the warning is enabled at the
3743   // location of at least one initializer.
3744   bool ShouldCheckOrder = false;
3745   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3746     CXXCtorInitializer *Init = Inits[InitIndex];
3747     if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3748                                          Init->getSourceLocation())
3749           != DiagnosticsEngine::Ignored) {
3750       ShouldCheckOrder = true;
3751       break;
3752     }
3753   }
3754   if (!ShouldCheckOrder)
3755     return;
3756 
3757   // Build the list of bases and members in the order that they'll
3758   // actually be initialized.  The explicit initializers should be in
3759   // this same order but may be missing things.
3760   SmallVector<const void*, 32> IdealInitKeys;
3761 
3762   const CXXRecordDecl *ClassDecl = Constructor->getParent();
3763 
3764   // 1. Virtual bases.
3765   for (CXXRecordDecl::base_class_const_iterator VBase =
3766        ClassDecl->vbases_begin(),
3767        E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3768     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3769 
3770   // 2. Non-virtual bases.
3771   for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3772        E = ClassDecl->bases_end(); Base != E; ++Base) {
3773     if (Base->isVirtual())
3774       continue;
3775     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3776   }
3777 
3778   // 3. Direct fields.
3779   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3780        E = ClassDecl->field_end(); Field != E; ++Field) {
3781     if (Field->isUnnamedBitfield())
3782       continue;
3783 
3784     PopulateKeysForFields(*Field, IdealInitKeys);
3785   }
3786 
3787   unsigned NumIdealInits = IdealInitKeys.size();
3788   unsigned IdealIndex = 0;
3789 
3790   CXXCtorInitializer *PrevInit = 0;
3791   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3792     CXXCtorInitializer *Init = Inits[InitIndex];
3793     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3794 
3795     // Scan forward to try to find this initializer in the idealized
3796     // initializers list.
3797     for (; IdealIndex != NumIdealInits; ++IdealIndex)
3798       if (InitKey == IdealInitKeys[IdealIndex])
3799         break;
3800 
3801     // If we didn't find this initializer, it must be because we
3802     // scanned past it on a previous iteration.  That can only
3803     // happen if we're out of order;  emit a warning.
3804     if (IdealIndex == NumIdealInits && PrevInit) {
3805       Sema::SemaDiagnosticBuilder D =
3806         SemaRef.Diag(PrevInit->getSourceLocation(),
3807                      diag::warn_initializer_out_of_order);
3808 
3809       if (PrevInit->isAnyMemberInitializer())
3810         D << 0 << PrevInit->getAnyMember()->getDeclName();
3811       else
3812         D << 1 << PrevInit->getTypeSourceInfo()->getType();
3813 
3814       if (Init->isAnyMemberInitializer())
3815         D << 0 << Init->getAnyMember()->getDeclName();
3816       else
3817         D << 1 << Init->getTypeSourceInfo()->getType();
3818 
3819       // Move back to the initializer's location in the ideal list.
3820       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3821         if (InitKey == IdealInitKeys[IdealIndex])
3822           break;
3823 
3824       assert(IdealIndex != NumIdealInits &&
3825              "initializer not found in initializer list");
3826     }
3827 
3828     PrevInit = Init;
3829   }
3830 }
3831 
3832 namespace {
3833 bool CheckRedundantInit(Sema &S,
3834                         CXXCtorInitializer *Init,
3835                         CXXCtorInitializer *&PrevInit) {
3836   if (!PrevInit) {
3837     PrevInit = Init;
3838     return false;
3839   }
3840 
3841   if (FieldDecl *Field = Init->getAnyMember())
3842     S.Diag(Init->getSourceLocation(),
3843            diag::err_multiple_mem_initialization)
3844       << Field->getDeclName()
3845       << Init->getSourceRange();
3846   else {
3847     const Type *BaseClass = Init->getBaseClass();
3848     assert(BaseClass && "neither field nor base");
3849     S.Diag(Init->getSourceLocation(),
3850            diag::err_multiple_base_initialization)
3851       << QualType(BaseClass, 0)
3852       << Init->getSourceRange();
3853   }
3854   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3855     << 0 << PrevInit->getSourceRange();
3856 
3857   return true;
3858 }
3859 
3860 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3861 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3862 
3863 bool CheckRedundantUnionInit(Sema &S,
3864                              CXXCtorInitializer *Init,
3865                              RedundantUnionMap &Unions) {
3866   FieldDecl *Field = Init->getAnyMember();
3867   RecordDecl *Parent = Field->getParent();
3868   NamedDecl *Child = Field;
3869 
3870   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3871     if (Parent->isUnion()) {
3872       UnionEntry &En = Unions[Parent];
3873       if (En.first && En.first != Child) {
3874         S.Diag(Init->getSourceLocation(),
3875                diag::err_multiple_mem_union_initialization)
3876           << Field->getDeclName()
3877           << Init->getSourceRange();
3878         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3879           << 0 << En.second->getSourceRange();
3880         return true;
3881       }
3882       if (!En.first) {
3883         En.first = Child;
3884         En.second = Init;
3885       }
3886       if (!Parent->isAnonymousStructOrUnion())
3887         return false;
3888     }
3889 
3890     Child = Parent;
3891     Parent = cast<RecordDecl>(Parent->getDeclContext());
3892   }
3893 
3894   return false;
3895 }
3896 }
3897 
3898 /// ActOnMemInitializers - Handle the member initializers for a constructor.
3899 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3900                                 SourceLocation ColonLoc,
3901                                 ArrayRef<CXXCtorInitializer*> MemInits,
3902                                 bool AnyErrors) {
3903   if (!ConstructorDecl)
3904     return;
3905 
3906   AdjustDeclIfTemplate(ConstructorDecl);
3907 
3908   CXXConstructorDecl *Constructor
3909     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3910 
3911   if (!Constructor) {
3912     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3913     return;
3914   }
3915 
3916   // Mapping for the duplicate initializers check.
3917   // For member initializers, this is keyed with a FieldDecl*.
3918   // For base initializers, this is keyed with a Type*.
3919   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
3920 
3921   // Mapping for the inconsistent anonymous-union initializers check.
3922   RedundantUnionMap MemberUnions;
3923 
3924   bool HadError = false;
3925   for (unsigned i = 0; i < MemInits.size(); i++) {
3926     CXXCtorInitializer *Init = MemInits[i];
3927 
3928     // Set the source order index.
3929     Init->setSourceOrder(i);
3930 
3931     if (Init->isAnyMemberInitializer()) {
3932       FieldDecl *Field = Init->getAnyMember();
3933       if (CheckRedundantInit(*this, Init, Members[Field]) ||
3934           CheckRedundantUnionInit(*this, Init, MemberUnions))
3935         HadError = true;
3936     } else if (Init->isBaseInitializer()) {
3937       const void *Key =
3938           GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3939       if (CheckRedundantInit(*this, Init, Members[Key]))
3940         HadError = true;
3941     } else {
3942       assert(Init->isDelegatingInitializer());
3943       // This must be the only initializer
3944       if (MemInits.size() != 1) {
3945         Diag(Init->getSourceLocation(),
3946              diag::err_delegating_initializer_alone)
3947           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3948         // We will treat this as being the only initializer.
3949       }
3950       SetDelegatingInitializer(Constructor, MemInits[i]);
3951       // Return immediately as the initializer is set.
3952       return;
3953     }
3954   }
3955 
3956   if (HadError)
3957     return;
3958 
3959   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
3960 
3961   SetCtorInitializers(Constructor, AnyErrors, MemInits);
3962 
3963   DiagnoseUninitializedFields(*this, Constructor);
3964 }
3965 
3966 void
3967 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3968                                              CXXRecordDecl *ClassDecl) {
3969   // Ignore dependent contexts. Also ignore unions, since their members never
3970   // have destructors implicitly called.
3971   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3972     return;
3973 
3974   // FIXME: all the access-control diagnostics are positioned on the
3975   // field/base declaration.  That's probably good; that said, the
3976   // user might reasonably want to know why the destructor is being
3977   // emitted, and we currently don't say.
3978 
3979   // Non-static data members.
3980   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3981        E = ClassDecl->field_end(); I != E; ++I) {
3982     FieldDecl *Field = *I;
3983     if (Field->isInvalidDecl())
3984       continue;
3985 
3986     // Don't destroy incomplete or zero-length arrays.
3987     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3988       continue;
3989 
3990     QualType FieldType = Context.getBaseElementType(Field->getType());
3991 
3992     const RecordType* RT = FieldType->getAs<RecordType>();
3993     if (!RT)
3994       continue;
3995 
3996     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3997     if (FieldClassDecl->isInvalidDecl())
3998       continue;
3999     if (FieldClassDecl->hasIrrelevantDestructor())
4000       continue;
4001     // The destructor for an implicit anonymous union member is never invoked.
4002     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4003       continue;
4004 
4005     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4006     assert(Dtor && "No dtor found for FieldClassDecl!");
4007     CheckDestructorAccess(Field->getLocation(), Dtor,
4008                           PDiag(diag::err_access_dtor_field)
4009                             << Field->getDeclName()
4010                             << FieldType);
4011 
4012     MarkFunctionReferenced(Location, Dtor);
4013     DiagnoseUseOfDecl(Dtor, Location);
4014   }
4015 
4016   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4017 
4018   // Bases.
4019   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4020        E = ClassDecl->bases_end(); Base != E; ++Base) {
4021     // Bases are always records in a well-formed non-dependent class.
4022     const RecordType *RT = Base->getType()->getAs<RecordType>();
4023 
4024     // Remember direct virtual bases.
4025     if (Base->isVirtual())
4026       DirectVirtualBases.insert(RT);
4027 
4028     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4029     // If our base class is invalid, we probably can't get its dtor anyway.
4030     if (BaseClassDecl->isInvalidDecl())
4031       continue;
4032     if (BaseClassDecl->hasIrrelevantDestructor())
4033       continue;
4034 
4035     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4036     assert(Dtor && "No dtor found for BaseClassDecl!");
4037 
4038     // FIXME: caret should be on the start of the class name
4039     CheckDestructorAccess(Base->getLocStart(), Dtor,
4040                           PDiag(diag::err_access_dtor_base)
4041                             << Base->getType()
4042                             << Base->getSourceRange(),
4043                           Context.getTypeDeclType(ClassDecl));
4044 
4045     MarkFunctionReferenced(Location, Dtor);
4046     DiagnoseUseOfDecl(Dtor, Location);
4047   }
4048 
4049   // Virtual bases.
4050   for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
4051        E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
4052 
4053     // Bases are always records in a well-formed non-dependent class.
4054     const RecordType *RT = VBase->getType()->castAs<RecordType>();
4055 
4056     // Ignore direct virtual bases.
4057     if (DirectVirtualBases.count(RT))
4058       continue;
4059 
4060     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4061     // If our base class is invalid, we probably can't get its dtor anyway.
4062     if (BaseClassDecl->isInvalidDecl())
4063       continue;
4064     if (BaseClassDecl->hasIrrelevantDestructor())
4065       continue;
4066 
4067     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4068     assert(Dtor && "No dtor found for BaseClassDecl!");
4069     if (CheckDestructorAccess(
4070             ClassDecl->getLocation(), Dtor,
4071             PDiag(diag::err_access_dtor_vbase)
4072                 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
4073             Context.getTypeDeclType(ClassDecl)) ==
4074         AR_accessible) {
4075       CheckDerivedToBaseConversion(
4076           Context.getTypeDeclType(ClassDecl), VBase->getType(),
4077           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4078           SourceRange(), DeclarationName(), 0);
4079     }
4080 
4081     MarkFunctionReferenced(Location, Dtor);
4082     DiagnoseUseOfDecl(Dtor, Location);
4083   }
4084 }
4085 
4086 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4087   if (!CDtorDecl)
4088     return;
4089 
4090   if (CXXConstructorDecl *Constructor
4091       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4092     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4093     DiagnoseUninitializedFields(*this, Constructor);
4094   }
4095 }
4096 
4097 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4098                                   unsigned DiagID, AbstractDiagSelID SelID) {
4099   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4100     unsigned DiagID;
4101     AbstractDiagSelID SelID;
4102 
4103   public:
4104     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4105       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4106 
4107     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4108       if (Suppressed) return;
4109       if (SelID == -1)
4110         S.Diag(Loc, DiagID) << T;
4111       else
4112         S.Diag(Loc, DiagID) << SelID << T;
4113     }
4114   } Diagnoser(DiagID, SelID);
4115 
4116   return RequireNonAbstractType(Loc, T, Diagnoser);
4117 }
4118 
4119 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4120                                   TypeDiagnoser &Diagnoser) {
4121   if (!getLangOpts().CPlusPlus)
4122     return false;
4123 
4124   if (const ArrayType *AT = Context.getAsArrayType(T))
4125     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4126 
4127   if (const PointerType *PT = T->getAs<PointerType>()) {
4128     // Find the innermost pointer type.
4129     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4130       PT = T;
4131 
4132     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4133       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4134   }
4135 
4136   const RecordType *RT = T->getAs<RecordType>();
4137   if (!RT)
4138     return false;
4139 
4140   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4141 
4142   // We can't answer whether something is abstract until it has a
4143   // definition.  If it's currently being defined, we'll walk back
4144   // over all the declarations when we have a full definition.
4145   const CXXRecordDecl *Def = RD->getDefinition();
4146   if (!Def || Def->isBeingDefined())
4147     return false;
4148 
4149   if (!RD->isAbstract())
4150     return false;
4151 
4152   Diagnoser.diagnose(*this, Loc, T);
4153   DiagnoseAbstractType(RD);
4154 
4155   return true;
4156 }
4157 
4158 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4159   // Check if we've already emitted the list of pure virtual functions
4160   // for this class.
4161   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4162     return;
4163 
4164   // If the diagnostic is suppressed, don't emit the notes. We're only
4165   // going to emit them once, so try to attach them to a diagnostic we're
4166   // actually going to show.
4167   if (Diags.isLastDiagnosticIgnored())
4168     return;
4169 
4170   CXXFinalOverriderMap FinalOverriders;
4171   RD->getFinalOverriders(FinalOverriders);
4172 
4173   // Keep a set of seen pure methods so we won't diagnose the same method
4174   // more than once.
4175   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4176 
4177   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4178                                    MEnd = FinalOverriders.end();
4179        M != MEnd;
4180        ++M) {
4181     for (OverridingMethods::iterator SO = M->second.begin(),
4182                                   SOEnd = M->second.end();
4183          SO != SOEnd; ++SO) {
4184       // C++ [class.abstract]p4:
4185       //   A class is abstract if it contains or inherits at least one
4186       //   pure virtual function for which the final overrider is pure
4187       //   virtual.
4188 
4189       //
4190       if (SO->second.size() != 1)
4191         continue;
4192 
4193       if (!SO->second.front().Method->isPure())
4194         continue;
4195 
4196       if (!SeenPureMethods.insert(SO->second.front().Method))
4197         continue;
4198 
4199       Diag(SO->second.front().Method->getLocation(),
4200            diag::note_pure_virtual_function)
4201         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4202     }
4203   }
4204 
4205   if (!PureVirtualClassDiagSet)
4206     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4207   PureVirtualClassDiagSet->insert(RD);
4208 }
4209 
4210 namespace {
4211 struct AbstractUsageInfo {
4212   Sema &S;
4213   CXXRecordDecl *Record;
4214   CanQualType AbstractType;
4215   bool Invalid;
4216 
4217   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4218     : S(S), Record(Record),
4219       AbstractType(S.Context.getCanonicalType(
4220                    S.Context.getTypeDeclType(Record))),
4221       Invalid(false) {}
4222 
4223   void DiagnoseAbstractType() {
4224     if (Invalid) return;
4225     S.DiagnoseAbstractType(Record);
4226     Invalid = true;
4227   }
4228 
4229   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4230 };
4231 
4232 struct CheckAbstractUsage {
4233   AbstractUsageInfo &Info;
4234   const NamedDecl *Ctx;
4235 
4236   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4237     : Info(Info), Ctx(Ctx) {}
4238 
4239   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4240     switch (TL.getTypeLocClass()) {
4241 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4242 #define TYPELOC(CLASS, PARENT) \
4243     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4244 #include "clang/AST/TypeLocNodes.def"
4245     }
4246   }
4247 
4248   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4249     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4250     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4251       if (!TL.getParam(I))
4252         continue;
4253 
4254       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4255       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4256     }
4257   }
4258 
4259   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4260     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4261   }
4262 
4263   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4264     // Visit the type parameters from a permissive context.
4265     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4266       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4267       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4268         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4269           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4270       // TODO: other template argument types?
4271     }
4272   }
4273 
4274   // Visit pointee types from a permissive context.
4275 #define CheckPolymorphic(Type) \
4276   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4277     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4278   }
4279   CheckPolymorphic(PointerTypeLoc)
4280   CheckPolymorphic(ReferenceTypeLoc)
4281   CheckPolymorphic(MemberPointerTypeLoc)
4282   CheckPolymorphic(BlockPointerTypeLoc)
4283   CheckPolymorphic(AtomicTypeLoc)
4284 
4285   /// Handle all the types we haven't given a more specific
4286   /// implementation for above.
4287   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4288     // Every other kind of type that we haven't called out already
4289     // that has an inner type is either (1) sugar or (2) contains that
4290     // inner type in some way as a subobject.
4291     if (TypeLoc Next = TL.getNextTypeLoc())
4292       return Visit(Next, Sel);
4293 
4294     // If there's no inner type and we're in a permissive context,
4295     // don't diagnose.
4296     if (Sel == Sema::AbstractNone) return;
4297 
4298     // Check whether the type matches the abstract type.
4299     QualType T = TL.getType();
4300     if (T->isArrayType()) {
4301       Sel = Sema::AbstractArrayType;
4302       T = Info.S.Context.getBaseElementType(T);
4303     }
4304     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4305     if (CT != Info.AbstractType) return;
4306 
4307     // It matched; do some magic.
4308     if (Sel == Sema::AbstractArrayType) {
4309       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4310         << T << TL.getSourceRange();
4311     } else {
4312       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4313         << Sel << T << TL.getSourceRange();
4314     }
4315     Info.DiagnoseAbstractType();
4316   }
4317 };
4318 
4319 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4320                                   Sema::AbstractDiagSelID Sel) {
4321   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4322 }
4323 
4324 }
4325 
4326 /// Check for invalid uses of an abstract type in a method declaration.
4327 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4328                                     CXXMethodDecl *MD) {
4329   // No need to do the check on definitions, which require that
4330   // the return/param types be complete.
4331   if (MD->doesThisDeclarationHaveABody())
4332     return;
4333 
4334   // For safety's sake, just ignore it if we don't have type source
4335   // information.  This should never happen for non-implicit methods,
4336   // but...
4337   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4338     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4339 }
4340 
4341 /// Check for invalid uses of an abstract type within a class definition.
4342 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4343                                     CXXRecordDecl *RD) {
4344   for (CXXRecordDecl::decl_iterator
4345          I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4346     Decl *D = *I;
4347     if (D->isImplicit()) continue;
4348 
4349     // Methods and method templates.
4350     if (isa<CXXMethodDecl>(D)) {
4351       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4352     } else if (isa<FunctionTemplateDecl>(D)) {
4353       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4354       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4355 
4356     // Fields and static variables.
4357     } else if (isa<FieldDecl>(D)) {
4358       FieldDecl *FD = cast<FieldDecl>(D);
4359       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4360         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4361     } else if (isa<VarDecl>(D)) {
4362       VarDecl *VD = cast<VarDecl>(D);
4363       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4364         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4365 
4366     // Nested classes and class templates.
4367     } else if (isa<CXXRecordDecl>(D)) {
4368       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4369     } else if (isa<ClassTemplateDecl>(D)) {
4370       CheckAbstractClassUsage(Info,
4371                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4372     }
4373   }
4374 }
4375 
4376 /// \brief Perform semantic checks on a class definition that has been
4377 /// completing, introducing implicitly-declared members, checking for
4378 /// abstract types, etc.
4379 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4380   if (!Record)
4381     return;
4382 
4383   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4384     AbstractUsageInfo Info(*this, Record);
4385     CheckAbstractClassUsage(Info, Record);
4386   }
4387 
4388   // If this is not an aggregate type and has no user-declared constructor,
4389   // complain about any non-static data members of reference or const scalar
4390   // type, since they will never get initializers.
4391   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4392       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4393       !Record->isLambda()) {
4394     bool Complained = false;
4395     for (RecordDecl::field_iterator F = Record->field_begin(),
4396                                  FEnd = Record->field_end();
4397          F != FEnd; ++F) {
4398       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4399         continue;
4400 
4401       if (F->getType()->isReferenceType() ||
4402           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4403         if (!Complained) {
4404           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4405             << Record->getTagKind() << Record;
4406           Complained = true;
4407         }
4408 
4409         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4410           << F->getType()->isReferenceType()
4411           << F->getDeclName();
4412       }
4413     }
4414   }
4415 
4416   if (Record->isDynamicClass() && !Record->isDependentType())
4417     DynamicClasses.push_back(Record);
4418 
4419   if (Record->getIdentifier()) {
4420     // C++ [class.mem]p13:
4421     //   If T is the name of a class, then each of the following shall have a
4422     //   name different from T:
4423     //     - every member of every anonymous union that is a member of class T.
4424     //
4425     // C++ [class.mem]p14:
4426     //   In addition, if class T has a user-declared constructor (12.1), every
4427     //   non-static data member of class T shall have a name different from T.
4428     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4429     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4430          ++I) {
4431       NamedDecl *D = *I;
4432       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4433           isa<IndirectFieldDecl>(D)) {
4434         Diag(D->getLocation(), diag::err_member_name_of_class)
4435           << D->getDeclName();
4436         break;
4437       }
4438     }
4439   }
4440 
4441   // Warn if the class has virtual methods but non-virtual public destructor.
4442   if (Record->isPolymorphic() && !Record->isDependentType()) {
4443     CXXDestructorDecl *dtor = Record->getDestructor();
4444     if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
4445       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4446            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4447   }
4448 
4449   if (Record->isAbstract()) {
4450     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4451       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4452         << FA->isSpelledAsSealed();
4453       DiagnoseAbstractType(Record);
4454     }
4455   }
4456 
4457   if (!Record->isDependentType()) {
4458     for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4459                                      MEnd = Record->method_end();
4460          M != MEnd; ++M) {
4461       // See if a method overloads virtual methods in a base
4462       // class without overriding any.
4463       if (!M->isStatic())
4464         DiagnoseHiddenVirtualMethods(*M);
4465 
4466       // Check whether the explicitly-defaulted special members are valid.
4467       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4468         CheckExplicitlyDefaultedSpecialMember(*M);
4469 
4470       // For an explicitly defaulted or deleted special member, we defer
4471       // determining triviality until the class is complete. That time is now!
4472       if (!M->isImplicit() && !M->isUserProvided()) {
4473         CXXSpecialMember CSM = getSpecialMember(*M);
4474         if (CSM != CXXInvalid) {
4475           M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4476 
4477           // Inform the class that we've finished declaring this member.
4478           Record->finishedDefaultedOrDeletedMember(*M);
4479         }
4480       }
4481     }
4482   }
4483 
4484   // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4485   // function that is not a constructor declares that member function to be
4486   // const. [...] The class of which that function is a member shall be
4487   // a literal type.
4488   //
4489   // If the class has virtual bases, any constexpr members will already have
4490   // been diagnosed by the checks performed on the member declaration, so
4491   // suppress this (less useful) diagnostic.
4492   //
4493   // We delay this until we know whether an explicitly-defaulted (or deleted)
4494   // destructor for the class is trivial.
4495   if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4496       !Record->isLiteral() && !Record->getNumVBases()) {
4497     for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4498                                      MEnd = Record->method_end();
4499          M != MEnd; ++M) {
4500       if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4501         switch (Record->getTemplateSpecializationKind()) {
4502         case TSK_ImplicitInstantiation:
4503         case TSK_ExplicitInstantiationDeclaration:
4504         case TSK_ExplicitInstantiationDefinition:
4505           // If a template instantiates to a non-literal type, but its members
4506           // instantiate to constexpr functions, the template is technically
4507           // ill-formed, but we allow it for sanity.
4508           continue;
4509 
4510         case TSK_Undeclared:
4511         case TSK_ExplicitSpecialization:
4512           RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4513                              diag::err_constexpr_method_non_literal);
4514           break;
4515         }
4516 
4517         // Only produce one error per class.
4518         break;
4519       }
4520     }
4521   }
4522 
4523   // ms_struct is a request to use the same ABI rules as MSVC.  Check
4524   // whether this class uses any C++ features that are implemented
4525   // completely differently in MSVC, and if so, emit a diagnostic.
4526   // That diagnostic defaults to an error, but we allow projects to
4527   // map it down to a warning (or ignore it).  It's a fairly common
4528   // practice among users of the ms_struct pragma to mass-annotate
4529   // headers, sweeping up a bunch of types that the project doesn't
4530   // really rely on MSVC-compatible layout for.  We must therefore
4531   // support "ms_struct except for C++ stuff" as a secondary ABI.
4532   if (Record->isMsStruct(Context) &&
4533       (Record->isPolymorphic() || Record->getNumBases())) {
4534     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
4535   }
4536 
4537   // Declare inheriting constructors. We do this eagerly here because:
4538   // - The standard requires an eager diagnostic for conflicting inheriting
4539   //   constructors from different classes.
4540   // - The lazy declaration of the other implicit constructors is so as to not
4541   //   waste space and performance on classes that are not meant to be
4542   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4543   //   have inheriting constructors.
4544   DeclareInheritingConstructors(Record);
4545 }
4546 
4547 /// Look up the special member function that would be called by a special
4548 /// member function for a subobject of class type.
4549 ///
4550 /// \param Class The class type of the subobject.
4551 /// \param CSM The kind of special member function.
4552 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4553 /// \param ConstRHS True if this is a copy operation with a const object
4554 ///        on its RHS, that is, if the argument to the outer special member
4555 ///        function is 'const' and this is not a field marked 'mutable'.
4556 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4557     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4558     unsigned FieldQuals, bool ConstRHS) {
4559   unsigned LHSQuals = 0;
4560   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4561     LHSQuals = FieldQuals;
4562 
4563   unsigned RHSQuals = FieldQuals;
4564   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4565     RHSQuals = 0;
4566   else if (ConstRHS)
4567     RHSQuals |= Qualifiers::Const;
4568 
4569   return S.LookupSpecialMember(Class, CSM,
4570                                RHSQuals & Qualifiers::Const,
4571                                RHSQuals & Qualifiers::Volatile,
4572                                false,
4573                                LHSQuals & Qualifiers::Const,
4574                                LHSQuals & Qualifiers::Volatile);
4575 }
4576 
4577 /// Is the special member function which would be selected to perform the
4578 /// specified operation on the specified class type a constexpr constructor?
4579 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4580                                      Sema::CXXSpecialMember CSM,
4581                                      unsigned Quals, bool ConstRHS) {
4582   Sema::SpecialMemberOverloadResult *SMOR =
4583       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
4584   if (!SMOR || !SMOR->getMethod())
4585     // A constructor we wouldn't select can't be "involved in initializing"
4586     // anything.
4587     return true;
4588   return SMOR->getMethod()->isConstexpr();
4589 }
4590 
4591 /// Determine whether the specified special member function would be constexpr
4592 /// if it were implicitly defined.
4593 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4594                                               Sema::CXXSpecialMember CSM,
4595                                               bool ConstArg) {
4596   if (!S.getLangOpts().CPlusPlus11)
4597     return false;
4598 
4599   // C++11 [dcl.constexpr]p4:
4600   // In the definition of a constexpr constructor [...]
4601   bool Ctor = true;
4602   switch (CSM) {
4603   case Sema::CXXDefaultConstructor:
4604     // Since default constructor lookup is essentially trivial (and cannot
4605     // involve, for instance, template instantiation), we compute whether a
4606     // defaulted default constructor is constexpr directly within CXXRecordDecl.
4607     //
4608     // This is important for performance; we need to know whether the default
4609     // constructor is constexpr to determine whether the type is a literal type.
4610     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4611 
4612   case Sema::CXXCopyConstructor:
4613   case Sema::CXXMoveConstructor:
4614     // For copy or move constructors, we need to perform overload resolution.
4615     break;
4616 
4617   case Sema::CXXCopyAssignment:
4618   case Sema::CXXMoveAssignment:
4619     if (!S.getLangOpts().CPlusPlus1y)
4620       return false;
4621     // In C++1y, we need to perform overload resolution.
4622     Ctor = false;
4623     break;
4624 
4625   case Sema::CXXDestructor:
4626   case Sema::CXXInvalid:
4627     return false;
4628   }
4629 
4630   //   -- if the class is a non-empty union, or for each non-empty anonymous
4631   //      union member of a non-union class, exactly one non-static data member
4632   //      shall be initialized; [DR1359]
4633   //
4634   // If we squint, this is guaranteed, since exactly one non-static data member
4635   // will be initialized (if the constructor isn't deleted), we just don't know
4636   // which one.
4637   if (Ctor && ClassDecl->isUnion())
4638     return true;
4639 
4640   //   -- the class shall not have any virtual base classes;
4641   if (Ctor && ClassDecl->getNumVBases())
4642     return false;
4643 
4644   // C++1y [class.copy]p26:
4645   //   -- [the class] is a literal type, and
4646   if (!Ctor && !ClassDecl->isLiteral())
4647     return false;
4648 
4649   //   -- every constructor involved in initializing [...] base class
4650   //      sub-objects shall be a constexpr constructor;
4651   //   -- the assignment operator selected to copy/move each direct base
4652   //      class is a constexpr function, and
4653   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4654                                        BEnd = ClassDecl->bases_end();
4655        B != BEnd; ++B) {
4656     const RecordType *BaseType = B->getType()->getAs<RecordType>();
4657     if (!BaseType) continue;
4658 
4659     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4660     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
4661       return false;
4662   }
4663 
4664   //   -- every constructor involved in initializing non-static data members
4665   //      [...] shall be a constexpr constructor;
4666   //   -- every non-static data member and base class sub-object shall be
4667   //      initialized
4668   //   -- for each non-static data member of X that is of class type (or array
4669   //      thereof), the assignment operator selected to copy/move that member is
4670   //      a constexpr function
4671   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4672                                FEnd = ClassDecl->field_end();
4673        F != FEnd; ++F) {
4674     if (F->isInvalidDecl())
4675       continue;
4676     QualType BaseType = S.Context.getBaseElementType(F->getType());
4677     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
4678       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4679       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4680                                     BaseType.getCVRQualifiers(),
4681                                     ConstArg && !F->isMutable()))
4682         return false;
4683     }
4684   }
4685 
4686   // All OK, it's constexpr!
4687   return true;
4688 }
4689 
4690 static Sema::ImplicitExceptionSpecification
4691 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4692   switch (S.getSpecialMember(MD)) {
4693   case Sema::CXXDefaultConstructor:
4694     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4695   case Sema::CXXCopyConstructor:
4696     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4697   case Sema::CXXCopyAssignment:
4698     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4699   case Sema::CXXMoveConstructor:
4700     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4701   case Sema::CXXMoveAssignment:
4702     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4703   case Sema::CXXDestructor:
4704     return S.ComputeDefaultedDtorExceptionSpec(MD);
4705   case Sema::CXXInvalid:
4706     break;
4707   }
4708   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4709          "only special members have implicit exception specs");
4710   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4711 }
4712 
4713 static void
4714 updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4715                     const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4716   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4717   ExceptSpec.getEPI(EPI);
4718   FD->setType(S.Context.getFunctionType(FPT->getReturnType(),
4719                                         FPT->getParamTypes(), EPI));
4720 }
4721 
4722 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4723                                                             CXXMethodDecl *MD) {
4724   FunctionProtoType::ExtProtoInfo EPI;
4725 
4726   // Build an exception specification pointing back at this member.
4727   EPI.ExceptionSpecType = EST_Unevaluated;
4728   EPI.ExceptionSpecDecl = MD;
4729 
4730   // Set the calling convention to the default for C++ instance methods.
4731   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4732       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4733                                             /*IsCXXMethod=*/true));
4734   return EPI;
4735 }
4736 
4737 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4738   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4739   if (FPT->getExceptionSpecType() != EST_Unevaluated)
4740     return;
4741 
4742   // Evaluate the exception specification.
4743   ImplicitExceptionSpecification ExceptSpec =
4744       computeImplicitExceptionSpec(*this, Loc, MD);
4745 
4746   // Update the type of the special member to use it.
4747   updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4748 
4749   // A user-provided destructor can be defined outside the class. When that
4750   // happens, be sure to update the exception specification on both
4751   // declarations.
4752   const FunctionProtoType *CanonicalFPT =
4753     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4754   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4755     updateExceptionSpec(*this, MD->getCanonicalDecl(),
4756                         CanonicalFPT, ExceptSpec);
4757 }
4758 
4759 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4760   CXXRecordDecl *RD = MD->getParent();
4761   CXXSpecialMember CSM = getSpecialMember(MD);
4762 
4763   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4764          "not an explicitly-defaulted special member");
4765 
4766   // Whether this was the first-declared instance of the constructor.
4767   // This affects whether we implicitly add an exception spec and constexpr.
4768   bool First = MD == MD->getCanonicalDecl();
4769 
4770   bool HadError = false;
4771 
4772   // C++11 [dcl.fct.def.default]p1:
4773   //   A function that is explicitly defaulted shall
4774   //     -- be a special member function (checked elsewhere),
4775   //     -- have the same type (except for ref-qualifiers, and except that a
4776   //        copy operation can take a non-const reference) as an implicit
4777   //        declaration, and
4778   //     -- not have default arguments.
4779   unsigned ExpectedParams = 1;
4780   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4781     ExpectedParams = 0;
4782   if (MD->getNumParams() != ExpectedParams) {
4783     // This also checks for default arguments: a copy or move constructor with a
4784     // default argument is classified as a default constructor, and assignment
4785     // operations and destructors can't have default arguments.
4786     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4787       << CSM << MD->getSourceRange();
4788     HadError = true;
4789   } else if (MD->isVariadic()) {
4790     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4791       << CSM << MD->getSourceRange();
4792     HadError = true;
4793   }
4794 
4795   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4796 
4797   bool CanHaveConstParam = false;
4798   if (CSM == CXXCopyConstructor)
4799     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4800   else if (CSM == CXXCopyAssignment)
4801     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4802 
4803   QualType ReturnType = Context.VoidTy;
4804   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4805     // Check for return type matching.
4806     ReturnType = Type->getReturnType();
4807     QualType ExpectedReturnType =
4808         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4809     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4810       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4811         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4812       HadError = true;
4813     }
4814 
4815     // A defaulted special member cannot have cv-qualifiers.
4816     if (Type->getTypeQuals()) {
4817       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4818         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
4819       HadError = true;
4820     }
4821   }
4822 
4823   // Check for parameter type matching.
4824   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
4825   bool HasConstParam = false;
4826   if (ExpectedParams && ArgType->isReferenceType()) {
4827     // Argument must be reference to possibly-const T.
4828     QualType ReferentType = ArgType->getPointeeType();
4829     HasConstParam = ReferentType.isConstQualified();
4830 
4831     if (ReferentType.isVolatileQualified()) {
4832       Diag(MD->getLocation(),
4833            diag::err_defaulted_special_member_volatile_param) << CSM;
4834       HadError = true;
4835     }
4836 
4837     if (HasConstParam && !CanHaveConstParam) {
4838       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4839         Diag(MD->getLocation(),
4840              diag::err_defaulted_special_member_copy_const_param)
4841           << (CSM == CXXCopyAssignment);
4842         // FIXME: Explain why this special member can't be const.
4843       } else {
4844         Diag(MD->getLocation(),
4845              diag::err_defaulted_special_member_move_const_param)
4846           << (CSM == CXXMoveAssignment);
4847       }
4848       HadError = true;
4849     }
4850   } else if (ExpectedParams) {
4851     // A copy assignment operator can take its argument by value, but a
4852     // defaulted one cannot.
4853     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4854     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4855     HadError = true;
4856   }
4857 
4858   // C++11 [dcl.fct.def.default]p2:
4859   //   An explicitly-defaulted function may be declared constexpr only if it
4860   //   would have been implicitly declared as constexpr,
4861   // Do not apply this rule to members of class templates, since core issue 1358
4862   // makes such functions always instantiate to constexpr functions. For
4863   // functions which cannot be constexpr (for non-constructors in C++11 and for
4864   // destructors in C++1y), this is checked elsewhere.
4865   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4866                                                      HasConstParam);
4867   if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4868                                  : isa<CXXConstructorDecl>(MD)) &&
4869       MD->isConstexpr() && !Constexpr &&
4870       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4871     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4872     // FIXME: Explain why the special member can't be constexpr.
4873     HadError = true;
4874   }
4875 
4876   //   and may have an explicit exception-specification only if it is compatible
4877   //   with the exception-specification on the implicit declaration.
4878   if (Type->hasExceptionSpec()) {
4879     // Delay the check if this is the first declaration of the special member,
4880     // since we may not have parsed some necessary in-class initializers yet.
4881     if (First) {
4882       // If the exception specification needs to be instantiated, do so now,
4883       // before we clobber it with an EST_Unevaluated specification below.
4884       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4885         InstantiateExceptionSpec(MD->getLocStart(), MD);
4886         Type = MD->getType()->getAs<FunctionProtoType>();
4887       }
4888       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4889     } else
4890       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4891   }
4892 
4893   //   If a function is explicitly defaulted on its first declaration,
4894   if (First) {
4895     //  -- it is implicitly considered to be constexpr if the implicit
4896     //     definition would be,
4897     MD->setConstexpr(Constexpr);
4898 
4899     //  -- it is implicitly considered to have the same exception-specification
4900     //     as if it had been implicitly declared,
4901     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4902     EPI.ExceptionSpecType = EST_Unevaluated;
4903     EPI.ExceptionSpecDecl = MD;
4904     MD->setType(Context.getFunctionType(ReturnType,
4905                                         ArrayRef<QualType>(&ArgType,
4906                                                            ExpectedParams),
4907                                         EPI));
4908   }
4909 
4910   if (ShouldDeleteSpecialMember(MD, CSM)) {
4911     if (First) {
4912       SetDeclDeleted(MD, MD->getLocation());
4913     } else {
4914       // C++11 [dcl.fct.def.default]p4:
4915       //   [For a] user-provided explicitly-defaulted function [...] if such a
4916       //   function is implicitly defined as deleted, the program is ill-formed.
4917       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4918       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
4919       HadError = true;
4920     }
4921   }
4922 
4923   if (HadError)
4924     MD->setInvalidDecl();
4925 }
4926 
4927 /// Check whether the exception specification provided for an
4928 /// explicitly-defaulted special member matches the exception specification
4929 /// that would have been generated for an implicit special member, per
4930 /// C++11 [dcl.fct.def.default]p2.
4931 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4932     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4933   // Compute the implicit exception specification.
4934   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4935                                                        /*IsCXXMethod=*/true);
4936   FunctionProtoType::ExtProtoInfo EPI(CC);
4937   computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4938   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4939     Context.getFunctionType(Context.VoidTy, None, EPI));
4940 
4941   // Ensure that it matches.
4942   CheckEquivalentExceptionSpec(
4943     PDiag(diag::err_incorrect_defaulted_exception_spec)
4944       << getSpecialMember(MD), PDiag(),
4945     ImplicitType, SourceLocation(),
4946     SpecifiedType, MD->getLocation());
4947 }
4948 
4949 void Sema::CheckDelayedMemberExceptionSpecs() {
4950   SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4951               2> Checks;
4952   SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
4953 
4954   std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4955   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4956 
4957   // Perform any deferred checking of exception specifications for virtual
4958   // destructors.
4959   for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4960     const CXXDestructorDecl *Dtor = Checks[i].first;
4961     assert(!Dtor->getParent()->isDependentType() &&
4962            "Should not ever add destructors of templates into the list.");
4963     CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4964   }
4965 
4966   // Check that any explicitly-defaulted methods have exception specifications
4967   // compatible with their implicit exception specifications.
4968   for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4969     CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4970                                                 Specs[I].second);
4971 }
4972 
4973 namespace {
4974 struct SpecialMemberDeletionInfo {
4975   Sema &S;
4976   CXXMethodDecl *MD;
4977   Sema::CXXSpecialMember CSM;
4978   bool Diagnose;
4979 
4980   // Properties of the special member, computed for convenience.
4981   bool IsConstructor, IsAssignment, IsMove, ConstArg;
4982   SourceLocation Loc;
4983 
4984   bool AllFieldsAreConst;
4985 
4986   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4987                             Sema::CXXSpecialMember CSM, bool Diagnose)
4988     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4989       IsConstructor(false), IsAssignment(false), IsMove(false),
4990       ConstArg(false), Loc(MD->getLocation()),
4991       AllFieldsAreConst(true) {
4992     switch (CSM) {
4993       case Sema::CXXDefaultConstructor:
4994       case Sema::CXXCopyConstructor:
4995         IsConstructor = true;
4996         break;
4997       case Sema::CXXMoveConstructor:
4998         IsConstructor = true;
4999         IsMove = true;
5000         break;
5001       case Sema::CXXCopyAssignment:
5002         IsAssignment = true;
5003         break;
5004       case Sema::CXXMoveAssignment:
5005         IsAssignment = true;
5006         IsMove = true;
5007         break;
5008       case Sema::CXXDestructor:
5009         break;
5010       case Sema::CXXInvalid:
5011         llvm_unreachable("invalid special member kind");
5012     }
5013 
5014     if (MD->getNumParams()) {
5015       if (const ReferenceType *RT =
5016               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5017         ConstArg = RT->getPointeeType().isConstQualified();
5018     }
5019   }
5020 
5021   bool inUnion() const { return MD->getParent()->isUnion(); }
5022 
5023   /// Look up the corresponding special member in the given class.
5024   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5025                                               unsigned Quals, bool IsMutable) {
5026     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5027                                        ConstArg && !IsMutable);
5028   }
5029 
5030   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5031 
5032   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5033   bool shouldDeleteForField(FieldDecl *FD);
5034   bool shouldDeleteForAllConstMembers();
5035 
5036   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5037                                      unsigned Quals);
5038   bool shouldDeleteForSubobjectCall(Subobject Subobj,
5039                                     Sema::SpecialMemberOverloadResult *SMOR,
5040                                     bool IsDtorCallInCtor);
5041 
5042   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5043 };
5044 }
5045 
5046 /// Is the given special member inaccessible when used on the given
5047 /// sub-object.
5048 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5049                                              CXXMethodDecl *target) {
5050   /// If we're operating on a base class, the object type is the
5051   /// type of this special member.
5052   QualType objectTy;
5053   AccessSpecifier access = target->getAccess();
5054   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5055     objectTy = S.Context.getTypeDeclType(MD->getParent());
5056     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5057 
5058   // If we're operating on a field, the object type is the type of the field.
5059   } else {
5060     objectTy = S.Context.getTypeDeclType(target->getParent());
5061   }
5062 
5063   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5064 }
5065 
5066 /// Check whether we should delete a special member due to the implicit
5067 /// definition containing a call to a special member of a subobject.
5068 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5069     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5070     bool IsDtorCallInCtor) {
5071   CXXMethodDecl *Decl = SMOR->getMethod();
5072   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5073 
5074   int DiagKind = -1;
5075 
5076   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5077     DiagKind = !Decl ? 0 : 1;
5078   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5079     DiagKind = 2;
5080   else if (!isAccessible(Subobj, Decl))
5081     DiagKind = 3;
5082   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5083            !Decl->isTrivial()) {
5084     // A member of a union must have a trivial corresponding special member.
5085     // As a weird special case, a destructor call from a union's constructor
5086     // must be accessible and non-deleted, but need not be trivial. Such a
5087     // destructor is never actually called, but is semantically checked as
5088     // if it were.
5089     DiagKind = 4;
5090   }
5091 
5092   if (DiagKind == -1)
5093     return false;
5094 
5095   if (Diagnose) {
5096     if (Field) {
5097       S.Diag(Field->getLocation(),
5098              diag::note_deleted_special_member_class_subobject)
5099         << CSM << MD->getParent() << /*IsField*/true
5100         << Field << DiagKind << IsDtorCallInCtor;
5101     } else {
5102       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5103       S.Diag(Base->getLocStart(),
5104              diag::note_deleted_special_member_class_subobject)
5105         << CSM << MD->getParent() << /*IsField*/false
5106         << Base->getType() << DiagKind << IsDtorCallInCtor;
5107     }
5108 
5109     if (DiagKind == 1)
5110       S.NoteDeletedFunction(Decl);
5111     // FIXME: Explain inaccessibility if DiagKind == 3.
5112   }
5113 
5114   return true;
5115 }
5116 
5117 /// Check whether we should delete a special member function due to having a
5118 /// direct or virtual base class or non-static data member of class type M.
5119 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5120     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5121   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5122   bool IsMutable = Field && Field->isMutable();
5123 
5124   // C++11 [class.ctor]p5:
5125   // -- any direct or virtual base class, or non-static data member with no
5126   //    brace-or-equal-initializer, has class type M (or array thereof) and
5127   //    either M has no default constructor or overload resolution as applied
5128   //    to M's default constructor results in an ambiguity or in a function
5129   //    that is deleted or inaccessible
5130   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5131   // -- a direct or virtual base class B that cannot be copied/moved because
5132   //    overload resolution, as applied to B's corresponding special member,
5133   //    results in an ambiguity or a function that is deleted or inaccessible
5134   //    from the defaulted special member
5135   // C++11 [class.dtor]p5:
5136   // -- any direct or virtual base class [...] has a type with a destructor
5137   //    that is deleted or inaccessible
5138   if (!(CSM == Sema::CXXDefaultConstructor &&
5139         Field && Field->hasInClassInitializer()) &&
5140       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5141                                    false))
5142     return true;
5143 
5144   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5145   // -- any direct or virtual base class or non-static data member has a
5146   //    type with a destructor that is deleted or inaccessible
5147   if (IsConstructor) {
5148     Sema::SpecialMemberOverloadResult *SMOR =
5149         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5150                               false, false, false, false, false);
5151     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5152       return true;
5153   }
5154 
5155   return false;
5156 }
5157 
5158 /// Check whether we should delete a special member function due to the class
5159 /// having a particular direct or virtual base class.
5160 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5161   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5162   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5163 }
5164 
5165 /// Check whether we should delete a special member function due to the class
5166 /// having a particular non-static data member.
5167 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5168   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5169   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5170 
5171   if (CSM == Sema::CXXDefaultConstructor) {
5172     // For a default constructor, all references must be initialized in-class
5173     // and, if a union, it must have a non-const member.
5174     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5175       if (Diagnose)
5176         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5177           << MD->getParent() << FD << FieldType << /*Reference*/0;
5178       return true;
5179     }
5180     // C++11 [class.ctor]p5: any non-variant non-static data member of
5181     // const-qualified type (or array thereof) with no
5182     // brace-or-equal-initializer does not have a user-provided default
5183     // constructor.
5184     if (!inUnion() && FieldType.isConstQualified() &&
5185         !FD->hasInClassInitializer() &&
5186         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5187       if (Diagnose)
5188         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5189           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5190       return true;
5191     }
5192 
5193     if (inUnion() && !FieldType.isConstQualified())
5194       AllFieldsAreConst = false;
5195   } else if (CSM == Sema::CXXCopyConstructor) {
5196     // For a copy constructor, data members must not be of rvalue reference
5197     // type.
5198     if (FieldType->isRValueReferenceType()) {
5199       if (Diagnose)
5200         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5201           << MD->getParent() << FD << FieldType;
5202       return true;
5203     }
5204   } else if (IsAssignment) {
5205     // For an assignment operator, data members must not be of reference type.
5206     if (FieldType->isReferenceType()) {
5207       if (Diagnose)
5208         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5209           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5210       return true;
5211     }
5212     if (!FieldRecord && FieldType.isConstQualified()) {
5213       // C++11 [class.copy]p23:
5214       // -- a non-static data member of const non-class type (or array thereof)
5215       if (Diagnose)
5216         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5217           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5218       return true;
5219     }
5220   }
5221 
5222   if (FieldRecord) {
5223     // Some additional restrictions exist on the variant members.
5224     if (!inUnion() && FieldRecord->isUnion() &&
5225         FieldRecord->isAnonymousStructOrUnion()) {
5226       bool AllVariantFieldsAreConst = true;
5227 
5228       // FIXME: Handle anonymous unions declared within anonymous unions.
5229       for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
5230                                          UE = FieldRecord->field_end();
5231            UI != UE; ++UI) {
5232         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5233 
5234         if (!UnionFieldType.isConstQualified())
5235           AllVariantFieldsAreConst = false;
5236 
5237         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5238         if (UnionFieldRecord &&
5239             shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
5240                                           UnionFieldType.getCVRQualifiers()))
5241           return true;
5242       }
5243 
5244       // At least one member in each anonymous union must be non-const
5245       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5246           FieldRecord->field_begin() != FieldRecord->field_end()) {
5247         if (Diagnose)
5248           S.Diag(FieldRecord->getLocation(),
5249                  diag::note_deleted_default_ctor_all_const)
5250             << MD->getParent() << /*anonymous union*/1;
5251         return true;
5252       }
5253 
5254       // Don't check the implicit member of the anonymous union type.
5255       // This is technically non-conformant, but sanity demands it.
5256       return false;
5257     }
5258 
5259     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5260                                       FieldType.getCVRQualifiers()))
5261       return true;
5262   }
5263 
5264   return false;
5265 }
5266 
5267 /// C++11 [class.ctor] p5:
5268 ///   A defaulted default constructor for a class X is defined as deleted if
5269 /// X is a union and all of its variant members are of const-qualified type.
5270 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5271   // This is a silly definition, because it gives an empty union a deleted
5272   // default constructor. Don't do that.
5273   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5274       (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5275     if (Diagnose)
5276       S.Diag(MD->getParent()->getLocation(),
5277              diag::note_deleted_default_ctor_all_const)
5278         << MD->getParent() << /*not anonymous union*/0;
5279     return true;
5280   }
5281   return false;
5282 }
5283 
5284 /// Determine whether a defaulted special member function should be defined as
5285 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5286 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5287 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5288                                      bool Diagnose) {
5289   if (MD->isInvalidDecl())
5290     return false;
5291   CXXRecordDecl *RD = MD->getParent();
5292   assert(!RD->isDependentType() && "do deletion after instantiation");
5293   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5294     return false;
5295 
5296   // C++11 [expr.lambda.prim]p19:
5297   //   The closure type associated with a lambda-expression has a
5298   //   deleted (8.4.3) default constructor and a deleted copy
5299   //   assignment operator.
5300   if (RD->isLambda() &&
5301       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5302     if (Diagnose)
5303       Diag(RD->getLocation(), diag::note_lambda_decl);
5304     return true;
5305   }
5306 
5307   // For an anonymous struct or union, the copy and assignment special members
5308   // will never be used, so skip the check. For an anonymous union declared at
5309   // namespace scope, the constructor and destructor are used.
5310   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5311       RD->isAnonymousStructOrUnion())
5312     return false;
5313 
5314   // C++11 [class.copy]p7, p18:
5315   //   If the class definition declares a move constructor or move assignment
5316   //   operator, an implicitly declared copy constructor or copy assignment
5317   //   operator is defined as deleted.
5318   if (MD->isImplicit() &&
5319       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5320     CXXMethodDecl *UserDeclaredMove = 0;
5321 
5322     // In Microsoft mode, a user-declared move only causes the deletion of the
5323     // corresponding copy operation, not both copy operations.
5324     if (RD->hasUserDeclaredMoveConstructor() &&
5325         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5326       if (!Diagnose) return true;
5327 
5328       // Find any user-declared move constructor.
5329       for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5330                                         E = RD->ctor_end(); I != E; ++I) {
5331         if (I->isMoveConstructor()) {
5332           UserDeclaredMove = *I;
5333           break;
5334         }
5335       }
5336       assert(UserDeclaredMove);
5337     } else if (RD->hasUserDeclaredMoveAssignment() &&
5338                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5339       if (!Diagnose) return true;
5340 
5341       // Find any user-declared move assignment operator.
5342       for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5343                                           E = RD->method_end(); I != E; ++I) {
5344         if (I->isMoveAssignmentOperator()) {
5345           UserDeclaredMove = *I;
5346           break;
5347         }
5348       }
5349       assert(UserDeclaredMove);
5350     }
5351 
5352     if (UserDeclaredMove) {
5353       Diag(UserDeclaredMove->getLocation(),
5354            diag::note_deleted_copy_user_declared_move)
5355         << (CSM == CXXCopyAssignment) << RD
5356         << UserDeclaredMove->isMoveAssignmentOperator();
5357       return true;
5358     }
5359   }
5360 
5361   // Do access control from the special member function
5362   ContextRAII MethodContext(*this, MD);
5363 
5364   // C++11 [class.dtor]p5:
5365   // -- for a virtual destructor, lookup of the non-array deallocation function
5366   //    results in an ambiguity or in a function that is deleted or inaccessible
5367   if (CSM == CXXDestructor && MD->isVirtual()) {
5368     FunctionDecl *OperatorDelete = 0;
5369     DeclarationName Name =
5370       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5371     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5372                                  OperatorDelete, false)) {
5373       if (Diagnose)
5374         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5375       return true;
5376     }
5377   }
5378 
5379   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5380 
5381   for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5382                                           BE = RD->bases_end(); BI != BE; ++BI)
5383     if (!BI->isVirtual() &&
5384         SMI.shouldDeleteForBase(BI))
5385       return true;
5386 
5387   // Per DR1611, do not consider virtual bases of constructors of abstract
5388   // classes, since we are not going to construct them.
5389   if (!RD->isAbstract() || !SMI.IsConstructor) {
5390     for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5391                                             BE = RD->vbases_end();
5392          BI != BE; ++BI)
5393       if (SMI.shouldDeleteForBase(BI))
5394         return true;
5395   }
5396 
5397   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5398                                      FE = RD->field_end(); FI != FE; ++FI)
5399     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5400         SMI.shouldDeleteForField(*FI))
5401       return true;
5402 
5403   if (SMI.shouldDeleteForAllConstMembers())
5404     return true;
5405 
5406   return false;
5407 }
5408 
5409 /// Perform lookup for a special member of the specified kind, and determine
5410 /// whether it is trivial. If the triviality can be determined without the
5411 /// lookup, skip it. This is intended for use when determining whether a
5412 /// special member of a containing object is trivial, and thus does not ever
5413 /// perform overload resolution for default constructors.
5414 ///
5415 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5416 /// member that was most likely to be intended to be trivial, if any.
5417 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5418                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5419                                      bool ConstRHS, CXXMethodDecl **Selected) {
5420   if (Selected)
5421     *Selected = 0;
5422 
5423   switch (CSM) {
5424   case Sema::CXXInvalid:
5425     llvm_unreachable("not a special member");
5426 
5427   case Sema::CXXDefaultConstructor:
5428     // C++11 [class.ctor]p5:
5429     //   A default constructor is trivial if:
5430     //    - all the [direct subobjects] have trivial default constructors
5431     //
5432     // Note, no overload resolution is performed in this case.
5433     if (RD->hasTrivialDefaultConstructor())
5434       return true;
5435 
5436     if (Selected) {
5437       // If there's a default constructor which could have been trivial, dig it
5438       // out. Otherwise, if there's any user-provided default constructor, point
5439       // to that as an example of why there's not a trivial one.
5440       CXXConstructorDecl *DefCtor = 0;
5441       if (RD->needsImplicitDefaultConstructor())
5442         S.DeclareImplicitDefaultConstructor(RD);
5443       for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5444                                         CE = RD->ctor_end(); CI != CE; ++CI) {
5445         if (!CI->isDefaultConstructor())
5446           continue;
5447         DefCtor = *CI;
5448         if (!DefCtor->isUserProvided())
5449           break;
5450       }
5451 
5452       *Selected = DefCtor;
5453     }
5454 
5455     return false;
5456 
5457   case Sema::CXXDestructor:
5458     // C++11 [class.dtor]p5:
5459     //   A destructor is trivial if:
5460     //    - all the direct [subobjects] have trivial destructors
5461     if (RD->hasTrivialDestructor())
5462       return true;
5463 
5464     if (Selected) {
5465       if (RD->needsImplicitDestructor())
5466         S.DeclareImplicitDestructor(RD);
5467       *Selected = RD->getDestructor();
5468     }
5469 
5470     return false;
5471 
5472   case Sema::CXXCopyConstructor:
5473     // C++11 [class.copy]p12:
5474     //   A copy constructor is trivial if:
5475     //    - the constructor selected to copy each direct [subobject] is trivial
5476     if (RD->hasTrivialCopyConstructor()) {
5477       if (Quals == Qualifiers::Const)
5478         // We must either select the trivial copy constructor or reach an
5479         // ambiguity; no need to actually perform overload resolution.
5480         return true;
5481     } else if (!Selected) {
5482       return false;
5483     }
5484     // In C++98, we are not supposed to perform overload resolution here, but we
5485     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5486     // cases like B as having a non-trivial copy constructor:
5487     //   struct A { template<typename T> A(T&); };
5488     //   struct B { mutable A a; };
5489     goto NeedOverloadResolution;
5490 
5491   case Sema::CXXCopyAssignment:
5492     // C++11 [class.copy]p25:
5493     //   A copy assignment operator is trivial if:
5494     //    - the assignment operator selected to copy each direct [subobject] is
5495     //      trivial
5496     if (RD->hasTrivialCopyAssignment()) {
5497       if (Quals == Qualifiers::Const)
5498         return true;
5499     } else if (!Selected) {
5500       return false;
5501     }
5502     // In C++98, we are not supposed to perform overload resolution here, but we
5503     // treat that as a language defect.
5504     goto NeedOverloadResolution;
5505 
5506   case Sema::CXXMoveConstructor:
5507   case Sema::CXXMoveAssignment:
5508   NeedOverloadResolution:
5509     Sema::SpecialMemberOverloadResult *SMOR =
5510         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5511 
5512     // The standard doesn't describe how to behave if the lookup is ambiguous.
5513     // We treat it as not making the member non-trivial, just like the standard
5514     // mandates for the default constructor. This should rarely matter, because
5515     // the member will also be deleted.
5516     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5517       return true;
5518 
5519     if (!SMOR->getMethod()) {
5520       assert(SMOR->getKind() ==
5521              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5522       return false;
5523     }
5524 
5525     // We deliberately don't check if we found a deleted special member. We're
5526     // not supposed to!
5527     if (Selected)
5528       *Selected = SMOR->getMethod();
5529     return SMOR->getMethod()->isTrivial();
5530   }
5531 
5532   llvm_unreachable("unknown special method kind");
5533 }
5534 
5535 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5536   for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5537        CI != CE; ++CI)
5538     if (!CI->isImplicit())
5539       return *CI;
5540 
5541   // Look for constructor templates.
5542   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5543   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5544     if (CXXConstructorDecl *CD =
5545           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5546       return CD;
5547   }
5548 
5549   return 0;
5550 }
5551 
5552 /// The kind of subobject we are checking for triviality. The values of this
5553 /// enumeration are used in diagnostics.
5554 enum TrivialSubobjectKind {
5555   /// The subobject is a base class.
5556   TSK_BaseClass,
5557   /// The subobject is a non-static data member.
5558   TSK_Field,
5559   /// The object is actually the complete object.
5560   TSK_CompleteObject
5561 };
5562 
5563 /// Check whether the special member selected for a given type would be trivial.
5564 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5565                                       QualType SubType, bool ConstRHS,
5566                                       Sema::CXXSpecialMember CSM,
5567                                       TrivialSubobjectKind Kind,
5568                                       bool Diagnose) {
5569   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5570   if (!SubRD)
5571     return true;
5572 
5573   CXXMethodDecl *Selected;
5574   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5575                                ConstRHS, Diagnose ? &Selected : 0))
5576     return true;
5577 
5578   if (Diagnose) {
5579     if (ConstRHS)
5580       SubType.addConst();
5581 
5582     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5583       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5584         << Kind << SubType.getUnqualifiedType();
5585       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5586         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5587     } else if (!Selected)
5588       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5589         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5590     else if (Selected->isUserProvided()) {
5591       if (Kind == TSK_CompleteObject)
5592         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5593           << Kind << SubType.getUnqualifiedType() << CSM;
5594       else {
5595         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5596           << Kind << SubType.getUnqualifiedType() << CSM;
5597         S.Diag(Selected->getLocation(), diag::note_declared_at);
5598       }
5599     } else {
5600       if (Kind != TSK_CompleteObject)
5601         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5602           << Kind << SubType.getUnqualifiedType() << CSM;
5603 
5604       // Explain why the defaulted or deleted special member isn't trivial.
5605       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5606     }
5607   }
5608 
5609   return false;
5610 }
5611 
5612 /// Check whether the members of a class type allow a special member to be
5613 /// trivial.
5614 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5615                                      Sema::CXXSpecialMember CSM,
5616                                      bool ConstArg, bool Diagnose) {
5617   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5618                                      FE = RD->field_end(); FI != FE; ++FI) {
5619     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5620       continue;
5621 
5622     QualType FieldType = S.Context.getBaseElementType(FI->getType());
5623 
5624     // Pretend anonymous struct or union members are members of this class.
5625     if (FI->isAnonymousStructOrUnion()) {
5626       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5627                                     CSM, ConstArg, Diagnose))
5628         return false;
5629       continue;
5630     }
5631 
5632     // C++11 [class.ctor]p5:
5633     //   A default constructor is trivial if [...]
5634     //    -- no non-static data member of its class has a
5635     //       brace-or-equal-initializer
5636     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5637       if (Diagnose)
5638         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5639       return false;
5640     }
5641 
5642     // Objective C ARC 4.3.5:
5643     //   [...] nontrivally ownership-qualified types are [...] not trivially
5644     //   default constructible, copy constructible, move constructible, copy
5645     //   assignable, move assignable, or destructible [...]
5646     if (S.getLangOpts().ObjCAutoRefCount &&
5647         FieldType.hasNonTrivialObjCLifetime()) {
5648       if (Diagnose)
5649         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5650           << RD << FieldType.getObjCLifetime();
5651       return false;
5652     }
5653 
5654     bool ConstRHS = ConstArg && !FI->isMutable();
5655     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5656                                    CSM, TSK_Field, Diagnose))
5657       return false;
5658   }
5659 
5660   return true;
5661 }
5662 
5663 /// Diagnose why the specified class does not have a trivial special member of
5664 /// the given kind.
5665 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5666   QualType Ty = Context.getRecordType(RD);
5667 
5668   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5669   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
5670                             TSK_CompleteObject, /*Diagnose*/true);
5671 }
5672 
5673 /// Determine whether a defaulted or deleted special member function is trivial,
5674 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5675 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5676 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5677                                   bool Diagnose) {
5678   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5679 
5680   CXXRecordDecl *RD = MD->getParent();
5681 
5682   bool ConstArg = false;
5683 
5684   // C++11 [class.copy]p12, p25: [DR1593]
5685   //   A [special member] is trivial if [...] its parameter-type-list is
5686   //   equivalent to the parameter-type-list of an implicit declaration [...]
5687   switch (CSM) {
5688   case CXXDefaultConstructor:
5689   case CXXDestructor:
5690     // Trivial default constructors and destructors cannot have parameters.
5691     break;
5692 
5693   case CXXCopyConstructor:
5694   case CXXCopyAssignment: {
5695     // Trivial copy operations always have const, non-volatile parameter types.
5696     ConstArg = true;
5697     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5698     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5699     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5700       if (Diagnose)
5701         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5702           << Param0->getSourceRange() << Param0->getType()
5703           << Context.getLValueReferenceType(
5704                Context.getRecordType(RD).withConst());
5705       return false;
5706     }
5707     break;
5708   }
5709 
5710   case CXXMoveConstructor:
5711   case CXXMoveAssignment: {
5712     // Trivial move operations always have non-cv-qualified parameters.
5713     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5714     const RValueReferenceType *RT =
5715       Param0->getType()->getAs<RValueReferenceType>();
5716     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5717       if (Diagnose)
5718         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5719           << Param0->getSourceRange() << Param0->getType()
5720           << Context.getRValueReferenceType(Context.getRecordType(RD));
5721       return false;
5722     }
5723     break;
5724   }
5725 
5726   case CXXInvalid:
5727     llvm_unreachable("not a special member");
5728   }
5729 
5730   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5731     if (Diagnose)
5732       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5733            diag::note_nontrivial_default_arg)
5734         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5735     return false;
5736   }
5737   if (MD->isVariadic()) {
5738     if (Diagnose)
5739       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5740     return false;
5741   }
5742 
5743   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5744   //   A copy/move [constructor or assignment operator] is trivial if
5745   //    -- the [member] selected to copy/move each direct base class subobject
5746   //       is trivial
5747   //
5748   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5749   //   A [default constructor or destructor] is trivial if
5750   //    -- all the direct base classes have trivial [default constructors or
5751   //       destructors]
5752   for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5753                                           BE = RD->bases_end(); BI != BE; ++BI)
5754     if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), BI->getType(),
5755                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
5756       return false;
5757 
5758   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5759   //   A copy/move [constructor or assignment operator] for a class X is
5760   //   trivial if
5761   //    -- for each non-static data member of X that is of class type (or array
5762   //       thereof), the constructor selected to copy/move that member is
5763   //       trivial
5764   //
5765   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5766   //   A [default constructor or destructor] is trivial if
5767   //    -- for all of the non-static data members of its class that are of class
5768   //       type (or array thereof), each such class has a trivial [default
5769   //       constructor or destructor]
5770   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5771     return false;
5772 
5773   // C++11 [class.dtor]p5:
5774   //   A destructor is trivial if [...]
5775   //    -- the destructor is not virtual
5776   if (CSM == CXXDestructor && MD->isVirtual()) {
5777     if (Diagnose)
5778       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5779     return false;
5780   }
5781 
5782   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5783   //   A [special member] for class X is trivial if [...]
5784   //    -- class X has no virtual functions and no virtual base classes
5785   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5786     if (!Diagnose)
5787       return false;
5788 
5789     if (RD->getNumVBases()) {
5790       // Check for virtual bases. We already know that the corresponding
5791       // member in all bases is trivial, so vbases must all be direct.
5792       CXXBaseSpecifier &BS = *RD->vbases_begin();
5793       assert(BS.isVirtual());
5794       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5795       return false;
5796     }
5797 
5798     // Must have a virtual method.
5799     for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5800                                         ME = RD->method_end(); MI != ME; ++MI) {
5801       if (MI->isVirtual()) {
5802         SourceLocation MLoc = MI->getLocStart();
5803         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5804         return false;
5805       }
5806     }
5807 
5808     llvm_unreachable("dynamic class with no vbases and no virtual functions");
5809   }
5810 
5811   // Looks like it's trivial!
5812   return true;
5813 }
5814 
5815 /// \brief Data used with FindHiddenVirtualMethod
5816 namespace {
5817   struct FindHiddenVirtualMethodData {
5818     Sema *S;
5819     CXXMethodDecl *Method;
5820     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5821     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5822   };
5823 }
5824 
5825 /// \brief Check whether any most overriden method from MD in Methods
5826 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5827                    const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5828   if (MD->size_overridden_methods() == 0)
5829     return Methods.count(MD->getCanonicalDecl());
5830   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5831                                       E = MD->end_overridden_methods();
5832        I != E; ++I)
5833     if (CheckMostOverridenMethods(*I, Methods))
5834       return true;
5835   return false;
5836 }
5837 
5838 /// \brief Member lookup function that determines whether a given C++
5839 /// method overloads virtual methods in a base class without overriding any,
5840 /// to be used with CXXRecordDecl::lookupInBases().
5841 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5842                                     CXXBasePath &Path,
5843                                     void *UserData) {
5844   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5845 
5846   FindHiddenVirtualMethodData &Data
5847     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5848 
5849   DeclarationName Name = Data.Method->getDeclName();
5850   assert(Name.getNameKind() == DeclarationName::Identifier);
5851 
5852   bool foundSameNameMethod = false;
5853   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5854   for (Path.Decls = BaseRecord->lookup(Name);
5855        !Path.Decls.empty();
5856        Path.Decls = Path.Decls.slice(1)) {
5857     NamedDecl *D = Path.Decls.front();
5858     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5859       MD = MD->getCanonicalDecl();
5860       foundSameNameMethod = true;
5861       // Interested only in hidden virtual methods.
5862       if (!MD->isVirtual())
5863         continue;
5864       // If the method we are checking overrides a method from its base
5865       // don't warn about the other overloaded methods.
5866       if (!Data.S->IsOverload(Data.Method, MD, false))
5867         return true;
5868       // Collect the overload only if its hidden.
5869       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5870         overloadedMethods.push_back(MD);
5871     }
5872   }
5873 
5874   if (foundSameNameMethod)
5875     Data.OverloadedMethods.append(overloadedMethods.begin(),
5876                                    overloadedMethods.end());
5877   return foundSameNameMethod;
5878 }
5879 
5880 /// \brief Add the most overriden methods from MD to Methods
5881 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5882                          llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5883   if (MD->size_overridden_methods() == 0)
5884     Methods.insert(MD->getCanonicalDecl());
5885   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5886                                       E = MD->end_overridden_methods();
5887        I != E; ++I)
5888     AddMostOverridenMethods(*I, Methods);
5889 }
5890 
5891 /// \brief Check if a method overloads virtual methods in a base class without
5892 /// overriding any.
5893 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5894                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5895   if (!MD->getDeclName().isIdentifier())
5896     return;
5897 
5898   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5899                      /*bool RecordPaths=*/false,
5900                      /*bool DetectVirtual=*/false);
5901   FindHiddenVirtualMethodData Data;
5902   Data.Method = MD;
5903   Data.S = this;
5904 
5905   // Keep the base methods that were overriden or introduced in the subclass
5906   // by 'using' in a set. A base method not in this set is hidden.
5907   CXXRecordDecl *DC = MD->getParent();
5908   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5909   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5910     NamedDecl *ND = *I;
5911     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5912       ND = shad->getTargetDecl();
5913     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5914       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5915   }
5916 
5917   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5918     OverloadedMethods = Data.OverloadedMethods;
5919 }
5920 
5921 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5922                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5923   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5924     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5925     PartialDiagnostic PD = PDiag(
5926          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5927     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5928     Diag(overloadedMD->getLocation(), PD);
5929   }
5930 }
5931 
5932 /// \brief Diagnose methods which overload virtual methods in a base class
5933 /// without overriding any.
5934 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5935   if (MD->isInvalidDecl())
5936     return;
5937 
5938   if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5939                                MD->getLocation()) == DiagnosticsEngine::Ignored)
5940     return;
5941 
5942   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5943   FindHiddenVirtualMethods(MD, OverloadedMethods);
5944   if (!OverloadedMethods.empty()) {
5945     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5946       << MD << (OverloadedMethods.size() > 1);
5947 
5948     NoteHiddenVirtualMethods(MD, OverloadedMethods);
5949   }
5950 }
5951 
5952 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5953                                              Decl *TagDecl,
5954                                              SourceLocation LBrac,
5955                                              SourceLocation RBrac,
5956                                              AttributeList *AttrList) {
5957   if (!TagDecl)
5958     return;
5959 
5960   AdjustDeclIfTemplate(TagDecl);
5961 
5962   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5963     if (l->getKind() != AttributeList::AT_Visibility)
5964       continue;
5965     l->setInvalid();
5966     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5967       l->getName();
5968   }
5969 
5970   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5971               // strict aliasing violation!
5972               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5973               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5974 
5975   CheckCompletedCXXClass(
5976                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5977 }
5978 
5979 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5980 /// special functions, such as the default constructor, copy
5981 /// constructor, or destructor, to the given C++ class (C++
5982 /// [special]p1).  This routine can only be executed just before the
5983 /// definition of the class is complete.
5984 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
5985   if (!ClassDecl->hasUserDeclaredConstructor())
5986     ++ASTContext::NumImplicitDefaultConstructors;
5987 
5988   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
5989     ++ASTContext::NumImplicitCopyConstructors;
5990 
5991     // If the properties or semantics of the copy constructor couldn't be
5992     // determined while the class was being declared, force a declaration
5993     // of it now.
5994     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5995       DeclareImplicitCopyConstructor(ClassDecl);
5996   }
5997 
5998   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
5999     ++ASTContext::NumImplicitMoveConstructors;
6000 
6001     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6002       DeclareImplicitMoveConstructor(ClassDecl);
6003   }
6004 
6005   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6006     ++ASTContext::NumImplicitCopyAssignmentOperators;
6007 
6008     // If we have a dynamic class, then the copy assignment operator may be
6009     // virtual, so we have to declare it immediately. This ensures that, e.g.,
6010     // it shows up in the right place in the vtable and that we diagnose
6011     // problems with the implicit exception specification.
6012     if (ClassDecl->isDynamicClass() ||
6013         ClassDecl->needsOverloadResolutionForCopyAssignment())
6014       DeclareImplicitCopyAssignment(ClassDecl);
6015   }
6016 
6017   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6018     ++ASTContext::NumImplicitMoveAssignmentOperators;
6019 
6020     // Likewise for the move assignment operator.
6021     if (ClassDecl->isDynamicClass() ||
6022         ClassDecl->needsOverloadResolutionForMoveAssignment())
6023       DeclareImplicitMoveAssignment(ClassDecl);
6024   }
6025 
6026   if (!ClassDecl->hasUserDeclaredDestructor()) {
6027     ++ASTContext::NumImplicitDestructors;
6028 
6029     // If we have a dynamic class, then the destructor may be virtual, so we
6030     // have to declare the destructor immediately. This ensures that, e.g., it
6031     // shows up in the right place in the vtable and that we diagnose problems
6032     // with the implicit exception specification.
6033     if (ClassDecl->isDynamicClass() ||
6034         ClassDecl->needsOverloadResolutionForDestructor())
6035       DeclareImplicitDestructor(ClassDecl);
6036   }
6037 }
6038 
6039 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
6040   if (!D)
6041     return;
6042 
6043   int NumParamList = D->getNumTemplateParameterLists();
6044   for (int i = 0; i < NumParamList; i++) {
6045     TemplateParameterList* Params = D->getTemplateParameterList(i);
6046     for (TemplateParameterList::iterator Param = Params->begin(),
6047                                       ParamEnd = Params->end();
6048           Param != ParamEnd; ++Param) {
6049       NamedDecl *Named = cast<NamedDecl>(*Param);
6050       if (Named->getDeclName()) {
6051         S->AddDecl(Named);
6052         IdResolver.AddDecl(Named);
6053       }
6054     }
6055   }
6056 }
6057 
6058 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6059   if (!D)
6060     return;
6061 
6062   TemplateParameterList *Params = 0;
6063   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
6064     Params = Template->getTemplateParameters();
6065   else if (ClassTemplatePartialSpecializationDecl *PartialSpec
6066            = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6067     Params = PartialSpec->getTemplateParameters();
6068   else
6069     return;
6070 
6071   for (TemplateParameterList::iterator Param = Params->begin(),
6072                                     ParamEnd = Params->end();
6073        Param != ParamEnd; ++Param) {
6074     NamedDecl *Named = cast<NamedDecl>(*Param);
6075     if (Named->getDeclName()) {
6076       S->AddDecl(Named);
6077       IdResolver.AddDecl(Named);
6078     }
6079   }
6080 }
6081 
6082 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6083   if (!RecordD) return;
6084   AdjustDeclIfTemplate(RecordD);
6085   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6086   PushDeclContext(S, Record);
6087 }
6088 
6089 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6090   if (!RecordD) return;
6091   PopDeclContext();
6092 }
6093 
6094 /// This is used to implement the constant expression evaluation part of the
6095 /// attribute enable_if extension. There is nothing in standard C++ which would
6096 /// require reentering parameters.
6097 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6098   if (!Param)
6099     return;
6100 
6101   S->AddDecl(Param);
6102   if (Param->getDeclName())
6103     IdResolver.AddDecl(Param);
6104 }
6105 
6106 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6107 /// parsing a top-level (non-nested) C++ class, and we are now
6108 /// parsing those parts of the given Method declaration that could
6109 /// not be parsed earlier (C++ [class.mem]p2), such as default
6110 /// arguments. This action should enter the scope of the given
6111 /// Method declaration as if we had just parsed the qualified method
6112 /// name. However, it should not bring the parameters into scope;
6113 /// that will be performed by ActOnDelayedCXXMethodParameter.
6114 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6115 }
6116 
6117 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6118 /// C++ method declaration. We're (re-)introducing the given
6119 /// function parameter into scope for use in parsing later parts of
6120 /// the method declaration. For example, we could see an
6121 /// ActOnParamDefaultArgument event for this parameter.
6122 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6123   if (!ParamD)
6124     return;
6125 
6126   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6127 
6128   // If this parameter has an unparsed default argument, clear it out
6129   // to make way for the parsed default argument.
6130   if (Param->hasUnparsedDefaultArg())
6131     Param->setDefaultArg(0);
6132 
6133   S->AddDecl(Param);
6134   if (Param->getDeclName())
6135     IdResolver.AddDecl(Param);
6136 }
6137 
6138 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6139 /// processing the delayed method declaration for Method. The method
6140 /// declaration is now considered finished. There may be a separate
6141 /// ActOnStartOfFunctionDef action later (not necessarily
6142 /// immediately!) for this method, if it was also defined inside the
6143 /// class body.
6144 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6145   if (!MethodD)
6146     return;
6147 
6148   AdjustDeclIfTemplate(MethodD);
6149 
6150   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6151 
6152   // Now that we have our default arguments, check the constructor
6153   // again. It could produce additional diagnostics or affect whether
6154   // the class has implicitly-declared destructors, among other
6155   // things.
6156   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6157     CheckConstructor(Constructor);
6158 
6159   // Check the default arguments, which we may have added.
6160   if (!Method->isInvalidDecl())
6161     CheckCXXDefaultArguments(Method);
6162 }
6163 
6164 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6165 /// the well-formedness of the constructor declarator @p D with type @p
6166 /// R. If there are any errors in the declarator, this routine will
6167 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6168 /// will be updated to reflect a well-formed type for the constructor and
6169 /// returned.
6170 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6171                                           StorageClass &SC) {
6172   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6173 
6174   // C++ [class.ctor]p3:
6175   //   A constructor shall not be virtual (10.3) or static (9.4). A
6176   //   constructor can be invoked for a const, volatile or const
6177   //   volatile object. A constructor shall not be declared const,
6178   //   volatile, or const volatile (9.3.2).
6179   if (isVirtual) {
6180     if (!D.isInvalidType())
6181       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6182         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6183         << SourceRange(D.getIdentifierLoc());
6184     D.setInvalidType();
6185   }
6186   if (SC == SC_Static) {
6187     if (!D.isInvalidType())
6188       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6189         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6190         << SourceRange(D.getIdentifierLoc());
6191     D.setInvalidType();
6192     SC = SC_None;
6193   }
6194 
6195   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6196   if (FTI.TypeQuals != 0) {
6197     if (FTI.TypeQuals & Qualifiers::Const)
6198       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6199         << "const" << SourceRange(D.getIdentifierLoc());
6200     if (FTI.TypeQuals & Qualifiers::Volatile)
6201       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6202         << "volatile" << SourceRange(D.getIdentifierLoc());
6203     if (FTI.TypeQuals & Qualifiers::Restrict)
6204       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6205         << "restrict" << SourceRange(D.getIdentifierLoc());
6206     D.setInvalidType();
6207   }
6208 
6209   // C++0x [class.ctor]p4:
6210   //   A constructor shall not be declared with a ref-qualifier.
6211   if (FTI.hasRefQualifier()) {
6212     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6213       << FTI.RefQualifierIsLValueRef
6214       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6215     D.setInvalidType();
6216   }
6217 
6218   // Rebuild the function type "R" without any type qualifiers (in
6219   // case any of the errors above fired) and with "void" as the
6220   // return type, since constructors don't have return types.
6221   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6222   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6223     return R;
6224 
6225   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6226   EPI.TypeQuals = 0;
6227   EPI.RefQualifier = RQ_None;
6228 
6229   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6230 }
6231 
6232 /// CheckConstructor - Checks a fully-formed constructor for
6233 /// well-formedness, issuing any diagnostics required. Returns true if
6234 /// the constructor declarator is invalid.
6235 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6236   CXXRecordDecl *ClassDecl
6237     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6238   if (!ClassDecl)
6239     return Constructor->setInvalidDecl();
6240 
6241   // C++ [class.copy]p3:
6242   //   A declaration of a constructor for a class X is ill-formed if
6243   //   its first parameter is of type (optionally cv-qualified) X and
6244   //   either there are no other parameters or else all other
6245   //   parameters have default arguments.
6246   if (!Constructor->isInvalidDecl() &&
6247       ((Constructor->getNumParams() == 1) ||
6248        (Constructor->getNumParams() > 1 &&
6249         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6250       Constructor->getTemplateSpecializationKind()
6251                                               != TSK_ImplicitInstantiation) {
6252     QualType ParamType = Constructor->getParamDecl(0)->getType();
6253     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6254     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6255       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6256       const char *ConstRef
6257         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6258                                                         : " const &";
6259       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6260         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6261 
6262       // FIXME: Rather that making the constructor invalid, we should endeavor
6263       // to fix the type.
6264       Constructor->setInvalidDecl();
6265     }
6266   }
6267 }
6268 
6269 /// CheckDestructor - Checks a fully-formed destructor definition for
6270 /// well-formedness, issuing any diagnostics required.  Returns true
6271 /// on error.
6272 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6273   CXXRecordDecl *RD = Destructor->getParent();
6274 
6275   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6276     SourceLocation Loc;
6277 
6278     if (!Destructor->isImplicit())
6279       Loc = Destructor->getLocation();
6280     else
6281       Loc = RD->getLocation();
6282 
6283     // If we have a virtual destructor, look up the deallocation function
6284     FunctionDecl *OperatorDelete = 0;
6285     DeclarationName Name =
6286     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6287     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6288       return true;
6289     // If there's no class-specific operator delete, look up the global
6290     // non-array delete.
6291     if (!OperatorDelete)
6292       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6293 
6294     MarkFunctionReferenced(Loc, OperatorDelete);
6295 
6296     Destructor->setOperatorDelete(OperatorDelete);
6297   }
6298 
6299   return false;
6300 }
6301 
6302 static inline bool
6303 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6304   return (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
6305           FTI.Params[0].Param &&
6306           cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType());
6307 }
6308 
6309 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6310 /// the well-formednes of the destructor declarator @p D with type @p
6311 /// R. If there are any errors in the declarator, this routine will
6312 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6313 /// will be updated to reflect a well-formed type for the destructor and
6314 /// returned.
6315 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6316                                          StorageClass& SC) {
6317   // C++ [class.dtor]p1:
6318   //   [...] A typedef-name that names a class is a class-name
6319   //   (7.1.3); however, a typedef-name that names a class shall not
6320   //   be used as the identifier in the declarator for a destructor
6321   //   declaration.
6322   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6323   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6324     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6325       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6326   else if (const TemplateSpecializationType *TST =
6327              DeclaratorType->getAs<TemplateSpecializationType>())
6328     if (TST->isTypeAlias())
6329       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6330         << DeclaratorType << 1;
6331 
6332   // C++ [class.dtor]p2:
6333   //   A destructor is used to destroy objects of its class type. A
6334   //   destructor takes no parameters, and no return type can be
6335   //   specified for it (not even void). The address of a destructor
6336   //   shall not be taken. A destructor shall not be static. A
6337   //   destructor can be invoked for a const, volatile or const
6338   //   volatile object. A destructor shall not be declared const,
6339   //   volatile or const volatile (9.3.2).
6340   if (SC == SC_Static) {
6341     if (!D.isInvalidType())
6342       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6343         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6344         << SourceRange(D.getIdentifierLoc())
6345         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6346 
6347     SC = SC_None;
6348   }
6349   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6350     // Destructors don't have return types, but the parser will
6351     // happily parse something like:
6352     //
6353     //   class X {
6354     //     float ~X();
6355     //   };
6356     //
6357     // The return type will be eliminated later.
6358     Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6359       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6360       << SourceRange(D.getIdentifierLoc());
6361   }
6362 
6363   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6364   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6365     if (FTI.TypeQuals & Qualifiers::Const)
6366       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6367         << "const" << SourceRange(D.getIdentifierLoc());
6368     if (FTI.TypeQuals & Qualifiers::Volatile)
6369       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6370         << "volatile" << SourceRange(D.getIdentifierLoc());
6371     if (FTI.TypeQuals & Qualifiers::Restrict)
6372       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6373         << "restrict" << SourceRange(D.getIdentifierLoc());
6374     D.setInvalidType();
6375   }
6376 
6377   // C++0x [class.dtor]p2:
6378   //   A destructor shall not be declared with a ref-qualifier.
6379   if (FTI.hasRefQualifier()) {
6380     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6381       << FTI.RefQualifierIsLValueRef
6382       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6383     D.setInvalidType();
6384   }
6385 
6386   // Make sure we don't have any parameters.
6387   if (FTI.NumParams > 0 && !FTIHasSingleVoidArgument(FTI)) {
6388     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6389 
6390     // Delete the parameters.
6391     FTI.freeParams();
6392     D.setInvalidType();
6393   }
6394 
6395   // Make sure the destructor isn't variadic.
6396   if (FTI.isVariadic) {
6397     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6398     D.setInvalidType();
6399   }
6400 
6401   // Rebuild the function type "R" without any type qualifiers or
6402   // parameters (in case any of the errors above fired) and with
6403   // "void" as the return type, since destructors don't have return
6404   // types.
6405   if (!D.isInvalidType())
6406     return R;
6407 
6408   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6409   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6410   EPI.Variadic = false;
6411   EPI.TypeQuals = 0;
6412   EPI.RefQualifier = RQ_None;
6413   return Context.getFunctionType(Context.VoidTy, None, EPI);
6414 }
6415 
6416 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6417 /// well-formednes of the conversion function declarator @p D with
6418 /// type @p R. If there are any errors in the declarator, this routine
6419 /// will emit diagnostics and return true. Otherwise, it will return
6420 /// false. Either way, the type @p R will be updated to reflect a
6421 /// well-formed type for the conversion operator.
6422 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6423                                      StorageClass& SC) {
6424   // C++ [class.conv.fct]p1:
6425   //   Neither parameter types nor return type can be specified. The
6426   //   type of a conversion function (8.3.5) is "function taking no
6427   //   parameter returning conversion-type-id."
6428   if (SC == SC_Static) {
6429     if (!D.isInvalidType())
6430       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6431         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6432         << D.getName().getSourceRange();
6433     D.setInvalidType();
6434     SC = SC_None;
6435   }
6436 
6437   QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6438 
6439   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6440     // Conversion functions don't have return types, but the parser will
6441     // happily parse something like:
6442     //
6443     //   class X {
6444     //     float operator bool();
6445     //   };
6446     //
6447     // The return type will be changed later anyway.
6448     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6449       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6450       << SourceRange(D.getIdentifierLoc());
6451     D.setInvalidType();
6452   }
6453 
6454   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6455 
6456   // Make sure we don't have any parameters.
6457   if (Proto->getNumParams() > 0) {
6458     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6459 
6460     // Delete the parameters.
6461     D.getFunctionTypeInfo().freeParams();
6462     D.setInvalidType();
6463   } else if (Proto->isVariadic()) {
6464     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6465     D.setInvalidType();
6466   }
6467 
6468   // Diagnose "&operator bool()" and other such nonsense.  This
6469   // is actually a gcc extension which we don't support.
6470   if (Proto->getReturnType() != ConvType) {
6471     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6472         << Proto->getReturnType();
6473     D.setInvalidType();
6474     ConvType = Proto->getReturnType();
6475   }
6476 
6477   // C++ [class.conv.fct]p4:
6478   //   The conversion-type-id shall not represent a function type nor
6479   //   an array type.
6480   if (ConvType->isArrayType()) {
6481     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6482     ConvType = Context.getPointerType(ConvType);
6483     D.setInvalidType();
6484   } else if (ConvType->isFunctionType()) {
6485     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6486     ConvType = Context.getPointerType(ConvType);
6487     D.setInvalidType();
6488   }
6489 
6490   // Rebuild the function type "R" without any parameters (in case any
6491   // of the errors above fired) and with the conversion type as the
6492   // return type.
6493   if (D.isInvalidType())
6494     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6495 
6496   // C++0x explicit conversion operators.
6497   if (D.getDeclSpec().isExplicitSpecified())
6498     Diag(D.getDeclSpec().getExplicitSpecLoc(),
6499          getLangOpts().CPlusPlus11 ?
6500            diag::warn_cxx98_compat_explicit_conversion_functions :
6501            diag::ext_explicit_conversion_functions)
6502       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6503 }
6504 
6505 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6506 /// the declaration of the given C++ conversion function. This routine
6507 /// is responsible for recording the conversion function in the C++
6508 /// class, if possible.
6509 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6510   assert(Conversion && "Expected to receive a conversion function declaration");
6511 
6512   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6513 
6514   // Make sure we aren't redeclaring the conversion function.
6515   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6516 
6517   // C++ [class.conv.fct]p1:
6518   //   [...] A conversion function is never used to convert a
6519   //   (possibly cv-qualified) object to the (possibly cv-qualified)
6520   //   same object type (or a reference to it), to a (possibly
6521   //   cv-qualified) base class of that type (or a reference to it),
6522   //   or to (possibly cv-qualified) void.
6523   // FIXME: Suppress this warning if the conversion function ends up being a
6524   // virtual function that overrides a virtual function in a base class.
6525   QualType ClassType
6526     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6527   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6528     ConvType = ConvTypeRef->getPointeeType();
6529   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6530       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6531     /* Suppress diagnostics for instantiations. */;
6532   else if (ConvType->isRecordType()) {
6533     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6534     if (ConvType == ClassType)
6535       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6536         << ClassType;
6537     else if (IsDerivedFrom(ClassType, ConvType))
6538       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6539         <<  ClassType << ConvType;
6540   } else if (ConvType->isVoidType()) {
6541     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6542       << ClassType << ConvType;
6543   }
6544 
6545   if (FunctionTemplateDecl *ConversionTemplate
6546                                 = Conversion->getDescribedFunctionTemplate())
6547     return ConversionTemplate;
6548 
6549   return Conversion;
6550 }
6551 
6552 //===----------------------------------------------------------------------===//
6553 // Namespace Handling
6554 //===----------------------------------------------------------------------===//
6555 
6556 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6557 /// reopened.
6558 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6559                                             SourceLocation Loc,
6560                                             IdentifierInfo *II, bool *IsInline,
6561                                             NamespaceDecl *PrevNS) {
6562   assert(*IsInline != PrevNS->isInline());
6563 
6564   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6565   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6566   // inline namespaces, with the intention of bringing names into namespace std.
6567   //
6568   // We support this just well enough to get that case working; this is not
6569   // sufficient to support reopening namespaces as inline in general.
6570   if (*IsInline && II && II->getName().startswith("__atomic") &&
6571       S.getSourceManager().isInSystemHeader(Loc)) {
6572     // Mark all prior declarations of the namespace as inline.
6573     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6574          NS = NS->getPreviousDecl())
6575       NS->setInline(*IsInline);
6576     // Patch up the lookup table for the containing namespace. This isn't really
6577     // correct, but it's good enough for this particular case.
6578     for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6579                                     E = PrevNS->decls_end(); I != E; ++I)
6580       if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6581         PrevNS->getParent()->makeDeclVisibleInContext(ND);
6582     return;
6583   }
6584 
6585   if (PrevNS->isInline())
6586     // The user probably just forgot the 'inline', so suggest that it
6587     // be added back.
6588     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6589       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6590   else
6591     S.Diag(Loc, diag::err_inline_namespace_mismatch)
6592       << IsInline;
6593 
6594   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6595   *IsInline = PrevNS->isInline();
6596 }
6597 
6598 /// ActOnStartNamespaceDef - This is called at the start of a namespace
6599 /// definition.
6600 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6601                                    SourceLocation InlineLoc,
6602                                    SourceLocation NamespaceLoc,
6603                                    SourceLocation IdentLoc,
6604                                    IdentifierInfo *II,
6605                                    SourceLocation LBrace,
6606                                    AttributeList *AttrList) {
6607   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6608   // For anonymous namespace, take the location of the left brace.
6609   SourceLocation Loc = II ? IdentLoc : LBrace;
6610   bool IsInline = InlineLoc.isValid();
6611   bool IsInvalid = false;
6612   bool IsStd = false;
6613   bool AddToKnown = false;
6614   Scope *DeclRegionScope = NamespcScope->getParent();
6615 
6616   NamespaceDecl *PrevNS = 0;
6617   if (II) {
6618     // C++ [namespace.def]p2:
6619     //   The identifier in an original-namespace-definition shall not
6620     //   have been previously defined in the declarative region in
6621     //   which the original-namespace-definition appears. The
6622     //   identifier in an original-namespace-definition is the name of
6623     //   the namespace. Subsequently in that declarative region, it is
6624     //   treated as an original-namespace-name.
6625     //
6626     // Since namespace names are unique in their scope, and we don't
6627     // look through using directives, just look for any ordinary names.
6628 
6629     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6630     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6631     Decl::IDNS_Namespace;
6632     NamedDecl *PrevDecl = 0;
6633     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6634     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6635          ++I) {
6636       if ((*I)->getIdentifierNamespace() & IDNS) {
6637         PrevDecl = *I;
6638         break;
6639       }
6640     }
6641 
6642     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6643 
6644     if (PrevNS) {
6645       // This is an extended namespace definition.
6646       if (IsInline != PrevNS->isInline())
6647         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6648                                         &IsInline, PrevNS);
6649     } else if (PrevDecl) {
6650       // This is an invalid name redefinition.
6651       Diag(Loc, diag::err_redefinition_different_kind)
6652         << II;
6653       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6654       IsInvalid = true;
6655       // Continue on to push Namespc as current DeclContext and return it.
6656     } else if (II->isStr("std") &&
6657                CurContext->getRedeclContext()->isTranslationUnit()) {
6658       // This is the first "real" definition of the namespace "std", so update
6659       // our cache of the "std" namespace to point at this definition.
6660       PrevNS = getStdNamespace();
6661       IsStd = true;
6662       AddToKnown = !IsInline;
6663     } else {
6664       // We've seen this namespace for the first time.
6665       AddToKnown = !IsInline;
6666     }
6667   } else {
6668     // Anonymous namespaces.
6669 
6670     // Determine whether the parent already has an anonymous namespace.
6671     DeclContext *Parent = CurContext->getRedeclContext();
6672     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6673       PrevNS = TU->getAnonymousNamespace();
6674     } else {
6675       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6676       PrevNS = ND->getAnonymousNamespace();
6677     }
6678 
6679     if (PrevNS && IsInline != PrevNS->isInline())
6680       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6681                                       &IsInline, PrevNS);
6682   }
6683 
6684   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6685                                                  StartLoc, Loc, II, PrevNS);
6686   if (IsInvalid)
6687     Namespc->setInvalidDecl();
6688 
6689   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6690 
6691   // FIXME: Should we be merging attributes?
6692   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6693     PushNamespaceVisibilityAttr(Attr, Loc);
6694 
6695   if (IsStd)
6696     StdNamespace = Namespc;
6697   if (AddToKnown)
6698     KnownNamespaces[Namespc] = false;
6699 
6700   if (II) {
6701     PushOnScopeChains(Namespc, DeclRegionScope);
6702   } else {
6703     // Link the anonymous namespace into its parent.
6704     DeclContext *Parent = CurContext->getRedeclContext();
6705     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6706       TU->setAnonymousNamespace(Namespc);
6707     } else {
6708       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6709     }
6710 
6711     CurContext->addDecl(Namespc);
6712 
6713     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6714     //   behaves as if it were replaced by
6715     //     namespace unique { /* empty body */ }
6716     //     using namespace unique;
6717     //     namespace unique { namespace-body }
6718     //   where all occurrences of 'unique' in a translation unit are
6719     //   replaced by the same identifier and this identifier differs
6720     //   from all other identifiers in the entire program.
6721 
6722     // We just create the namespace with an empty name and then add an
6723     // implicit using declaration, just like the standard suggests.
6724     //
6725     // CodeGen enforces the "universally unique" aspect by giving all
6726     // declarations semantically contained within an anonymous
6727     // namespace internal linkage.
6728 
6729     if (!PrevNS) {
6730       UsingDirectiveDecl* UD
6731         = UsingDirectiveDecl::Create(Context, Parent,
6732                                      /* 'using' */ LBrace,
6733                                      /* 'namespace' */ SourceLocation(),
6734                                      /* qualifier */ NestedNameSpecifierLoc(),
6735                                      /* identifier */ SourceLocation(),
6736                                      Namespc,
6737                                      /* Ancestor */ Parent);
6738       UD->setImplicit();
6739       Parent->addDecl(UD);
6740     }
6741   }
6742 
6743   ActOnDocumentableDecl(Namespc);
6744 
6745   // Although we could have an invalid decl (i.e. the namespace name is a
6746   // redefinition), push it as current DeclContext and try to continue parsing.
6747   // FIXME: We should be able to push Namespc here, so that the each DeclContext
6748   // for the namespace has the declarations that showed up in that particular
6749   // namespace definition.
6750   PushDeclContext(NamespcScope, Namespc);
6751   return Namespc;
6752 }
6753 
6754 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6755 /// is a namespace alias, returns the namespace it points to.
6756 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6757   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6758     return AD->getNamespace();
6759   return dyn_cast_or_null<NamespaceDecl>(D);
6760 }
6761 
6762 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
6763 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6764 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6765   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6766   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6767   Namespc->setRBraceLoc(RBrace);
6768   PopDeclContext();
6769   if (Namespc->hasAttr<VisibilityAttr>())
6770     PopPragmaVisibility(true, RBrace);
6771 }
6772 
6773 CXXRecordDecl *Sema::getStdBadAlloc() const {
6774   return cast_or_null<CXXRecordDecl>(
6775                                   StdBadAlloc.get(Context.getExternalSource()));
6776 }
6777 
6778 NamespaceDecl *Sema::getStdNamespace() const {
6779   return cast_or_null<NamespaceDecl>(
6780                                  StdNamespace.get(Context.getExternalSource()));
6781 }
6782 
6783 /// \brief Retrieve the special "std" namespace, which may require us to
6784 /// implicitly define the namespace.
6785 NamespaceDecl *Sema::getOrCreateStdNamespace() {
6786   if (!StdNamespace) {
6787     // The "std" namespace has not yet been defined, so build one implicitly.
6788     StdNamespace = NamespaceDecl::Create(Context,
6789                                          Context.getTranslationUnitDecl(),
6790                                          /*Inline=*/false,
6791                                          SourceLocation(), SourceLocation(),
6792                                          &PP.getIdentifierTable().get("std"),
6793                                          /*PrevDecl=*/0);
6794     getStdNamespace()->setImplicit(true);
6795   }
6796 
6797   return getStdNamespace();
6798 }
6799 
6800 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6801   assert(getLangOpts().CPlusPlus &&
6802          "Looking for std::initializer_list outside of C++.");
6803 
6804   // We're looking for implicit instantiations of
6805   // template <typename E> class std::initializer_list.
6806 
6807   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6808     return false;
6809 
6810   ClassTemplateDecl *Template = 0;
6811   const TemplateArgument *Arguments = 0;
6812 
6813   if (const RecordType *RT = Ty->getAs<RecordType>()) {
6814 
6815     ClassTemplateSpecializationDecl *Specialization =
6816         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6817     if (!Specialization)
6818       return false;
6819 
6820     Template = Specialization->getSpecializedTemplate();
6821     Arguments = Specialization->getTemplateArgs().data();
6822   } else if (const TemplateSpecializationType *TST =
6823                  Ty->getAs<TemplateSpecializationType>()) {
6824     Template = dyn_cast_or_null<ClassTemplateDecl>(
6825         TST->getTemplateName().getAsTemplateDecl());
6826     Arguments = TST->getArgs();
6827   }
6828   if (!Template)
6829     return false;
6830 
6831   if (!StdInitializerList) {
6832     // Haven't recognized std::initializer_list yet, maybe this is it.
6833     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6834     if (TemplateClass->getIdentifier() !=
6835             &PP.getIdentifierTable().get("initializer_list") ||
6836         !getStdNamespace()->InEnclosingNamespaceSetOf(
6837             TemplateClass->getDeclContext()))
6838       return false;
6839     // This is a template called std::initializer_list, but is it the right
6840     // template?
6841     TemplateParameterList *Params = Template->getTemplateParameters();
6842     if (Params->getMinRequiredArguments() != 1)
6843       return false;
6844     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6845       return false;
6846 
6847     // It's the right template.
6848     StdInitializerList = Template;
6849   }
6850 
6851   if (Template != StdInitializerList)
6852     return false;
6853 
6854   // This is an instance of std::initializer_list. Find the argument type.
6855   if (Element)
6856     *Element = Arguments[0].getAsType();
6857   return true;
6858 }
6859 
6860 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6861   NamespaceDecl *Std = S.getStdNamespace();
6862   if (!Std) {
6863     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6864     return 0;
6865   }
6866 
6867   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6868                       Loc, Sema::LookupOrdinaryName);
6869   if (!S.LookupQualifiedName(Result, Std)) {
6870     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6871     return 0;
6872   }
6873   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6874   if (!Template) {
6875     Result.suppressDiagnostics();
6876     // We found something weird. Complain about the first thing we found.
6877     NamedDecl *Found = *Result.begin();
6878     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6879     return 0;
6880   }
6881 
6882   // We found some template called std::initializer_list. Now verify that it's
6883   // correct.
6884   TemplateParameterList *Params = Template->getTemplateParameters();
6885   if (Params->getMinRequiredArguments() != 1 ||
6886       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6887     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6888     return 0;
6889   }
6890 
6891   return Template;
6892 }
6893 
6894 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6895   if (!StdInitializerList) {
6896     StdInitializerList = LookupStdInitializerList(*this, Loc);
6897     if (!StdInitializerList)
6898       return QualType();
6899   }
6900 
6901   TemplateArgumentListInfo Args(Loc, Loc);
6902   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6903                                        Context.getTrivialTypeSourceInfo(Element,
6904                                                                         Loc)));
6905   return Context.getCanonicalType(
6906       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6907 }
6908 
6909 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6910   // C++ [dcl.init.list]p2:
6911   //   A constructor is an initializer-list constructor if its first parameter
6912   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
6913   //   std::initializer_list<E> for some type E, and either there are no other
6914   //   parameters or else all other parameters have default arguments.
6915   if (Ctor->getNumParams() < 1 ||
6916       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6917     return false;
6918 
6919   QualType ArgType = Ctor->getParamDecl(0)->getType();
6920   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6921     ArgType = RT->getPointeeType().getUnqualifiedType();
6922 
6923   return isStdInitializerList(ArgType, 0);
6924 }
6925 
6926 /// \brief Determine whether a using statement is in a context where it will be
6927 /// apply in all contexts.
6928 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6929   switch (CurContext->getDeclKind()) {
6930     case Decl::TranslationUnit:
6931       return true;
6932     case Decl::LinkageSpec:
6933       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6934     default:
6935       return false;
6936   }
6937 }
6938 
6939 namespace {
6940 
6941 // Callback to only accept typo corrections that are namespaces.
6942 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6943 public:
6944   bool ValidateCandidate(const TypoCorrection &candidate) override {
6945     if (NamedDecl *ND = candidate.getCorrectionDecl())
6946       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6947     return false;
6948   }
6949 };
6950 
6951 }
6952 
6953 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6954                                        CXXScopeSpec &SS,
6955                                        SourceLocation IdentLoc,
6956                                        IdentifierInfo *Ident) {
6957   NamespaceValidatorCCC Validator;
6958   R.clear();
6959   if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6960                                                R.getLookupKind(), Sc, &SS,
6961                                                Validator)) {
6962     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
6963       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6964       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
6965                               Ident->getName().equals(CorrectedStr);
6966       S.diagnoseTypo(Corrected,
6967                      S.PDiag(diag::err_using_directive_member_suggest)
6968                        << Ident << DC << DroppedSpecifier << SS.getRange(),
6969                      S.PDiag(diag::note_namespace_defined_here));
6970     } else {
6971       S.diagnoseTypo(Corrected,
6972                      S.PDiag(diag::err_using_directive_suggest) << Ident,
6973                      S.PDiag(diag::note_namespace_defined_here));
6974     }
6975     R.addDecl(Corrected.getCorrectionDecl());
6976     return true;
6977   }
6978   return false;
6979 }
6980 
6981 Decl *Sema::ActOnUsingDirective(Scope *S,
6982                                           SourceLocation UsingLoc,
6983                                           SourceLocation NamespcLoc,
6984                                           CXXScopeSpec &SS,
6985                                           SourceLocation IdentLoc,
6986                                           IdentifierInfo *NamespcName,
6987                                           AttributeList *AttrList) {
6988   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6989   assert(NamespcName && "Invalid NamespcName.");
6990   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
6991 
6992   // This can only happen along a recovery path.
6993   while (S->getFlags() & Scope::TemplateParamScope)
6994     S = S->getParent();
6995   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6996 
6997   UsingDirectiveDecl *UDir = 0;
6998   NestedNameSpecifier *Qualifier = 0;
6999   if (SS.isSet())
7000     Qualifier = SS.getScopeRep();
7001 
7002   // Lookup namespace name.
7003   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7004   LookupParsedName(R, S, &SS);
7005   if (R.isAmbiguous())
7006     return 0;
7007 
7008   if (R.empty()) {
7009     R.clear();
7010     // Allow "using namespace std;" or "using namespace ::std;" even if
7011     // "std" hasn't been defined yet, for GCC compatibility.
7012     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7013         NamespcName->isStr("std")) {
7014       Diag(IdentLoc, diag::ext_using_undefined_std);
7015       R.addDecl(getOrCreateStdNamespace());
7016       R.resolveKind();
7017     }
7018     // Otherwise, attempt typo correction.
7019     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7020   }
7021 
7022   if (!R.empty()) {
7023     NamedDecl *Named = R.getFoundDecl();
7024     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7025         && "expected namespace decl");
7026     // C++ [namespace.udir]p1:
7027     //   A using-directive specifies that the names in the nominated
7028     //   namespace can be used in the scope in which the
7029     //   using-directive appears after the using-directive. During
7030     //   unqualified name lookup (3.4.1), the names appear as if they
7031     //   were declared in the nearest enclosing namespace which
7032     //   contains both the using-directive and the nominated
7033     //   namespace. [Note: in this context, "contains" means "contains
7034     //   directly or indirectly". ]
7035 
7036     // Find enclosing context containing both using-directive and
7037     // nominated namespace.
7038     NamespaceDecl *NS = getNamespaceDecl(Named);
7039     DeclContext *CommonAncestor = cast<DeclContext>(NS);
7040     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7041       CommonAncestor = CommonAncestor->getParent();
7042 
7043     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7044                                       SS.getWithLocInContext(Context),
7045                                       IdentLoc, Named, CommonAncestor);
7046 
7047     if (IsUsingDirectiveInToplevelContext(CurContext) &&
7048         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7049       Diag(IdentLoc, diag::warn_using_directive_in_header);
7050     }
7051 
7052     PushUsingDirective(S, UDir);
7053   } else {
7054     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7055   }
7056 
7057   if (UDir)
7058     ProcessDeclAttributeList(S, UDir, AttrList);
7059 
7060   return UDir;
7061 }
7062 
7063 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7064   // If the scope has an associated entity and the using directive is at
7065   // namespace or translation unit scope, add the UsingDirectiveDecl into
7066   // its lookup structure so qualified name lookup can find it.
7067   DeclContext *Ctx = S->getEntity();
7068   if (Ctx && !Ctx->isFunctionOrMethod())
7069     Ctx->addDecl(UDir);
7070   else
7071     // Otherwise, it is at block sope. The using-directives will affect lookup
7072     // only to the end of the scope.
7073     S->PushUsingDirective(UDir);
7074 }
7075 
7076 
7077 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7078                                   AccessSpecifier AS,
7079                                   bool HasUsingKeyword,
7080                                   SourceLocation UsingLoc,
7081                                   CXXScopeSpec &SS,
7082                                   UnqualifiedId &Name,
7083                                   AttributeList *AttrList,
7084                                   bool HasTypenameKeyword,
7085                                   SourceLocation TypenameLoc) {
7086   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7087 
7088   switch (Name.getKind()) {
7089   case UnqualifiedId::IK_ImplicitSelfParam:
7090   case UnqualifiedId::IK_Identifier:
7091   case UnqualifiedId::IK_OperatorFunctionId:
7092   case UnqualifiedId::IK_LiteralOperatorId:
7093   case UnqualifiedId::IK_ConversionFunctionId:
7094     break;
7095 
7096   case UnqualifiedId::IK_ConstructorName:
7097   case UnqualifiedId::IK_ConstructorTemplateId:
7098     // C++11 inheriting constructors.
7099     Diag(Name.getLocStart(),
7100          getLangOpts().CPlusPlus11 ?
7101            diag::warn_cxx98_compat_using_decl_constructor :
7102            diag::err_using_decl_constructor)
7103       << SS.getRange();
7104 
7105     if (getLangOpts().CPlusPlus11) break;
7106 
7107     return 0;
7108 
7109   case UnqualifiedId::IK_DestructorName:
7110     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7111       << SS.getRange();
7112     return 0;
7113 
7114   case UnqualifiedId::IK_TemplateId:
7115     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7116       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7117     return 0;
7118   }
7119 
7120   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7121   DeclarationName TargetName = TargetNameInfo.getName();
7122   if (!TargetName)
7123     return 0;
7124 
7125   // Warn about access declarations.
7126   if (!HasUsingKeyword) {
7127     Diag(Name.getLocStart(),
7128          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7129                                    : diag::warn_access_decl_deprecated)
7130       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7131   }
7132 
7133   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7134       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7135     return 0;
7136 
7137   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7138                                         TargetNameInfo, AttrList,
7139                                         /* IsInstantiation */ false,
7140                                         HasTypenameKeyword, TypenameLoc);
7141   if (UD)
7142     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7143 
7144   return UD;
7145 }
7146 
7147 /// \brief Determine whether a using declaration considers the given
7148 /// declarations as "equivalent", e.g., if they are redeclarations of
7149 /// the same entity or are both typedefs of the same type.
7150 static bool
7151 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7152   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7153     return true;
7154 
7155   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7156     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7157       return Context.hasSameType(TD1->getUnderlyingType(),
7158                                  TD2->getUnderlyingType());
7159 
7160   return false;
7161 }
7162 
7163 
7164 /// Determines whether to create a using shadow decl for a particular
7165 /// decl, given the set of decls existing prior to this using lookup.
7166 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7167                                 const LookupResult &Previous,
7168                                 UsingShadowDecl *&PrevShadow) {
7169   // Diagnose finding a decl which is not from a base class of the
7170   // current class.  We do this now because there are cases where this
7171   // function will silently decide not to build a shadow decl, which
7172   // will pre-empt further diagnostics.
7173   //
7174   // We don't need to do this in C++0x because we do the check once on
7175   // the qualifier.
7176   //
7177   // FIXME: diagnose the following if we care enough:
7178   //   struct A { int foo; };
7179   //   struct B : A { using A::foo; };
7180   //   template <class T> struct C : A {};
7181   //   template <class T> struct D : C<T> { using B::foo; } // <---
7182   // This is invalid (during instantiation) in C++03 because B::foo
7183   // resolves to the using decl in B, which is not a base class of D<T>.
7184   // We can't diagnose it immediately because C<T> is an unknown
7185   // specialization.  The UsingShadowDecl in D<T> then points directly
7186   // to A::foo, which will look well-formed when we instantiate.
7187   // The right solution is to not collapse the shadow-decl chain.
7188   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7189     DeclContext *OrigDC = Orig->getDeclContext();
7190 
7191     // Handle enums and anonymous structs.
7192     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7193     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7194     while (OrigRec->isAnonymousStructOrUnion())
7195       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7196 
7197     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7198       if (OrigDC == CurContext) {
7199         Diag(Using->getLocation(),
7200              diag::err_using_decl_nested_name_specifier_is_current_class)
7201           << Using->getQualifierLoc().getSourceRange();
7202         Diag(Orig->getLocation(), diag::note_using_decl_target);
7203         return true;
7204       }
7205 
7206       Diag(Using->getQualifierLoc().getBeginLoc(),
7207            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7208         << Using->getQualifier()
7209         << cast<CXXRecordDecl>(CurContext)
7210         << Using->getQualifierLoc().getSourceRange();
7211       Diag(Orig->getLocation(), diag::note_using_decl_target);
7212       return true;
7213     }
7214   }
7215 
7216   if (Previous.empty()) return false;
7217 
7218   NamedDecl *Target = Orig;
7219   if (isa<UsingShadowDecl>(Target))
7220     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7221 
7222   // If the target happens to be one of the previous declarations, we
7223   // don't have a conflict.
7224   //
7225   // FIXME: but we might be increasing its access, in which case we
7226   // should redeclare it.
7227   NamedDecl *NonTag = 0, *Tag = 0;
7228   bool FoundEquivalentDecl = false;
7229   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7230          I != E; ++I) {
7231     NamedDecl *D = (*I)->getUnderlyingDecl();
7232     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7233       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7234         PrevShadow = Shadow;
7235       FoundEquivalentDecl = true;
7236     }
7237 
7238     (isa<TagDecl>(D) ? Tag : NonTag) = D;
7239   }
7240 
7241   if (FoundEquivalentDecl)
7242     return false;
7243 
7244   if (FunctionDecl *FD = Target->getAsFunction()) {
7245     NamedDecl *OldDecl = 0;
7246     switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
7247     case Ovl_Overload:
7248       return false;
7249 
7250     case Ovl_NonFunction:
7251       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7252       break;
7253 
7254     // We found a decl with the exact signature.
7255     case Ovl_Match:
7256       // If we're in a record, we want to hide the target, so we
7257       // return true (without a diagnostic) to tell the caller not to
7258       // build a shadow decl.
7259       if (CurContext->isRecord())
7260         return true;
7261 
7262       // If we're not in a record, this is an error.
7263       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7264       break;
7265     }
7266 
7267     Diag(Target->getLocation(), diag::note_using_decl_target);
7268     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7269     return true;
7270   }
7271 
7272   // Target is not a function.
7273 
7274   if (isa<TagDecl>(Target)) {
7275     // No conflict between a tag and a non-tag.
7276     if (!Tag) return false;
7277 
7278     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7279     Diag(Target->getLocation(), diag::note_using_decl_target);
7280     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7281     return true;
7282   }
7283 
7284   // No conflict between a tag and a non-tag.
7285   if (!NonTag) return false;
7286 
7287   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7288   Diag(Target->getLocation(), diag::note_using_decl_target);
7289   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7290   return true;
7291 }
7292 
7293 /// Builds a shadow declaration corresponding to a 'using' declaration.
7294 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7295                                             UsingDecl *UD,
7296                                             NamedDecl *Orig,
7297                                             UsingShadowDecl *PrevDecl) {
7298 
7299   // If we resolved to another shadow declaration, just coalesce them.
7300   NamedDecl *Target = Orig;
7301   if (isa<UsingShadowDecl>(Target)) {
7302     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7303     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7304   }
7305 
7306   UsingShadowDecl *Shadow
7307     = UsingShadowDecl::Create(Context, CurContext,
7308                               UD->getLocation(), UD, Target);
7309   UD->addShadowDecl(Shadow);
7310 
7311   Shadow->setAccess(UD->getAccess());
7312   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7313     Shadow->setInvalidDecl();
7314 
7315   Shadow->setPreviousDecl(PrevDecl);
7316 
7317   if (S)
7318     PushOnScopeChains(Shadow, S);
7319   else
7320     CurContext->addDecl(Shadow);
7321 
7322 
7323   return Shadow;
7324 }
7325 
7326 /// Hides a using shadow declaration.  This is required by the current
7327 /// using-decl implementation when a resolvable using declaration in a
7328 /// class is followed by a declaration which would hide or override
7329 /// one or more of the using decl's targets; for example:
7330 ///
7331 ///   struct Base { void foo(int); };
7332 ///   struct Derived : Base {
7333 ///     using Base::foo;
7334 ///     void foo(int);
7335 ///   };
7336 ///
7337 /// The governing language is C++03 [namespace.udecl]p12:
7338 ///
7339 ///   When a using-declaration brings names from a base class into a
7340 ///   derived class scope, member functions in the derived class
7341 ///   override and/or hide member functions with the same name and
7342 ///   parameter types in a base class (rather than conflicting).
7343 ///
7344 /// There are two ways to implement this:
7345 ///   (1) optimistically create shadow decls when they're not hidden
7346 ///       by existing declarations, or
7347 ///   (2) don't create any shadow decls (or at least don't make them
7348 ///       visible) until we've fully parsed/instantiated the class.
7349 /// The problem with (1) is that we might have to retroactively remove
7350 /// a shadow decl, which requires several O(n) operations because the
7351 /// decl structures are (very reasonably) not designed for removal.
7352 /// (2) avoids this but is very fiddly and phase-dependent.
7353 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7354   if (Shadow->getDeclName().getNameKind() ==
7355         DeclarationName::CXXConversionFunctionName)
7356     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7357 
7358   // Remove it from the DeclContext...
7359   Shadow->getDeclContext()->removeDecl(Shadow);
7360 
7361   // ...and the scope, if applicable...
7362   if (S) {
7363     S->RemoveDecl(Shadow);
7364     IdResolver.RemoveDecl(Shadow);
7365   }
7366 
7367   // ...and the using decl.
7368   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7369 
7370   // TODO: complain somehow if Shadow was used.  It shouldn't
7371   // be possible for this to happen, because...?
7372 }
7373 
7374 namespace {
7375 class UsingValidatorCCC : public CorrectionCandidateCallback {
7376 public:
7377   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7378                     bool RequireMember)
7379       : HasTypenameKeyword(HasTypenameKeyword),
7380         IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
7381 
7382   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7383     NamedDecl *ND = Candidate.getCorrectionDecl();
7384 
7385     // Keywords are not valid here.
7386     if (!ND || isa<NamespaceDecl>(ND))
7387       return false;
7388 
7389     if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7390         !isa<TypeDecl>(ND))
7391       return false;
7392 
7393     // Completely unqualified names are invalid for a 'using' declaration.
7394     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7395       return false;
7396 
7397     if (isa<TypeDecl>(ND))
7398       return HasTypenameKeyword || !IsInstantiation;
7399 
7400     return !HasTypenameKeyword;
7401   }
7402 
7403 private:
7404   bool HasTypenameKeyword;
7405   bool IsInstantiation;
7406   bool RequireMember;
7407 };
7408 } // end anonymous namespace
7409 
7410 /// Builds a using declaration.
7411 ///
7412 /// \param IsInstantiation - Whether this call arises from an
7413 ///   instantiation of an unresolved using declaration.  We treat
7414 ///   the lookup differently for these declarations.
7415 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7416                                        SourceLocation UsingLoc,
7417                                        CXXScopeSpec &SS,
7418                                        const DeclarationNameInfo &NameInfo,
7419                                        AttributeList *AttrList,
7420                                        bool IsInstantiation,
7421                                        bool HasTypenameKeyword,
7422                                        SourceLocation TypenameLoc) {
7423   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7424   SourceLocation IdentLoc = NameInfo.getLoc();
7425   assert(IdentLoc.isValid() && "Invalid TargetName location.");
7426 
7427   // FIXME: We ignore attributes for now.
7428 
7429   if (SS.isEmpty()) {
7430     Diag(IdentLoc, diag::err_using_requires_qualname);
7431     return 0;
7432   }
7433 
7434   // Do the redeclaration lookup in the current scope.
7435   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7436                         ForRedeclaration);
7437   Previous.setHideTags(false);
7438   if (S) {
7439     LookupName(Previous, S);
7440 
7441     // It is really dumb that we have to do this.
7442     LookupResult::Filter F = Previous.makeFilter();
7443     while (F.hasNext()) {
7444       NamedDecl *D = F.next();
7445       if (!isDeclInScope(D, CurContext, S))
7446         F.erase();
7447     }
7448     F.done();
7449   } else {
7450     assert(IsInstantiation && "no scope in non-instantiation");
7451     assert(CurContext->isRecord() && "scope not record in instantiation");
7452     LookupQualifiedName(Previous, CurContext);
7453   }
7454 
7455   // Check for invalid redeclarations.
7456   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7457                                   SS, IdentLoc, Previous))
7458     return 0;
7459 
7460   // Check for bad qualifiers.
7461   if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7462     return 0;
7463 
7464   DeclContext *LookupContext = computeDeclContext(SS);
7465   NamedDecl *D;
7466   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7467   if (!LookupContext) {
7468     if (HasTypenameKeyword) {
7469       // FIXME: not all declaration name kinds are legal here
7470       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7471                                               UsingLoc, TypenameLoc,
7472                                               QualifierLoc,
7473                                               IdentLoc, NameInfo.getName());
7474     } else {
7475       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7476                                            QualifierLoc, NameInfo);
7477     }
7478   } else {
7479     D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7480                           NameInfo, HasTypenameKeyword);
7481   }
7482   D->setAccess(AS);
7483   CurContext->addDecl(D);
7484 
7485   if (!LookupContext) return D;
7486   UsingDecl *UD = cast<UsingDecl>(D);
7487 
7488   if (RequireCompleteDeclContext(SS, LookupContext)) {
7489     UD->setInvalidDecl();
7490     return UD;
7491   }
7492 
7493   // The normal rules do not apply to inheriting constructor declarations.
7494   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7495     if (CheckInheritingConstructorUsingDecl(UD))
7496       UD->setInvalidDecl();
7497     return UD;
7498   }
7499 
7500   // Otherwise, look up the target name.
7501 
7502   LookupResult R(*this, NameInfo, LookupOrdinaryName);
7503 
7504   // Unlike most lookups, we don't always want to hide tag
7505   // declarations: tag names are visible through the using declaration
7506   // even if hidden by ordinary names, *except* in a dependent context
7507   // where it's important for the sanity of two-phase lookup.
7508   if (!IsInstantiation)
7509     R.setHideTags(false);
7510 
7511   // For the purposes of this lookup, we have a base object type
7512   // equal to that of the current context.
7513   if (CurContext->isRecord()) {
7514     R.setBaseObjectType(
7515                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7516   }
7517 
7518   LookupQualifiedName(R, LookupContext);
7519 
7520   // Try to correct typos if possible.
7521   if (R.empty()) {
7522     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7523                           CurContext->isRecord());
7524     if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7525                                                R.getLookupKind(), S, &SS, CCC)){
7526       // We reject any correction for which ND would be NULL.
7527       NamedDecl *ND = Corrected.getCorrectionDecl();
7528       R.setLookupName(Corrected.getCorrection());
7529       R.addDecl(ND);
7530       // We reject candidates where DroppedSpecifier == true, hence the
7531       // literal '0' below.
7532       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7533                                 << NameInfo.getName() << LookupContext << 0
7534                                 << SS.getRange());
7535     } else {
7536       Diag(IdentLoc, diag::err_no_member)
7537         << NameInfo.getName() << LookupContext << SS.getRange();
7538       UD->setInvalidDecl();
7539       return UD;
7540     }
7541   }
7542 
7543   if (R.isAmbiguous()) {
7544     UD->setInvalidDecl();
7545     return UD;
7546   }
7547 
7548   if (HasTypenameKeyword) {
7549     // If we asked for a typename and got a non-type decl, error out.
7550     if (!R.getAsSingle<TypeDecl>()) {
7551       Diag(IdentLoc, diag::err_using_typename_non_type);
7552       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7553         Diag((*I)->getUnderlyingDecl()->getLocation(),
7554              diag::note_using_decl_target);
7555       UD->setInvalidDecl();
7556       return UD;
7557     }
7558   } else {
7559     // If we asked for a non-typename and we got a type, error out,
7560     // but only if this is an instantiation of an unresolved using
7561     // decl.  Otherwise just silently find the type name.
7562     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7563       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7564       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7565       UD->setInvalidDecl();
7566       return UD;
7567     }
7568   }
7569 
7570   // C++0x N2914 [namespace.udecl]p6:
7571   // A using-declaration shall not name a namespace.
7572   if (R.getAsSingle<NamespaceDecl>()) {
7573     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7574       << SS.getRange();
7575     UD->setInvalidDecl();
7576     return UD;
7577   }
7578 
7579   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7580     UsingShadowDecl *PrevDecl = 0;
7581     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7582       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
7583   }
7584 
7585   return UD;
7586 }
7587 
7588 /// Additional checks for a using declaration referring to a constructor name.
7589 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7590   assert(!UD->hasTypename() && "expecting a constructor name");
7591 
7592   const Type *SourceType = UD->getQualifier()->getAsType();
7593   assert(SourceType &&
7594          "Using decl naming constructor doesn't have type in scope spec.");
7595   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7596 
7597   // Check whether the named type is a direct base class.
7598   CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7599   CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7600   for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7601        BaseIt != BaseE; ++BaseIt) {
7602     CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7603     if (CanonicalSourceType == BaseType)
7604       break;
7605     if (BaseIt->getType()->isDependentType())
7606       break;
7607   }
7608 
7609   if (BaseIt == BaseE) {
7610     // Did not find SourceType in the bases.
7611     Diag(UD->getUsingLoc(),
7612          diag::err_using_decl_constructor_not_in_direct_base)
7613       << UD->getNameInfo().getSourceRange()
7614       << QualType(SourceType, 0) << TargetClass;
7615     return true;
7616   }
7617 
7618   if (!CurContext->isDependentContext())
7619     BaseIt->setInheritConstructors();
7620 
7621   return false;
7622 }
7623 
7624 /// Checks that the given using declaration is not an invalid
7625 /// redeclaration.  Note that this is checking only for the using decl
7626 /// itself, not for any ill-formedness among the UsingShadowDecls.
7627 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7628                                        bool HasTypenameKeyword,
7629                                        const CXXScopeSpec &SS,
7630                                        SourceLocation NameLoc,
7631                                        const LookupResult &Prev) {
7632   // C++03 [namespace.udecl]p8:
7633   // C++0x [namespace.udecl]p10:
7634   //   A using-declaration is a declaration and can therefore be used
7635   //   repeatedly where (and only where) multiple declarations are
7636   //   allowed.
7637   //
7638   // That's in non-member contexts.
7639   if (!CurContext->getRedeclContext()->isRecord())
7640     return false;
7641 
7642   NestedNameSpecifier *Qual = SS.getScopeRep();
7643 
7644   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7645     NamedDecl *D = *I;
7646 
7647     bool DTypename;
7648     NestedNameSpecifier *DQual;
7649     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7650       DTypename = UD->hasTypename();
7651       DQual = UD->getQualifier();
7652     } else if (UnresolvedUsingValueDecl *UD
7653                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7654       DTypename = false;
7655       DQual = UD->getQualifier();
7656     } else if (UnresolvedUsingTypenameDecl *UD
7657                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7658       DTypename = true;
7659       DQual = UD->getQualifier();
7660     } else continue;
7661 
7662     // using decls differ if one says 'typename' and the other doesn't.
7663     // FIXME: non-dependent using decls?
7664     if (HasTypenameKeyword != DTypename) continue;
7665 
7666     // using decls differ if they name different scopes (but note that
7667     // template instantiation can cause this check to trigger when it
7668     // didn't before instantiation).
7669     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7670         Context.getCanonicalNestedNameSpecifier(DQual))
7671       continue;
7672 
7673     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7674     Diag(D->getLocation(), diag::note_using_decl) << 1;
7675     return true;
7676   }
7677 
7678   return false;
7679 }
7680 
7681 
7682 /// Checks that the given nested-name qualifier used in a using decl
7683 /// in the current context is appropriately related to the current
7684 /// scope.  If an error is found, diagnoses it and returns true.
7685 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7686                                    const CXXScopeSpec &SS,
7687                                    SourceLocation NameLoc) {
7688   DeclContext *NamedContext = computeDeclContext(SS);
7689 
7690   if (!CurContext->isRecord()) {
7691     // C++03 [namespace.udecl]p3:
7692     // C++0x [namespace.udecl]p8:
7693     //   A using-declaration for a class member shall be a member-declaration.
7694 
7695     // If we weren't able to compute a valid scope, it must be a
7696     // dependent class scope.
7697     if (!NamedContext || NamedContext->isRecord()) {
7698       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7699         << SS.getRange();
7700       return true;
7701     }
7702 
7703     // Otherwise, everything is known to be fine.
7704     return false;
7705   }
7706 
7707   // The current scope is a record.
7708 
7709   // If the named context is dependent, we can't decide much.
7710   if (!NamedContext) {
7711     // FIXME: in C++0x, we can diagnose if we can prove that the
7712     // nested-name-specifier does not refer to a base class, which is
7713     // still possible in some cases.
7714 
7715     // Otherwise we have to conservatively report that things might be
7716     // okay.
7717     return false;
7718   }
7719 
7720   if (!NamedContext->isRecord()) {
7721     // Ideally this would point at the last name in the specifier,
7722     // but we don't have that level of source info.
7723     Diag(SS.getRange().getBegin(),
7724          diag::err_using_decl_nested_name_specifier_is_not_class)
7725       << SS.getScopeRep() << SS.getRange();
7726     return true;
7727   }
7728 
7729   if (!NamedContext->isDependentContext() &&
7730       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7731     return true;
7732 
7733   if (getLangOpts().CPlusPlus11) {
7734     // C++0x [namespace.udecl]p3:
7735     //   In a using-declaration used as a member-declaration, the
7736     //   nested-name-specifier shall name a base class of the class
7737     //   being defined.
7738 
7739     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7740                                  cast<CXXRecordDecl>(NamedContext))) {
7741       if (CurContext == NamedContext) {
7742         Diag(NameLoc,
7743              diag::err_using_decl_nested_name_specifier_is_current_class)
7744           << SS.getRange();
7745         return true;
7746       }
7747 
7748       Diag(SS.getRange().getBegin(),
7749            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7750         << SS.getScopeRep()
7751         << cast<CXXRecordDecl>(CurContext)
7752         << SS.getRange();
7753       return true;
7754     }
7755 
7756     return false;
7757   }
7758 
7759   // C++03 [namespace.udecl]p4:
7760   //   A using-declaration used as a member-declaration shall refer
7761   //   to a member of a base class of the class being defined [etc.].
7762 
7763   // Salient point: SS doesn't have to name a base class as long as
7764   // lookup only finds members from base classes.  Therefore we can
7765   // diagnose here only if we can prove that that can't happen,
7766   // i.e. if the class hierarchies provably don't intersect.
7767 
7768   // TODO: it would be nice if "definitely valid" results were cached
7769   // in the UsingDecl and UsingShadowDecl so that these checks didn't
7770   // need to be repeated.
7771 
7772   struct UserData {
7773     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7774 
7775     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7776       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7777       Data->Bases.insert(Base);
7778       return true;
7779     }
7780 
7781     bool hasDependentBases(const CXXRecordDecl *Class) {
7782       return !Class->forallBases(collect, this);
7783     }
7784 
7785     /// Returns true if the base is dependent or is one of the
7786     /// accumulated base classes.
7787     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7788       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7789       return !Data->Bases.count(Base);
7790     }
7791 
7792     bool mightShareBases(const CXXRecordDecl *Class) {
7793       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7794     }
7795   };
7796 
7797   UserData Data;
7798 
7799   // Returns false if we find a dependent base.
7800   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7801     return false;
7802 
7803   // Returns false if the class has a dependent base or if it or one
7804   // of its bases is present in the base set of the current context.
7805   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7806     return false;
7807 
7808   Diag(SS.getRange().getBegin(),
7809        diag::err_using_decl_nested_name_specifier_is_not_base_class)
7810     << SS.getScopeRep()
7811     << cast<CXXRecordDecl>(CurContext)
7812     << SS.getRange();
7813 
7814   return true;
7815 }
7816 
7817 Decl *Sema::ActOnAliasDeclaration(Scope *S,
7818                                   AccessSpecifier AS,
7819                                   MultiTemplateParamsArg TemplateParamLists,
7820                                   SourceLocation UsingLoc,
7821                                   UnqualifiedId &Name,
7822                                   AttributeList *AttrList,
7823                                   TypeResult Type) {
7824   // Skip up to the relevant declaration scope.
7825   while (S->getFlags() & Scope::TemplateParamScope)
7826     S = S->getParent();
7827   assert((S->getFlags() & Scope::DeclScope) &&
7828          "got alias-declaration outside of declaration scope");
7829 
7830   if (Type.isInvalid())
7831     return 0;
7832 
7833   bool Invalid = false;
7834   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7835   TypeSourceInfo *TInfo = 0;
7836   GetTypeFromParser(Type.get(), &TInfo);
7837 
7838   if (DiagnoseClassNameShadow(CurContext, NameInfo))
7839     return 0;
7840 
7841   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7842                                       UPPC_DeclarationType)) {
7843     Invalid = true;
7844     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7845                                              TInfo->getTypeLoc().getBeginLoc());
7846   }
7847 
7848   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7849   LookupName(Previous, S);
7850 
7851   // Warn about shadowing the name of a template parameter.
7852   if (Previous.isSingleResult() &&
7853       Previous.getFoundDecl()->isTemplateParameter()) {
7854     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
7855     Previous.clear();
7856   }
7857 
7858   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7859          "name in alias declaration must be an identifier");
7860   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7861                                                Name.StartLocation,
7862                                                Name.Identifier, TInfo);
7863 
7864   NewTD->setAccess(AS);
7865 
7866   if (Invalid)
7867     NewTD->setInvalidDecl();
7868 
7869   ProcessDeclAttributeList(S, NewTD, AttrList);
7870 
7871   CheckTypedefForVariablyModifiedType(S, NewTD);
7872   Invalid |= NewTD->isInvalidDecl();
7873 
7874   bool Redeclaration = false;
7875 
7876   NamedDecl *NewND;
7877   if (TemplateParamLists.size()) {
7878     TypeAliasTemplateDecl *OldDecl = 0;
7879     TemplateParameterList *OldTemplateParams = 0;
7880 
7881     if (TemplateParamLists.size() != 1) {
7882       Diag(UsingLoc, diag::err_alias_template_extra_headers)
7883         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7884          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
7885     }
7886     TemplateParameterList *TemplateParams = TemplateParamLists[0];
7887 
7888     // Only consider previous declarations in the same scope.
7889     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7890                          /*ExplicitInstantiationOrSpecialization*/false);
7891     if (!Previous.empty()) {
7892       Redeclaration = true;
7893 
7894       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7895       if (!OldDecl && !Invalid) {
7896         Diag(UsingLoc, diag::err_redefinition_different_kind)
7897           << Name.Identifier;
7898 
7899         NamedDecl *OldD = Previous.getRepresentativeDecl();
7900         if (OldD->getLocation().isValid())
7901           Diag(OldD->getLocation(), diag::note_previous_definition);
7902 
7903         Invalid = true;
7904       }
7905 
7906       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7907         if (TemplateParameterListsAreEqual(TemplateParams,
7908                                            OldDecl->getTemplateParameters(),
7909                                            /*Complain=*/true,
7910                                            TPL_TemplateMatch))
7911           OldTemplateParams = OldDecl->getTemplateParameters();
7912         else
7913           Invalid = true;
7914 
7915         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7916         if (!Invalid &&
7917             !Context.hasSameType(OldTD->getUnderlyingType(),
7918                                  NewTD->getUnderlyingType())) {
7919           // FIXME: The C++0x standard does not clearly say this is ill-formed,
7920           // but we can't reasonably accept it.
7921           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7922             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7923           if (OldTD->getLocation().isValid())
7924             Diag(OldTD->getLocation(), diag::note_previous_definition);
7925           Invalid = true;
7926         }
7927       }
7928     }
7929 
7930     // Merge any previous default template arguments into our parameters,
7931     // and check the parameter list.
7932     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7933                                    TPC_TypeAliasTemplate))
7934       return 0;
7935 
7936     TypeAliasTemplateDecl *NewDecl =
7937       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7938                                     Name.Identifier, TemplateParams,
7939                                     NewTD);
7940 
7941     NewDecl->setAccess(AS);
7942 
7943     if (Invalid)
7944       NewDecl->setInvalidDecl();
7945     else if (OldDecl)
7946       NewDecl->setPreviousDecl(OldDecl);
7947 
7948     NewND = NewDecl;
7949   } else {
7950     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7951     NewND = NewTD;
7952   }
7953 
7954   if (!Redeclaration)
7955     PushOnScopeChains(NewND, S);
7956 
7957   ActOnDocumentableDecl(NewND);
7958   return NewND;
7959 }
7960 
7961 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
7962                                              SourceLocation NamespaceLoc,
7963                                              SourceLocation AliasLoc,
7964                                              IdentifierInfo *Alias,
7965                                              CXXScopeSpec &SS,
7966                                              SourceLocation IdentLoc,
7967                                              IdentifierInfo *Ident) {
7968 
7969   // Lookup the namespace name.
7970   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7971   LookupParsedName(R, S, &SS);
7972 
7973   // Check if we have a previous declaration with the same name.
7974   NamedDecl *PrevDecl
7975     = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7976                        ForRedeclaration);
7977   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7978     PrevDecl = 0;
7979 
7980   if (PrevDecl) {
7981     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
7982       // We already have an alias with the same name that points to the same
7983       // namespace, so don't create a new one.
7984       // FIXME: At some point, we'll want to create the (redundant)
7985       // declaration to maintain better source information.
7986       if (!R.isAmbiguous() && !R.empty() &&
7987           AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
7988         return 0;
7989     }
7990 
7991     unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7992       diag::err_redefinition_different_kind;
7993     Diag(AliasLoc, DiagID) << Alias;
7994     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7995     return 0;
7996   }
7997 
7998   if (R.isAmbiguous())
7999     return 0;
8000 
8001   if (R.empty()) {
8002     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8003       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8004       return 0;
8005     }
8006   }
8007 
8008   NamespaceAliasDecl *AliasDecl =
8009     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8010                                Alias, SS.getWithLocInContext(Context),
8011                                IdentLoc, R.getFoundDecl());
8012 
8013   PushOnScopeChains(AliasDecl, S);
8014   return AliasDecl;
8015 }
8016 
8017 Sema::ImplicitExceptionSpecification
8018 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8019                                                CXXMethodDecl *MD) {
8020   CXXRecordDecl *ClassDecl = MD->getParent();
8021 
8022   // C++ [except.spec]p14:
8023   //   An implicitly declared special member function (Clause 12) shall have an
8024   //   exception-specification. [...]
8025   ImplicitExceptionSpecification ExceptSpec(*this);
8026   if (ClassDecl->isInvalidDecl())
8027     return ExceptSpec;
8028 
8029   // Direct base-class constructors.
8030   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8031                                        BEnd = ClassDecl->bases_end();
8032        B != BEnd; ++B) {
8033     if (B->isVirtual()) // Handled below.
8034       continue;
8035 
8036     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8037       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8038       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8039       // If this is a deleted function, add it anyway. This might be conformant
8040       // with the standard. This might not. I'm not sure. It might not matter.
8041       if (Constructor)
8042         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8043     }
8044   }
8045 
8046   // Virtual base-class constructors.
8047   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8048                                        BEnd = ClassDecl->vbases_end();
8049        B != BEnd; ++B) {
8050     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8051       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8052       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8053       // If this is a deleted function, add it anyway. This might be conformant
8054       // with the standard. This might not. I'm not sure. It might not matter.
8055       if (Constructor)
8056         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8057     }
8058   }
8059 
8060   // Field constructors.
8061   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8062                                FEnd = ClassDecl->field_end();
8063        F != FEnd; ++F) {
8064     if (F->hasInClassInitializer()) {
8065       if (Expr *E = F->getInClassInitializer())
8066         ExceptSpec.CalledExpr(E);
8067       else if (!F->isInvalidDecl())
8068         // DR1351:
8069         //   If the brace-or-equal-initializer of a non-static data member
8070         //   invokes a defaulted default constructor of its class or of an
8071         //   enclosing class in a potentially evaluated subexpression, the
8072         //   program is ill-formed.
8073         //
8074         // This resolution is unworkable: the exception specification of the
8075         // default constructor can be needed in an unevaluated context, in
8076         // particular, in the operand of a noexcept-expression, and we can be
8077         // unable to compute an exception specification for an enclosed class.
8078         //
8079         // We do not allow an in-class initializer to require the evaluation
8080         // of the exception specification for any in-class initializer whose
8081         // definition is not lexically complete.
8082         Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
8083     } else if (const RecordType *RecordTy
8084               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8085       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8086       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8087       // If this is a deleted function, add it anyway. This might be conformant
8088       // with the standard. This might not. I'm not sure. It might not matter.
8089       // In particular, the problem is that this function never gets called. It
8090       // might just be ill-formed because this function attempts to refer to
8091       // a deleted function here.
8092       if (Constructor)
8093         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8094     }
8095   }
8096 
8097   return ExceptSpec;
8098 }
8099 
8100 Sema::ImplicitExceptionSpecification
8101 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8102   CXXRecordDecl *ClassDecl = CD->getParent();
8103 
8104   // C++ [except.spec]p14:
8105   //   An inheriting constructor [...] shall have an exception-specification. [...]
8106   ImplicitExceptionSpecification ExceptSpec(*this);
8107   if (ClassDecl->isInvalidDecl())
8108     return ExceptSpec;
8109 
8110   // Inherited constructor.
8111   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8112   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8113   // FIXME: Copying or moving the parameters could add extra exceptions to the
8114   // set, as could the default arguments for the inherited constructor. This
8115   // will be addressed when we implement the resolution of core issue 1351.
8116   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8117 
8118   // Direct base-class constructors.
8119   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8120                                        BEnd = ClassDecl->bases_end();
8121        B != BEnd; ++B) {
8122     if (B->isVirtual()) // Handled below.
8123       continue;
8124 
8125     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8126       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8127       if (BaseClassDecl == InheritedDecl)
8128         continue;
8129       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8130       if (Constructor)
8131         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8132     }
8133   }
8134 
8135   // Virtual base-class constructors.
8136   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8137                                        BEnd = ClassDecl->vbases_end();
8138        B != BEnd; ++B) {
8139     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8140       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8141       if (BaseClassDecl == InheritedDecl)
8142         continue;
8143       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8144       if (Constructor)
8145         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8146     }
8147   }
8148 
8149   // Field constructors.
8150   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8151                                FEnd = ClassDecl->field_end();
8152        F != FEnd; ++F) {
8153     if (F->hasInClassInitializer()) {
8154       if (Expr *E = F->getInClassInitializer())
8155         ExceptSpec.CalledExpr(E);
8156       else if (!F->isInvalidDecl())
8157         Diag(CD->getLocation(),
8158              diag::err_in_class_initializer_references_def_ctor) << CD;
8159     } else if (const RecordType *RecordTy
8160               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8161       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8162       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8163       if (Constructor)
8164         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8165     }
8166   }
8167 
8168   return ExceptSpec;
8169 }
8170 
8171 namespace {
8172 /// RAII object to register a special member as being currently declared.
8173 struct DeclaringSpecialMember {
8174   Sema &S;
8175   Sema::SpecialMemberDecl D;
8176   bool WasAlreadyBeingDeclared;
8177 
8178   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8179     : S(S), D(RD, CSM) {
8180     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8181     if (WasAlreadyBeingDeclared)
8182       // This almost never happens, but if it does, ensure that our cache
8183       // doesn't contain a stale result.
8184       S.SpecialMemberCache.clear();
8185 
8186     // FIXME: Register a note to be produced if we encounter an error while
8187     // declaring the special member.
8188   }
8189   ~DeclaringSpecialMember() {
8190     if (!WasAlreadyBeingDeclared)
8191       S.SpecialMembersBeingDeclared.erase(D);
8192   }
8193 
8194   /// \brief Are we already trying to declare this special member?
8195   bool isAlreadyBeingDeclared() const {
8196     return WasAlreadyBeingDeclared;
8197   }
8198 };
8199 }
8200 
8201 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8202                                                      CXXRecordDecl *ClassDecl) {
8203   // C++ [class.ctor]p5:
8204   //   A default constructor for a class X is a constructor of class X
8205   //   that can be called without an argument. If there is no
8206   //   user-declared constructor for class X, a default constructor is
8207   //   implicitly declared. An implicitly-declared default constructor
8208   //   is an inline public member of its class.
8209   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8210          "Should not build implicit default constructor!");
8211 
8212   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8213   if (DSM.isAlreadyBeingDeclared())
8214     return 0;
8215 
8216   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8217                                                      CXXDefaultConstructor,
8218                                                      false);
8219 
8220   // Create the actual constructor declaration.
8221   CanQualType ClassType
8222     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8223   SourceLocation ClassLoc = ClassDecl->getLocation();
8224   DeclarationName Name
8225     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8226   DeclarationNameInfo NameInfo(Name, ClassLoc);
8227   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8228       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
8229       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8230       Constexpr);
8231   DefaultCon->setAccess(AS_public);
8232   DefaultCon->setDefaulted();
8233   DefaultCon->setImplicit();
8234 
8235   // Build an exception specification pointing back at this constructor.
8236   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8237   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8238 
8239   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8240   // constructors is easy to compute.
8241   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8242 
8243   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8244     SetDeclDeleted(DefaultCon, ClassLoc);
8245 
8246   // Note that we have declared this constructor.
8247   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8248 
8249   if (Scope *S = getScopeForContext(ClassDecl))
8250     PushOnScopeChains(DefaultCon, S, false);
8251   ClassDecl->addDecl(DefaultCon);
8252 
8253   return DefaultCon;
8254 }
8255 
8256 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8257                                             CXXConstructorDecl *Constructor) {
8258   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8259           !Constructor->doesThisDeclarationHaveABody() &&
8260           !Constructor->isDeleted()) &&
8261     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8262 
8263   CXXRecordDecl *ClassDecl = Constructor->getParent();
8264   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8265 
8266   SynthesizedFunctionScope Scope(*this, Constructor);
8267   DiagnosticErrorTrap Trap(Diags);
8268   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8269       Trap.hasErrorOccurred()) {
8270     Diag(CurrentLocation, diag::note_member_synthesized_at)
8271       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8272     Constructor->setInvalidDecl();
8273     return;
8274   }
8275 
8276   SourceLocation Loc = Constructor->getLocation();
8277   Constructor->setBody(new (Context) CompoundStmt(Loc));
8278 
8279   Constructor->markUsed(Context);
8280   MarkVTableUsed(CurrentLocation, ClassDecl);
8281 
8282   if (ASTMutationListener *L = getASTMutationListener()) {
8283     L->CompletedImplicitDefinition(Constructor);
8284   }
8285 
8286   DiagnoseUninitializedFields(*this, Constructor);
8287 }
8288 
8289 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8290   // Perform any delayed checks on exception specifications.
8291   CheckDelayedMemberExceptionSpecs();
8292 }
8293 
8294 namespace {
8295 /// Information on inheriting constructors to declare.
8296 class InheritingConstructorInfo {
8297 public:
8298   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8299       : SemaRef(SemaRef), Derived(Derived) {
8300     // Mark the constructors that we already have in the derived class.
8301     //
8302     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8303     //   unless there is a user-declared constructor with the same signature in
8304     //   the class where the using-declaration appears.
8305     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8306   }
8307 
8308   void inheritAll(CXXRecordDecl *RD) {
8309     visitAll(RD, &InheritingConstructorInfo::inherit);
8310   }
8311 
8312 private:
8313   /// Information about an inheriting constructor.
8314   struct InheritingConstructor {
8315     InheritingConstructor()
8316       : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8317 
8318     /// If \c true, a constructor with this signature is already declared
8319     /// in the derived class.
8320     bool DeclaredInDerived;
8321 
8322     /// The constructor which is inherited.
8323     const CXXConstructorDecl *BaseCtor;
8324 
8325     /// The derived constructor we declared.
8326     CXXConstructorDecl *DerivedCtor;
8327   };
8328 
8329   /// Inheriting constructors with a given canonical type. There can be at
8330   /// most one such non-template constructor, and any number of templated
8331   /// constructors.
8332   struct InheritingConstructorsForType {
8333     InheritingConstructor NonTemplate;
8334     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8335         Templates;
8336 
8337     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8338       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8339         TemplateParameterList *ParamList = FTD->getTemplateParameters();
8340         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8341           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8342                                                false, S.TPL_TemplateMatch))
8343             return Templates[I].second;
8344         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8345         return Templates.back().second;
8346       }
8347 
8348       return NonTemplate;
8349     }
8350   };
8351 
8352   /// Get or create the inheriting constructor record for a constructor.
8353   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8354                                   QualType CtorType) {
8355     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8356         .getEntry(SemaRef, Ctor);
8357   }
8358 
8359   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8360 
8361   /// Process all constructors for a class.
8362   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8363     for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8364                                       CtorE = RD->ctor_end();
8365          CtorIt != CtorE; ++CtorIt)
8366       (this->*Callback)(*CtorIt);
8367     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8368              I(RD->decls_begin()), E(RD->decls_end());
8369          I != E; ++I) {
8370       const FunctionDecl *FD = (*I)->getTemplatedDecl();
8371       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8372         (this->*Callback)(CD);
8373     }
8374   }
8375 
8376   /// Note that a constructor (or constructor template) was declared in Derived.
8377   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8378     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8379   }
8380 
8381   /// Inherit a single constructor.
8382   void inherit(const CXXConstructorDecl *Ctor) {
8383     const FunctionProtoType *CtorType =
8384         Ctor->getType()->castAs<FunctionProtoType>();
8385     ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
8386     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8387 
8388     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8389 
8390     // Core issue (no number yet): the ellipsis is always discarded.
8391     if (EPI.Variadic) {
8392       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8393       SemaRef.Diag(Ctor->getLocation(),
8394                    diag::note_using_decl_constructor_ellipsis);
8395       EPI.Variadic = false;
8396     }
8397 
8398     // Declare a constructor for each number of parameters.
8399     //
8400     // C++11 [class.inhctor]p1:
8401     //   The candidate set of inherited constructors from the class X named in
8402     //   the using-declaration consists of [... modulo defects ...] for each
8403     //   constructor or constructor template of X, the set of constructors or
8404     //   constructor templates that results from omitting any ellipsis parameter
8405     //   specification and successively omitting parameters with a default
8406     //   argument from the end of the parameter-type-list
8407     unsigned MinParams = minParamsToInherit(Ctor);
8408     unsigned Params = Ctor->getNumParams();
8409     if (Params >= MinParams) {
8410       do
8411         declareCtor(UsingLoc, Ctor,
8412                     SemaRef.Context.getFunctionType(
8413                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
8414       while (Params > MinParams &&
8415              Ctor->getParamDecl(--Params)->hasDefaultArg());
8416     }
8417   }
8418 
8419   /// Find the using-declaration which specified that we should inherit the
8420   /// constructors of \p Base.
8421   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8422     // No fancy lookup required; just look for the base constructor name
8423     // directly within the derived class.
8424     ASTContext &Context = SemaRef.Context;
8425     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8426         Context.getCanonicalType(Context.getRecordType(Base)));
8427     DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8428     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8429   }
8430 
8431   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8432     // C++11 [class.inhctor]p3:
8433     //   [F]or each constructor template in the candidate set of inherited
8434     //   constructors, a constructor template is implicitly declared
8435     if (Ctor->getDescribedFunctionTemplate())
8436       return 0;
8437 
8438     //   For each non-template constructor in the candidate set of inherited
8439     //   constructors other than a constructor having no parameters or a
8440     //   copy/move constructor having a single parameter, a constructor is
8441     //   implicitly declared [...]
8442     if (Ctor->getNumParams() == 0)
8443       return 1;
8444     if (Ctor->isCopyOrMoveConstructor())
8445       return 2;
8446 
8447     // Per discussion on core reflector, never inherit a constructor which
8448     // would become a default, copy, or move constructor of Derived either.
8449     const ParmVarDecl *PD = Ctor->getParamDecl(0);
8450     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8451     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8452   }
8453 
8454   /// Declare a single inheriting constructor, inheriting the specified
8455   /// constructor, with the given type.
8456   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8457                    QualType DerivedType) {
8458     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8459 
8460     // C++11 [class.inhctor]p3:
8461     //   ... a constructor is implicitly declared with the same constructor
8462     //   characteristics unless there is a user-declared constructor with
8463     //   the same signature in the class where the using-declaration appears
8464     if (Entry.DeclaredInDerived)
8465       return;
8466 
8467     // C++11 [class.inhctor]p7:
8468     //   If two using-declarations declare inheriting constructors with the
8469     //   same signature, the program is ill-formed
8470     if (Entry.DerivedCtor) {
8471       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8472         // Only diagnose this once per constructor.
8473         if (Entry.DerivedCtor->isInvalidDecl())
8474           return;
8475         Entry.DerivedCtor->setInvalidDecl();
8476 
8477         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8478         SemaRef.Diag(BaseCtor->getLocation(),
8479                      diag::note_using_decl_constructor_conflict_current_ctor);
8480         SemaRef.Diag(Entry.BaseCtor->getLocation(),
8481                      diag::note_using_decl_constructor_conflict_previous_ctor);
8482         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8483                      diag::note_using_decl_constructor_conflict_previous_using);
8484       } else {
8485         // Core issue (no number): if the same inheriting constructor is
8486         // produced by multiple base class constructors from the same base
8487         // class, the inheriting constructor is defined as deleted.
8488         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8489       }
8490 
8491       return;
8492     }
8493 
8494     ASTContext &Context = SemaRef.Context;
8495     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8496         Context.getCanonicalType(Context.getRecordType(Derived)));
8497     DeclarationNameInfo NameInfo(Name, UsingLoc);
8498 
8499     TemplateParameterList *TemplateParams = 0;
8500     if (const FunctionTemplateDecl *FTD =
8501             BaseCtor->getDescribedFunctionTemplate()) {
8502       TemplateParams = FTD->getTemplateParameters();
8503       // We're reusing template parameters from a different DeclContext. This
8504       // is questionable at best, but works out because the template depth in
8505       // both places is guaranteed to be 0.
8506       // FIXME: Rebuild the template parameters in the new context, and
8507       // transform the function type to refer to them.
8508     }
8509 
8510     // Build type source info pointing at the using-declaration. This is
8511     // required by template instantiation.
8512     TypeSourceInfo *TInfo =
8513         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8514     FunctionProtoTypeLoc ProtoLoc =
8515         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8516 
8517     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8518         Context, Derived, UsingLoc, NameInfo, DerivedType,
8519         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8520         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8521 
8522     // Build an unevaluated exception specification for this constructor.
8523     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8524     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8525     EPI.ExceptionSpecType = EST_Unevaluated;
8526     EPI.ExceptionSpecDecl = DerivedCtor;
8527     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
8528                                                  FPT->getParamTypes(), EPI));
8529 
8530     // Build the parameter declarations.
8531     SmallVector<ParmVarDecl *, 16> ParamDecls;
8532     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
8533       TypeSourceInfo *TInfo =
8534           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
8535       ParmVarDecl *PD = ParmVarDecl::Create(
8536           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8537           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/0);
8538       PD->setScopeInfo(0, I);
8539       PD->setImplicit();
8540       ParamDecls.push_back(PD);
8541       ProtoLoc.setParam(I, PD);
8542     }
8543 
8544     // Set up the new constructor.
8545     DerivedCtor->setAccess(BaseCtor->getAccess());
8546     DerivedCtor->setParams(ParamDecls);
8547     DerivedCtor->setInheritedConstructor(BaseCtor);
8548     if (BaseCtor->isDeleted())
8549       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8550 
8551     // If this is a constructor template, build the template declaration.
8552     if (TemplateParams) {
8553       FunctionTemplateDecl *DerivedTemplate =
8554           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8555                                        TemplateParams, DerivedCtor);
8556       DerivedTemplate->setAccess(BaseCtor->getAccess());
8557       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8558       Derived->addDecl(DerivedTemplate);
8559     } else {
8560       Derived->addDecl(DerivedCtor);
8561     }
8562 
8563     Entry.BaseCtor = BaseCtor;
8564     Entry.DerivedCtor = DerivedCtor;
8565   }
8566 
8567   Sema &SemaRef;
8568   CXXRecordDecl *Derived;
8569   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8570   MapType Map;
8571 };
8572 }
8573 
8574 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8575   // Defer declaring the inheriting constructors until the class is
8576   // instantiated.
8577   if (ClassDecl->isDependentContext())
8578     return;
8579 
8580   // Find base classes from which we might inherit constructors.
8581   SmallVector<CXXRecordDecl*, 4> InheritedBases;
8582   for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8583                                           BaseE = ClassDecl->bases_end();
8584        BaseIt != BaseE; ++BaseIt)
8585     if (BaseIt->getInheritConstructors())
8586       InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
8587 
8588   // Go no further if we're not inheriting any constructors.
8589   if (InheritedBases.empty())
8590     return;
8591 
8592   // Declare the inherited constructors.
8593   InheritingConstructorInfo ICI(*this, ClassDecl);
8594   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8595     ICI.inheritAll(InheritedBases[I]);
8596 }
8597 
8598 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8599                                        CXXConstructorDecl *Constructor) {
8600   CXXRecordDecl *ClassDecl = Constructor->getParent();
8601   assert(Constructor->getInheritedConstructor() &&
8602          !Constructor->doesThisDeclarationHaveABody() &&
8603          !Constructor->isDeleted());
8604 
8605   SynthesizedFunctionScope Scope(*this, Constructor);
8606   DiagnosticErrorTrap Trap(Diags);
8607   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8608       Trap.hasErrorOccurred()) {
8609     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8610       << Context.getTagDeclType(ClassDecl);
8611     Constructor->setInvalidDecl();
8612     return;
8613   }
8614 
8615   SourceLocation Loc = Constructor->getLocation();
8616   Constructor->setBody(new (Context) CompoundStmt(Loc));
8617 
8618   Constructor->markUsed(Context);
8619   MarkVTableUsed(CurrentLocation, ClassDecl);
8620 
8621   if (ASTMutationListener *L = getASTMutationListener()) {
8622     L->CompletedImplicitDefinition(Constructor);
8623   }
8624 }
8625 
8626 
8627 Sema::ImplicitExceptionSpecification
8628 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8629   CXXRecordDecl *ClassDecl = MD->getParent();
8630 
8631   // C++ [except.spec]p14:
8632   //   An implicitly declared special member function (Clause 12) shall have
8633   //   an exception-specification.
8634   ImplicitExceptionSpecification ExceptSpec(*this);
8635   if (ClassDecl->isInvalidDecl())
8636     return ExceptSpec;
8637 
8638   // Direct base-class destructors.
8639   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8640                                        BEnd = ClassDecl->bases_end();
8641        B != BEnd; ++B) {
8642     if (B->isVirtual()) // Handled below.
8643       continue;
8644 
8645     if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8646       ExceptSpec.CalledDecl(B->getLocStart(),
8647                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8648   }
8649 
8650   // Virtual base-class destructors.
8651   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8652                                        BEnd = ClassDecl->vbases_end();
8653        B != BEnd; ++B) {
8654     if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8655       ExceptSpec.CalledDecl(B->getLocStart(),
8656                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8657   }
8658 
8659   // Field destructors.
8660   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8661                                FEnd = ClassDecl->field_end();
8662        F != FEnd; ++F) {
8663     if (const RecordType *RecordTy
8664         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8665       ExceptSpec.CalledDecl(F->getLocation(),
8666                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8667   }
8668 
8669   return ExceptSpec;
8670 }
8671 
8672 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8673   // C++ [class.dtor]p2:
8674   //   If a class has no user-declared destructor, a destructor is
8675   //   declared implicitly. An implicitly-declared destructor is an
8676   //   inline public member of its class.
8677   assert(ClassDecl->needsImplicitDestructor());
8678 
8679   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8680   if (DSM.isAlreadyBeingDeclared())
8681     return 0;
8682 
8683   // Create the actual destructor declaration.
8684   CanQualType ClassType
8685     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8686   SourceLocation ClassLoc = ClassDecl->getLocation();
8687   DeclarationName Name
8688     = Context.DeclarationNames.getCXXDestructorName(ClassType);
8689   DeclarationNameInfo NameInfo(Name, ClassLoc);
8690   CXXDestructorDecl *Destructor
8691       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8692                                   QualType(), 0, /*isInline=*/true,
8693                                   /*isImplicitlyDeclared=*/true);
8694   Destructor->setAccess(AS_public);
8695   Destructor->setDefaulted();
8696   Destructor->setImplicit();
8697 
8698   // Build an exception specification pointing back at this destructor.
8699   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
8700   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8701 
8702   AddOverriddenMethods(ClassDecl, Destructor);
8703 
8704   // We don't need to use SpecialMemberIsTrivial here; triviality for
8705   // destructors is easy to compute.
8706   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8707 
8708   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8709     SetDeclDeleted(Destructor, ClassLoc);
8710 
8711   // Note that we have declared this destructor.
8712   ++ASTContext::NumImplicitDestructorsDeclared;
8713 
8714   // Introduce this destructor into its scope.
8715   if (Scope *S = getScopeForContext(ClassDecl))
8716     PushOnScopeChains(Destructor, S, false);
8717   ClassDecl->addDecl(Destructor);
8718 
8719   return Destructor;
8720 }
8721 
8722 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
8723                                     CXXDestructorDecl *Destructor) {
8724   assert((Destructor->isDefaulted() &&
8725           !Destructor->doesThisDeclarationHaveABody() &&
8726           !Destructor->isDeleted()) &&
8727          "DefineImplicitDestructor - call it for implicit default dtor");
8728   CXXRecordDecl *ClassDecl = Destructor->getParent();
8729   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
8730 
8731   if (Destructor->isInvalidDecl())
8732     return;
8733 
8734   SynthesizedFunctionScope Scope(*this, Destructor);
8735 
8736   DiagnosticErrorTrap Trap(Diags);
8737   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8738                                          Destructor->getParent());
8739 
8740   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
8741     Diag(CurrentLocation, diag::note_member_synthesized_at)
8742       << CXXDestructor << Context.getTagDeclType(ClassDecl);
8743 
8744     Destructor->setInvalidDecl();
8745     return;
8746   }
8747 
8748   SourceLocation Loc = Destructor->getLocation();
8749   Destructor->setBody(new (Context) CompoundStmt(Loc));
8750   Destructor->markUsed(Context);
8751   MarkVTableUsed(CurrentLocation, ClassDecl);
8752 
8753   if (ASTMutationListener *L = getASTMutationListener()) {
8754     L->CompletedImplicitDefinition(Destructor);
8755   }
8756 }
8757 
8758 /// \brief Perform any semantic analysis which needs to be delayed until all
8759 /// pending class member declarations have been parsed.
8760 void Sema::ActOnFinishCXXMemberDecls() {
8761   // If the context is an invalid C++ class, just suppress these checks.
8762   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8763     if (Record->isInvalidDecl()) {
8764       DelayedDefaultedMemberExceptionSpecs.clear();
8765       DelayedDestructorExceptionSpecChecks.clear();
8766       return;
8767     }
8768   }
8769 }
8770 
8771 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8772                                          CXXDestructorDecl *Destructor) {
8773   assert(getLangOpts().CPlusPlus11 &&
8774          "adjusting dtor exception specs was introduced in c++11");
8775 
8776   // C++11 [class.dtor]p3:
8777   //   A declaration of a destructor that does not have an exception-
8778   //   specification is implicitly considered to have the same exception-
8779   //   specification as an implicit declaration.
8780   const FunctionProtoType *DtorType = Destructor->getType()->
8781                                         getAs<FunctionProtoType>();
8782   if (DtorType->hasExceptionSpec())
8783     return;
8784 
8785   // Replace the destructor's type, building off the existing one. Fortunately,
8786   // the only thing of interest in the destructor type is its extended info.
8787   // The return and arguments are fixed.
8788   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8789   EPI.ExceptionSpecType = EST_Unevaluated;
8790   EPI.ExceptionSpecDecl = Destructor;
8791   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8792 
8793   // FIXME: If the destructor has a body that could throw, and the newly created
8794   // spec doesn't allow exceptions, we should emit a warning, because this
8795   // change in behavior can break conforming C++03 programs at runtime.
8796   // However, we don't have a body or an exception specification yet, so it
8797   // needs to be done somewhere else.
8798 }
8799 
8800 namespace {
8801 /// \brief An abstract base class for all helper classes used in building the
8802 //  copy/move operators. These classes serve as factory functions and help us
8803 //  avoid using the same Expr* in the AST twice.
8804 class ExprBuilder {
8805   ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8806   ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8807 
8808 protected:
8809   static Expr *assertNotNull(Expr *E) {
8810     assert(E && "Expression construction must not fail.");
8811     return E;
8812   }
8813 
8814 public:
8815   ExprBuilder() {}
8816   virtual ~ExprBuilder() {}
8817 
8818   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8819 };
8820 
8821 class RefBuilder: public ExprBuilder {
8822   VarDecl *Var;
8823   QualType VarType;
8824 
8825 public:
8826   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8827     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8828   }
8829 
8830   RefBuilder(VarDecl *Var, QualType VarType)
8831       : Var(Var), VarType(VarType) {}
8832 };
8833 
8834 class ThisBuilder: public ExprBuilder {
8835 public:
8836   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8837     return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8838   }
8839 };
8840 
8841 class CastBuilder: public ExprBuilder {
8842   const ExprBuilder &Builder;
8843   QualType Type;
8844   ExprValueKind Kind;
8845   const CXXCastPath &Path;
8846 
8847 public:
8848   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8849     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8850                                              CK_UncheckedDerivedToBase, Kind,
8851                                              &Path).take());
8852   }
8853 
8854   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8855               const CXXCastPath &Path)
8856       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8857 };
8858 
8859 class DerefBuilder: public ExprBuilder {
8860   const ExprBuilder &Builder;
8861 
8862 public:
8863   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8864     return assertNotNull(
8865         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8866   }
8867 
8868   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8869 };
8870 
8871 class MemberBuilder: public ExprBuilder {
8872   const ExprBuilder &Builder;
8873   QualType Type;
8874   CXXScopeSpec SS;
8875   bool IsArrow;
8876   LookupResult &MemberLookup;
8877 
8878 public:
8879   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8880     return assertNotNull(S.BuildMemberReferenceExpr(
8881         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8882         MemberLookup, 0).take());
8883   }
8884 
8885   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8886                 LookupResult &MemberLookup)
8887       : Builder(Builder), Type(Type), IsArrow(IsArrow),
8888         MemberLookup(MemberLookup) {}
8889 };
8890 
8891 class MoveCastBuilder: public ExprBuilder {
8892   const ExprBuilder &Builder;
8893 
8894 public:
8895   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8896     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8897   }
8898 
8899   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8900 };
8901 
8902 class LvalueConvBuilder: public ExprBuilder {
8903   const ExprBuilder &Builder;
8904 
8905 public:
8906   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8907     return assertNotNull(
8908         S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8909   }
8910 
8911   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8912 };
8913 
8914 class SubscriptBuilder: public ExprBuilder {
8915   const ExprBuilder &Base;
8916   const ExprBuilder &Index;
8917 
8918 public:
8919   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8920     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8921         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8922   }
8923 
8924   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8925       : Base(Base), Index(Index) {}
8926 };
8927 
8928 } // end anonymous namespace
8929 
8930 /// When generating a defaulted copy or move assignment operator, if a field
8931 /// should be copied with __builtin_memcpy rather than via explicit assignments,
8932 /// do so. This optimization only applies for arrays of scalars, and for arrays
8933 /// of class type where the selected copy/move-assignment operator is trivial.
8934 static StmtResult
8935 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8936                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
8937   // Compute the size of the memory buffer to be copied.
8938   QualType SizeType = S.Context.getSizeType();
8939   llvm::APInt Size(S.Context.getTypeSize(SizeType),
8940                    S.Context.getTypeSizeInChars(T).getQuantity());
8941 
8942   // Take the address of the field references for "from" and "to". We
8943   // directly construct UnaryOperators here because semantic analysis
8944   // does not permit us to take the address of an xvalue.
8945   Expr *From = FromB.build(S, Loc);
8946   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8947                          S.Context.getPointerType(From->getType()),
8948                          VK_RValue, OK_Ordinary, Loc);
8949   Expr *To = ToB.build(S, Loc);
8950   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8951                        S.Context.getPointerType(To->getType()),
8952                        VK_RValue, OK_Ordinary, Loc);
8953 
8954   const Type *E = T->getBaseElementTypeUnsafe();
8955   bool NeedsCollectableMemCpy =
8956     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8957 
8958   // Create a reference to the __builtin_objc_memmove_collectable function
8959   StringRef MemCpyName = NeedsCollectableMemCpy ?
8960     "__builtin_objc_memmove_collectable" :
8961     "__builtin_memcpy";
8962   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8963                  Sema::LookupOrdinaryName);
8964   S.LookupName(R, S.TUScope, true);
8965 
8966   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8967   if (!MemCpy)
8968     // Something went horribly wrong earlier, and we will have complained
8969     // about it.
8970     return StmtError();
8971 
8972   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8973                                             VK_RValue, Loc, 0);
8974   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8975 
8976   Expr *CallArgs[] = {
8977     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8978   };
8979   ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8980                                     Loc, CallArgs, Loc);
8981 
8982   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8983   return S.Owned(Call.takeAs<Stmt>());
8984 }
8985 
8986 /// \brief Builds a statement that copies/moves the given entity from \p From to
8987 /// \c To.
8988 ///
8989 /// This routine is used to copy/move the members of a class with an
8990 /// implicitly-declared copy/move assignment operator. When the entities being
8991 /// copied are arrays, this routine builds for loops to copy them.
8992 ///
8993 /// \param S The Sema object used for type-checking.
8994 ///
8995 /// \param Loc The location where the implicit copy/move is being generated.
8996 ///
8997 /// \param T The type of the expressions being copied/moved. Both expressions
8998 /// must have this type.
8999 ///
9000 /// \param To The expression we are copying/moving to.
9001 ///
9002 /// \param From The expression we are copying/moving from.
9003 ///
9004 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9005 /// Otherwise, it's a non-static member subobject.
9006 ///
9007 /// \param Copying Whether we're copying or moving.
9008 ///
9009 /// \param Depth Internal parameter recording the depth of the recursion.
9010 ///
9011 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9012 /// if a memcpy should be used instead.
9013 static StmtResult
9014 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9015                                  const ExprBuilder &To, const ExprBuilder &From,
9016                                  bool CopyingBaseSubobject, bool Copying,
9017                                  unsigned Depth = 0) {
9018   // C++11 [class.copy]p28:
9019   //   Each subobject is assigned in the manner appropriate to its type:
9020   //
9021   //     - if the subobject is of class type, as if by a call to operator= with
9022   //       the subobject as the object expression and the corresponding
9023   //       subobject of x as a single function argument (as if by explicit
9024   //       qualification; that is, ignoring any possible virtual overriding
9025   //       functions in more derived classes);
9026   //
9027   // C++03 [class.copy]p13:
9028   //     - if the subobject is of class type, the copy assignment operator for
9029   //       the class is used (as if by explicit qualification; that is,
9030   //       ignoring any possible virtual overriding functions in more derived
9031   //       classes);
9032   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9033     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9034 
9035     // Look for operator=.
9036     DeclarationName Name
9037       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9038     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9039     S.LookupQualifiedName(OpLookup, ClassDecl, false);
9040 
9041     // Prior to C++11, filter out any result that isn't a copy/move-assignment
9042     // operator.
9043     if (!S.getLangOpts().CPlusPlus11) {
9044       LookupResult::Filter F = OpLookup.makeFilter();
9045       while (F.hasNext()) {
9046         NamedDecl *D = F.next();
9047         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9048           if (Method->isCopyAssignmentOperator() ||
9049               (!Copying && Method->isMoveAssignmentOperator()))
9050             continue;
9051 
9052         F.erase();
9053       }
9054       F.done();
9055     }
9056 
9057     // Suppress the protected check (C++ [class.protected]) for each of the
9058     // assignment operators we found. This strange dance is required when
9059     // we're assigning via a base classes's copy-assignment operator. To
9060     // ensure that we're getting the right base class subobject (without
9061     // ambiguities), we need to cast "this" to that subobject type; to
9062     // ensure that we don't go through the virtual call mechanism, we need
9063     // to qualify the operator= name with the base class (see below). However,
9064     // this means that if the base class has a protected copy assignment
9065     // operator, the protected member access check will fail. So, we
9066     // rewrite "protected" access to "public" access in this case, since we
9067     // know by construction that we're calling from a derived class.
9068     if (CopyingBaseSubobject) {
9069       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9070            L != LEnd; ++L) {
9071         if (L.getAccess() == AS_protected)
9072           L.setAccess(AS_public);
9073       }
9074     }
9075 
9076     // Create the nested-name-specifier that will be used to qualify the
9077     // reference to operator=; this is required to suppress the virtual
9078     // call mechanism.
9079     CXXScopeSpec SS;
9080     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9081     SS.MakeTrivial(S.Context,
9082                    NestedNameSpecifier::Create(S.Context, 0, false,
9083                                                CanonicalT),
9084                    Loc);
9085 
9086     // Create the reference to operator=.
9087     ExprResult OpEqualRef
9088       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9089                                    SS, /*TemplateKWLoc=*/SourceLocation(),
9090                                    /*FirstQualifierInScope=*/0,
9091                                    OpLookup,
9092                                    /*TemplateArgs=*/0,
9093                                    /*SuppressQualifierCheck=*/true);
9094     if (OpEqualRef.isInvalid())
9095       return StmtError();
9096 
9097     // Build the call to the assignment operator.
9098 
9099     Expr *FromInst = From.build(S, Loc);
9100     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
9101                                                   OpEqualRef.takeAs<Expr>(),
9102                                                   Loc, FromInst, Loc);
9103     if (Call.isInvalid())
9104       return StmtError();
9105 
9106     // If we built a call to a trivial 'operator=' while copying an array,
9107     // bail out. We'll replace the whole shebang with a memcpy.
9108     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9109     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9110       return StmtResult((Stmt*)0);
9111 
9112     // Convert to an expression-statement, and clean up any produced
9113     // temporaries.
9114     return S.ActOnExprStmt(Call);
9115   }
9116 
9117   //     - if the subobject is of scalar type, the built-in assignment
9118   //       operator is used.
9119   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9120   if (!ArrayTy) {
9121     ExprResult Assignment = S.CreateBuiltinBinOp(
9122         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9123     if (Assignment.isInvalid())
9124       return StmtError();
9125     return S.ActOnExprStmt(Assignment);
9126   }
9127 
9128   //     - if the subobject is an array, each element is assigned, in the
9129   //       manner appropriate to the element type;
9130 
9131   // Construct a loop over the array bounds, e.g.,
9132   //
9133   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9134   //
9135   // that will copy each of the array elements.
9136   QualType SizeType = S.Context.getSizeType();
9137 
9138   // Create the iteration variable.
9139   IdentifierInfo *IterationVarName = 0;
9140   {
9141     SmallString<8> Str;
9142     llvm::raw_svector_ostream OS(Str);
9143     OS << "__i" << Depth;
9144     IterationVarName = &S.Context.Idents.get(OS.str());
9145   }
9146   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9147                                           IterationVarName, SizeType,
9148                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9149                                           SC_None);
9150 
9151   // Initialize the iteration variable to zero.
9152   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9153   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9154 
9155   // Creates a reference to the iteration variable.
9156   RefBuilder IterationVarRef(IterationVar, SizeType);
9157   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9158 
9159   // Create the DeclStmt that holds the iteration variable.
9160   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9161 
9162   // Subscript the "from" and "to" expressions with the iteration variable.
9163   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9164   MoveCastBuilder FromIndexMove(FromIndexCopy);
9165   const ExprBuilder *FromIndex;
9166   if (Copying)
9167     FromIndex = &FromIndexCopy;
9168   else
9169     FromIndex = &FromIndexMove;
9170 
9171   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9172 
9173   // Build the copy/move for an individual element of the array.
9174   StmtResult Copy =
9175     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9176                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9177                                      Copying, Depth + 1);
9178   // Bail out if copying fails or if we determined that we should use memcpy.
9179   if (Copy.isInvalid() || !Copy.get())
9180     return Copy;
9181 
9182   // Create the comparison against the array bound.
9183   llvm::APInt Upper
9184     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9185   Expr *Comparison
9186     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9187                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9188                                      BO_NE, S.Context.BoolTy,
9189                                      VK_RValue, OK_Ordinary, Loc, false);
9190 
9191   // Create the pre-increment of the iteration variable.
9192   Expr *Increment
9193     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9194                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9195 
9196   // Construct the loop that copies all elements of this array.
9197   return S.ActOnForStmt(Loc, Loc, InitStmt,
9198                         S.MakeFullExpr(Comparison),
9199                         0, S.MakeFullDiscardedValueExpr(Increment),
9200                         Loc, Copy.take());
9201 }
9202 
9203 static StmtResult
9204 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9205                       const ExprBuilder &To, const ExprBuilder &From,
9206                       bool CopyingBaseSubobject, bool Copying) {
9207   // Maybe we should use a memcpy?
9208   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9209       T.isTriviallyCopyableType(S.Context))
9210     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9211 
9212   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9213                                                      CopyingBaseSubobject,
9214                                                      Copying, 0));
9215 
9216   // If we ended up picking a trivial assignment operator for an array of a
9217   // non-trivially-copyable class type, just emit a memcpy.
9218   if (!Result.isInvalid() && !Result.get())
9219     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9220 
9221   return Result;
9222 }
9223 
9224 Sema::ImplicitExceptionSpecification
9225 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9226   CXXRecordDecl *ClassDecl = MD->getParent();
9227 
9228   ImplicitExceptionSpecification ExceptSpec(*this);
9229   if (ClassDecl->isInvalidDecl())
9230     return ExceptSpec;
9231 
9232   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9233   assert(T->getNumParams() == 1 && "not a copy assignment op");
9234   unsigned ArgQuals =
9235       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9236 
9237   // C++ [except.spec]p14:
9238   //   An implicitly declared special member function (Clause 12) shall have an
9239   //   exception-specification. [...]
9240 
9241   // It is unspecified whether or not an implicit copy assignment operator
9242   // attempts to deduplicate calls to assignment operators of virtual bases are
9243   // made. As such, this exception specification is effectively unspecified.
9244   // Based on a similar decision made for constness in C++0x, we're erring on
9245   // the side of assuming such calls to be made regardless of whether they
9246   // actually happen.
9247   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9248                                        BaseEnd = ClassDecl->bases_end();
9249        Base != BaseEnd; ++Base) {
9250     if (Base->isVirtual())
9251       continue;
9252 
9253     CXXRecordDecl *BaseClassDecl
9254       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9255     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9256                                                             ArgQuals, false, 0))
9257       ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
9258   }
9259 
9260   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9261                                        BaseEnd = ClassDecl->vbases_end();
9262        Base != BaseEnd; ++Base) {
9263     CXXRecordDecl *BaseClassDecl
9264       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9265     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9266                                                             ArgQuals, false, 0))
9267       ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
9268   }
9269 
9270   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9271                                   FieldEnd = ClassDecl->field_end();
9272        Field != FieldEnd;
9273        ++Field) {
9274     QualType FieldType = Context.getBaseElementType(Field->getType());
9275     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9276       if (CXXMethodDecl *CopyAssign =
9277           LookupCopyingAssignment(FieldClassDecl,
9278                                   ArgQuals | FieldType.getCVRQualifiers(),
9279                                   false, 0))
9280         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
9281     }
9282   }
9283 
9284   return ExceptSpec;
9285 }
9286 
9287 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9288   // Note: The following rules are largely analoguous to the copy
9289   // constructor rules. Note that virtual bases are not taken into account
9290   // for determining the argument type of the operator. Note also that
9291   // operators taking an object instead of a reference are allowed.
9292   assert(ClassDecl->needsImplicitCopyAssignment());
9293 
9294   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9295   if (DSM.isAlreadyBeingDeclared())
9296     return 0;
9297 
9298   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9299   QualType RetType = Context.getLValueReferenceType(ArgType);
9300   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9301   if (Const)
9302     ArgType = ArgType.withConst();
9303   ArgType = Context.getLValueReferenceType(ArgType);
9304 
9305   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9306                                                      CXXCopyAssignment,
9307                                                      Const);
9308 
9309   //   An implicitly-declared copy assignment operator is an inline public
9310   //   member of its class.
9311   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9312   SourceLocation ClassLoc = ClassDecl->getLocation();
9313   DeclarationNameInfo NameInfo(Name, ClassLoc);
9314   CXXMethodDecl *CopyAssignment =
9315       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9316                             /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9317                             /*isInline=*/ true, Constexpr, SourceLocation());
9318   CopyAssignment->setAccess(AS_public);
9319   CopyAssignment->setDefaulted();
9320   CopyAssignment->setImplicit();
9321 
9322   // Build an exception specification pointing back at this member.
9323   FunctionProtoType::ExtProtoInfo EPI =
9324       getImplicitMethodEPI(*this, CopyAssignment);
9325   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9326 
9327   // Add the parameter to the operator.
9328   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
9329                                                ClassLoc, ClassLoc, /*Id=*/0,
9330                                                ArgType, /*TInfo=*/0,
9331                                                SC_None, 0);
9332   CopyAssignment->setParams(FromParam);
9333 
9334   AddOverriddenMethods(ClassDecl, CopyAssignment);
9335 
9336   CopyAssignment->setTrivial(
9337     ClassDecl->needsOverloadResolutionForCopyAssignment()
9338       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9339       : ClassDecl->hasTrivialCopyAssignment());
9340 
9341   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
9342     SetDeclDeleted(CopyAssignment, ClassLoc);
9343 
9344   // Note that we have added this copy-assignment operator.
9345   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9346 
9347   if (Scope *S = getScopeForContext(ClassDecl))
9348     PushOnScopeChains(CopyAssignment, S, false);
9349   ClassDecl->addDecl(CopyAssignment);
9350 
9351   return CopyAssignment;
9352 }
9353 
9354 /// Diagnose an implicit copy operation for a class which is odr-used, but
9355 /// which is deprecated because the class has a user-declared copy constructor,
9356 /// copy assignment operator, or destructor.
9357 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9358                                             SourceLocation UseLoc) {
9359   assert(CopyOp->isImplicit());
9360 
9361   CXXRecordDecl *RD = CopyOp->getParent();
9362   CXXMethodDecl *UserDeclaredOperation = 0;
9363 
9364   // In Microsoft mode, assignment operations don't affect constructors and
9365   // vice versa.
9366   if (RD->hasUserDeclaredDestructor()) {
9367     UserDeclaredOperation = RD->getDestructor();
9368   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9369              RD->hasUserDeclaredCopyConstructor() &&
9370              !S.getLangOpts().MSVCCompat) {
9371     // Find any user-declared copy constructor.
9372     for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9373                                       E = RD->ctor_end(); I != E; ++I) {
9374       if (I->isCopyConstructor()) {
9375         UserDeclaredOperation = *I;
9376         break;
9377       }
9378     }
9379     assert(UserDeclaredOperation);
9380   } else if (isa<CXXConstructorDecl>(CopyOp) &&
9381              RD->hasUserDeclaredCopyAssignment() &&
9382              !S.getLangOpts().MSVCCompat) {
9383     // Find any user-declared move assignment operator.
9384     for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9385                                         E = RD->method_end(); I != E; ++I) {
9386       if (I->isCopyAssignmentOperator()) {
9387         UserDeclaredOperation = *I;
9388         break;
9389       }
9390     }
9391     assert(UserDeclaredOperation);
9392   }
9393 
9394   if (UserDeclaredOperation) {
9395     S.Diag(UserDeclaredOperation->getLocation(),
9396          diag::warn_deprecated_copy_operation)
9397       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9398       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9399     S.Diag(UseLoc, diag::note_member_synthesized_at)
9400       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9401                                           : Sema::CXXCopyAssignment)
9402       << RD;
9403   }
9404 }
9405 
9406 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9407                                         CXXMethodDecl *CopyAssignOperator) {
9408   assert((CopyAssignOperator->isDefaulted() &&
9409           CopyAssignOperator->isOverloadedOperator() &&
9410           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
9411           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9412           !CopyAssignOperator->isDeleted()) &&
9413          "DefineImplicitCopyAssignment called for wrong function");
9414 
9415   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9416 
9417   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9418     CopyAssignOperator->setInvalidDecl();
9419     return;
9420   }
9421 
9422   // C++11 [class.copy]p18:
9423   //   The [definition of an implicitly declared copy assignment operator] is
9424   //   deprecated if the class has a user-declared copy constructor or a
9425   //   user-declared destructor.
9426   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9427     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9428 
9429   CopyAssignOperator->markUsed(Context);
9430 
9431   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
9432   DiagnosticErrorTrap Trap(Diags);
9433 
9434   // C++0x [class.copy]p30:
9435   //   The implicitly-defined or explicitly-defaulted copy assignment operator
9436   //   for a non-union class X performs memberwise copy assignment of its
9437   //   subobjects. The direct base classes of X are assigned first, in the
9438   //   order of their declaration in the base-specifier-list, and then the
9439   //   immediate non-static data members of X are assigned, in the order in
9440   //   which they were declared in the class definition.
9441 
9442   // The statements that form the synthesized function body.
9443   SmallVector<Stmt*, 8> Statements;
9444 
9445   // The parameter for the "other" object, which we are copying from.
9446   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9447   Qualifiers OtherQuals = Other->getType().getQualifiers();
9448   QualType OtherRefType = Other->getType();
9449   if (const LValueReferenceType *OtherRef
9450                                 = OtherRefType->getAs<LValueReferenceType>()) {
9451     OtherRefType = OtherRef->getPointeeType();
9452     OtherQuals = OtherRefType.getQualifiers();
9453   }
9454 
9455   // Our location for everything implicitly-generated.
9456   SourceLocation Loc = CopyAssignOperator->getLocation();
9457 
9458   // Builds a DeclRefExpr for the "other" object.
9459   RefBuilder OtherRef(Other, OtherRefType);
9460 
9461   // Builds the "this" pointer.
9462   ThisBuilder This;
9463 
9464   // Assign base classes.
9465   bool Invalid = false;
9466   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9467        E = ClassDecl->bases_end(); Base != E; ++Base) {
9468     // Form the assignment:
9469     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9470     QualType BaseType = Base->getType().getUnqualifiedType();
9471     if (!BaseType->isRecordType()) {
9472       Invalid = true;
9473       continue;
9474     }
9475 
9476     CXXCastPath BasePath;
9477     BasePath.push_back(Base);
9478 
9479     // Construct the "from" expression, which is an implicit cast to the
9480     // appropriately-qualified base type.
9481     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9482                      VK_LValue, BasePath);
9483 
9484     // Dereference "this".
9485     DerefBuilder DerefThis(This);
9486     CastBuilder To(DerefThis,
9487                    Context.getCVRQualifiedType(
9488                        BaseType, CopyAssignOperator->getTypeQualifiers()),
9489                    VK_LValue, BasePath);
9490 
9491     // Build the copy.
9492     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
9493                                             To, From,
9494                                             /*CopyingBaseSubobject=*/true,
9495                                             /*Copying=*/true);
9496     if (Copy.isInvalid()) {
9497       Diag(CurrentLocation, diag::note_member_synthesized_at)
9498         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9499       CopyAssignOperator->setInvalidDecl();
9500       return;
9501     }
9502 
9503     // Success! Record the copy.
9504     Statements.push_back(Copy.takeAs<Expr>());
9505   }
9506 
9507   // Assign non-static members.
9508   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9509                                   FieldEnd = ClassDecl->field_end();
9510        Field != FieldEnd; ++Field) {
9511     if (Field->isUnnamedBitfield())
9512       continue;
9513 
9514     if (Field->isInvalidDecl()) {
9515       Invalid = true;
9516       continue;
9517     }
9518 
9519     // Check for members of reference type; we can't copy those.
9520     if (Field->getType()->isReferenceType()) {
9521       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9522         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9523       Diag(Field->getLocation(), diag::note_declared_at);
9524       Diag(CurrentLocation, diag::note_member_synthesized_at)
9525         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9526       Invalid = true;
9527       continue;
9528     }
9529 
9530     // Check for members of const-qualified, non-class type.
9531     QualType BaseType = Context.getBaseElementType(Field->getType());
9532     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9533       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9534         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9535       Diag(Field->getLocation(), diag::note_declared_at);
9536       Diag(CurrentLocation, diag::note_member_synthesized_at)
9537         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9538       Invalid = true;
9539       continue;
9540     }
9541 
9542     // Suppress assigning zero-width bitfields.
9543     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9544       continue;
9545 
9546     QualType FieldType = Field->getType().getNonReferenceType();
9547     if (FieldType->isIncompleteArrayType()) {
9548       assert(ClassDecl->hasFlexibleArrayMember() &&
9549              "Incomplete array type is not valid");
9550       continue;
9551     }
9552 
9553     // Build references to the field in the object we're copying from and to.
9554     CXXScopeSpec SS; // Intentionally empty
9555     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9556                               LookupMemberName);
9557     MemberLookup.addDecl(*Field);
9558     MemberLookup.resolveKind();
9559 
9560     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9561 
9562     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
9563 
9564     // Build the copy of this field.
9565     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
9566                                             To, From,
9567                                             /*CopyingBaseSubobject=*/false,
9568                                             /*Copying=*/true);
9569     if (Copy.isInvalid()) {
9570       Diag(CurrentLocation, diag::note_member_synthesized_at)
9571         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9572       CopyAssignOperator->setInvalidDecl();
9573       return;
9574     }
9575 
9576     // Success! Record the copy.
9577     Statements.push_back(Copy.takeAs<Stmt>());
9578   }
9579 
9580   if (!Invalid) {
9581     // Add a "return *this;"
9582     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9583 
9584     StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9585     if (Return.isInvalid())
9586       Invalid = true;
9587     else {
9588       Statements.push_back(Return.takeAs<Stmt>());
9589 
9590       if (Trap.hasErrorOccurred()) {
9591         Diag(CurrentLocation, diag::note_member_synthesized_at)
9592           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9593         Invalid = true;
9594       }
9595     }
9596   }
9597 
9598   if (Invalid) {
9599     CopyAssignOperator->setInvalidDecl();
9600     return;
9601   }
9602 
9603   StmtResult Body;
9604   {
9605     CompoundScopeRAII CompoundScope(*this);
9606     Body = ActOnCompoundStmt(Loc, Loc, Statements,
9607                              /*isStmtExpr=*/false);
9608     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9609   }
9610   CopyAssignOperator->setBody(Body.takeAs<Stmt>());
9611 
9612   if (ASTMutationListener *L = getASTMutationListener()) {
9613     L->CompletedImplicitDefinition(CopyAssignOperator);
9614   }
9615 }
9616 
9617 Sema::ImplicitExceptionSpecification
9618 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9619   CXXRecordDecl *ClassDecl = MD->getParent();
9620 
9621   ImplicitExceptionSpecification ExceptSpec(*this);
9622   if (ClassDecl->isInvalidDecl())
9623     return ExceptSpec;
9624 
9625   // C++0x [except.spec]p14:
9626   //   An implicitly declared special member function (Clause 12) shall have an
9627   //   exception-specification. [...]
9628 
9629   // It is unspecified whether or not an implicit move assignment operator
9630   // attempts to deduplicate calls to assignment operators of virtual bases are
9631   // made. As such, this exception specification is effectively unspecified.
9632   // Based on a similar decision made for constness in C++0x, we're erring on
9633   // the side of assuming such calls to be made regardless of whether they
9634   // actually happen.
9635   // Note that a move constructor is not implicitly declared when there are
9636   // virtual bases, but it can still be user-declared and explicitly defaulted.
9637   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9638                                        BaseEnd = ClassDecl->bases_end();
9639        Base != BaseEnd; ++Base) {
9640     if (Base->isVirtual())
9641       continue;
9642 
9643     CXXRecordDecl *BaseClassDecl
9644       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9645     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9646                                                            0, false, 0))
9647       ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9648   }
9649 
9650   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9651                                        BaseEnd = ClassDecl->vbases_end();
9652        Base != BaseEnd; ++Base) {
9653     CXXRecordDecl *BaseClassDecl
9654       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9655     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9656                                                            0, false, 0))
9657       ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9658   }
9659 
9660   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9661                                   FieldEnd = ClassDecl->field_end();
9662        Field != FieldEnd;
9663        ++Field) {
9664     QualType FieldType = Context.getBaseElementType(Field->getType());
9665     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9666       if (CXXMethodDecl *MoveAssign =
9667               LookupMovingAssignment(FieldClassDecl,
9668                                      FieldType.getCVRQualifiers(),
9669                                      false, 0))
9670         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
9671     }
9672   }
9673 
9674   return ExceptSpec;
9675 }
9676 
9677 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9678   assert(ClassDecl->needsImplicitMoveAssignment());
9679 
9680   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9681   if (DSM.isAlreadyBeingDeclared())
9682     return 0;
9683 
9684   // Note: The following rules are largely analoguous to the move
9685   // constructor rules.
9686 
9687   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9688   QualType RetType = Context.getLValueReferenceType(ArgType);
9689   ArgType = Context.getRValueReferenceType(ArgType);
9690 
9691   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9692                                                      CXXMoveAssignment,
9693                                                      false);
9694 
9695   //   An implicitly-declared move assignment operator is an inline public
9696   //   member of its class.
9697   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9698   SourceLocation ClassLoc = ClassDecl->getLocation();
9699   DeclarationNameInfo NameInfo(Name, ClassLoc);
9700   CXXMethodDecl *MoveAssignment =
9701       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9702                             /*TInfo=*/0, /*StorageClass=*/SC_None,
9703                             /*isInline=*/true, Constexpr, SourceLocation());
9704   MoveAssignment->setAccess(AS_public);
9705   MoveAssignment->setDefaulted();
9706   MoveAssignment->setImplicit();
9707 
9708   // Build an exception specification pointing back at this member.
9709   FunctionProtoType::ExtProtoInfo EPI =
9710       getImplicitMethodEPI(*this, MoveAssignment);
9711   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9712 
9713   // Add the parameter to the operator.
9714   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9715                                                ClassLoc, ClassLoc, /*Id=*/0,
9716                                                ArgType, /*TInfo=*/0,
9717                                                SC_None, 0);
9718   MoveAssignment->setParams(FromParam);
9719 
9720   AddOverriddenMethods(ClassDecl, MoveAssignment);
9721 
9722   MoveAssignment->setTrivial(
9723     ClassDecl->needsOverloadResolutionForMoveAssignment()
9724       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9725       : ClassDecl->hasTrivialMoveAssignment());
9726 
9727   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
9728     ClassDecl->setImplicitMoveAssignmentIsDeleted();
9729     SetDeclDeleted(MoveAssignment, ClassLoc);
9730   }
9731 
9732   // Note that we have added this copy-assignment operator.
9733   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9734 
9735   if (Scope *S = getScopeForContext(ClassDecl))
9736     PushOnScopeChains(MoveAssignment, S, false);
9737   ClassDecl->addDecl(MoveAssignment);
9738 
9739   return MoveAssignment;
9740 }
9741 
9742 /// Check if we're implicitly defining a move assignment operator for a class
9743 /// with virtual bases. Such a move assignment might move-assign the virtual
9744 /// base multiple times.
9745 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9746                                                SourceLocation CurrentLocation) {
9747   assert(!Class->isDependentContext() && "should not define dependent move");
9748 
9749   // Only a virtual base could get implicitly move-assigned multiple times.
9750   // Only a non-trivial move assignment can observe this. We only want to
9751   // diagnose if we implicitly define an assignment operator that assigns
9752   // two base classes, both of which move-assign the same virtual base.
9753   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9754       Class->getNumBases() < 2)
9755     return;
9756 
9757   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9758   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9759   VBaseMap VBases;
9760 
9761   for (CXXRecordDecl::base_class_iterator BI = Class->bases_begin(),
9762                                           BE = Class->bases_end();
9763        BI != BE; ++BI) {
9764     Worklist.push_back(&*BI);
9765     while (!Worklist.empty()) {
9766       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9767       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9768 
9769       // If the base has no non-trivial move assignment operators,
9770       // we don't care about moves from it.
9771       if (!Base->hasNonTrivialMoveAssignment())
9772         continue;
9773 
9774       // If there's nothing virtual here, skip it.
9775       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9776         continue;
9777 
9778       // If we're not actually going to call a move assignment for this base,
9779       // or the selected move assignment is trivial, skip it.
9780       Sema::SpecialMemberOverloadResult *SMOR =
9781         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9782                               /*ConstArg*/false, /*VolatileArg*/false,
9783                               /*RValueThis*/true, /*ConstThis*/false,
9784                               /*VolatileThis*/false);
9785       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9786           !SMOR->getMethod()->isMoveAssignmentOperator())
9787         continue;
9788 
9789       if (BaseSpec->isVirtual()) {
9790         // We're going to move-assign this virtual base, and its move
9791         // assignment operator is not trivial. If this can happen for
9792         // multiple distinct direct bases of Class, diagnose it. (If it
9793         // only happens in one base, we'll diagnose it when synthesizing
9794         // that base class's move assignment operator.)
9795         CXXBaseSpecifier *&Existing =
9796             VBases.insert(std::make_pair(Base->getCanonicalDecl(), BI))
9797                 .first->second;
9798         if (Existing && Existing != BI) {
9799           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9800             << Class << Base;
9801           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9802             << (Base->getCanonicalDecl() ==
9803                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9804             << Base << Existing->getType() << Existing->getSourceRange();
9805           S.Diag(BI->getLocStart(), diag::note_vbase_moved_here)
9806             << (Base->getCanonicalDecl() ==
9807                 BI->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9808             << Base << BI->getType() << BaseSpec->getSourceRange();
9809 
9810           // Only diagnose each vbase once.
9811           Existing = 0;
9812         }
9813       } else {
9814         // Only walk over bases that have defaulted move assignment operators.
9815         // We assume that any user-provided move assignment operator handles
9816         // the multiple-moves-of-vbase case itself somehow.
9817         if (!SMOR->getMethod()->isDefaulted())
9818           continue;
9819 
9820         // We're going to move the base classes of Base. Add them to the list.
9821         for (CXXRecordDecl::base_class_iterator BI = Base->bases_begin(),
9822                                                 BE = Base->bases_end();
9823              BI != BE; ++BI)
9824           Worklist.push_back(&*BI);
9825       }
9826     }
9827   }
9828 }
9829 
9830 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9831                                         CXXMethodDecl *MoveAssignOperator) {
9832   assert((MoveAssignOperator->isDefaulted() &&
9833           MoveAssignOperator->isOverloadedOperator() &&
9834           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
9835           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9836           !MoveAssignOperator->isDeleted()) &&
9837          "DefineImplicitMoveAssignment called for wrong function");
9838 
9839   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9840 
9841   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9842     MoveAssignOperator->setInvalidDecl();
9843     return;
9844   }
9845 
9846   MoveAssignOperator->markUsed(Context);
9847 
9848   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
9849   DiagnosticErrorTrap Trap(Diags);
9850 
9851   // C++0x [class.copy]p28:
9852   //   The implicitly-defined or move assignment operator for a non-union class
9853   //   X performs memberwise move assignment of its subobjects. The direct base
9854   //   classes of X are assigned first, in the order of their declaration in the
9855   //   base-specifier-list, and then the immediate non-static data members of X
9856   //   are assigned, in the order in which they were declared in the class
9857   //   definition.
9858 
9859   // Issue a warning if our implicit move assignment operator will move
9860   // from a virtual base more than once.
9861   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
9862 
9863   // The statements that form the synthesized function body.
9864   SmallVector<Stmt*, 8> Statements;
9865 
9866   // The parameter for the "other" object, which we are move from.
9867   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9868   QualType OtherRefType = Other->getType()->
9869       getAs<RValueReferenceType>()->getPointeeType();
9870   assert(!OtherRefType.getQualifiers() &&
9871          "Bad argument type of defaulted move assignment");
9872 
9873   // Our location for everything implicitly-generated.
9874   SourceLocation Loc = MoveAssignOperator->getLocation();
9875 
9876   // Builds a reference to the "other" object.
9877   RefBuilder OtherRef(Other, OtherRefType);
9878   // Cast to rvalue.
9879   MoveCastBuilder MoveOther(OtherRef);
9880 
9881   // Builds the "this" pointer.
9882   ThisBuilder This;
9883 
9884   // Assign base classes.
9885   bool Invalid = false;
9886   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9887        E = ClassDecl->bases_end(); Base != E; ++Base) {
9888     // C++11 [class.copy]p28:
9889     //   It is unspecified whether subobjects representing virtual base classes
9890     //   are assigned more than once by the implicitly-defined copy assignment
9891     //   operator.
9892     // FIXME: Do not assign to a vbase that will be assigned by some other base
9893     // class. For a move-assignment, this can result in the vbase being moved
9894     // multiple times.
9895 
9896     // Form the assignment:
9897     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9898     QualType BaseType = Base->getType().getUnqualifiedType();
9899     if (!BaseType->isRecordType()) {
9900       Invalid = true;
9901       continue;
9902     }
9903 
9904     CXXCastPath BasePath;
9905     BasePath.push_back(Base);
9906 
9907     // Construct the "from" expression, which is an implicit cast to the
9908     // appropriately-qualified base type.
9909     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
9910 
9911     // Dereference "this".
9912     DerefBuilder DerefThis(This);
9913 
9914     // Implicitly cast "this" to the appropriately-qualified base type.
9915     CastBuilder To(DerefThis,
9916                    Context.getCVRQualifiedType(
9917                        BaseType, MoveAssignOperator->getTypeQualifiers()),
9918                    VK_LValue, BasePath);
9919 
9920     // Build the move.
9921     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
9922                                             To, From,
9923                                             /*CopyingBaseSubobject=*/true,
9924                                             /*Copying=*/false);
9925     if (Move.isInvalid()) {
9926       Diag(CurrentLocation, diag::note_member_synthesized_at)
9927         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9928       MoveAssignOperator->setInvalidDecl();
9929       return;
9930     }
9931 
9932     // Success! Record the move.
9933     Statements.push_back(Move.takeAs<Expr>());
9934   }
9935 
9936   // Assign non-static members.
9937   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9938                                   FieldEnd = ClassDecl->field_end();
9939        Field != FieldEnd; ++Field) {
9940     if (Field->isUnnamedBitfield())
9941       continue;
9942 
9943     if (Field->isInvalidDecl()) {
9944       Invalid = true;
9945       continue;
9946     }
9947 
9948     // Check for members of reference type; we can't move those.
9949     if (Field->getType()->isReferenceType()) {
9950       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9951         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9952       Diag(Field->getLocation(), diag::note_declared_at);
9953       Diag(CurrentLocation, diag::note_member_synthesized_at)
9954         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9955       Invalid = true;
9956       continue;
9957     }
9958 
9959     // Check for members of const-qualified, non-class type.
9960     QualType BaseType = Context.getBaseElementType(Field->getType());
9961     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9962       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9963         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9964       Diag(Field->getLocation(), diag::note_declared_at);
9965       Diag(CurrentLocation, diag::note_member_synthesized_at)
9966         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9967       Invalid = true;
9968       continue;
9969     }
9970 
9971     // Suppress assigning zero-width bitfields.
9972     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9973       continue;
9974 
9975     QualType FieldType = Field->getType().getNonReferenceType();
9976     if (FieldType->isIncompleteArrayType()) {
9977       assert(ClassDecl->hasFlexibleArrayMember() &&
9978              "Incomplete array type is not valid");
9979       continue;
9980     }
9981 
9982     // Build references to the field in the object we're copying from and to.
9983     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9984                               LookupMemberName);
9985     MemberLookup.addDecl(*Field);
9986     MemberLookup.resolveKind();
9987     MemberBuilder From(MoveOther, OtherRefType,
9988                        /*IsArrow=*/false, MemberLookup);
9989     MemberBuilder To(This, getCurrentThisType(),
9990                      /*IsArrow=*/true, MemberLookup);
9991 
9992     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
9993         "Member reference with rvalue base must be rvalue except for reference "
9994         "members, which aren't allowed for move assignment.");
9995 
9996     // Build the move of this field.
9997     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
9998                                             To, From,
9999                                             /*CopyingBaseSubobject=*/false,
10000                                             /*Copying=*/false);
10001     if (Move.isInvalid()) {
10002       Diag(CurrentLocation, diag::note_member_synthesized_at)
10003         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10004       MoveAssignOperator->setInvalidDecl();
10005       return;
10006     }
10007 
10008     // Success! Record the copy.
10009     Statements.push_back(Move.takeAs<Stmt>());
10010   }
10011 
10012   if (!Invalid) {
10013     // Add a "return *this;"
10014     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10015 
10016     StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
10017     if (Return.isInvalid())
10018       Invalid = true;
10019     else {
10020       Statements.push_back(Return.takeAs<Stmt>());
10021 
10022       if (Trap.hasErrorOccurred()) {
10023         Diag(CurrentLocation, diag::note_member_synthesized_at)
10024           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10025         Invalid = true;
10026       }
10027     }
10028   }
10029 
10030   if (Invalid) {
10031     MoveAssignOperator->setInvalidDecl();
10032     return;
10033   }
10034 
10035   StmtResult Body;
10036   {
10037     CompoundScopeRAII CompoundScope(*this);
10038     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10039                              /*isStmtExpr=*/false);
10040     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10041   }
10042   MoveAssignOperator->setBody(Body.takeAs<Stmt>());
10043 
10044   if (ASTMutationListener *L = getASTMutationListener()) {
10045     L->CompletedImplicitDefinition(MoveAssignOperator);
10046   }
10047 }
10048 
10049 Sema::ImplicitExceptionSpecification
10050 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10051   CXXRecordDecl *ClassDecl = MD->getParent();
10052 
10053   ImplicitExceptionSpecification ExceptSpec(*this);
10054   if (ClassDecl->isInvalidDecl())
10055     return ExceptSpec;
10056 
10057   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10058   assert(T->getNumParams() >= 1 && "not a copy ctor");
10059   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10060 
10061   // C++ [except.spec]p14:
10062   //   An implicitly declared special member function (Clause 12) shall have an
10063   //   exception-specification. [...]
10064   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
10065                                        BaseEnd = ClassDecl->bases_end();
10066        Base != BaseEnd;
10067        ++Base) {
10068     // Virtual bases are handled below.
10069     if (Base->isVirtual())
10070       continue;
10071 
10072     CXXRecordDecl *BaseClassDecl
10073       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
10074     if (CXXConstructorDecl *CopyConstructor =
10075           LookupCopyingConstructor(BaseClassDecl, Quals))
10076       ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
10077   }
10078   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
10079                                        BaseEnd = ClassDecl->vbases_end();
10080        Base != BaseEnd;
10081        ++Base) {
10082     CXXRecordDecl *BaseClassDecl
10083       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
10084     if (CXXConstructorDecl *CopyConstructor =
10085           LookupCopyingConstructor(BaseClassDecl, Quals))
10086       ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
10087   }
10088   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
10089                                   FieldEnd = ClassDecl->field_end();
10090        Field != FieldEnd;
10091        ++Field) {
10092     QualType FieldType = Context.getBaseElementType(Field->getType());
10093     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10094       if (CXXConstructorDecl *CopyConstructor =
10095               LookupCopyingConstructor(FieldClassDecl,
10096                                        Quals | FieldType.getCVRQualifiers()))
10097       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10098     }
10099   }
10100 
10101   return ExceptSpec;
10102 }
10103 
10104 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10105                                                     CXXRecordDecl *ClassDecl) {
10106   // C++ [class.copy]p4:
10107   //   If the class definition does not explicitly declare a copy
10108   //   constructor, one is declared implicitly.
10109   assert(ClassDecl->needsImplicitCopyConstructor());
10110 
10111   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10112   if (DSM.isAlreadyBeingDeclared())
10113     return 0;
10114 
10115   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10116   QualType ArgType = ClassType;
10117   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10118   if (Const)
10119     ArgType = ArgType.withConst();
10120   ArgType = Context.getLValueReferenceType(ArgType);
10121 
10122   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10123                                                      CXXCopyConstructor,
10124                                                      Const);
10125 
10126   DeclarationName Name
10127     = Context.DeclarationNames.getCXXConstructorName(
10128                                            Context.getCanonicalType(ClassType));
10129   SourceLocation ClassLoc = ClassDecl->getLocation();
10130   DeclarationNameInfo NameInfo(Name, ClassLoc);
10131 
10132   //   An implicitly-declared copy constructor is an inline public
10133   //   member of its class.
10134   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10135       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
10136       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10137       Constexpr);
10138   CopyConstructor->setAccess(AS_public);
10139   CopyConstructor->setDefaulted();
10140 
10141   // Build an exception specification pointing back at this member.
10142   FunctionProtoType::ExtProtoInfo EPI =
10143       getImplicitMethodEPI(*this, CopyConstructor);
10144   CopyConstructor->setType(
10145       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10146 
10147   // Add the parameter to the constructor.
10148   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10149                                                ClassLoc, ClassLoc,
10150                                                /*IdentifierInfo=*/0,
10151                                                ArgType, /*TInfo=*/0,
10152                                                SC_None, 0);
10153   CopyConstructor->setParams(FromParam);
10154 
10155   CopyConstructor->setTrivial(
10156     ClassDecl->needsOverloadResolutionForCopyConstructor()
10157       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10158       : ClassDecl->hasTrivialCopyConstructor());
10159 
10160   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10161     SetDeclDeleted(CopyConstructor, ClassLoc);
10162 
10163   // Note that we have declared this constructor.
10164   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10165 
10166   if (Scope *S = getScopeForContext(ClassDecl))
10167     PushOnScopeChains(CopyConstructor, S, false);
10168   ClassDecl->addDecl(CopyConstructor);
10169 
10170   return CopyConstructor;
10171 }
10172 
10173 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10174                                    CXXConstructorDecl *CopyConstructor) {
10175   assert((CopyConstructor->isDefaulted() &&
10176           CopyConstructor->isCopyConstructor() &&
10177           !CopyConstructor->doesThisDeclarationHaveABody() &&
10178           !CopyConstructor->isDeleted()) &&
10179          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10180 
10181   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10182   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10183 
10184   // C++11 [class.copy]p7:
10185   //   The [definition of an implicitly declared copy constructor] is
10186   //   deprecated if the class has a user-declared copy assignment operator
10187   //   or a user-declared destructor.
10188   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10189     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10190 
10191   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10192   DiagnosticErrorTrap Trap(Diags);
10193 
10194   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10195       Trap.hasErrorOccurred()) {
10196     Diag(CurrentLocation, diag::note_member_synthesized_at)
10197       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10198     CopyConstructor->setInvalidDecl();
10199   }  else {
10200     Sema::CompoundScopeRAII CompoundScope(*this);
10201     CopyConstructor->setBody(ActOnCompoundStmt(
10202         CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10203         /*isStmtExpr=*/ false).takeAs<Stmt>());
10204   }
10205 
10206   CopyConstructor->markUsed(Context);
10207   if (ASTMutationListener *L = getASTMutationListener()) {
10208     L->CompletedImplicitDefinition(CopyConstructor);
10209   }
10210 }
10211 
10212 Sema::ImplicitExceptionSpecification
10213 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10214   CXXRecordDecl *ClassDecl = MD->getParent();
10215 
10216   // C++ [except.spec]p14:
10217   //   An implicitly declared special member function (Clause 12) shall have an
10218   //   exception-specification. [...]
10219   ImplicitExceptionSpecification ExceptSpec(*this);
10220   if (ClassDecl->isInvalidDecl())
10221     return ExceptSpec;
10222 
10223   // Direct base-class constructors.
10224   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
10225                                        BEnd = ClassDecl->bases_end();
10226        B != BEnd; ++B) {
10227     if (B->isVirtual()) // Handled below.
10228       continue;
10229 
10230     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10231       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10232       CXXConstructorDecl *Constructor =
10233           LookupMovingConstructor(BaseClassDecl, 0);
10234       // If this is a deleted function, add it anyway. This might be conformant
10235       // with the standard. This might not. I'm not sure. It might not matter.
10236       if (Constructor)
10237         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
10238     }
10239   }
10240 
10241   // Virtual base-class constructors.
10242   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
10243                                        BEnd = ClassDecl->vbases_end();
10244        B != BEnd; ++B) {
10245     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10246       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10247       CXXConstructorDecl *Constructor =
10248           LookupMovingConstructor(BaseClassDecl, 0);
10249       // If this is a deleted function, add it anyway. This might be conformant
10250       // with the standard. This might not. I'm not sure. It might not matter.
10251       if (Constructor)
10252         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
10253     }
10254   }
10255 
10256   // Field constructors.
10257   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10258                                FEnd = ClassDecl->field_end();
10259        F != FEnd; ++F) {
10260     QualType FieldType = Context.getBaseElementType(F->getType());
10261     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10262       CXXConstructorDecl *Constructor =
10263           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10264       // If this is a deleted function, add it anyway. This might be conformant
10265       // with the standard. This might not. I'm not sure. It might not matter.
10266       // In particular, the problem is that this function never gets called. It
10267       // might just be ill-formed because this function attempts to refer to
10268       // a deleted function here.
10269       if (Constructor)
10270         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10271     }
10272   }
10273 
10274   return ExceptSpec;
10275 }
10276 
10277 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10278                                                     CXXRecordDecl *ClassDecl) {
10279   assert(ClassDecl->needsImplicitMoveConstructor());
10280 
10281   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10282   if (DSM.isAlreadyBeingDeclared())
10283     return 0;
10284 
10285   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10286   QualType ArgType = Context.getRValueReferenceType(ClassType);
10287 
10288   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10289                                                      CXXMoveConstructor,
10290                                                      false);
10291 
10292   DeclarationName Name
10293     = Context.DeclarationNames.getCXXConstructorName(
10294                                            Context.getCanonicalType(ClassType));
10295   SourceLocation ClassLoc = ClassDecl->getLocation();
10296   DeclarationNameInfo NameInfo(Name, ClassLoc);
10297 
10298   // C++11 [class.copy]p11:
10299   //   An implicitly-declared copy/move constructor is an inline public
10300   //   member of its class.
10301   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10302       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
10303       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10304       Constexpr);
10305   MoveConstructor->setAccess(AS_public);
10306   MoveConstructor->setDefaulted();
10307 
10308   // Build an exception specification pointing back at this member.
10309   FunctionProtoType::ExtProtoInfo EPI =
10310       getImplicitMethodEPI(*this, MoveConstructor);
10311   MoveConstructor->setType(
10312       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10313 
10314   // Add the parameter to the constructor.
10315   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10316                                                ClassLoc, ClassLoc,
10317                                                /*IdentifierInfo=*/0,
10318                                                ArgType, /*TInfo=*/0,
10319                                                SC_None, 0);
10320   MoveConstructor->setParams(FromParam);
10321 
10322   MoveConstructor->setTrivial(
10323     ClassDecl->needsOverloadResolutionForMoveConstructor()
10324       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10325       : ClassDecl->hasTrivialMoveConstructor());
10326 
10327   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10328     ClassDecl->setImplicitMoveConstructorIsDeleted();
10329     SetDeclDeleted(MoveConstructor, ClassLoc);
10330   }
10331 
10332   // Note that we have declared this constructor.
10333   ++ASTContext::NumImplicitMoveConstructorsDeclared;
10334 
10335   if (Scope *S = getScopeForContext(ClassDecl))
10336     PushOnScopeChains(MoveConstructor, S, false);
10337   ClassDecl->addDecl(MoveConstructor);
10338 
10339   return MoveConstructor;
10340 }
10341 
10342 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10343                                    CXXConstructorDecl *MoveConstructor) {
10344   assert((MoveConstructor->isDefaulted() &&
10345           MoveConstructor->isMoveConstructor() &&
10346           !MoveConstructor->doesThisDeclarationHaveABody() &&
10347           !MoveConstructor->isDeleted()) &&
10348          "DefineImplicitMoveConstructor - call it for implicit move ctor");
10349 
10350   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10351   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10352 
10353   SynthesizedFunctionScope Scope(*this, MoveConstructor);
10354   DiagnosticErrorTrap Trap(Diags);
10355 
10356   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
10357       Trap.hasErrorOccurred()) {
10358     Diag(CurrentLocation, diag::note_member_synthesized_at)
10359       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10360     MoveConstructor->setInvalidDecl();
10361   }  else {
10362     Sema::CompoundScopeRAII CompoundScope(*this);
10363     MoveConstructor->setBody(ActOnCompoundStmt(
10364         MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10365         /*isStmtExpr=*/ false).takeAs<Stmt>());
10366   }
10367 
10368   MoveConstructor->markUsed(Context);
10369 
10370   if (ASTMutationListener *L = getASTMutationListener()) {
10371     L->CompletedImplicitDefinition(MoveConstructor);
10372   }
10373 }
10374 
10375 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
10376   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
10377 }
10378 
10379 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10380                             SourceLocation CurrentLocation,
10381                             CXXConversionDecl *Conv) {
10382   CXXRecordDecl *Lambda = Conv->getParent();
10383   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10384   // If we are defining a specialization of a conversion to function-ptr
10385   // cache the deduced template arguments for this specialization
10386   // so that we can use them to retrieve the corresponding call-operator
10387   // and static-invoker.
10388   const TemplateArgumentList *DeducedTemplateArgs = 0;
10389 
10390 
10391   // Retrieve the corresponding call-operator specialization.
10392   if (Lambda->isGenericLambda()) {
10393     assert(Conv->isFunctionTemplateSpecialization());
10394     FunctionTemplateDecl *CallOpTemplate =
10395         CallOp->getDescribedFunctionTemplate();
10396     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10397     void *InsertPos = 0;
10398     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10399                                                 DeducedTemplateArgs->data(),
10400                                                 DeducedTemplateArgs->size(),
10401                                                 InsertPos);
10402     assert(CallOpSpec &&
10403           "Conversion operator must have a corresponding call operator");
10404     CallOp = cast<CXXMethodDecl>(CallOpSpec);
10405   }
10406   // Mark the call operator referenced (and add to pending instantiations
10407   // if necessary).
10408   // For both the conversion and static-invoker template specializations
10409   // we construct their body's in this function, so no need to add them
10410   // to the PendingInstantiations.
10411   MarkFunctionReferenced(CurrentLocation, CallOp);
10412 
10413   SynthesizedFunctionScope Scope(*this, Conv);
10414   DiagnosticErrorTrap Trap(Diags);
10415 
10416   // Retrieve the static invoker...
10417   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10418   // ... and get the corresponding specialization for a generic lambda.
10419   if (Lambda->isGenericLambda()) {
10420     assert(DeducedTemplateArgs &&
10421       "Must have deduced template arguments from Conversion Operator");
10422     FunctionTemplateDecl *InvokeTemplate =
10423                           Invoker->getDescribedFunctionTemplate();
10424     void *InsertPos = 0;
10425     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10426                                                 DeducedTemplateArgs->data(),
10427                                                 DeducedTemplateArgs->size(),
10428                                                 InsertPos);
10429     assert(InvokeSpec &&
10430       "Must have a corresponding static invoker specialization");
10431     Invoker = cast<CXXMethodDecl>(InvokeSpec);
10432   }
10433   // Construct the body of the conversion function { return __invoke; }.
10434   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10435                                         VK_LValue, Conv->getLocation()).take();
10436    assert(FunctionRef && "Can't refer to __invoke function?");
10437    Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10438    Conv->setBody(new (Context) CompoundStmt(Context, Return,
10439                                             Conv->getLocation(),
10440                                             Conv->getLocation()));
10441 
10442   Conv->markUsed(Context);
10443   Conv->setReferenced();
10444 
10445   // Fill in the __invoke function with a dummy implementation. IR generation
10446   // will fill in the actual details.
10447   Invoker->markUsed(Context);
10448   Invoker->setReferenced();
10449   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10450 
10451   if (ASTMutationListener *L = getASTMutationListener()) {
10452     L->CompletedImplicitDefinition(Conv);
10453     L->CompletedImplicitDefinition(Invoker);
10454    }
10455 }
10456 
10457 
10458 
10459 void Sema::DefineImplicitLambdaToBlockPointerConversion(
10460        SourceLocation CurrentLocation,
10461        CXXConversionDecl *Conv)
10462 {
10463   assert(!Conv->getParent()->isGenericLambda());
10464 
10465   Conv->markUsed(Context);
10466 
10467   SynthesizedFunctionScope Scope(*this, Conv);
10468   DiagnosticErrorTrap Trap(Diags);
10469 
10470   // Copy-initialize the lambda object as needed to capture it.
10471   Expr *This = ActOnCXXThis(CurrentLocation).take();
10472   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
10473 
10474   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10475                                                         Conv->getLocation(),
10476                                                         Conv, DerefThis);
10477 
10478   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10479   // behavior.  Note that only the general conversion function does this
10480   // (since it's unusable otherwise); in the case where we inline the
10481   // block literal, it has block literal lifetime semantics.
10482   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
10483     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10484                                           CK_CopyAndAutoreleaseBlockObject,
10485                                           BuildBlock.get(), 0, VK_RValue);
10486 
10487   if (BuildBlock.isInvalid()) {
10488     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10489     Conv->setInvalidDecl();
10490     return;
10491   }
10492 
10493   // Create the return statement that returns the block from the conversion
10494   // function.
10495   StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
10496   if (Return.isInvalid()) {
10497     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10498     Conv->setInvalidDecl();
10499     return;
10500   }
10501 
10502   // Set the body of the conversion function.
10503   Stmt *ReturnS = Return.take();
10504   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
10505                                            Conv->getLocation(),
10506                                            Conv->getLocation()));
10507 
10508   // We're done; notify the mutation listener, if any.
10509   if (ASTMutationListener *L = getASTMutationListener()) {
10510     L->CompletedImplicitDefinition(Conv);
10511   }
10512 }
10513 
10514 /// \brief Determine whether the given list arguments contains exactly one
10515 /// "real" (non-default) argument.
10516 static bool hasOneRealArgument(MultiExprArg Args) {
10517   switch (Args.size()) {
10518   case 0:
10519     return false;
10520 
10521   default:
10522     if (!Args[1]->isDefaultArgument())
10523       return false;
10524 
10525     // fall through
10526   case 1:
10527     return !Args[0]->isDefaultArgument();
10528   }
10529 
10530   return false;
10531 }
10532 
10533 ExprResult
10534 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10535                             CXXConstructorDecl *Constructor,
10536                             MultiExprArg ExprArgs,
10537                             bool HadMultipleCandidates,
10538                             bool IsListInitialization,
10539                             bool RequiresZeroInit,
10540                             unsigned ConstructKind,
10541                             SourceRange ParenRange) {
10542   bool Elidable = false;
10543 
10544   // C++0x [class.copy]p34:
10545   //   When certain criteria are met, an implementation is allowed to
10546   //   omit the copy/move construction of a class object, even if the
10547   //   copy/move constructor and/or destructor for the object have
10548   //   side effects. [...]
10549   //     - when a temporary class object that has not been bound to a
10550   //       reference (12.2) would be copied/moved to a class object
10551   //       with the same cv-unqualified type, the copy/move operation
10552   //       can be omitted by constructing the temporary object
10553   //       directly into the target of the omitted copy/move
10554   if (ConstructKind == CXXConstructExpr::CK_Complete &&
10555       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
10556     Expr *SubExpr = ExprArgs[0];
10557     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
10558   }
10559 
10560   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
10561                                Elidable, ExprArgs, HadMultipleCandidates,
10562                                IsListInitialization, RequiresZeroInit,
10563                                ConstructKind, ParenRange);
10564 }
10565 
10566 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
10567 /// including handling of its default argument expressions.
10568 ExprResult
10569 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10570                             CXXConstructorDecl *Constructor, bool Elidable,
10571                             MultiExprArg ExprArgs,
10572                             bool HadMultipleCandidates,
10573                             bool IsListInitialization,
10574                             bool RequiresZeroInit,
10575                             unsigned ConstructKind,
10576                             SourceRange ParenRange) {
10577   MarkFunctionReferenced(ConstructLoc, Constructor);
10578   return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
10579                                         Constructor, Elidable, ExprArgs,
10580                                         HadMultipleCandidates,
10581                                         IsListInitialization, RequiresZeroInit,
10582               static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10583                                         ParenRange));
10584 }
10585 
10586 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
10587   if (VD->isInvalidDecl()) return;
10588 
10589   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
10590   if (ClassDecl->isInvalidDecl()) return;
10591   if (ClassDecl->hasIrrelevantDestructor()) return;
10592   if (ClassDecl->isDependentContext()) return;
10593 
10594   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10595   MarkFunctionReferenced(VD->getLocation(), Destructor);
10596   CheckDestructorAccess(VD->getLocation(), Destructor,
10597                         PDiag(diag::err_access_dtor_var)
10598                         << VD->getDeclName()
10599                         << VD->getType());
10600   DiagnoseUseOfDecl(Destructor, VD->getLocation());
10601 
10602   if (!VD->hasGlobalStorage()) return;
10603 
10604   // Emit warning for non-trivial dtor in global scope (a real global,
10605   // class-static, function-static).
10606   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10607 
10608   // TODO: this should be re-enabled for static locals by !CXAAtExit
10609   if (!VD->isStaticLocal())
10610     Diag(VD->getLocation(), diag::warn_global_destructor);
10611 }
10612 
10613 /// \brief Given a constructor and the set of arguments provided for the
10614 /// constructor, convert the arguments and add any required default arguments
10615 /// to form a proper call to this constructor.
10616 ///
10617 /// \returns true if an error occurred, false otherwise.
10618 bool
10619 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10620                               MultiExprArg ArgsPtr,
10621                               SourceLocation Loc,
10622                               SmallVectorImpl<Expr*> &ConvertedArgs,
10623                               bool AllowExplicit,
10624                               bool IsListInitialization) {
10625   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10626   unsigned NumArgs = ArgsPtr.size();
10627   Expr **Args = ArgsPtr.data();
10628 
10629   const FunctionProtoType *Proto
10630     = Constructor->getType()->getAs<FunctionProtoType>();
10631   assert(Proto && "Constructor without a prototype?");
10632   unsigned NumParams = Proto->getNumParams();
10633 
10634   // If too few arguments are available, we'll fill in the rest with defaults.
10635   if (NumArgs < NumParams)
10636     ConvertedArgs.reserve(NumParams);
10637   else
10638     ConvertedArgs.reserve(NumArgs);
10639 
10640   VariadicCallType CallType =
10641     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
10642   SmallVector<Expr *, 8> AllArgs;
10643   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10644                                         Proto, 0,
10645                                         llvm::makeArrayRef(Args, NumArgs),
10646                                         AllArgs,
10647                                         CallType, AllowExplicit,
10648                                         IsListInitialization);
10649   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
10650 
10651   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
10652 
10653   CheckConstructorCall(Constructor,
10654                        llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10655                                                         AllArgs.size()),
10656                        Proto, Loc);
10657 
10658   return Invalid;
10659 }
10660 
10661 static inline bool
10662 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10663                                        const FunctionDecl *FnDecl) {
10664   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
10665   if (isa<NamespaceDecl>(DC)) {
10666     return SemaRef.Diag(FnDecl->getLocation(),
10667                         diag::err_operator_new_delete_declared_in_namespace)
10668       << FnDecl->getDeclName();
10669   }
10670 
10671   if (isa<TranslationUnitDecl>(DC) &&
10672       FnDecl->getStorageClass() == SC_Static) {
10673     return SemaRef.Diag(FnDecl->getLocation(),
10674                         diag::err_operator_new_delete_declared_static)
10675       << FnDecl->getDeclName();
10676   }
10677 
10678   return false;
10679 }
10680 
10681 static inline bool
10682 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10683                             CanQualType ExpectedResultType,
10684                             CanQualType ExpectedFirstParamType,
10685                             unsigned DependentParamTypeDiag,
10686                             unsigned InvalidParamTypeDiag) {
10687   QualType ResultType =
10688       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
10689 
10690   // Check that the result type is not dependent.
10691   if (ResultType->isDependentType())
10692     return SemaRef.Diag(FnDecl->getLocation(),
10693                         diag::err_operator_new_delete_dependent_result_type)
10694     << FnDecl->getDeclName() << ExpectedResultType;
10695 
10696   // Check that the result type is what we expect.
10697   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10698     return SemaRef.Diag(FnDecl->getLocation(),
10699                         diag::err_operator_new_delete_invalid_result_type)
10700     << FnDecl->getDeclName() << ExpectedResultType;
10701 
10702   // A function template must have at least 2 parameters.
10703   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10704     return SemaRef.Diag(FnDecl->getLocation(),
10705                       diag::err_operator_new_delete_template_too_few_parameters)
10706         << FnDecl->getDeclName();
10707 
10708   // The function decl must have at least 1 parameter.
10709   if (FnDecl->getNumParams() == 0)
10710     return SemaRef.Diag(FnDecl->getLocation(),
10711                         diag::err_operator_new_delete_too_few_parameters)
10712       << FnDecl->getDeclName();
10713 
10714   // Check the first parameter type is not dependent.
10715   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10716   if (FirstParamType->isDependentType())
10717     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10718       << FnDecl->getDeclName() << ExpectedFirstParamType;
10719 
10720   // Check that the first parameter type is what we expect.
10721   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10722       ExpectedFirstParamType)
10723     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10724     << FnDecl->getDeclName() << ExpectedFirstParamType;
10725 
10726   return false;
10727 }
10728 
10729 static bool
10730 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10731   // C++ [basic.stc.dynamic.allocation]p1:
10732   //   A program is ill-formed if an allocation function is declared in a
10733   //   namespace scope other than global scope or declared static in global
10734   //   scope.
10735   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10736     return true;
10737 
10738   CanQualType SizeTy =
10739     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10740 
10741   // C++ [basic.stc.dynamic.allocation]p1:
10742   //  The return type shall be void*. The first parameter shall have type
10743   //  std::size_t.
10744   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10745                                   SizeTy,
10746                                   diag::err_operator_new_dependent_param_type,
10747                                   diag::err_operator_new_param_type))
10748     return true;
10749 
10750   // C++ [basic.stc.dynamic.allocation]p1:
10751   //  The first parameter shall not have an associated default argument.
10752   if (FnDecl->getParamDecl(0)->hasDefaultArg())
10753     return SemaRef.Diag(FnDecl->getLocation(),
10754                         diag::err_operator_new_default_arg)
10755       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10756 
10757   return false;
10758 }
10759 
10760 static bool
10761 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
10762   // C++ [basic.stc.dynamic.deallocation]p1:
10763   //   A program is ill-formed if deallocation functions are declared in a
10764   //   namespace scope other than global scope or declared static in global
10765   //   scope.
10766   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10767     return true;
10768 
10769   // C++ [basic.stc.dynamic.deallocation]p2:
10770   //   Each deallocation function shall return void and its first parameter
10771   //   shall be void*.
10772   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10773                                   SemaRef.Context.VoidPtrTy,
10774                                  diag::err_operator_delete_dependent_param_type,
10775                                  diag::err_operator_delete_param_type))
10776     return true;
10777 
10778   return false;
10779 }
10780 
10781 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
10782 /// of this overloaded operator is well-formed. If so, returns false;
10783 /// otherwise, emits appropriate diagnostics and returns true.
10784 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
10785   assert(FnDecl && FnDecl->isOverloadedOperator() &&
10786          "Expected an overloaded operator declaration");
10787 
10788   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10789 
10790   // C++ [over.oper]p5:
10791   //   The allocation and deallocation functions, operator new,
10792   //   operator new[], operator delete and operator delete[], are
10793   //   described completely in 3.7.3. The attributes and restrictions
10794   //   found in the rest of this subclause do not apply to them unless
10795   //   explicitly stated in 3.7.3.
10796   if (Op == OO_Delete || Op == OO_Array_Delete)
10797     return CheckOperatorDeleteDeclaration(*this, FnDecl);
10798 
10799   if (Op == OO_New || Op == OO_Array_New)
10800     return CheckOperatorNewDeclaration(*this, FnDecl);
10801 
10802   // C++ [over.oper]p6:
10803   //   An operator function shall either be a non-static member
10804   //   function or be a non-member function and have at least one
10805   //   parameter whose type is a class, a reference to a class, an
10806   //   enumeration, or a reference to an enumeration.
10807   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10808     if (MethodDecl->isStatic())
10809       return Diag(FnDecl->getLocation(),
10810                   diag::err_operator_overload_static) << FnDecl->getDeclName();
10811   } else {
10812     bool ClassOrEnumParam = false;
10813     for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10814                                    ParamEnd = FnDecl->param_end();
10815          Param != ParamEnd; ++Param) {
10816       QualType ParamType = (*Param)->getType().getNonReferenceType();
10817       if (ParamType->isDependentType() || ParamType->isRecordType() ||
10818           ParamType->isEnumeralType()) {
10819         ClassOrEnumParam = true;
10820         break;
10821       }
10822     }
10823 
10824     if (!ClassOrEnumParam)
10825       return Diag(FnDecl->getLocation(),
10826                   diag::err_operator_overload_needs_class_or_enum)
10827         << FnDecl->getDeclName();
10828   }
10829 
10830   // C++ [over.oper]p8:
10831   //   An operator function cannot have default arguments (8.3.6),
10832   //   except where explicitly stated below.
10833   //
10834   // Only the function-call operator allows default arguments
10835   // (C++ [over.call]p1).
10836   if (Op != OO_Call) {
10837     for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10838          Param != FnDecl->param_end(); ++Param) {
10839       if ((*Param)->hasDefaultArg())
10840         return Diag((*Param)->getLocation(),
10841                     diag::err_operator_overload_default_arg)
10842           << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
10843     }
10844   }
10845 
10846   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10847     { false, false, false }
10848 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10849     , { Unary, Binary, MemberOnly }
10850 #include "clang/Basic/OperatorKinds.def"
10851   };
10852 
10853   bool CanBeUnaryOperator = OperatorUses[Op][0];
10854   bool CanBeBinaryOperator = OperatorUses[Op][1];
10855   bool MustBeMemberOperator = OperatorUses[Op][2];
10856 
10857   // C++ [over.oper]p8:
10858   //   [...] Operator functions cannot have more or fewer parameters
10859   //   than the number required for the corresponding operator, as
10860   //   described in the rest of this subclause.
10861   unsigned NumParams = FnDecl->getNumParams()
10862                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
10863   if (Op != OO_Call &&
10864       ((NumParams == 1 && !CanBeUnaryOperator) ||
10865        (NumParams == 2 && !CanBeBinaryOperator) ||
10866        (NumParams < 1) || (NumParams > 2))) {
10867     // We have the wrong number of parameters.
10868     unsigned ErrorKind;
10869     if (CanBeUnaryOperator && CanBeBinaryOperator) {
10870       ErrorKind = 2;  // 2 -> unary or binary.
10871     } else if (CanBeUnaryOperator) {
10872       ErrorKind = 0;  // 0 -> unary
10873     } else {
10874       assert(CanBeBinaryOperator &&
10875              "All non-call overloaded operators are unary or binary!");
10876       ErrorKind = 1;  // 1 -> binary
10877     }
10878 
10879     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
10880       << FnDecl->getDeclName() << NumParams << ErrorKind;
10881   }
10882 
10883   // Overloaded operators other than operator() cannot be variadic.
10884   if (Op != OO_Call &&
10885       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
10886     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
10887       << FnDecl->getDeclName();
10888   }
10889 
10890   // Some operators must be non-static member functions.
10891   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10892     return Diag(FnDecl->getLocation(),
10893                 diag::err_operator_overload_must_be_member)
10894       << FnDecl->getDeclName();
10895   }
10896 
10897   // C++ [over.inc]p1:
10898   //   The user-defined function called operator++ implements the
10899   //   prefix and postfix ++ operator. If this function is a member
10900   //   function with no parameters, or a non-member function with one
10901   //   parameter of class or enumeration type, it defines the prefix
10902   //   increment operator ++ for objects of that type. If the function
10903   //   is a member function with one parameter (which shall be of type
10904   //   int) or a non-member function with two parameters (the second
10905   //   of which shall be of type int), it defines the postfix
10906   //   increment operator ++ for objects of that type.
10907   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10908     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10909     QualType ParamType = LastParam->getType();
10910 
10911     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
10912         !ParamType->isDependentType())
10913       return Diag(LastParam->getLocation(),
10914                   diag::err_operator_overload_post_incdec_must_be_int)
10915         << LastParam->getType() << (Op == OO_MinusMinus);
10916   }
10917 
10918   return false;
10919 }
10920 
10921 /// CheckLiteralOperatorDeclaration - Check whether the declaration
10922 /// of this literal operator function is well-formed. If so, returns
10923 /// false; otherwise, emits appropriate diagnostics and returns true.
10924 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
10925   if (isa<CXXMethodDecl>(FnDecl)) {
10926     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10927       << FnDecl->getDeclName();
10928     return true;
10929   }
10930 
10931   if (FnDecl->isExternC()) {
10932     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10933     return true;
10934   }
10935 
10936   bool Valid = false;
10937 
10938   // This might be the definition of a literal operator template.
10939   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10940   // This might be a specialization of a literal operator template.
10941   if (!TpDecl)
10942     TpDecl = FnDecl->getPrimaryTemplate();
10943 
10944   // template <char...> type operator "" name() and
10945   // template <class T, T...> type operator "" name() are the only valid
10946   // template signatures, and the only valid signatures with no parameters.
10947   if (TpDecl) {
10948     if (FnDecl->param_size() == 0) {
10949       // Must have one or two template parameters
10950       TemplateParameterList *Params = TpDecl->getTemplateParameters();
10951       if (Params->size() == 1) {
10952         NonTypeTemplateParmDecl *PmDecl =
10953           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
10954 
10955         // The template parameter must be a char parameter pack.
10956         if (PmDecl && PmDecl->isTemplateParameterPack() &&
10957             Context.hasSameType(PmDecl->getType(), Context.CharTy))
10958           Valid = true;
10959       } else if (Params->size() == 2) {
10960         TemplateTypeParmDecl *PmType =
10961           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10962         NonTypeTemplateParmDecl *PmArgs =
10963           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10964 
10965         // The second template parameter must be a parameter pack with the
10966         // first template parameter as its type.
10967         if (PmType && PmArgs &&
10968             !PmType->isTemplateParameterPack() &&
10969             PmArgs->isTemplateParameterPack()) {
10970           const TemplateTypeParmType *TArgs =
10971             PmArgs->getType()->getAs<TemplateTypeParmType>();
10972           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10973               TArgs->getIndex() == PmType->getIndex()) {
10974             Valid = true;
10975             if (ActiveTemplateInstantiations.empty())
10976               Diag(FnDecl->getLocation(),
10977                    diag::ext_string_literal_operator_template);
10978           }
10979         }
10980       }
10981     }
10982   } else if (FnDecl->param_size()) {
10983     // Check the first parameter
10984     FunctionDecl::param_iterator Param = FnDecl->param_begin();
10985 
10986     QualType T = (*Param)->getType().getUnqualifiedType();
10987 
10988     // unsigned long long int, long double, and any character type are allowed
10989     // as the only parameters.
10990     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10991         Context.hasSameType(T, Context.LongDoubleTy) ||
10992         Context.hasSameType(T, Context.CharTy) ||
10993         Context.hasSameType(T, Context.WideCharTy) ||
10994         Context.hasSameType(T, Context.Char16Ty) ||
10995         Context.hasSameType(T, Context.Char32Ty)) {
10996       if (++Param == FnDecl->param_end())
10997         Valid = true;
10998       goto FinishedParams;
10999     }
11000 
11001     // Otherwise it must be a pointer to const; let's strip those qualifiers.
11002     const PointerType *PT = T->getAs<PointerType>();
11003     if (!PT)
11004       goto FinishedParams;
11005     T = PT->getPointeeType();
11006     if (!T.isConstQualified() || T.isVolatileQualified())
11007       goto FinishedParams;
11008     T = T.getUnqualifiedType();
11009 
11010     // Move on to the second parameter;
11011     ++Param;
11012 
11013     // If there is no second parameter, the first must be a const char *
11014     if (Param == FnDecl->param_end()) {
11015       if (Context.hasSameType(T, Context.CharTy))
11016         Valid = true;
11017       goto FinishedParams;
11018     }
11019 
11020     // const char *, const wchar_t*, const char16_t*, and const char32_t*
11021     // are allowed as the first parameter to a two-parameter function
11022     if (!(Context.hasSameType(T, Context.CharTy) ||
11023           Context.hasSameType(T, Context.WideCharTy) ||
11024           Context.hasSameType(T, Context.Char16Ty) ||
11025           Context.hasSameType(T, Context.Char32Ty)))
11026       goto FinishedParams;
11027 
11028     // The second and final parameter must be an std::size_t
11029     T = (*Param)->getType().getUnqualifiedType();
11030     if (Context.hasSameType(T, Context.getSizeType()) &&
11031         ++Param == FnDecl->param_end())
11032       Valid = true;
11033   }
11034 
11035   // FIXME: This diagnostic is absolutely terrible.
11036 FinishedParams:
11037   if (!Valid) {
11038     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11039       << FnDecl->getDeclName();
11040     return true;
11041   }
11042 
11043   // A parameter-declaration-clause containing a default argument is not
11044   // equivalent to any of the permitted forms.
11045   for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
11046                                     ParamEnd = FnDecl->param_end();
11047        Param != ParamEnd; ++Param) {
11048     if ((*Param)->hasDefaultArg()) {
11049       Diag((*Param)->getDefaultArgRange().getBegin(),
11050            diag::err_literal_operator_default_argument)
11051         << (*Param)->getDefaultArgRange();
11052       break;
11053     }
11054   }
11055 
11056   StringRef LiteralName
11057     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11058   if (LiteralName[0] != '_') {
11059     // C++11 [usrlit.suffix]p1:
11060     //   Literal suffix identifiers that do not start with an underscore
11061     //   are reserved for future standardization.
11062     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11063       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11064   }
11065 
11066   return false;
11067 }
11068 
11069 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11070 /// linkage specification, including the language and (if present)
11071 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11072 /// language string literal. LBraceLoc, if valid, provides the location of
11073 /// the '{' brace. Otherwise, this linkage specification does not
11074 /// have any braces.
11075 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11076                                            Expr *LangStr,
11077                                            SourceLocation LBraceLoc) {
11078   StringLiteral *Lit = cast<StringLiteral>(LangStr);
11079   if (!Lit->isAscii()) {
11080     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11081       << LangStr->getSourceRange();
11082     return 0;
11083   }
11084 
11085   StringRef Lang = Lit->getString();
11086   LinkageSpecDecl::LanguageIDs Language;
11087   if (Lang == "C")
11088     Language = LinkageSpecDecl::lang_c;
11089   else if (Lang == "C++")
11090     Language = LinkageSpecDecl::lang_cxx;
11091   else {
11092     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11093       << LangStr->getSourceRange();
11094     return 0;
11095   }
11096 
11097   // FIXME: Add all the various semantics of linkage specifications
11098 
11099   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11100                                                LangStr->getExprLoc(), Language,
11101                                                LBraceLoc.isValid());
11102   CurContext->addDecl(D);
11103   PushDeclContext(S, D);
11104   return D;
11105 }
11106 
11107 /// ActOnFinishLinkageSpecification - Complete the definition of
11108 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11109 /// valid, it's the position of the closing '}' brace in a linkage
11110 /// specification that uses braces.
11111 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11112                                             Decl *LinkageSpec,
11113                                             SourceLocation RBraceLoc) {
11114   if (RBraceLoc.isValid()) {
11115     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11116     LSDecl->setRBraceLoc(RBraceLoc);
11117   }
11118   PopDeclContext();
11119   return LinkageSpec;
11120 }
11121 
11122 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11123                                   AttributeList *AttrList,
11124                                   SourceLocation SemiLoc) {
11125   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11126   // Attribute declarations appertain to empty declaration so we handle
11127   // them here.
11128   if (AttrList)
11129     ProcessDeclAttributeList(S, ED, AttrList);
11130 
11131   CurContext->addDecl(ED);
11132   return ED;
11133 }
11134 
11135 /// \brief Perform semantic analysis for the variable declaration that
11136 /// occurs within a C++ catch clause, returning the newly-created
11137 /// variable.
11138 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11139                                          TypeSourceInfo *TInfo,
11140                                          SourceLocation StartLoc,
11141                                          SourceLocation Loc,
11142                                          IdentifierInfo *Name) {
11143   bool Invalid = false;
11144   QualType ExDeclType = TInfo->getType();
11145 
11146   // Arrays and functions decay.
11147   if (ExDeclType->isArrayType())
11148     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11149   else if (ExDeclType->isFunctionType())
11150     ExDeclType = Context.getPointerType(ExDeclType);
11151 
11152   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11153   // The exception-declaration shall not denote a pointer or reference to an
11154   // incomplete type, other than [cv] void*.
11155   // N2844 forbids rvalue references.
11156   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11157     Diag(Loc, diag::err_catch_rvalue_ref);
11158     Invalid = true;
11159   }
11160 
11161   QualType BaseType = ExDeclType;
11162   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11163   unsigned DK = diag::err_catch_incomplete;
11164   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11165     BaseType = Ptr->getPointeeType();
11166     Mode = 1;
11167     DK = diag::err_catch_incomplete_ptr;
11168   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11169     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11170     BaseType = Ref->getPointeeType();
11171     Mode = 2;
11172     DK = diag::err_catch_incomplete_ref;
11173   }
11174   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11175       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11176     Invalid = true;
11177 
11178   if (!Invalid && !ExDeclType->isDependentType() &&
11179       RequireNonAbstractType(Loc, ExDeclType,
11180                              diag::err_abstract_type_in_decl,
11181                              AbstractVariableType))
11182     Invalid = true;
11183 
11184   // Only the non-fragile NeXT runtime currently supports C++ catches
11185   // of ObjC types, and no runtime supports catching ObjC types by value.
11186   if (!Invalid && getLangOpts().ObjC1) {
11187     QualType T = ExDeclType;
11188     if (const ReferenceType *RT = T->getAs<ReferenceType>())
11189       T = RT->getPointeeType();
11190 
11191     if (T->isObjCObjectType()) {
11192       Diag(Loc, diag::err_objc_object_catch);
11193       Invalid = true;
11194     } else if (T->isObjCObjectPointerType()) {
11195       // FIXME: should this be a test for macosx-fragile specifically?
11196       if (getLangOpts().ObjCRuntime.isFragile())
11197         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
11198     }
11199   }
11200 
11201   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
11202                                     ExDeclType, TInfo, SC_None);
11203   ExDecl->setExceptionVariable(true);
11204 
11205   // In ARC, infer 'retaining' for variables of retainable type.
11206   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
11207     Invalid = true;
11208 
11209   if (!Invalid && !ExDeclType->isDependentType()) {
11210     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
11211       // Insulate this from anything else we might currently be parsing.
11212       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11213 
11214       // C++ [except.handle]p16:
11215       //   The object declared in an exception-declaration or, if the
11216       //   exception-declaration does not specify a name, a temporary (12.2) is
11217       //   copy-initialized (8.5) from the exception object. [...]
11218       //   The object is destroyed when the handler exits, after the destruction
11219       //   of any automatic objects initialized within the handler.
11220       //
11221       // We just pretend to initialize the object with itself, then make sure
11222       // it can be destroyed later.
11223       QualType initType = ExDeclType;
11224 
11225       InitializedEntity entity =
11226         InitializedEntity::InitializeVariable(ExDecl);
11227       InitializationKind initKind =
11228         InitializationKind::CreateCopy(Loc, SourceLocation());
11229 
11230       Expr *opaqueValue =
11231         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
11232       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11233       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
11234       if (result.isInvalid())
11235         Invalid = true;
11236       else {
11237         // If the constructor used was non-trivial, set this as the
11238         // "initializer".
11239         CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
11240         if (!construct->getConstructor()->isTrivial()) {
11241           Expr *init = MaybeCreateExprWithCleanups(construct);
11242           ExDecl->setInit(init);
11243         }
11244 
11245         // And make sure it's destructable.
11246         FinalizeVarWithDestructor(ExDecl, recordType);
11247       }
11248     }
11249   }
11250 
11251   if (Invalid)
11252     ExDecl->setInvalidDecl();
11253 
11254   return ExDecl;
11255 }
11256 
11257 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11258 /// handler.
11259 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
11260   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11261   bool Invalid = D.isInvalidType();
11262 
11263   // Check for unexpanded parameter packs.
11264   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11265                                       UPPC_ExceptionType)) {
11266     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11267                                              D.getIdentifierLoc());
11268     Invalid = true;
11269   }
11270 
11271   IdentifierInfo *II = D.getIdentifier();
11272   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11273                                              LookupOrdinaryName,
11274                                              ForRedeclaration)) {
11275     // The scope should be freshly made just for us. There is just no way
11276     // it contains any previous declaration.
11277     assert(!S->isDeclScope(PrevDecl));
11278     if (PrevDecl->isTemplateParameter()) {
11279       // Maybe we will complain about the shadowed template parameter.
11280       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11281       PrevDecl = 0;
11282     }
11283   }
11284 
11285   if (D.getCXXScopeSpec().isSet() && !Invalid) {
11286     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11287       << D.getCXXScopeSpec().getRange();
11288     Invalid = true;
11289   }
11290 
11291   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
11292                                               D.getLocStart(),
11293                                               D.getIdentifierLoc(),
11294                                               D.getIdentifier());
11295   if (Invalid)
11296     ExDecl->setInvalidDecl();
11297 
11298   // Add the exception declaration into this scope.
11299   if (II)
11300     PushOnScopeChains(ExDecl, S);
11301   else
11302     CurContext->addDecl(ExDecl);
11303 
11304   ProcessDeclAttributes(S, ExDecl, D);
11305   return ExDecl;
11306 }
11307 
11308 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11309                                          Expr *AssertExpr,
11310                                          Expr *AssertMessageExpr,
11311                                          SourceLocation RParenLoc) {
11312   StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
11313 
11314   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11315     return 0;
11316 
11317   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11318                                       AssertMessage, RParenLoc, false);
11319 }
11320 
11321 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11322                                          Expr *AssertExpr,
11323                                          StringLiteral *AssertMessage,
11324                                          SourceLocation RParenLoc,
11325                                          bool Failed) {
11326   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11327       !Failed) {
11328     // In a static_assert-declaration, the constant-expression shall be a
11329     // constant expression that can be contextually converted to bool.
11330     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11331     if (Converted.isInvalid())
11332       Failed = true;
11333 
11334     llvm::APSInt Cond;
11335     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
11336           diag::err_static_assert_expression_is_not_constant,
11337           /*AllowFold=*/false).isInvalid())
11338       Failed = true;
11339 
11340     if (!Failed && !Cond) {
11341       SmallString<256> MsgBuffer;
11342       llvm::raw_svector_ostream Msg(MsgBuffer);
11343       AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
11344       Diag(StaticAssertLoc, diag::err_static_assert_failed)
11345         << Msg.str() << AssertExpr->getSourceRange();
11346       Failed = true;
11347     }
11348   }
11349 
11350   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
11351                                         AssertExpr, AssertMessage, RParenLoc,
11352                                         Failed);
11353 
11354   CurContext->addDecl(Decl);
11355   return Decl;
11356 }
11357 
11358 /// \brief Perform semantic analysis of the given friend type declaration.
11359 ///
11360 /// \returns A friend declaration that.
11361 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
11362                                       SourceLocation FriendLoc,
11363                                       TypeSourceInfo *TSInfo) {
11364   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11365 
11366   QualType T = TSInfo->getType();
11367   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
11368 
11369   // C++03 [class.friend]p2:
11370   //   An elaborated-type-specifier shall be used in a friend declaration
11371   //   for a class.*
11372   //
11373   //   * The class-key of the elaborated-type-specifier is required.
11374   if (!ActiveTemplateInstantiations.empty()) {
11375     // Do not complain about the form of friend template types during
11376     // template instantiation; we will already have complained when the
11377     // template was declared.
11378   } else {
11379     if (!T->isElaboratedTypeSpecifier()) {
11380       // If we evaluated the type to a record type, suggest putting
11381       // a tag in front.
11382       if (const RecordType *RT = T->getAs<RecordType>()) {
11383         RecordDecl *RD = RT->getDecl();
11384 
11385         std::string InsertionText = std::string(" ") + RD->getKindName();
11386 
11387         Diag(TypeRange.getBegin(),
11388              getLangOpts().CPlusPlus11 ?
11389                diag::warn_cxx98_compat_unelaborated_friend_type :
11390                diag::ext_unelaborated_friend_type)
11391           << (unsigned) RD->getTagKind()
11392           << T
11393           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11394                                         InsertionText);
11395       } else {
11396         Diag(FriendLoc,
11397              getLangOpts().CPlusPlus11 ?
11398                diag::warn_cxx98_compat_nonclass_type_friend :
11399                diag::ext_nonclass_type_friend)
11400           << T
11401           << TypeRange;
11402       }
11403     } else if (T->getAs<EnumType>()) {
11404       Diag(FriendLoc,
11405            getLangOpts().CPlusPlus11 ?
11406              diag::warn_cxx98_compat_enum_friend :
11407              diag::ext_enum_friend)
11408         << T
11409         << TypeRange;
11410     }
11411 
11412     // C++11 [class.friend]p3:
11413     //   A friend declaration that does not declare a function shall have one
11414     //   of the following forms:
11415     //     friend elaborated-type-specifier ;
11416     //     friend simple-type-specifier ;
11417     //     friend typename-specifier ;
11418     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11419       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11420   }
11421 
11422   //   If the type specifier in a friend declaration designates a (possibly
11423   //   cv-qualified) class type, that class is declared as a friend; otherwise,
11424   //   the friend declaration is ignored.
11425   return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
11426 }
11427 
11428 /// Handle a friend tag declaration where the scope specifier was
11429 /// templated.
11430 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11431                                     unsigned TagSpec, SourceLocation TagLoc,
11432                                     CXXScopeSpec &SS,
11433                                     IdentifierInfo *Name,
11434                                     SourceLocation NameLoc,
11435                                     AttributeList *Attr,
11436                                     MultiTemplateParamsArg TempParamLists) {
11437   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11438 
11439   bool isExplicitSpecialization = false;
11440   bool Invalid = false;
11441 
11442   if (TemplateParameterList *TemplateParams =
11443           MatchTemplateParametersToScopeSpecifier(
11444               TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11445               isExplicitSpecialization, Invalid)) {
11446     if (TemplateParams->size() > 0) {
11447       // This is a declaration of a class template.
11448       if (Invalid)
11449         return 0;
11450 
11451       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11452                                 SS, Name, NameLoc, Attr,
11453                                 TemplateParams, AS_public,
11454                                 /*ModulePrivateLoc=*/SourceLocation(),
11455                                 TempParamLists.size() - 1,
11456                                 TempParamLists.data()).take();
11457     } else {
11458       // The "template<>" header is extraneous.
11459       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11460         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11461       isExplicitSpecialization = true;
11462     }
11463   }
11464 
11465   if (Invalid) return 0;
11466 
11467   bool isAllExplicitSpecializations = true;
11468   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
11469     if (TempParamLists[I]->size()) {
11470       isAllExplicitSpecializations = false;
11471       break;
11472     }
11473   }
11474 
11475   // FIXME: don't ignore attributes.
11476 
11477   // If it's explicit specializations all the way down, just forget
11478   // about the template header and build an appropriate non-templated
11479   // friend.  TODO: for source fidelity, remember the headers.
11480   if (isAllExplicitSpecializations) {
11481     if (SS.isEmpty()) {
11482       bool Owned = false;
11483       bool IsDependent = false;
11484       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11485                       Attr, AS_public,
11486                       /*ModulePrivateLoc=*/SourceLocation(),
11487                       MultiTemplateParamsArg(), Owned, IsDependent,
11488                       /*ScopedEnumKWLoc=*/SourceLocation(),
11489                       /*ScopedEnumUsesClassTag=*/false,
11490                       /*UnderlyingType=*/TypeResult(),
11491                       /*IsTypeSpecifier=*/false);
11492     }
11493 
11494     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11495     ElaboratedTypeKeyword Keyword
11496       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11497     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
11498                                    *Name, NameLoc);
11499     if (T.isNull())
11500       return 0;
11501 
11502     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11503     if (isa<DependentNameType>(T)) {
11504       DependentNameTypeLoc TL =
11505           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11506       TL.setElaboratedKeywordLoc(TagLoc);
11507       TL.setQualifierLoc(QualifierLoc);
11508       TL.setNameLoc(NameLoc);
11509     } else {
11510       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
11511       TL.setElaboratedKeywordLoc(TagLoc);
11512       TL.setQualifierLoc(QualifierLoc);
11513       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
11514     }
11515 
11516     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11517                                             TSI, FriendLoc, TempParamLists);
11518     Friend->setAccess(AS_public);
11519     CurContext->addDecl(Friend);
11520     return Friend;
11521   }
11522 
11523   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11524 
11525 
11526 
11527   // Handle the case of a templated-scope friend class.  e.g.
11528   //   template <class T> class A<T>::B;
11529   // FIXME: we don't support these right now.
11530   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11531     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
11532   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11533   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11534   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11535   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11536   TL.setElaboratedKeywordLoc(TagLoc);
11537   TL.setQualifierLoc(SS.getWithLocInContext(Context));
11538   TL.setNameLoc(NameLoc);
11539 
11540   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11541                                           TSI, FriendLoc, TempParamLists);
11542   Friend->setAccess(AS_public);
11543   Friend->setUnsupportedFriend(true);
11544   CurContext->addDecl(Friend);
11545   return Friend;
11546 }
11547 
11548 
11549 /// Handle a friend type declaration.  This works in tandem with
11550 /// ActOnTag.
11551 ///
11552 /// Notes on friend class templates:
11553 ///
11554 /// We generally treat friend class declarations as if they were
11555 /// declaring a class.  So, for example, the elaborated type specifier
11556 /// in a friend declaration is required to obey the restrictions of a
11557 /// class-head (i.e. no typedefs in the scope chain), template
11558 /// parameters are required to match up with simple template-ids, &c.
11559 /// However, unlike when declaring a template specialization, it's
11560 /// okay to refer to a template specialization without an empty
11561 /// template parameter declaration, e.g.
11562 ///   friend class A<T>::B<unsigned>;
11563 /// We permit this as a special case; if there are any template
11564 /// parameters present at all, require proper matching, i.e.
11565 ///   template <> template \<class T> friend class A<int>::B;
11566 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
11567                                 MultiTemplateParamsArg TempParams) {
11568   SourceLocation Loc = DS.getLocStart();
11569 
11570   assert(DS.isFriendSpecified());
11571   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11572 
11573   // Try to convert the decl specifier to a type.  This works for
11574   // friend templates because ActOnTag never produces a ClassTemplateDecl
11575   // for a TUK_Friend.
11576   Declarator TheDeclarator(DS, Declarator::MemberContext);
11577   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11578   QualType T = TSI->getType();
11579   if (TheDeclarator.isInvalidType())
11580     return 0;
11581 
11582   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11583     return 0;
11584 
11585   // This is definitely an error in C++98.  It's probably meant to
11586   // be forbidden in C++0x, too, but the specification is just
11587   // poorly written.
11588   //
11589   // The problem is with declarations like the following:
11590   //   template <T> friend A<T>::foo;
11591   // where deciding whether a class C is a friend or not now hinges
11592   // on whether there exists an instantiation of A that causes
11593   // 'foo' to equal C.  There are restrictions on class-heads
11594   // (which we declare (by fiat) elaborated friend declarations to
11595   // be) that makes this tractable.
11596   //
11597   // FIXME: handle "template <> friend class A<T>;", which
11598   // is possibly well-formed?  Who even knows?
11599   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
11600     Diag(Loc, diag::err_tagless_friend_type_template)
11601       << DS.getSourceRange();
11602     return 0;
11603   }
11604 
11605   // C++98 [class.friend]p1: A friend of a class is a function
11606   //   or class that is not a member of the class . . .
11607   // This is fixed in DR77, which just barely didn't make the C++03
11608   // deadline.  It's also a very silly restriction that seriously
11609   // affects inner classes and which nobody else seems to implement;
11610   // thus we never diagnose it, not even in -pedantic.
11611   //
11612   // But note that we could warn about it: it's always useless to
11613   // friend one of your own members (it's not, however, worthless to
11614   // friend a member of an arbitrary specialization of your template).
11615 
11616   Decl *D;
11617   if (unsigned NumTempParamLists = TempParams.size())
11618     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
11619                                    NumTempParamLists,
11620                                    TempParams.data(),
11621                                    TSI,
11622                                    DS.getFriendSpecLoc());
11623   else
11624     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
11625 
11626   if (!D)
11627     return 0;
11628 
11629   D->setAccess(AS_public);
11630   CurContext->addDecl(D);
11631 
11632   return D;
11633 }
11634 
11635 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11636                                         MultiTemplateParamsArg TemplateParams) {
11637   const DeclSpec &DS = D.getDeclSpec();
11638 
11639   assert(DS.isFriendSpecified());
11640   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11641 
11642   SourceLocation Loc = D.getIdentifierLoc();
11643   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11644 
11645   // C++ [class.friend]p1
11646   //   A friend of a class is a function or class....
11647   // Note that this sees through typedefs, which is intended.
11648   // It *doesn't* see through dependent types, which is correct
11649   // according to [temp.arg.type]p3:
11650   //   If a declaration acquires a function type through a
11651   //   type dependent on a template-parameter and this causes
11652   //   a declaration that does not use the syntactic form of a
11653   //   function declarator to have a function type, the program
11654   //   is ill-formed.
11655   if (!TInfo->getType()->isFunctionType()) {
11656     Diag(Loc, diag::err_unexpected_friend);
11657 
11658     // It might be worthwhile to try to recover by creating an
11659     // appropriate declaration.
11660     return 0;
11661   }
11662 
11663   // C++ [namespace.memdef]p3
11664   //  - If a friend declaration in a non-local class first declares a
11665   //    class or function, the friend class or function is a member
11666   //    of the innermost enclosing namespace.
11667   //  - The name of the friend is not found by simple name lookup
11668   //    until a matching declaration is provided in that namespace
11669   //    scope (either before or after the class declaration granting
11670   //    friendship).
11671   //  - If a friend function is called, its name may be found by the
11672   //    name lookup that considers functions from namespaces and
11673   //    classes associated with the types of the function arguments.
11674   //  - When looking for a prior declaration of a class or a function
11675   //    declared as a friend, scopes outside the innermost enclosing
11676   //    namespace scope are not considered.
11677 
11678   CXXScopeSpec &SS = D.getCXXScopeSpec();
11679   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11680   DeclarationName Name = NameInfo.getName();
11681   assert(Name);
11682 
11683   // Check for unexpanded parameter packs.
11684   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11685       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11686       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11687     return 0;
11688 
11689   // The context we found the declaration in, or in which we should
11690   // create the declaration.
11691   DeclContext *DC;
11692   Scope *DCScope = S;
11693   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
11694                         ForRedeclaration);
11695 
11696   // There are five cases here.
11697   //   - There's no scope specifier and we're in a local class. Only look
11698   //     for functions declared in the immediately-enclosing block scope.
11699   // We recover from invalid scope qualifiers as if they just weren't there.
11700   FunctionDecl *FunctionContainingLocalClass = 0;
11701   if ((SS.isInvalid() || !SS.isSet()) &&
11702       (FunctionContainingLocalClass =
11703            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11704     // C++11 [class.friend]p11:
11705     //   If a friend declaration appears in a local class and the name
11706     //   specified is an unqualified name, a prior declaration is
11707     //   looked up without considering scopes that are outside the
11708     //   innermost enclosing non-class scope. For a friend function
11709     //   declaration, if there is no prior declaration, the program is
11710     //   ill-formed.
11711 
11712     // Find the innermost enclosing non-class scope. This is the block
11713     // scope containing the local class definition (or for a nested class,
11714     // the outer local class).
11715     DCScope = S->getFnParent();
11716 
11717     // Look up the function name in the scope.
11718     Previous.clear(LookupLocalFriendName);
11719     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11720 
11721     if (!Previous.empty()) {
11722       // All possible previous declarations must have the same context:
11723       // either they were declared at block scope or they are members of
11724       // one of the enclosing local classes.
11725       DC = Previous.getRepresentativeDecl()->getDeclContext();
11726     } else {
11727       // This is ill-formed, but provide the context that we would have
11728       // declared the function in, if we were permitted to, for error recovery.
11729       DC = FunctionContainingLocalClass;
11730     }
11731     adjustContextForLocalExternDecl(DC);
11732 
11733     // C++ [class.friend]p6:
11734     //   A function can be defined in a friend declaration of a class if and
11735     //   only if the class is a non-local class (9.8), the function name is
11736     //   unqualified, and the function has namespace scope.
11737     if (D.isFunctionDefinition()) {
11738       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11739     }
11740 
11741   //   - There's no scope specifier, in which case we just go to the
11742   //     appropriate scope and look for a function or function template
11743   //     there as appropriate.
11744   } else if (SS.isInvalid() || !SS.isSet()) {
11745     // C++11 [namespace.memdef]p3:
11746     //   If the name in a friend declaration is neither qualified nor
11747     //   a template-id and the declaration is a function or an
11748     //   elaborated-type-specifier, the lookup to determine whether
11749     //   the entity has been previously declared shall not consider
11750     //   any scopes outside the innermost enclosing namespace.
11751     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
11752 
11753     // Find the appropriate context according to the above.
11754     DC = CurContext;
11755 
11756     // Skip class contexts.  If someone can cite chapter and verse
11757     // for this behavior, that would be nice --- it's what GCC and
11758     // EDG do, and it seems like a reasonable intent, but the spec
11759     // really only says that checks for unqualified existing
11760     // declarations should stop at the nearest enclosing namespace,
11761     // not that they should only consider the nearest enclosing
11762     // namespace.
11763     while (DC->isRecord())
11764       DC = DC->getParent();
11765 
11766     DeclContext *LookupDC = DC;
11767     while (LookupDC->isTransparentContext())
11768       LookupDC = LookupDC->getParent();
11769 
11770     while (true) {
11771       LookupQualifiedName(Previous, LookupDC);
11772 
11773       if (!Previous.empty()) {
11774         DC = LookupDC;
11775         break;
11776       }
11777 
11778       if (isTemplateId) {
11779         if (isa<TranslationUnitDecl>(LookupDC)) break;
11780       } else {
11781         if (LookupDC->isFileContext()) break;
11782       }
11783       LookupDC = LookupDC->getParent();
11784     }
11785 
11786     DCScope = getScopeForDeclContext(S, DC);
11787 
11788   //   - There's a non-dependent scope specifier, in which case we
11789   //     compute it and do a previous lookup there for a function
11790   //     or function template.
11791   } else if (!SS.getScopeRep()->isDependent()) {
11792     DC = computeDeclContext(SS);
11793     if (!DC) return 0;
11794 
11795     if (RequireCompleteDeclContext(SS, DC)) return 0;
11796 
11797     LookupQualifiedName(Previous, DC);
11798 
11799     // Ignore things found implicitly in the wrong scope.
11800     // TODO: better diagnostics for this case.  Suggesting the right
11801     // qualified scope would be nice...
11802     LookupResult::Filter F = Previous.makeFilter();
11803     while (F.hasNext()) {
11804       NamedDecl *D = F.next();
11805       if (!DC->InEnclosingNamespaceSetOf(
11806               D->getDeclContext()->getRedeclContext()))
11807         F.erase();
11808     }
11809     F.done();
11810 
11811     if (Previous.empty()) {
11812       D.setInvalidType();
11813       Diag(Loc, diag::err_qualified_friend_not_found)
11814           << Name << TInfo->getType();
11815       return 0;
11816     }
11817 
11818     // C++ [class.friend]p1: A friend of a class is a function or
11819     //   class that is not a member of the class . . .
11820     if (DC->Equals(CurContext))
11821       Diag(DS.getFriendSpecLoc(),
11822            getLangOpts().CPlusPlus11 ?
11823              diag::warn_cxx98_compat_friend_is_member :
11824              diag::err_friend_is_member);
11825 
11826     if (D.isFunctionDefinition()) {
11827       // C++ [class.friend]p6:
11828       //   A function can be defined in a friend declaration of a class if and
11829       //   only if the class is a non-local class (9.8), the function name is
11830       //   unqualified, and the function has namespace scope.
11831       SemaDiagnosticBuilder DB
11832         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11833 
11834       DB << SS.getScopeRep();
11835       if (DC->isFileContext())
11836         DB << FixItHint::CreateRemoval(SS.getRange());
11837       SS.clear();
11838     }
11839 
11840   //   - There's a scope specifier that does not match any template
11841   //     parameter lists, in which case we use some arbitrary context,
11842   //     create a method or method template, and wait for instantiation.
11843   //   - There's a scope specifier that does match some template
11844   //     parameter lists, which we don't handle right now.
11845   } else {
11846     if (D.isFunctionDefinition()) {
11847       // C++ [class.friend]p6:
11848       //   A function can be defined in a friend declaration of a class if and
11849       //   only if the class is a non-local class (9.8), the function name is
11850       //   unqualified, and the function has namespace scope.
11851       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11852         << SS.getScopeRep();
11853     }
11854 
11855     DC = CurContext;
11856     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
11857   }
11858 
11859   if (!DC->isRecord()) {
11860     // This implies that it has to be an operator or function.
11861     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11862         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11863         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
11864       Diag(Loc, diag::err_introducing_special_friend) <<
11865         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11866          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
11867       return 0;
11868     }
11869   }
11870 
11871   // FIXME: This is an egregious hack to cope with cases where the scope stack
11872   // does not contain the declaration context, i.e., in an out-of-line
11873   // definition of a class.
11874   Scope FakeDCScope(S, Scope::DeclScope, Diags);
11875   if (!DCScope) {
11876     FakeDCScope.setEntity(DC);
11877     DCScope = &FakeDCScope;
11878   }
11879 
11880   bool AddToScope = true;
11881   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
11882                                           TemplateParams, AddToScope);
11883   if (!ND) return 0;
11884 
11885   assert(ND->getLexicalDeclContext() == CurContext);
11886 
11887   // If we performed typo correction, we might have added a scope specifier
11888   // and changed the decl context.
11889   DC = ND->getDeclContext();
11890 
11891   // Add the function declaration to the appropriate lookup tables,
11892   // adjusting the redeclarations list as necessary.  We don't
11893   // want to do this yet if the friending class is dependent.
11894   //
11895   // Also update the scope-based lookup if the target context's
11896   // lookup context is in lexical scope.
11897   if (!CurContext->isDependentContext()) {
11898     DC = DC->getRedeclContext();
11899     DC->makeDeclVisibleInContext(ND);
11900     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11901       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
11902   }
11903 
11904   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
11905                                        D.getIdentifierLoc(), ND,
11906                                        DS.getFriendSpecLoc());
11907   FrD->setAccess(AS_public);
11908   CurContext->addDecl(FrD);
11909 
11910   if (ND->isInvalidDecl()) {
11911     FrD->setInvalidDecl();
11912   } else {
11913     if (DC->isRecord()) CheckFriendAccess(ND);
11914 
11915     FunctionDecl *FD;
11916     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11917       FD = FTD->getTemplatedDecl();
11918     else
11919       FD = cast<FunctionDecl>(ND);
11920 
11921     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11922     // default argument expression, that declaration shall be a definition
11923     // and shall be the only declaration of the function or function
11924     // template in the translation unit.
11925     if (functionDeclHasDefaultArgument(FD)) {
11926       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11927         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11928         Diag(OldFD->getLocation(), diag::note_previous_declaration);
11929       } else if (!D.isFunctionDefinition())
11930         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11931     }
11932 
11933     // Mark templated-scope function declarations as unsupported.
11934     if (FD->getNumTemplateParameterLists())
11935       FrD->setUnsupportedFriend(true);
11936   }
11937 
11938   return ND;
11939 }
11940 
11941 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11942   AdjustDeclIfTemplate(Dcl);
11943 
11944   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
11945   if (!Fn) {
11946     Diag(DelLoc, diag::err_deleted_non_function);
11947     return;
11948   }
11949 
11950   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
11951     // Don't consider the implicit declaration we generate for explicit
11952     // specializations. FIXME: Do not generate these implicit declarations.
11953     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
11954          Prev->getPreviousDecl()) &&
11955         !Prev->isDefined()) {
11956       Diag(DelLoc, diag::err_deleted_decl_not_first);
11957       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
11958            Prev->isImplicit() ? diag::note_previous_implicit_declaration
11959                               : diag::note_previous_declaration);
11960     }
11961     // If the declaration wasn't the first, we delete the function anyway for
11962     // recovery.
11963     Fn = Fn->getCanonicalDecl();
11964   }
11965 
11966   if (Fn->isDeleted())
11967     return;
11968 
11969   // See if we're deleting a function which is already known to override a
11970   // non-deleted virtual function.
11971   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11972     bool IssuedDiagnostic = false;
11973     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11974                                         E = MD->end_overridden_methods();
11975          I != E; ++I) {
11976       if (!(*MD->begin_overridden_methods())->isDeleted()) {
11977         if (!IssuedDiagnostic) {
11978           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11979           IssuedDiagnostic = true;
11980         }
11981         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11982       }
11983     }
11984   }
11985 
11986   // C++11 [basic.start.main]p3:
11987   //   A program that defines main as deleted [...] is ill-formed.
11988   if (Fn->isMain())
11989     Diag(DelLoc, diag::err_deleted_main);
11990 
11991   Fn->setDeletedAsWritten();
11992 }
11993 
11994 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
11995   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
11996 
11997   if (MD) {
11998     if (MD->getParent()->isDependentType()) {
11999       MD->setDefaulted();
12000       MD->setExplicitlyDefaulted();
12001       return;
12002     }
12003 
12004     CXXSpecialMember Member = getSpecialMember(MD);
12005     if (Member == CXXInvalid) {
12006       if (!MD->isInvalidDecl())
12007         Diag(DefaultLoc, diag::err_default_special_members);
12008       return;
12009     }
12010 
12011     MD->setDefaulted();
12012     MD->setExplicitlyDefaulted();
12013 
12014     // If this definition appears within the record, do the checking when
12015     // the record is complete.
12016     const FunctionDecl *Primary = MD;
12017     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12018       // Find the uninstantiated declaration that actually had the '= default'
12019       // on it.
12020       Pattern->isDefined(Primary);
12021 
12022     // If the method was defaulted on its first declaration, we will have
12023     // already performed the checking in CheckCompletedCXXClass. Such a
12024     // declaration doesn't trigger an implicit definition.
12025     if (Primary == Primary->getCanonicalDecl())
12026       return;
12027 
12028     CheckExplicitlyDefaultedSpecialMember(MD);
12029 
12030     // The exception specification is needed because we are defining the
12031     // function.
12032     ResolveExceptionSpec(DefaultLoc,
12033                          MD->getType()->castAs<FunctionProtoType>());
12034 
12035     if (MD->isInvalidDecl())
12036       return;
12037 
12038     switch (Member) {
12039     case CXXDefaultConstructor:
12040       DefineImplicitDefaultConstructor(DefaultLoc,
12041                                        cast<CXXConstructorDecl>(MD));
12042       break;
12043     case CXXCopyConstructor:
12044       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12045       break;
12046     case CXXCopyAssignment:
12047       DefineImplicitCopyAssignment(DefaultLoc, MD);
12048       break;
12049     case CXXDestructor:
12050       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12051       break;
12052     case CXXMoveConstructor:
12053       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12054       break;
12055     case CXXMoveAssignment:
12056       DefineImplicitMoveAssignment(DefaultLoc, MD);
12057       break;
12058     case CXXInvalid:
12059       llvm_unreachable("Invalid special member.");
12060     }
12061   } else {
12062     Diag(DefaultLoc, diag::err_default_special_members);
12063   }
12064 }
12065 
12066 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12067   for (Stmt::child_range CI = S->children(); CI; ++CI) {
12068     Stmt *SubStmt = *CI;
12069     if (!SubStmt)
12070       continue;
12071     if (isa<ReturnStmt>(SubStmt))
12072       Self.Diag(SubStmt->getLocStart(),
12073            diag::err_return_in_constructor_handler);
12074     if (!isa<Expr>(SubStmt))
12075       SearchForReturnInStmt(Self, SubStmt);
12076   }
12077 }
12078 
12079 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12080   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12081     CXXCatchStmt *Handler = TryBlock->getHandler(I);
12082     SearchForReturnInStmt(*this, Handler);
12083   }
12084 }
12085 
12086 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12087                                              const CXXMethodDecl *Old) {
12088   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12089   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12090 
12091   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12092 
12093   // If the calling conventions match, everything is fine
12094   if (NewCC == OldCC)
12095     return false;
12096 
12097   // If the calling conventions mismatch because the new function is static,
12098   // suppress the calling convention mismatch error; the error about static
12099   // function override (err_static_overrides_virtual from
12100   // Sema::CheckFunctionDeclaration) is more clear.
12101   if (New->getStorageClass() == SC_Static)
12102     return false;
12103 
12104   Diag(New->getLocation(),
12105        diag::err_conflicting_overriding_cc_attributes)
12106     << New->getDeclName() << New->getType() << Old->getType();
12107   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12108   return true;
12109 }
12110 
12111 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12112                                              const CXXMethodDecl *Old) {
12113   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12114   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12115 
12116   if (Context.hasSameType(NewTy, OldTy) ||
12117       NewTy->isDependentType() || OldTy->isDependentType())
12118     return false;
12119 
12120   // Check if the return types are covariant
12121   QualType NewClassTy, OldClassTy;
12122 
12123   /// Both types must be pointers or references to classes.
12124   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12125     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12126       NewClassTy = NewPT->getPointeeType();
12127       OldClassTy = OldPT->getPointeeType();
12128     }
12129   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12130     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12131       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12132         NewClassTy = NewRT->getPointeeType();
12133         OldClassTy = OldRT->getPointeeType();
12134       }
12135     }
12136   }
12137 
12138   // The return types aren't either both pointers or references to a class type.
12139   if (NewClassTy.isNull()) {
12140     Diag(New->getLocation(),
12141          diag::err_different_return_type_for_overriding_virtual_function)
12142       << New->getDeclName() << NewTy << OldTy;
12143     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12144 
12145     return true;
12146   }
12147 
12148   // C++ [class.virtual]p6:
12149   //   If the return type of D::f differs from the return type of B::f, the
12150   //   class type in the return type of D::f shall be complete at the point of
12151   //   declaration of D::f or shall be the class type D.
12152   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12153     if (!RT->isBeingDefined() &&
12154         RequireCompleteType(New->getLocation(), NewClassTy,
12155                             diag::err_covariant_return_incomplete,
12156                             New->getDeclName()))
12157     return true;
12158   }
12159 
12160   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12161     // Check if the new class derives from the old class.
12162     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12163       Diag(New->getLocation(),
12164            diag::err_covariant_return_not_derived)
12165       << New->getDeclName() << NewTy << OldTy;
12166       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12167       return true;
12168     }
12169 
12170     // Check if we the conversion from derived to base is valid.
12171     if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
12172                     diag::err_covariant_return_inaccessible_base,
12173                     diag::err_covariant_return_ambiguous_derived_to_base_conv,
12174                     // FIXME: Should this point to the return type?
12175                     New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
12176       // FIXME: this note won't trigger for delayed access control
12177       // diagnostics, and it's impossible to get an undelayed error
12178       // here from access control during the original parse because
12179       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
12180       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12181       return true;
12182     }
12183   }
12184 
12185   // The qualifiers of the return types must be the same.
12186   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
12187     Diag(New->getLocation(),
12188          diag::err_covariant_return_type_different_qualifications)
12189     << New->getDeclName() << NewTy << OldTy;
12190     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12191     return true;
12192   };
12193 
12194 
12195   // The new class type must have the same or less qualifiers as the old type.
12196   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12197     Diag(New->getLocation(),
12198          diag::err_covariant_return_type_class_type_more_qualified)
12199     << New->getDeclName() << NewTy << OldTy;
12200     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12201     return true;
12202   };
12203 
12204   return false;
12205 }
12206 
12207 /// \brief Mark the given method pure.
12208 ///
12209 /// \param Method the method to be marked pure.
12210 ///
12211 /// \param InitRange the source range that covers the "0" initializer.
12212 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
12213   SourceLocation EndLoc = InitRange.getEnd();
12214   if (EndLoc.isValid())
12215     Method->setRangeEnd(EndLoc);
12216 
12217   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12218     Method->setPure();
12219     return false;
12220   }
12221 
12222   if (!Method->isInvalidDecl())
12223     Diag(Method->getLocation(), diag::err_non_virtual_pure)
12224       << Method->getDeclName() << InitRange;
12225   return true;
12226 }
12227 
12228 /// \brief Determine whether the given declaration is a static data member.
12229 static bool isStaticDataMember(const Decl *D) {
12230   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12231     return Var->isStaticDataMember();
12232 
12233   return false;
12234 }
12235 
12236 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12237 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
12238 /// is a fresh scope pushed for just this purpose.
12239 ///
12240 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12241 /// static data member of class X, names should be looked up in the scope of
12242 /// class X.
12243 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
12244   // If there is no declaration, there was an error parsing it.
12245   if (D == 0 || D->isInvalidDecl()) return;
12246 
12247   // We will always have a nested name specifier here, but this declaration
12248   // might not be out of line if the specifier names the current namespace:
12249   //   extern int n;
12250   //   int ::n = 0;
12251   if (D->isOutOfLine())
12252     EnterDeclaratorContext(S, D->getDeclContext());
12253 
12254   // If we are parsing the initializer for a static data member, push a
12255   // new expression evaluation context that is associated with this static
12256   // data member.
12257   if (isStaticDataMember(D))
12258     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
12259 }
12260 
12261 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
12262 /// initializer for the out-of-line declaration 'D'.
12263 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
12264   // If there is no declaration, there was an error parsing it.
12265   if (D == 0 || D->isInvalidDecl()) return;
12266 
12267   if (isStaticDataMember(D))
12268     PopExpressionEvaluationContext();
12269 
12270   if (D->isOutOfLine())
12271     ExitDeclaratorContext(S);
12272 }
12273 
12274 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12275 /// C++ if/switch/while/for statement.
12276 /// e.g: "if (int x = f()) {...}"
12277 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
12278   // C++ 6.4p2:
12279   // The declarator shall not specify a function or an array.
12280   // The type-specifier-seq shall not contain typedef and shall not declare a
12281   // new class or enumeration.
12282   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12283          "Parser allowed 'typedef' as storage class of condition decl.");
12284 
12285   Decl *Dcl = ActOnDeclarator(S, D);
12286   if (!Dcl)
12287     return true;
12288 
12289   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12290     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
12291       << D.getSourceRange();
12292     return true;
12293   }
12294 
12295   return Dcl;
12296 }
12297 
12298 void Sema::LoadExternalVTableUses() {
12299   if (!ExternalSource)
12300     return;
12301 
12302   SmallVector<ExternalVTableUse, 4> VTables;
12303   ExternalSource->ReadUsedVTables(VTables);
12304   SmallVector<VTableUse, 4> NewUses;
12305   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12306     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12307       = VTablesUsed.find(VTables[I].Record);
12308     // Even if a definition wasn't required before, it may be required now.
12309     if (Pos != VTablesUsed.end()) {
12310       if (!Pos->second && VTables[I].DefinitionRequired)
12311         Pos->second = true;
12312       continue;
12313     }
12314 
12315     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12316     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12317   }
12318 
12319   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12320 }
12321 
12322 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12323                           bool DefinitionRequired) {
12324   // Ignore any vtable uses in unevaluated operands or for classes that do
12325   // not have a vtable.
12326   if (!Class->isDynamicClass() || Class->isDependentContext() ||
12327       CurContext->isDependentContext() || isUnevaluatedContext())
12328     return;
12329 
12330   // Try to insert this class into the map.
12331   LoadExternalVTableUses();
12332   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12333   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12334     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12335   if (!Pos.second) {
12336     // If we already had an entry, check to see if we are promoting this vtable
12337     // to required a definition. If so, we need to reappend to the VTableUses
12338     // list, since we may have already processed the first entry.
12339     if (DefinitionRequired && !Pos.first->second) {
12340       Pos.first->second = true;
12341     } else {
12342       // Otherwise, we can early exit.
12343       return;
12344     }
12345   } else {
12346     // The Microsoft ABI requires that we perform the destructor body
12347     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12348     // the deleting destructor is emitted with the vtable, not with the
12349     // destructor definition as in the Itanium ABI.
12350     // If it has a definition, we do the check at that point instead.
12351     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12352         Class->hasUserDeclaredDestructor() &&
12353         !Class->getDestructor()->isDefined() &&
12354         !Class->getDestructor()->isDeleted()) {
12355       CheckDestructor(Class->getDestructor());
12356     }
12357   }
12358 
12359   // Local classes need to have their virtual members marked
12360   // immediately. For all other classes, we mark their virtual members
12361   // at the end of the translation unit.
12362   if (Class->isLocalClass())
12363     MarkVirtualMembersReferenced(Loc, Class);
12364   else
12365     VTableUses.push_back(std::make_pair(Class, Loc));
12366 }
12367 
12368 bool Sema::DefineUsedVTables() {
12369   LoadExternalVTableUses();
12370   if (VTableUses.empty())
12371     return false;
12372 
12373   // Note: The VTableUses vector could grow as a result of marking
12374   // the members of a class as "used", so we check the size each
12375   // time through the loop and prefer indices (which are stable) to
12376   // iterators (which are not).
12377   bool DefinedAnything = false;
12378   for (unsigned I = 0; I != VTableUses.size(); ++I) {
12379     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
12380     if (!Class)
12381       continue;
12382 
12383     SourceLocation Loc = VTableUses[I].second;
12384 
12385     bool DefineVTable = true;
12386 
12387     // If this class has a key function, but that key function is
12388     // defined in another translation unit, we don't need to emit the
12389     // vtable even though we're using it.
12390     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
12391     if (KeyFunction && !KeyFunction->hasBody()) {
12392       // The key function is in another translation unit.
12393       DefineVTable = false;
12394       TemplateSpecializationKind TSK =
12395           KeyFunction->getTemplateSpecializationKind();
12396       assert(TSK != TSK_ExplicitInstantiationDefinition &&
12397              TSK != TSK_ImplicitInstantiation &&
12398              "Instantiations don't have key functions");
12399       (void)TSK;
12400     } else if (!KeyFunction) {
12401       // If we have a class with no key function that is the subject
12402       // of an explicit instantiation declaration, suppress the
12403       // vtable; it will live with the explicit instantiation
12404       // definition.
12405       bool IsExplicitInstantiationDeclaration
12406         = Class->getTemplateSpecializationKind()
12407                                       == TSK_ExplicitInstantiationDeclaration;
12408       for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12409                                  REnd = Class->redecls_end();
12410            R != REnd; ++R) {
12411         TemplateSpecializationKind TSK
12412           = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12413         if (TSK == TSK_ExplicitInstantiationDeclaration)
12414           IsExplicitInstantiationDeclaration = true;
12415         else if (TSK == TSK_ExplicitInstantiationDefinition) {
12416           IsExplicitInstantiationDeclaration = false;
12417           break;
12418         }
12419       }
12420 
12421       if (IsExplicitInstantiationDeclaration)
12422         DefineVTable = false;
12423     }
12424 
12425     // The exception specifications for all virtual members may be needed even
12426     // if we are not providing an authoritative form of the vtable in this TU.
12427     // We may choose to emit it available_externally anyway.
12428     if (!DefineVTable) {
12429       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12430       continue;
12431     }
12432 
12433     // Mark all of the virtual members of this class as referenced, so
12434     // that we can build a vtable. Then, tell the AST consumer that a
12435     // vtable for this class is required.
12436     DefinedAnything = true;
12437     MarkVirtualMembersReferenced(Loc, Class);
12438     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12439     Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12440 
12441     // Optionally warn if we're emitting a weak vtable.
12442     if (Class->isExternallyVisible() &&
12443         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
12444       const FunctionDecl *KeyFunctionDef = 0;
12445       if (!KeyFunction ||
12446           (KeyFunction->hasBody(KeyFunctionDef) &&
12447            KeyFunctionDef->isInlined()))
12448         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12449              TSK_ExplicitInstantiationDefinition
12450              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12451           << Class;
12452     }
12453   }
12454   VTableUses.clear();
12455 
12456   return DefinedAnything;
12457 }
12458 
12459 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12460                                                  const CXXRecordDecl *RD) {
12461   for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12462                                       E = RD->method_end(); I != E; ++I)
12463     if ((*I)->isVirtual() && !(*I)->isPure())
12464       ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12465 }
12466 
12467 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12468                                         const CXXRecordDecl *RD) {
12469   // Mark all functions which will appear in RD's vtable as used.
12470   CXXFinalOverriderMap FinalOverriders;
12471   RD->getFinalOverriders(FinalOverriders);
12472   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12473                                             E = FinalOverriders.end();
12474        I != E; ++I) {
12475     for (OverridingMethods::const_iterator OI = I->second.begin(),
12476                                            OE = I->second.end();
12477          OI != OE; ++OI) {
12478       assert(OI->second.size() > 0 && "no final overrider");
12479       CXXMethodDecl *Overrider = OI->second.front().Method;
12480 
12481       // C++ [basic.def.odr]p2:
12482       //   [...] A virtual member function is used if it is not pure. [...]
12483       if (!Overrider->isPure())
12484         MarkFunctionReferenced(Loc, Overrider);
12485     }
12486   }
12487 
12488   // Only classes that have virtual bases need a VTT.
12489   if (RD->getNumVBases() == 0)
12490     return;
12491 
12492   for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12493            e = RD->bases_end(); i != e; ++i) {
12494     const CXXRecordDecl *Base =
12495         cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
12496     if (Base->getNumVBases() == 0)
12497       continue;
12498     MarkVirtualMembersReferenced(Loc, Base);
12499   }
12500 }
12501 
12502 /// SetIvarInitializers - This routine builds initialization ASTs for the
12503 /// Objective-C implementation whose ivars need be initialized.
12504 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
12505   if (!getLangOpts().CPlusPlus)
12506     return;
12507   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
12508     SmallVector<ObjCIvarDecl*, 8> ivars;
12509     CollectIvarsToConstructOrDestruct(OID, ivars);
12510     if (ivars.empty())
12511       return;
12512     SmallVector<CXXCtorInitializer*, 32> AllToInit;
12513     for (unsigned i = 0; i < ivars.size(); i++) {
12514       FieldDecl *Field = ivars[i];
12515       if (Field->isInvalidDecl())
12516         continue;
12517 
12518       CXXCtorInitializer *Member;
12519       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12520       InitializationKind InitKind =
12521         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
12522 
12523       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12524       ExprResult MemberInit =
12525         InitSeq.Perform(*this, InitEntity, InitKind, None);
12526       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
12527       // Note, MemberInit could actually come back empty if no initialization
12528       // is required (e.g., because it would call a trivial default constructor)
12529       if (!MemberInit.get() || MemberInit.isInvalid())
12530         continue;
12531 
12532       Member =
12533         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12534                                          SourceLocation(),
12535                                          MemberInit.takeAs<Expr>(),
12536                                          SourceLocation());
12537       AllToInit.push_back(Member);
12538 
12539       // Be sure that the destructor is accessible and is marked as referenced.
12540       if (const RecordType *RecordTy
12541                   = Context.getBaseElementType(Field->getType())
12542                                                         ->getAs<RecordType>()) {
12543                     CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
12544         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
12545           MarkFunctionReferenced(Field->getLocation(), Destructor);
12546           CheckDestructorAccess(Field->getLocation(), Destructor,
12547                             PDiag(diag::err_access_dtor_ivar)
12548                               << Context.getBaseElementType(Field->getType()));
12549         }
12550       }
12551     }
12552     ObjCImplementation->setIvarInitializers(Context,
12553                                             AllToInit.data(), AllToInit.size());
12554   }
12555 }
12556 
12557 static
12558 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12559                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12560                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12561                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12562                            Sema &S) {
12563   if (Ctor->isInvalidDecl())
12564     return;
12565 
12566   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12567 
12568   // Target may not be determinable yet, for instance if this is a dependent
12569   // call in an uninstantiated template.
12570   if (Target) {
12571     const FunctionDecl *FNTarget = 0;
12572     (void)Target->hasBody(FNTarget);
12573     Target = const_cast<CXXConstructorDecl*>(
12574       cast_or_null<CXXConstructorDecl>(FNTarget));
12575   }
12576 
12577   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12578                      // Avoid dereferencing a null pointer here.
12579                      *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12580 
12581   if (!Current.insert(Canonical))
12582     return;
12583 
12584   // We know that beyond here, we aren't chaining into a cycle.
12585   if (!Target || !Target->isDelegatingConstructor() ||
12586       Target->isInvalidDecl() || Valid.count(TCanonical)) {
12587     Valid.insert(Current.begin(), Current.end());
12588     Current.clear();
12589   // We've hit a cycle.
12590   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12591              Current.count(TCanonical)) {
12592     // If we haven't diagnosed this cycle yet, do so now.
12593     if (!Invalid.count(TCanonical)) {
12594       S.Diag((*Ctor->init_begin())->getSourceLocation(),
12595              diag::warn_delegating_ctor_cycle)
12596         << Ctor;
12597 
12598       // Don't add a note for a function delegating directly to itself.
12599       if (TCanonical != Canonical)
12600         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12601 
12602       CXXConstructorDecl *C = Target;
12603       while (C->getCanonicalDecl() != Canonical) {
12604         const FunctionDecl *FNTarget = 0;
12605         (void)C->getTargetConstructor()->hasBody(FNTarget);
12606         assert(FNTarget && "Ctor cycle through bodiless function");
12607 
12608         C = const_cast<CXXConstructorDecl*>(
12609           cast<CXXConstructorDecl>(FNTarget));
12610         S.Diag(C->getLocation(), diag::note_which_delegates_to);
12611       }
12612     }
12613 
12614     Invalid.insert(Current.begin(), Current.end());
12615     Current.clear();
12616   } else {
12617     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12618   }
12619 }
12620 
12621 
12622 void Sema::CheckDelegatingCtorCycles() {
12623   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12624 
12625   for (DelegatingCtorDeclsType::iterator
12626          I = DelegatingCtorDecls.begin(ExternalSource),
12627          E = DelegatingCtorDecls.end();
12628        I != E; ++I)
12629     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
12630 
12631   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12632                                                          CE = Invalid.end();
12633        CI != CE; ++CI)
12634     (*CI)->setInvalidDecl();
12635 }
12636 
12637 namespace {
12638   /// \brief AST visitor that finds references to the 'this' expression.
12639   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12640     Sema &S;
12641 
12642   public:
12643     explicit FindCXXThisExpr(Sema &S) : S(S) { }
12644 
12645     bool VisitCXXThisExpr(CXXThisExpr *E) {
12646       S.Diag(E->getLocation(), diag::err_this_static_member_func)
12647         << E->isImplicit();
12648       return false;
12649     }
12650   };
12651 }
12652 
12653 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12654   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12655   if (!TSInfo)
12656     return false;
12657 
12658   TypeLoc TL = TSInfo->getTypeLoc();
12659   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12660   if (!ProtoTL)
12661     return false;
12662 
12663   // C++11 [expr.prim.general]p3:
12664   //   [The expression this] shall not appear before the optional
12665   //   cv-qualifier-seq and it shall not appear within the declaration of a
12666   //   static member function (although its type and value category are defined
12667   //   within a static member function as they are within a non-static member
12668   //   function). [ Note: this is because declaration matching does not occur
12669   //  until the complete declarator is known. - end note ]
12670   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12671   FindCXXThisExpr Finder(*this);
12672 
12673   // If the return type came after the cv-qualifier-seq, check it now.
12674   if (Proto->hasTrailingReturn() &&
12675       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
12676     return true;
12677 
12678   // Check the exception specification.
12679   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12680     return true;
12681 
12682   return checkThisInStaticMemberFunctionAttributes(Method);
12683 }
12684 
12685 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12686   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12687   if (!TSInfo)
12688     return false;
12689 
12690   TypeLoc TL = TSInfo->getTypeLoc();
12691   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12692   if (!ProtoTL)
12693     return false;
12694 
12695   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12696   FindCXXThisExpr Finder(*this);
12697 
12698   switch (Proto->getExceptionSpecType()) {
12699   case EST_Uninstantiated:
12700   case EST_Unevaluated:
12701   case EST_BasicNoexcept:
12702   case EST_DynamicNone:
12703   case EST_MSAny:
12704   case EST_None:
12705     break;
12706 
12707   case EST_ComputedNoexcept:
12708     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12709       return true;
12710 
12711   case EST_Dynamic:
12712     for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
12713          EEnd = Proto->exception_end();
12714          E != EEnd; ++E) {
12715       if (!Finder.TraverseType(*E))
12716         return true;
12717     }
12718     break;
12719   }
12720 
12721   return false;
12722 }
12723 
12724 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12725   FindCXXThisExpr Finder(*this);
12726 
12727   // Check attributes.
12728   for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12729        A != AEnd; ++A) {
12730     // FIXME: This should be emitted by tblgen.
12731     Expr *Arg = 0;
12732     ArrayRef<Expr *> Args;
12733     if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12734       Arg = G->getArg();
12735     else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12736       Arg = G->getArg();
12737     else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12738       Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12739     else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12740       Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12741     else if (ExclusiveLockFunctionAttr *ELF
12742                = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12743       Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12744     else if (SharedLockFunctionAttr *SLF
12745                = dyn_cast<SharedLockFunctionAttr>(*A))
12746       Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12747     else if (ExclusiveTrylockFunctionAttr *ETLF
12748                = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12749       Arg = ETLF->getSuccessValue();
12750       Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12751     } else if (SharedTrylockFunctionAttr *STLF
12752                  = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12753       Arg = STLF->getSuccessValue();
12754       Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12755     } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12756       Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12757     else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12758       Arg = LR->getArg();
12759     else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12760       Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12761     else if (RequiresCapabilityAttr *RC
12762                = dyn_cast<RequiresCapabilityAttr>(*A))
12763       Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
12764     else if (AcquireCapabilityAttr *AC = dyn_cast<AcquireCapabilityAttr>(*A))
12765       Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12766     else if (TryAcquireCapabilityAttr *AC
12767              = dyn_cast<TryAcquireCapabilityAttr>(*A))
12768              Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12769     else if (ReleaseCapabilityAttr *RC = dyn_cast<ReleaseCapabilityAttr>(*A))
12770       Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
12771 
12772     if (Arg && !Finder.TraverseStmt(Arg))
12773       return true;
12774 
12775     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12776       if (!Finder.TraverseStmt(Args[I]))
12777         return true;
12778     }
12779   }
12780 
12781   return false;
12782 }
12783 
12784 void
12785 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12786                                   ArrayRef<ParsedType> DynamicExceptions,
12787                                   ArrayRef<SourceRange> DynamicExceptionRanges,
12788                                   Expr *NoexceptExpr,
12789                                   SmallVectorImpl<QualType> &Exceptions,
12790                                   FunctionProtoType::ExtProtoInfo &EPI) {
12791   Exceptions.clear();
12792   EPI.ExceptionSpecType = EST;
12793   if (EST == EST_Dynamic) {
12794     Exceptions.reserve(DynamicExceptions.size());
12795     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12796       // FIXME: Preserve type source info.
12797       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12798 
12799       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12800       collectUnexpandedParameterPacks(ET, Unexpanded);
12801       if (!Unexpanded.empty()) {
12802         DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12803                                          UPPC_ExceptionType,
12804                                          Unexpanded);
12805         continue;
12806       }
12807 
12808       // Check that the type is valid for an exception spec, and
12809       // drop it if not.
12810       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12811         Exceptions.push_back(ET);
12812     }
12813     EPI.NumExceptions = Exceptions.size();
12814     EPI.Exceptions = Exceptions.data();
12815     return;
12816   }
12817 
12818   if (EST == EST_ComputedNoexcept) {
12819     // If an error occurred, there's no expression here.
12820     if (NoexceptExpr) {
12821       assert((NoexceptExpr->isTypeDependent() ||
12822               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12823               Context.BoolTy) &&
12824              "Parser should have made sure that the expression is boolean");
12825       if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12826         EPI.ExceptionSpecType = EST_BasicNoexcept;
12827         return;
12828       }
12829 
12830       if (!NoexceptExpr->isValueDependent())
12831         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
12832                          diag::err_noexcept_needs_constant_expression,
12833                          /*AllowFold*/ false).take();
12834       EPI.NoexceptExpr = NoexceptExpr;
12835     }
12836     return;
12837   }
12838 }
12839 
12840 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12841 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12842   // Implicitly declared functions (e.g. copy constructors) are
12843   // __host__ __device__
12844   if (D->isImplicit())
12845     return CFT_HostDevice;
12846 
12847   if (D->hasAttr<CUDAGlobalAttr>())
12848     return CFT_Global;
12849 
12850   if (D->hasAttr<CUDADeviceAttr>()) {
12851     if (D->hasAttr<CUDAHostAttr>())
12852       return CFT_HostDevice;
12853     return CFT_Device;
12854   }
12855 
12856   return CFT_Host;
12857 }
12858 
12859 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12860                            CUDAFunctionTarget CalleeTarget) {
12861   // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12862   // Callable from the device only."
12863   if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12864     return true;
12865 
12866   // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12867   // Callable from the host only."
12868   // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12869   // Callable from the host only."
12870   if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12871       (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12872     return true;
12873 
12874   if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12875     return true;
12876 
12877   return false;
12878 }
12879 
12880 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12881 ///
12882 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12883                                        SourceLocation DeclStart,
12884                                        Declarator &D, Expr *BitWidth,
12885                                        InClassInitStyle InitStyle,
12886                                        AccessSpecifier AS,
12887                                        AttributeList *MSPropertyAttr) {
12888   IdentifierInfo *II = D.getIdentifier();
12889   if (!II) {
12890     Diag(DeclStart, diag::err_anonymous_property);
12891     return NULL;
12892   }
12893   SourceLocation Loc = D.getIdentifierLoc();
12894 
12895   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12896   QualType T = TInfo->getType();
12897   if (getLangOpts().CPlusPlus) {
12898     CheckExtraCXXDefaultArguments(D);
12899 
12900     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12901                                         UPPC_DataMemberType)) {
12902       D.setInvalidType();
12903       T = Context.IntTy;
12904       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12905     }
12906   }
12907 
12908   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12909 
12910   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12911     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12912          diag::err_invalid_thread)
12913       << DeclSpec::getSpecifierName(TSCS);
12914 
12915   // Check to see if this name was declared as a member previously
12916   NamedDecl *PrevDecl = 0;
12917   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12918   LookupName(Previous, S);
12919   switch (Previous.getResultKind()) {
12920   case LookupResult::Found:
12921   case LookupResult::FoundUnresolvedValue:
12922     PrevDecl = Previous.getAsSingle<NamedDecl>();
12923     break;
12924 
12925   case LookupResult::FoundOverloaded:
12926     PrevDecl = Previous.getRepresentativeDecl();
12927     break;
12928 
12929   case LookupResult::NotFound:
12930   case LookupResult::NotFoundInCurrentInstantiation:
12931   case LookupResult::Ambiguous:
12932     break;
12933   }
12934 
12935   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12936     // Maybe we will complain about the shadowed template parameter.
12937     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12938     // Just pretend that we didn't see the previous declaration.
12939     PrevDecl = 0;
12940   }
12941 
12942   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12943     PrevDecl = 0;
12944 
12945   SourceLocation TSSL = D.getLocStart();
12946   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12947   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
12948       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
12949   ProcessDeclAttributes(TUScope, NewPD, D);
12950   NewPD->setAccess(AS);
12951 
12952   if (NewPD->isInvalidDecl())
12953     Record->setInvalidDecl();
12954 
12955   if (D.getDeclSpec().isModulePrivateSpecified())
12956     NewPD->setModulePrivate();
12957 
12958   if (NewPD->isInvalidDecl() && PrevDecl) {
12959     // Don't introduce NewFD into scope; there's already something
12960     // with the same name in the same scope.
12961   } else if (II) {
12962     PushOnScopeChains(NewPD, S);
12963   } else
12964     Record->addDecl(NewPD);
12965 
12966   return NewPD;
12967 }
12968