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/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/Template.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 (const auto &E : Proto->exceptions())
216     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
217       Exceptions.push_back(E);
218 }
219 
220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
221   if (!E || ComputedEST == EST_MSAny)
222     return;
223 
224   // FIXME:
225   //
226   // C++0x [except.spec]p14:
227   //   [An] implicit exception-specification specifies the type-id T if and
228   // only if T is allowed by the exception-specification of a function directly
229   // invoked by f's implicit definition; f shall allow all exceptions if any
230   // function it directly invokes allows all exceptions, and f shall allow no
231   // exceptions if every function it directly invokes allows no exceptions.
232   //
233   // Note in particular that if an implicit exception-specification is generated
234   // for a function containing a throw-expression, that specification can still
235   // be noexcept(true).
236   //
237   // Note also that 'directly invoked' is not defined in the standard, and there
238   // is no indication that we should only consider potentially-evaluated calls.
239   //
240   // Ultimately we should implement the intent of the standard: the exception
241   // specification should be the set of exceptions which can be thrown by the
242   // implicit definition. For now, we assume that any non-nothrow expression can
243   // throw any exception.
244 
245   if (Self->canThrow(E))
246     ComputedEST = EST_None;
247 }
248 
249 bool
250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
251                               SourceLocation EqualLoc) {
252   if (RequireCompleteType(Param->getLocation(), Param->getType(),
253                           diag::err_typecheck_decl_incomplete_type)) {
254     Param->setInvalidDecl();
255     return true;
256   }
257 
258   // C++ [dcl.fct.default]p5
259   //   A default argument expression is implicitly converted (clause
260   //   4) to the parameter type. The default argument expression has
261   //   the same semantic constraints as the initializer expression in
262   //   a declaration of a variable of the parameter type, using the
263   //   copy-initialization semantics (8.5).
264   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265                                                                     Param);
266   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267                                                            EqualLoc);
268   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
269   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
270   if (Result.isInvalid())
271     return true;
272   Arg = Result.getAs<Expr>();
273 
274   CheckCompletedExpr(Arg, EqualLoc);
275   Arg = MaybeCreateExprWithCleanups(Arg);
276 
277   // Okay: add the default argument to the parameter
278   Param->setDefaultArg(Arg);
279 
280   // We have already instantiated this parameter; provide each of the
281   // instantiations with the uninstantiated default argument.
282   UnparsedDefaultArgInstantiationsMap::iterator InstPos
283     = UnparsedDefaultArgInstantiations.find(Param);
284   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287 
288     // We're done tracking this parameter's instantiations.
289     UnparsedDefaultArgInstantiations.erase(InstPos);
290   }
291 
292   return false;
293 }
294 
295 /// ActOnParamDefaultArgument - Check whether the default argument
296 /// provided for a function parameter is well-formed. If so, attach it
297 /// to the parameter declaration.
298 void
299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
300                                 Expr *DefaultArg) {
301   if (!param || !DefaultArg)
302     return;
303 
304   ParmVarDecl *Param = cast<ParmVarDecl>(param);
305   UnparsedDefaultArgLocs.erase(Param);
306 
307   // Default arguments are only permitted in C++
308   if (!getLangOpts().CPlusPlus) {
309     Diag(EqualLoc, diag::err_param_default_argument)
310       << DefaultArg->getSourceRange();
311     Param->setInvalidDecl();
312     return;
313   }
314 
315   // Check for unexpanded parameter packs.
316   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317     Param->setInvalidDecl();
318     return;
319   }
320 
321   // Check that the default argument is well-formed
322   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323   if (DefaultArgChecker.Visit(DefaultArg)) {
324     Param->setInvalidDecl();
325     return;
326   }
327 
328   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
329 }
330 
331 /// ActOnParamUnparsedDefaultArgument - We've seen a default
332 /// argument for a function parameter, but we can't parse it yet
333 /// because we're inside a class definition. Note that this default
334 /// argument will be parsed later.
335 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
336                                              SourceLocation EqualLoc,
337                                              SourceLocation ArgLoc) {
338   if (!param)
339     return;
340 
341   ParmVarDecl *Param = cast<ParmVarDecl>(param);
342   Param->setUnparsedDefaultArg();
343   UnparsedDefaultArgLocs[Param] = ArgLoc;
344 }
345 
346 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
347 /// the default argument for the parameter param failed.
348 void Sema::ActOnParamDefaultArgumentError(Decl *param,
349                                           SourceLocation EqualLoc) {
350   if (!param)
351     return;
352 
353   ParmVarDecl *Param = cast<ParmVarDecl>(param);
354   Param->setInvalidDecl();
355   UnparsedDefaultArgLocs.erase(Param);
356   Param->setDefaultArg(new(Context)
357                        OpaqueValueExpr(EqualLoc,
358                                        Param->getType().getNonReferenceType(),
359                                        VK_RValue));
360 }
361 
362 /// CheckExtraCXXDefaultArguments - Check for any extra default
363 /// arguments in the declarator, which is not a function declaration
364 /// or definition and therefore is not permitted to have default
365 /// arguments. This routine should be invoked for every declarator
366 /// that is not a function declaration or definition.
367 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
368   // C++ [dcl.fct.default]p3
369   //   A default argument expression shall be specified only in the
370   //   parameter-declaration-clause of a function declaration or in a
371   //   template-parameter (14.1). It shall not be specified for a
372   //   parameter pack. If it is specified in a
373   //   parameter-declaration-clause, it shall not occur within a
374   //   declarator or abstract-declarator of a parameter-declaration.
375   bool MightBeFunction = D.isFunctionDeclarationContext();
376   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
377     DeclaratorChunk &chunk = D.getTypeObject(i);
378     if (chunk.Kind == DeclaratorChunk::Function) {
379       if (MightBeFunction) {
380         // This is a function declaration. It can have default arguments, but
381         // keep looking in case its return type is a function type with default
382         // arguments.
383         MightBeFunction = false;
384         continue;
385       }
386       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
387            ++argIdx) {
388         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
389         if (Param->hasUnparsedDefaultArg()) {
390           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
391           SourceRange SR;
392           if (Toks->size() > 1)
393             SR = SourceRange((*Toks)[1].getLocation(),
394                              Toks->back().getLocation());
395           else
396             SR = UnparsedDefaultArgLocs[Param];
397           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
398             << SR;
399           delete Toks;
400           chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
401         } else if (Param->getDefaultArg()) {
402           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
403             << Param->getDefaultArg()->getSourceRange();
404           Param->setDefaultArg(nullptr);
405         }
406       }
407     } else if (chunk.Kind != DeclaratorChunk::Paren) {
408       MightBeFunction = false;
409     }
410   }
411 }
412 
413 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
414   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
415     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
416     if (!PVD->hasDefaultArg())
417       return false;
418     if (!PVD->hasInheritedDefaultArg())
419       return true;
420   }
421   return false;
422 }
423 
424 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
425 /// function, once we already know that they have the same
426 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
427 /// error, false otherwise.
428 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
429                                 Scope *S) {
430   bool Invalid = false;
431 
432   // C++ [dcl.fct.default]p4:
433   //   For non-template functions, default arguments can be added in
434   //   later declarations of a function in the same
435   //   scope. Declarations in different scopes have completely
436   //   distinct sets of default arguments. That is, declarations in
437   //   inner scopes do not acquire default arguments from
438   //   declarations in outer scopes, and vice versa. In a given
439   //   function declaration, all parameters subsequent to a
440   //   parameter with a default argument shall have default
441   //   arguments supplied in this or previous declarations. A
442   //   default argument shall not be redefined by a later
443   //   declaration (not even to the same value).
444   //
445   // C++ [dcl.fct.default]p6:
446   //   Except for member functions of class templates, the default arguments
447   //   in a member function definition that appears outside of the class
448   //   definition are added to the set of default arguments provided by the
449   //   member function declaration in the class definition.
450   for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
451     ParmVarDecl *OldParam = Old->getParamDecl(p);
452     ParmVarDecl *NewParam = New->getParamDecl(p);
453 
454     bool OldParamHasDfl = OldParam->hasDefaultArg();
455     bool NewParamHasDfl = NewParam->hasDefaultArg();
456 
457     // The declaration context corresponding to the scope is the semantic
458     // parent, unless this is a local function declaration, in which case
459     // it is that surrounding function.
460     DeclContext *ScopeDC = New->isLocalExternDecl()
461                                ? New->getLexicalDeclContext()
462                                : New->getDeclContext();
463     if (S && !isDeclInScope(Old, ScopeDC, S) &&
464         !New->getDeclContext()->isRecord())
465       // Ignore default parameters of old decl if they are not in
466       // the same scope and this is not an out-of-line definition of
467       // a member function.
468       OldParamHasDfl = false;
469     if (New->isLocalExternDecl() != Old->isLocalExternDecl())
470       // If only one of these is a local function declaration, then they are
471       // declared in different scopes, even though isDeclInScope may think
472       // they're in the same scope. (If both are local, the scope check is
473       // sufficent, and if neither is local, then they are in the same scope.)
474       OldParamHasDfl = false;
475 
476     if (OldParamHasDfl && NewParamHasDfl) {
477 
478       unsigned DiagDefaultParamID =
479         diag::err_param_default_argument_redefinition;
480 
481       // MSVC accepts that default parameters be redefined for member functions
482       // of template class. The new default parameter's value is ignored.
483       Invalid = true;
484       if (getLangOpts().MicrosoftExt) {
485         CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
486         if (MD && MD->getParent()->getDescribedClassTemplate()) {
487           // Merge the old default argument into the new parameter.
488           NewParam->setHasInheritedDefaultArg();
489           if (OldParam->hasUninstantiatedDefaultArg())
490             NewParam->setUninstantiatedDefaultArg(
491                                       OldParam->getUninstantiatedDefaultArg());
492           else
493             NewParam->setDefaultArg(OldParam->getInit());
494           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
495           Invalid = false;
496         }
497       }
498 
499       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
500       // hint here. Alternatively, we could walk the type-source information
501       // for NewParam to find the last source location in the type... but it
502       // isn't worth the effort right now. This is the kind of test case that
503       // is hard to get right:
504       //   int f(int);
505       //   void g(int (*fp)(int) = f);
506       //   void g(int (*fp)(int) = &f);
507       Diag(NewParam->getLocation(), DiagDefaultParamID)
508         << NewParam->getDefaultArgRange();
509 
510       // Look for the function declaration where the default argument was
511       // actually written, which may be a declaration prior to Old.
512       for (auto Older = Old; OldParam->hasInheritedDefaultArg();) {
513         Older = Older->getPreviousDecl();
514         OldParam = Older->getParamDecl(p);
515       }
516 
517       Diag(OldParam->getLocation(), diag::note_previous_definition)
518         << OldParam->getDefaultArgRange();
519     } else if (OldParamHasDfl) {
520       // Merge the old default argument into the new parameter.
521       // It's important to use getInit() here;  getDefaultArg()
522       // strips off any top-level ExprWithCleanups.
523       NewParam->setHasInheritedDefaultArg();
524       if (OldParam->hasUninstantiatedDefaultArg())
525         NewParam->setUninstantiatedDefaultArg(
526                                       OldParam->getUninstantiatedDefaultArg());
527       else
528         NewParam->setDefaultArg(OldParam->getInit());
529     } else if (NewParamHasDfl) {
530       if (New->getDescribedFunctionTemplate()) {
531         // Paragraph 4, quoted above, only applies to non-template functions.
532         Diag(NewParam->getLocation(),
533              diag::err_param_default_argument_template_redecl)
534           << NewParam->getDefaultArgRange();
535         Diag(Old->getLocation(), diag::note_template_prev_declaration)
536           << false;
537       } else if (New->getTemplateSpecializationKind()
538                    != TSK_ImplicitInstantiation &&
539                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
540         // C++ [temp.expr.spec]p21:
541         //   Default function arguments shall not be specified in a declaration
542         //   or a definition for one of the following explicit specializations:
543         //     - the explicit specialization of a function template;
544         //     - the explicit specialization of a member function template;
545         //     - the explicit specialization of a member function of a class
546         //       template where the class template specialization to which the
547         //       member function specialization belongs is implicitly
548         //       instantiated.
549         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
550           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
551           << New->getDeclName()
552           << NewParam->getDefaultArgRange();
553       } else if (New->getDeclContext()->isDependentContext()) {
554         // C++ [dcl.fct.default]p6 (DR217):
555         //   Default arguments for a member function of a class template shall
556         //   be specified on the initial declaration of the member function
557         //   within the class template.
558         //
559         // Reading the tea leaves a bit in DR217 and its reference to DR205
560         // leads me to the conclusion that one cannot add default function
561         // arguments for an out-of-line definition of a member function of a
562         // dependent type.
563         int WhichKind = 2;
564         if (CXXRecordDecl *Record
565               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
566           if (Record->getDescribedClassTemplate())
567             WhichKind = 0;
568           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
569             WhichKind = 1;
570           else
571             WhichKind = 2;
572         }
573 
574         Diag(NewParam->getLocation(),
575              diag::err_param_default_argument_member_template_redecl)
576           << WhichKind
577           << NewParam->getDefaultArgRange();
578       }
579     }
580   }
581 
582   // DR1344: If a default argument is added outside a class definition and that
583   // default argument makes the function a special member function, the program
584   // is ill-formed. This can only happen for constructors.
585   if (isa<CXXConstructorDecl>(New) &&
586       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
587     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
588                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
589     if (NewSM != OldSM) {
590       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
591       assert(NewParam->hasDefaultArg());
592       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
593         << NewParam->getDefaultArgRange() << NewSM;
594       Diag(Old->getLocation(), diag::note_previous_declaration);
595     }
596   }
597 
598   const FunctionDecl *Def;
599   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
600   // template has a constexpr specifier then all its declarations shall
601   // contain the constexpr specifier.
602   if (New->isConstexpr() != Old->isConstexpr()) {
603     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
604       << New << New->isConstexpr();
605     Diag(Old->getLocation(), diag::note_previous_declaration);
606     Invalid = true;
607   } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
608     // C++11 [dcl.fcn.spec]p4:
609     //   If the definition of a function appears in a translation unit before its
610     //   first declaration as inline, the program is ill-formed.
611     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
612     Diag(Def->getLocation(), diag::note_previous_definition);
613     Invalid = true;
614   }
615 
616   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
617   // argument expression, that declaration shall be a definition and shall be
618   // the only declaration of the function or function template in the
619   // translation unit.
620   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
621       functionDeclHasDefaultArgument(Old)) {
622     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
623     Diag(Old->getLocation(), diag::note_previous_declaration);
624     Invalid = true;
625   }
626 
627   if (CheckEquivalentExceptionSpec(Old, New))
628     Invalid = true;
629 
630   return Invalid;
631 }
632 
633 /// \brief Merge the exception specifications of two variable declarations.
634 ///
635 /// This is called when there's a redeclaration of a VarDecl. The function
636 /// checks if the redeclaration might have an exception specification and
637 /// validates compatibility and merges the specs if necessary.
638 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
639   // Shortcut if exceptions are disabled.
640   if (!getLangOpts().CXXExceptions)
641     return;
642 
643   assert(Context.hasSameType(New->getType(), Old->getType()) &&
644          "Should only be called if types are otherwise the same.");
645 
646   QualType NewType = New->getType();
647   QualType OldType = Old->getType();
648 
649   // We're only interested in pointers and references to functions, as well
650   // as pointers to member functions.
651   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
652     NewType = R->getPointeeType();
653     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
654   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
655     NewType = P->getPointeeType();
656     OldType = OldType->getAs<PointerType>()->getPointeeType();
657   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
658     NewType = M->getPointeeType();
659     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
660   }
661 
662   if (!NewType->isFunctionProtoType())
663     return;
664 
665   // There's lots of special cases for functions. For function pointers, system
666   // libraries are hopefully not as broken so that we don't need these
667   // workarounds.
668   if (CheckEquivalentExceptionSpec(
669         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
670         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
671     New->setInvalidDecl();
672   }
673 }
674 
675 /// CheckCXXDefaultArguments - Verify that the default arguments for a
676 /// function declaration are well-formed according to C++
677 /// [dcl.fct.default].
678 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
679   unsigned NumParams = FD->getNumParams();
680   unsigned p;
681 
682   // Find first parameter with a default argument
683   for (p = 0; p < NumParams; ++p) {
684     ParmVarDecl *Param = FD->getParamDecl(p);
685     if (Param->hasDefaultArg())
686       break;
687   }
688 
689   // C++ [dcl.fct.default]p4:
690   //   In a given function declaration, all parameters
691   //   subsequent to a parameter with a default argument shall
692   //   have default arguments supplied in this or previous
693   //   declarations. A default argument shall not be redefined
694   //   by a later declaration (not even to the same value).
695   unsigned LastMissingDefaultArg = 0;
696   for (; p < NumParams; ++p) {
697     ParmVarDecl *Param = FD->getParamDecl(p);
698     if (!Param->hasDefaultArg()) {
699       if (Param->isInvalidDecl())
700         /* We already complained about this parameter. */;
701       else if (Param->getIdentifier())
702         Diag(Param->getLocation(),
703              diag::err_param_default_argument_missing_name)
704           << Param->getIdentifier();
705       else
706         Diag(Param->getLocation(),
707              diag::err_param_default_argument_missing);
708 
709       LastMissingDefaultArg = p;
710     }
711   }
712 
713   if (LastMissingDefaultArg > 0) {
714     // Some default arguments were missing. Clear out all of the
715     // default arguments up to (and including) the last missing
716     // default argument, so that we leave the function parameters
717     // in a semantically valid state.
718     for (p = 0; p <= LastMissingDefaultArg; ++p) {
719       ParmVarDecl *Param = FD->getParamDecl(p);
720       if (Param->hasDefaultArg()) {
721         Param->setDefaultArg(nullptr);
722       }
723     }
724   }
725 }
726 
727 // CheckConstexprParameterTypes - Check whether a function's parameter types
728 // are all literal types. If so, return true. If not, produce a suitable
729 // diagnostic and return false.
730 static bool CheckConstexprParameterTypes(Sema &SemaRef,
731                                          const FunctionDecl *FD) {
732   unsigned ArgIndex = 0;
733   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
734   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
735                                               e = FT->param_type_end();
736        i != e; ++i, ++ArgIndex) {
737     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
738     SourceLocation ParamLoc = PD->getLocation();
739     if (!(*i)->isDependentType() &&
740         SemaRef.RequireLiteralType(ParamLoc, *i,
741                                    diag::err_constexpr_non_literal_param,
742                                    ArgIndex+1, PD->getSourceRange(),
743                                    isa<CXXConstructorDecl>(FD)))
744       return false;
745   }
746   return true;
747 }
748 
749 /// \brief Get diagnostic %select index for tag kind for
750 /// record diagnostic message.
751 /// WARNING: Indexes apply to particular diagnostics only!
752 ///
753 /// \returns diagnostic %select index.
754 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
755   switch (Tag) {
756   case TTK_Struct: return 0;
757   case TTK_Interface: return 1;
758   case TTK_Class:  return 2;
759   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
760   }
761 }
762 
763 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
764 // the requirements of a constexpr function definition or a constexpr
765 // constructor definition. If so, return true. If not, produce appropriate
766 // diagnostics and return false.
767 //
768 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
769 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
770   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
771   if (MD && MD->isInstance()) {
772     // C++11 [dcl.constexpr]p4:
773     //  The definition of a constexpr constructor shall satisfy the following
774     //  constraints:
775     //  - the class shall not have any virtual base classes;
776     const CXXRecordDecl *RD = MD->getParent();
777     if (RD->getNumVBases()) {
778       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
779         << isa<CXXConstructorDecl>(NewFD)
780         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
781       for (const auto &I : RD->vbases())
782         Diag(I.getLocStart(),
783              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
784       return false;
785     }
786   }
787 
788   if (!isa<CXXConstructorDecl>(NewFD)) {
789     // C++11 [dcl.constexpr]p3:
790     //  The definition of a constexpr function shall satisfy the following
791     //  constraints:
792     // - it shall not be virtual;
793     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
794     if (Method && Method->isVirtual()) {
795       Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
796 
797       // If it's not obvious why this function is virtual, find an overridden
798       // function which uses the 'virtual' keyword.
799       const CXXMethodDecl *WrittenVirtual = Method;
800       while (!WrittenVirtual->isVirtualAsWritten())
801         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
802       if (WrittenVirtual != Method)
803         Diag(WrittenVirtual->getLocation(),
804              diag::note_overridden_virtual_function);
805       return false;
806     }
807 
808     // - its return type shall be a literal type;
809     QualType RT = NewFD->getReturnType();
810     if (!RT->isDependentType() &&
811         RequireLiteralType(NewFD->getLocation(), RT,
812                            diag::err_constexpr_non_literal_return))
813       return false;
814   }
815 
816   // - each of its parameter types shall be a literal type;
817   if (!CheckConstexprParameterTypes(*this, NewFD))
818     return false;
819 
820   return true;
821 }
822 
823 /// Check the given declaration statement is legal within a constexpr function
824 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
825 ///
826 /// \return true if the body is OK (maybe only as an extension), false if we
827 ///         have diagnosed a problem.
828 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
829                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
830   // C++11 [dcl.constexpr]p3 and p4:
831   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
832   //  contain only
833   for (const auto *DclIt : DS->decls()) {
834     switch (DclIt->getKind()) {
835     case Decl::StaticAssert:
836     case Decl::Using:
837     case Decl::UsingShadow:
838     case Decl::UsingDirective:
839     case Decl::UnresolvedUsingTypename:
840     case Decl::UnresolvedUsingValue:
841       //   - static_assert-declarations
842       //   - using-declarations,
843       //   - using-directives,
844       continue;
845 
846     case Decl::Typedef:
847     case Decl::TypeAlias: {
848       //   - typedef declarations and alias-declarations that do not define
849       //     classes or enumerations,
850       const auto *TN = cast<TypedefNameDecl>(DclIt);
851       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
852         // Don't allow variably-modified types in constexpr functions.
853         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
854         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
855           << TL.getSourceRange() << TL.getType()
856           << isa<CXXConstructorDecl>(Dcl);
857         return false;
858       }
859       continue;
860     }
861 
862     case Decl::Enum:
863     case Decl::CXXRecord:
864       // C++1y allows types to be defined, not just declared.
865       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
866         SemaRef.Diag(DS->getLocStart(),
867                      SemaRef.getLangOpts().CPlusPlus14
868                        ? diag::warn_cxx11_compat_constexpr_type_definition
869                        : diag::ext_constexpr_type_definition)
870           << isa<CXXConstructorDecl>(Dcl);
871       continue;
872 
873     case Decl::EnumConstant:
874     case Decl::IndirectField:
875     case Decl::ParmVar:
876       // These can only appear with other declarations which are banned in
877       // C++11 and permitted in C++1y, so ignore them.
878       continue;
879 
880     case Decl::Var: {
881       // C++1y [dcl.constexpr]p3 allows anything except:
882       //   a definition of a variable of non-literal type or of static or
883       //   thread storage duration or for which no initialization is performed.
884       const auto *VD = cast<VarDecl>(DclIt);
885       if (VD->isThisDeclarationADefinition()) {
886         if (VD->isStaticLocal()) {
887           SemaRef.Diag(VD->getLocation(),
888                        diag::err_constexpr_local_var_static)
889             << isa<CXXConstructorDecl>(Dcl)
890             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
891           return false;
892         }
893         if (!VD->getType()->isDependentType() &&
894             SemaRef.RequireLiteralType(
895               VD->getLocation(), VD->getType(),
896               diag::err_constexpr_local_var_non_literal_type,
897               isa<CXXConstructorDecl>(Dcl)))
898           return false;
899         if (!VD->getType()->isDependentType() &&
900             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
901           SemaRef.Diag(VD->getLocation(),
902                        diag::err_constexpr_local_var_no_init)
903             << isa<CXXConstructorDecl>(Dcl);
904           return false;
905         }
906       }
907       SemaRef.Diag(VD->getLocation(),
908                    SemaRef.getLangOpts().CPlusPlus14
909                     ? diag::warn_cxx11_compat_constexpr_local_var
910                     : diag::ext_constexpr_local_var)
911         << isa<CXXConstructorDecl>(Dcl);
912       continue;
913     }
914 
915     case Decl::NamespaceAlias:
916     case Decl::Function:
917       // These are disallowed in C++11 and permitted in C++1y. Allow them
918       // everywhere as an extension.
919       if (!Cxx1yLoc.isValid())
920         Cxx1yLoc = DS->getLocStart();
921       continue;
922 
923     default:
924       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
925         << isa<CXXConstructorDecl>(Dcl);
926       return false;
927     }
928   }
929 
930   return true;
931 }
932 
933 /// Check that the given field is initialized within a constexpr constructor.
934 ///
935 /// \param Dcl The constexpr constructor being checked.
936 /// \param Field The field being checked. This may be a member of an anonymous
937 ///        struct or union nested within the class being checked.
938 /// \param Inits All declarations, including anonymous struct/union members and
939 ///        indirect members, for which any initialization was provided.
940 /// \param Diagnosed Set to true if an error is produced.
941 static void CheckConstexprCtorInitializer(Sema &SemaRef,
942                                           const FunctionDecl *Dcl,
943                                           FieldDecl *Field,
944                                           llvm::SmallSet<Decl*, 16> &Inits,
945                                           bool &Diagnosed) {
946   if (Field->isInvalidDecl())
947     return;
948 
949   if (Field->isUnnamedBitfield())
950     return;
951 
952   // Anonymous unions with no variant members and empty anonymous structs do not
953   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
954   // indirect fields don't need initializing.
955   if (Field->isAnonymousStructOrUnion() &&
956       (Field->getType()->isUnionType()
957            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
958            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
959     return;
960 
961   if (!Inits.count(Field)) {
962     if (!Diagnosed) {
963       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
964       Diagnosed = true;
965     }
966     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
967   } else if (Field->isAnonymousStructOrUnion()) {
968     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
969     for (auto *I : RD->fields())
970       // If an anonymous union contains an anonymous struct of which any member
971       // is initialized, all members must be initialized.
972       if (!RD->isUnion() || Inits.count(I))
973         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
974   }
975 }
976 
977 /// Check the provided statement is allowed in a constexpr function
978 /// definition.
979 static bool
980 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
981                            SmallVectorImpl<SourceLocation> &ReturnStmts,
982                            SourceLocation &Cxx1yLoc) {
983   // - its function-body shall be [...] a compound-statement that contains only
984   switch (S->getStmtClass()) {
985   case Stmt::NullStmtClass:
986     //   - null statements,
987     return true;
988 
989   case Stmt::DeclStmtClass:
990     //   - static_assert-declarations
991     //   - using-declarations,
992     //   - using-directives,
993     //   - typedef declarations and alias-declarations that do not define
994     //     classes or enumerations,
995     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
996       return false;
997     return true;
998 
999   case Stmt::ReturnStmtClass:
1000     //   - and exactly one return statement;
1001     if (isa<CXXConstructorDecl>(Dcl)) {
1002       // C++1y allows return statements in constexpr constructors.
1003       if (!Cxx1yLoc.isValid())
1004         Cxx1yLoc = S->getLocStart();
1005       return true;
1006     }
1007 
1008     ReturnStmts.push_back(S->getLocStart());
1009     return true;
1010 
1011   case Stmt::CompoundStmtClass: {
1012     // C++1y allows compound-statements.
1013     if (!Cxx1yLoc.isValid())
1014       Cxx1yLoc = S->getLocStart();
1015 
1016     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1017     for (auto *BodyIt : CompStmt->body()) {
1018       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1019                                       Cxx1yLoc))
1020         return false;
1021     }
1022     return true;
1023   }
1024 
1025   case Stmt::AttributedStmtClass:
1026     if (!Cxx1yLoc.isValid())
1027       Cxx1yLoc = S->getLocStart();
1028     return true;
1029 
1030   case Stmt::IfStmtClass: {
1031     // C++1y allows if-statements.
1032     if (!Cxx1yLoc.isValid())
1033       Cxx1yLoc = S->getLocStart();
1034 
1035     IfStmt *If = cast<IfStmt>(S);
1036     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1037                                     Cxx1yLoc))
1038       return false;
1039     if (If->getElse() &&
1040         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1041                                     Cxx1yLoc))
1042       return false;
1043     return true;
1044   }
1045 
1046   case Stmt::WhileStmtClass:
1047   case Stmt::DoStmtClass:
1048   case Stmt::ForStmtClass:
1049   case Stmt::CXXForRangeStmtClass:
1050   case Stmt::ContinueStmtClass:
1051     // C++1y allows all of these. We don't allow them as extensions in C++11,
1052     // because they don't make sense without variable mutation.
1053     if (!SemaRef.getLangOpts().CPlusPlus14)
1054       break;
1055     if (!Cxx1yLoc.isValid())
1056       Cxx1yLoc = S->getLocStart();
1057     for (Stmt::child_range Children = S->children(); Children; ++Children)
1058       if (*Children &&
1059           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1060                                       Cxx1yLoc))
1061         return false;
1062     return true;
1063 
1064   case Stmt::SwitchStmtClass:
1065   case Stmt::CaseStmtClass:
1066   case Stmt::DefaultStmtClass:
1067   case Stmt::BreakStmtClass:
1068     // C++1y allows switch-statements, and since they don't need variable
1069     // mutation, we can reasonably allow them in C++11 as an extension.
1070     if (!Cxx1yLoc.isValid())
1071       Cxx1yLoc = S->getLocStart();
1072     for (Stmt::child_range Children = S->children(); Children; ++Children)
1073       if (*Children &&
1074           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1075                                       Cxx1yLoc))
1076         return false;
1077     return true;
1078 
1079   default:
1080     if (!isa<Expr>(S))
1081       break;
1082 
1083     // C++1y allows expression-statements.
1084     if (!Cxx1yLoc.isValid())
1085       Cxx1yLoc = S->getLocStart();
1086     return true;
1087   }
1088 
1089   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1090     << isa<CXXConstructorDecl>(Dcl);
1091   return false;
1092 }
1093 
1094 /// Check the body for the given constexpr function declaration only contains
1095 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1096 ///
1097 /// \return true if the body is OK, false if we have diagnosed a problem.
1098 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1099   if (isa<CXXTryStmt>(Body)) {
1100     // C++11 [dcl.constexpr]p3:
1101     //  The definition of a constexpr function shall satisfy the following
1102     //  constraints: [...]
1103     // - its function-body shall be = delete, = default, or a
1104     //   compound-statement
1105     //
1106     // C++11 [dcl.constexpr]p4:
1107     //  In the definition of a constexpr constructor, [...]
1108     // - its function-body shall not be a function-try-block;
1109     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1110       << isa<CXXConstructorDecl>(Dcl);
1111     return false;
1112   }
1113 
1114   SmallVector<SourceLocation, 4> ReturnStmts;
1115 
1116   // - its function-body shall be [...] a compound-statement that contains only
1117   //   [... list of cases ...]
1118   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1119   SourceLocation Cxx1yLoc;
1120   for (auto *BodyIt : CompBody->body()) {
1121     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1122       return false;
1123   }
1124 
1125   if (Cxx1yLoc.isValid())
1126     Diag(Cxx1yLoc,
1127          getLangOpts().CPlusPlus14
1128            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1129            : diag::ext_constexpr_body_invalid_stmt)
1130       << isa<CXXConstructorDecl>(Dcl);
1131 
1132   if (const CXXConstructorDecl *Constructor
1133         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1134     const CXXRecordDecl *RD = Constructor->getParent();
1135     // DR1359:
1136     // - every non-variant non-static data member and base class sub-object
1137     //   shall be initialized;
1138     // DR1460:
1139     // - if the class is a union having variant members, exactly one of them
1140     //   shall be initialized;
1141     if (RD->isUnion()) {
1142       if (Constructor->getNumCtorInitializers() == 0 &&
1143           RD->hasVariantMembers()) {
1144         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1145         return false;
1146       }
1147     } else if (!Constructor->isDependentContext() &&
1148                !Constructor->isDelegatingConstructor()) {
1149       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1150 
1151       // Skip detailed checking if we have enough initializers, and we would
1152       // allow at most one initializer per member.
1153       bool AnyAnonStructUnionMembers = false;
1154       unsigned Fields = 0;
1155       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1156            E = RD->field_end(); I != E; ++I, ++Fields) {
1157         if (I->isAnonymousStructOrUnion()) {
1158           AnyAnonStructUnionMembers = true;
1159           break;
1160         }
1161       }
1162       // DR1460:
1163       // - if the class is a union-like class, but is not a union, for each of
1164       //   its anonymous union members having variant members, exactly one of
1165       //   them shall be initialized;
1166       if (AnyAnonStructUnionMembers ||
1167           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1168         // Check initialization of non-static data members. Base classes are
1169         // always initialized so do not need to be checked. Dependent bases
1170         // might not have initializers in the member initializer list.
1171         llvm::SmallSet<Decl*, 16> Inits;
1172         for (const auto *I: Constructor->inits()) {
1173           if (FieldDecl *FD = I->getMember())
1174             Inits.insert(FD);
1175           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1176             Inits.insert(ID->chain_begin(), ID->chain_end());
1177         }
1178 
1179         bool Diagnosed = false;
1180         for (auto *I : RD->fields())
1181           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1182         if (Diagnosed)
1183           return false;
1184       }
1185     }
1186   } else {
1187     if (ReturnStmts.empty()) {
1188       // C++1y doesn't require constexpr functions to contain a 'return'
1189       // statement. We still do, unless the return type might be void, because
1190       // otherwise if there's no return statement, the function cannot
1191       // be used in a core constant expression.
1192       bool OK = getLangOpts().CPlusPlus14 &&
1193                 (Dcl->getReturnType()->isVoidType() ||
1194                  Dcl->getReturnType()->isDependentType());
1195       Diag(Dcl->getLocation(),
1196            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1197               : diag::err_constexpr_body_no_return);
1198       return OK;
1199     }
1200     if (ReturnStmts.size() > 1) {
1201       Diag(ReturnStmts.back(),
1202            getLangOpts().CPlusPlus14
1203              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1204              : diag::ext_constexpr_body_multiple_return);
1205       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1206         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1207     }
1208   }
1209 
1210   // C++11 [dcl.constexpr]p5:
1211   //   if no function argument values exist such that the function invocation
1212   //   substitution would produce a constant expression, the program is
1213   //   ill-formed; no diagnostic required.
1214   // C++11 [dcl.constexpr]p3:
1215   //   - every constructor call and implicit conversion used in initializing the
1216   //     return value shall be one of those allowed in a constant expression.
1217   // C++11 [dcl.constexpr]p4:
1218   //   - every constructor involved in initializing non-static data members and
1219   //     base class sub-objects shall be a constexpr constructor.
1220   SmallVector<PartialDiagnosticAt, 8> Diags;
1221   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1222     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1223       << isa<CXXConstructorDecl>(Dcl);
1224     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1225       Diag(Diags[I].first, Diags[I].second);
1226     // Don't return false here: we allow this for compatibility in
1227     // system headers.
1228   }
1229 
1230   return true;
1231 }
1232 
1233 /// isCurrentClassName - Determine whether the identifier II is the
1234 /// name of the class type currently being defined. In the case of
1235 /// nested classes, this will only return true if II is the name of
1236 /// the innermost class.
1237 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1238                               const CXXScopeSpec *SS) {
1239   assert(getLangOpts().CPlusPlus && "No class names in C!");
1240 
1241   CXXRecordDecl *CurDecl;
1242   if (SS && SS->isSet() && !SS->isInvalid()) {
1243     DeclContext *DC = computeDeclContext(*SS, true);
1244     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1245   } else
1246     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1247 
1248   if (CurDecl && CurDecl->getIdentifier())
1249     return &II == CurDecl->getIdentifier();
1250   return false;
1251 }
1252 
1253 /// \brief Determine whether the identifier II is a typo for the name of
1254 /// the class type currently being defined. If so, update it to the identifier
1255 /// that should have been used.
1256 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1257   assert(getLangOpts().CPlusPlus && "No class names in C!");
1258 
1259   if (!getLangOpts().SpellChecking)
1260     return false;
1261 
1262   CXXRecordDecl *CurDecl;
1263   if (SS && SS->isSet() && !SS->isInvalid()) {
1264     DeclContext *DC = computeDeclContext(*SS, true);
1265     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1266   } else
1267     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1268 
1269   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1270       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1271           < II->getLength()) {
1272     II = CurDecl->getIdentifier();
1273     return true;
1274   }
1275 
1276   return false;
1277 }
1278 
1279 /// \brief Determine whether the given class is a base class of the given
1280 /// class, including looking at dependent bases.
1281 static bool findCircularInheritance(const CXXRecordDecl *Class,
1282                                     const CXXRecordDecl *Current) {
1283   SmallVector<const CXXRecordDecl*, 8> Queue;
1284 
1285   Class = Class->getCanonicalDecl();
1286   while (true) {
1287     for (const auto &I : Current->bases()) {
1288       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1289       if (!Base)
1290         continue;
1291 
1292       Base = Base->getDefinition();
1293       if (!Base)
1294         continue;
1295 
1296       if (Base->getCanonicalDecl() == Class)
1297         return true;
1298 
1299       Queue.push_back(Base);
1300     }
1301 
1302     if (Queue.empty())
1303       return false;
1304 
1305     Current = Queue.pop_back_val();
1306   }
1307 
1308   return false;
1309 }
1310 
1311 /// \brief Perform propagation of DLL attributes from a derived class to a
1312 /// templated base class for MS compatibility.
1313 static void propagateDLLAttrToBaseClassTemplate(
1314     Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1315     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1316   if (getDLLAttr(
1317           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1318     // If the base class template has a DLL attribute, don't try to change it.
1319     return;
1320   }
1321 
1322   if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1323     // If the base class is not already specialized, we can do the propagation.
1324     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1325     NewAttr->setInherited(true);
1326     BaseTemplateSpec->addAttr(NewAttr);
1327     return;
1328   }
1329 
1330   bool DifferentAttribute = false;
1331   if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1332     if (!SpecializationAttr->isInherited()) {
1333       // The template has previously been specialized or instantiated with an
1334       // explicit attribute. We should not try to change it.
1335       return;
1336     }
1337     if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1338       // The specialization already has the right attribute.
1339       return;
1340     }
1341     DifferentAttribute = true;
1342   }
1343 
1344   // The template was previously instantiated or explicitly specialized without
1345   // a dll attribute, or the template was previously instantiated with a
1346   // different inherited attribute. It's too late for us to change the
1347   // attribute, so warn that this is unsupported.
1348   S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1349       << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1350   S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1351   if (BaseTemplateSpec->isExplicitSpecialization()) {
1352     S.Diag(BaseTemplateSpec->getLocation(),
1353            diag::note_template_class_explicit_specialization_was_here)
1354         << BaseTemplateSpec;
1355   } else {
1356     S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1357            diag::note_template_class_instantiation_was_here)
1358         << BaseTemplateSpec;
1359   }
1360 }
1361 
1362 /// \brief Check the validity of a C++ base class specifier.
1363 ///
1364 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1365 /// and returns NULL otherwise.
1366 CXXBaseSpecifier *
1367 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1368                          SourceRange SpecifierRange,
1369                          bool Virtual, AccessSpecifier Access,
1370                          TypeSourceInfo *TInfo,
1371                          SourceLocation EllipsisLoc) {
1372   QualType BaseType = TInfo->getType();
1373 
1374   // C++ [class.union]p1:
1375   //   A union shall not have base classes.
1376   if (Class->isUnion()) {
1377     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1378       << SpecifierRange;
1379     return nullptr;
1380   }
1381 
1382   if (EllipsisLoc.isValid() &&
1383       !TInfo->getType()->containsUnexpandedParameterPack()) {
1384     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1385       << TInfo->getTypeLoc().getSourceRange();
1386     EllipsisLoc = SourceLocation();
1387   }
1388 
1389   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1390 
1391   if (BaseType->isDependentType()) {
1392     // Make sure that we don't have circular inheritance among our dependent
1393     // bases. For non-dependent bases, the check for completeness below handles
1394     // this.
1395     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1396       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1397           ((BaseDecl = BaseDecl->getDefinition()) &&
1398            findCircularInheritance(Class, BaseDecl))) {
1399         Diag(BaseLoc, diag::err_circular_inheritance)
1400           << BaseType << Context.getTypeDeclType(Class);
1401 
1402         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1403           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1404             << BaseType;
1405 
1406         return nullptr;
1407       }
1408     }
1409 
1410     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1411                                           Class->getTagKind() == TTK_Class,
1412                                           Access, TInfo, EllipsisLoc);
1413   }
1414 
1415   // Base specifiers must be record types.
1416   if (!BaseType->isRecordType()) {
1417     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1418     return nullptr;
1419   }
1420 
1421   // C++ [class.union]p1:
1422   //   A union shall not be used as a base class.
1423   if (BaseType->isUnionType()) {
1424     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1425     return nullptr;
1426   }
1427 
1428   // For the MS ABI, propagate DLL attributes to base class templates.
1429   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1430     if (Attr *ClassAttr = getDLLAttr(Class)) {
1431       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1432               BaseType->getAsCXXRecordDecl())) {
1433         propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1434                                             BaseTemplate, BaseLoc);
1435       }
1436     }
1437   }
1438 
1439   // C++ [class.derived]p2:
1440   //   The class-name in a base-specifier shall not be an incompletely
1441   //   defined class.
1442   if (RequireCompleteType(BaseLoc, BaseType,
1443                           diag::err_incomplete_base_class, SpecifierRange)) {
1444     Class->setInvalidDecl();
1445     return nullptr;
1446   }
1447 
1448   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1449   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1450   assert(BaseDecl && "Record type has no declaration");
1451   BaseDecl = BaseDecl->getDefinition();
1452   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1453   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1454   assert(CXXBaseDecl && "Base type is not a C++ type");
1455 
1456   // A class which contains a flexible array member is not suitable for use as a
1457   // base class:
1458   //   - If the layout determines that a base comes before another base,
1459   //     the flexible array member would index into the subsequent base.
1460   //   - If the layout determines that base comes before the derived class,
1461   //     the flexible array member would index into the derived class.
1462   if (CXXBaseDecl->hasFlexibleArrayMember()) {
1463     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1464       << CXXBaseDecl->getDeclName();
1465     return nullptr;
1466   }
1467 
1468   // C++ [class]p3:
1469   //   If a class is marked final and it appears as a base-type-specifier in
1470   //   base-clause, the program is ill-formed.
1471   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1472     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1473       << CXXBaseDecl->getDeclName()
1474       << FA->isSpelledAsSealed();
1475     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1476         << CXXBaseDecl->getDeclName() << FA->getRange();
1477     return nullptr;
1478   }
1479 
1480   if (BaseDecl->isInvalidDecl())
1481     Class->setInvalidDecl();
1482 
1483   // Create the base specifier.
1484   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1485                                         Class->getTagKind() == TTK_Class,
1486                                         Access, TInfo, EllipsisLoc);
1487 }
1488 
1489 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1490 /// one entry in the base class list of a class specifier, for
1491 /// example:
1492 ///    class foo : public bar, virtual private baz {
1493 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1494 BaseResult
1495 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1496                          ParsedAttributes &Attributes,
1497                          bool Virtual, AccessSpecifier Access,
1498                          ParsedType basetype, SourceLocation BaseLoc,
1499                          SourceLocation EllipsisLoc) {
1500   if (!classdecl)
1501     return true;
1502 
1503   AdjustDeclIfTemplate(classdecl);
1504   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1505   if (!Class)
1506     return true;
1507 
1508   // We haven't yet attached the base specifiers.
1509   Class->setIsParsingBaseSpecifiers();
1510 
1511   // We do not support any C++11 attributes on base-specifiers yet.
1512   // Diagnose any attributes we see.
1513   if (!Attributes.empty()) {
1514     for (AttributeList *Attr = Attributes.getList(); Attr;
1515          Attr = Attr->getNext()) {
1516       if (Attr->isInvalid() ||
1517           Attr->getKind() == AttributeList::IgnoredAttribute)
1518         continue;
1519       Diag(Attr->getLoc(),
1520            Attr->getKind() == AttributeList::UnknownAttribute
1521              ? diag::warn_unknown_attribute_ignored
1522              : diag::err_base_specifier_attribute)
1523         << Attr->getName();
1524     }
1525   }
1526 
1527   TypeSourceInfo *TInfo = nullptr;
1528   GetTypeFromParser(basetype, &TInfo);
1529 
1530   if (EllipsisLoc.isInvalid() &&
1531       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1532                                       UPPC_BaseType))
1533     return true;
1534 
1535   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1536                                                       Virtual, Access, TInfo,
1537                                                       EllipsisLoc))
1538     return BaseSpec;
1539   else
1540     Class->setInvalidDecl();
1541 
1542   return true;
1543 }
1544 
1545 /// Use small set to collect indirect bases.  As this is only used
1546 /// locally, there's no need to abstract the small size parameter.
1547 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1548 
1549 /// \brief Recursively add the bases of Type.  Don't add Type itself.
1550 static void
1551 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1552                   const QualType &Type)
1553 {
1554   // Even though the incoming type is a base, it might not be
1555   // a class -- it could be a template parm, for instance.
1556   if (auto Rec = Type->getAs<RecordType>()) {
1557     auto Decl = Rec->getAsCXXRecordDecl();
1558 
1559     // Iterate over its bases.
1560     for (const auto &BaseSpec : Decl->bases()) {
1561       QualType Base = Context.getCanonicalType(BaseSpec.getType())
1562         .getUnqualifiedType();
1563       if (Set.insert(Base).second)
1564         // If we've not already seen it, recurse.
1565         NoteIndirectBases(Context, Set, Base);
1566     }
1567   }
1568 }
1569 
1570 /// \brief Performs the actual work of attaching the given base class
1571 /// specifiers to a C++ class.
1572 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1573                                 unsigned NumBases) {
1574  if (NumBases == 0)
1575     return false;
1576 
1577   // Used to keep track of which base types we have already seen, so
1578   // that we can properly diagnose redundant direct base types. Note
1579   // that the key is always the unqualified canonical type of the base
1580   // class.
1581   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1582 
1583   // Used to track indirect bases so we can see if a direct base is
1584   // ambiguous.
1585   IndirectBaseSet IndirectBaseTypes;
1586 
1587   // Copy non-redundant base specifiers into permanent storage.
1588   unsigned NumGoodBases = 0;
1589   bool Invalid = false;
1590   for (unsigned idx = 0; idx < NumBases; ++idx) {
1591     QualType NewBaseType
1592       = Context.getCanonicalType(Bases[idx]->getType());
1593     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1594 
1595     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1596     if (KnownBase) {
1597       // C++ [class.mi]p3:
1598       //   A class shall not be specified as a direct base class of a
1599       //   derived class more than once.
1600       Diag(Bases[idx]->getLocStart(),
1601            diag::err_duplicate_base_class)
1602         << KnownBase->getType()
1603         << Bases[idx]->getSourceRange();
1604 
1605       // Delete the duplicate base class specifier; we're going to
1606       // overwrite its pointer later.
1607       Context.Deallocate(Bases[idx]);
1608 
1609       Invalid = true;
1610     } else {
1611       // Okay, add this new base class.
1612       KnownBase = Bases[idx];
1613       Bases[NumGoodBases++] = Bases[idx];
1614 
1615       // Note this base's direct & indirect bases, if there could be ambiguity.
1616       if (NumBases > 1)
1617         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1618 
1619       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1620         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1621         if (Class->isInterface() &&
1622               (!RD->isInterface() ||
1623                KnownBase->getAccessSpecifier() != AS_public)) {
1624           // The Microsoft extension __interface does not permit bases that
1625           // are not themselves public interfaces.
1626           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1627             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1628             << RD->getSourceRange();
1629           Invalid = true;
1630         }
1631         if (RD->hasAttr<WeakAttr>())
1632           Class->addAttr(WeakAttr::CreateImplicit(Context));
1633       }
1634     }
1635   }
1636 
1637   // Attach the remaining base class specifiers to the derived class.
1638   Class->setBases(Bases, NumGoodBases);
1639 
1640   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1641     // Check whether this direct base is inaccessible due to ambiguity.
1642     QualType BaseType = Bases[idx]->getType();
1643     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1644       .getUnqualifiedType();
1645 
1646     if (IndirectBaseTypes.count(CanonicalBase)) {
1647       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1648                          /*DetectVirtual=*/true);
1649       bool found
1650         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1651       assert(found);
1652       (void)found;
1653 
1654       if (Paths.isAmbiguous(CanonicalBase))
1655         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1656           << BaseType << getAmbiguousPathsDisplayString(Paths)
1657           << Bases[idx]->getSourceRange();
1658       else
1659         assert(Bases[idx]->isVirtual());
1660     }
1661 
1662     // Delete the base class specifier, since its data has been copied
1663     // into the CXXRecordDecl.
1664     Context.Deallocate(Bases[idx]);
1665   }
1666 
1667   return Invalid;
1668 }
1669 
1670 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1671 /// class, after checking whether there are any duplicate base
1672 /// classes.
1673 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1674                                unsigned NumBases) {
1675   if (!ClassDecl || !Bases || !NumBases)
1676     return;
1677 
1678   AdjustDeclIfTemplate(ClassDecl);
1679   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1680 }
1681 
1682 /// \brief Determine whether the type \p Derived is a C++ class that is
1683 /// derived from the type \p Base.
1684 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1685   if (!getLangOpts().CPlusPlus)
1686     return false;
1687 
1688   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1689   if (!DerivedRD)
1690     return false;
1691 
1692   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1693   if (!BaseRD)
1694     return false;
1695 
1696   // If either the base or the derived type is invalid, don't try to
1697   // check whether one is derived from the other.
1698   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1699     return false;
1700 
1701   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1702   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1703 }
1704 
1705 /// \brief Determine whether the type \p Derived is a C++ class that is
1706 /// derived from the type \p Base.
1707 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1708   if (!getLangOpts().CPlusPlus)
1709     return false;
1710 
1711   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1712   if (!DerivedRD)
1713     return false;
1714 
1715   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1716   if (!BaseRD)
1717     return false;
1718 
1719   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1720 }
1721 
1722 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1723                               CXXCastPath &BasePathArray) {
1724   assert(BasePathArray.empty() && "Base path array must be empty!");
1725   assert(Paths.isRecordingPaths() && "Must record paths!");
1726 
1727   const CXXBasePath &Path = Paths.front();
1728 
1729   // We first go backward and check if we have a virtual base.
1730   // FIXME: It would be better if CXXBasePath had the base specifier for
1731   // the nearest virtual base.
1732   unsigned Start = 0;
1733   for (unsigned I = Path.size(); I != 0; --I) {
1734     if (Path[I - 1].Base->isVirtual()) {
1735       Start = I - 1;
1736       break;
1737     }
1738   }
1739 
1740   // Now add all bases.
1741   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1742     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1743 }
1744 
1745 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1746 /// conversion (where Derived and Base are class types) is
1747 /// well-formed, meaning that the conversion is unambiguous (and
1748 /// that all of the base classes are accessible). Returns true
1749 /// and emits a diagnostic if the code is ill-formed, returns false
1750 /// otherwise. Loc is the location where this routine should point to
1751 /// if there is an error, and Range is the source range to highlight
1752 /// if there is an error.
1753 bool
1754 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1755                                    unsigned InaccessibleBaseID,
1756                                    unsigned AmbigiousBaseConvID,
1757                                    SourceLocation Loc, SourceRange Range,
1758                                    DeclarationName Name,
1759                                    CXXCastPath *BasePath) {
1760   // First, determine whether the path from Derived to Base is
1761   // ambiguous. This is slightly more expensive than checking whether
1762   // the Derived to Base conversion exists, because here we need to
1763   // explore multiple paths to determine if there is an ambiguity.
1764   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1765                      /*DetectVirtual=*/false);
1766   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1767   assert(DerivationOkay &&
1768          "Can only be used with a derived-to-base conversion");
1769   (void)DerivationOkay;
1770 
1771   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1772     if (InaccessibleBaseID) {
1773       // Check that the base class can be accessed.
1774       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1775                                    InaccessibleBaseID)) {
1776         case AR_inaccessible:
1777           return true;
1778         case AR_accessible:
1779         case AR_dependent:
1780         case AR_delayed:
1781           break;
1782       }
1783     }
1784 
1785     // Build a base path if necessary.
1786     if (BasePath)
1787       BuildBasePathArray(Paths, *BasePath);
1788     return false;
1789   }
1790 
1791   if (AmbigiousBaseConvID) {
1792     // We know that the derived-to-base conversion is ambiguous, and
1793     // we're going to produce a diagnostic. Perform the derived-to-base
1794     // search just one more time to compute all of the possible paths so
1795     // that we can print them out. This is more expensive than any of
1796     // the previous derived-to-base checks we've done, but at this point
1797     // performance isn't as much of an issue.
1798     Paths.clear();
1799     Paths.setRecordingPaths(true);
1800     bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1801     assert(StillOkay && "Can only be used with a derived-to-base conversion");
1802     (void)StillOkay;
1803 
1804     // Build up a textual representation of the ambiguous paths, e.g.,
1805     // D -> B -> A, that will be used to illustrate the ambiguous
1806     // conversions in the diagnostic. We only print one of the paths
1807     // to each base class subobject.
1808     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1809 
1810     Diag(Loc, AmbigiousBaseConvID)
1811     << Derived << Base << PathDisplayStr << Range << Name;
1812   }
1813   return true;
1814 }
1815 
1816 bool
1817 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1818                                    SourceLocation Loc, SourceRange Range,
1819                                    CXXCastPath *BasePath,
1820                                    bool IgnoreAccess) {
1821   return CheckDerivedToBaseConversion(Derived, Base,
1822                                       IgnoreAccess ? 0
1823                                        : diag::err_upcast_to_inaccessible_base,
1824                                       diag::err_ambiguous_derived_to_base_conv,
1825                                       Loc, Range, DeclarationName(),
1826                                       BasePath);
1827 }
1828 
1829 
1830 /// @brief Builds a string representing ambiguous paths from a
1831 /// specific derived class to different subobjects of the same base
1832 /// class.
1833 ///
1834 /// This function builds a string that can be used in error messages
1835 /// to show the different paths that one can take through the
1836 /// inheritance hierarchy to go from the derived class to different
1837 /// subobjects of a base class. The result looks something like this:
1838 /// @code
1839 /// struct D -> struct B -> struct A
1840 /// struct D -> struct C -> struct A
1841 /// @endcode
1842 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1843   std::string PathDisplayStr;
1844   std::set<unsigned> DisplayedPaths;
1845   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1846        Path != Paths.end(); ++Path) {
1847     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1848       // We haven't displayed a path to this particular base
1849       // class subobject yet.
1850       PathDisplayStr += "\n    ";
1851       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1852       for (CXXBasePath::const_iterator Element = Path->begin();
1853            Element != Path->end(); ++Element)
1854         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1855     }
1856   }
1857 
1858   return PathDisplayStr;
1859 }
1860 
1861 //===----------------------------------------------------------------------===//
1862 // C++ class member Handling
1863 //===----------------------------------------------------------------------===//
1864 
1865 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1866 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1867                                 SourceLocation ASLoc,
1868                                 SourceLocation ColonLoc,
1869                                 AttributeList *Attrs) {
1870   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1871   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1872                                                   ASLoc, ColonLoc);
1873   CurContext->addHiddenDecl(ASDecl);
1874   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1875 }
1876 
1877 /// CheckOverrideControl - Check C++11 override control semantics.
1878 void Sema::CheckOverrideControl(NamedDecl *D) {
1879   if (D->isInvalidDecl())
1880     return;
1881 
1882   // We only care about "override" and "final" declarations.
1883   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1884     return;
1885 
1886   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1887 
1888   // We can't check dependent instance methods.
1889   if (MD && MD->isInstance() &&
1890       (MD->getParent()->hasAnyDependentBases() ||
1891        MD->getType()->isDependentType()))
1892     return;
1893 
1894   if (MD && !MD->isVirtual()) {
1895     // If we have a non-virtual method, check if if hides a virtual method.
1896     // (In that case, it's most likely the method has the wrong type.)
1897     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1898     FindHiddenVirtualMethods(MD, OverloadedMethods);
1899 
1900     if (!OverloadedMethods.empty()) {
1901       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1902         Diag(OA->getLocation(),
1903              diag::override_keyword_hides_virtual_member_function)
1904           << "override" << (OverloadedMethods.size() > 1);
1905       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1906         Diag(FA->getLocation(),
1907              diag::override_keyword_hides_virtual_member_function)
1908           << (FA->isSpelledAsSealed() ? "sealed" : "final")
1909           << (OverloadedMethods.size() > 1);
1910       }
1911       NoteHiddenVirtualMethods(MD, OverloadedMethods);
1912       MD->setInvalidDecl();
1913       return;
1914     }
1915     // Fall through into the general case diagnostic.
1916     // FIXME: We might want to attempt typo correction here.
1917   }
1918 
1919   if (!MD || !MD->isVirtual()) {
1920     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1921       Diag(OA->getLocation(),
1922            diag::override_keyword_only_allowed_on_virtual_member_functions)
1923         << "override" << FixItHint::CreateRemoval(OA->getLocation());
1924       D->dropAttr<OverrideAttr>();
1925     }
1926     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1927       Diag(FA->getLocation(),
1928            diag::override_keyword_only_allowed_on_virtual_member_functions)
1929         << (FA->isSpelledAsSealed() ? "sealed" : "final")
1930         << FixItHint::CreateRemoval(FA->getLocation());
1931       D->dropAttr<FinalAttr>();
1932     }
1933     return;
1934   }
1935 
1936   // C++11 [class.virtual]p5:
1937   //   If a function is marked with the virt-specifier override and
1938   //   does not override a member function of a base class, the program is
1939   //   ill-formed.
1940   bool HasOverriddenMethods =
1941     MD->begin_overridden_methods() != MD->end_overridden_methods();
1942   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1943     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1944       << MD->getDeclName();
1945 }
1946 
1947 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1948   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1949     return;
1950   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1951   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1952       isa<CXXDestructorDecl>(MD))
1953     return;
1954 
1955   SourceLocation Loc = MD->getLocation();
1956   SourceLocation SpellingLoc = Loc;
1957   if (getSourceManager().isMacroArgExpansion(Loc))
1958     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1959   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1960   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
1961       return;
1962 
1963   if (MD->size_overridden_methods() > 0) {
1964     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1965       << MD->getDeclName();
1966     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1967     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1968   }
1969 }
1970 
1971 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1972 /// function overrides a virtual member function marked 'final', according to
1973 /// C++11 [class.virtual]p4.
1974 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1975                                                   const CXXMethodDecl *Old) {
1976   FinalAttr *FA = Old->getAttr<FinalAttr>();
1977   if (!FA)
1978     return false;
1979 
1980   Diag(New->getLocation(), diag::err_final_function_overridden)
1981     << New->getDeclName()
1982     << FA->isSpelledAsSealed();
1983   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1984   return true;
1985 }
1986 
1987 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1988   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1989   // FIXME: Destruction of ObjC lifetime types has side-effects.
1990   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1991     return !RD->isCompleteDefinition() ||
1992            !RD->hasTrivialDefaultConstructor() ||
1993            !RD->hasTrivialDestructor();
1994   return false;
1995 }
1996 
1997 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1998   for (AttributeList *it = list; it != nullptr; it = it->getNext())
1999     if (it->isDeclspecPropertyAttribute())
2000       return it;
2001   return nullptr;
2002 }
2003 
2004 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2005 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2006 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2007 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2008 /// present (but parsing it has been deferred).
2009 NamedDecl *
2010 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2011                                MultiTemplateParamsArg TemplateParameterLists,
2012                                Expr *BW, const VirtSpecifiers &VS,
2013                                InClassInitStyle InitStyle) {
2014   const DeclSpec &DS = D.getDeclSpec();
2015   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2016   DeclarationName Name = NameInfo.getName();
2017   SourceLocation Loc = NameInfo.getLoc();
2018 
2019   // For anonymous bitfields, the location should point to the type.
2020   if (Loc.isInvalid())
2021     Loc = D.getLocStart();
2022 
2023   Expr *BitWidth = static_cast<Expr*>(BW);
2024 
2025   assert(isa<CXXRecordDecl>(CurContext));
2026   assert(!DS.isFriendSpecified());
2027 
2028   bool isFunc = D.isDeclarationOfFunction();
2029 
2030   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2031     // The Microsoft extension __interface only permits public member functions
2032     // and prohibits constructors, destructors, operators, non-public member
2033     // functions, static methods and data members.
2034     unsigned InvalidDecl;
2035     bool ShowDeclName = true;
2036     if (!isFunc)
2037       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2038     else if (AS != AS_public)
2039       InvalidDecl = 2;
2040     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2041       InvalidDecl = 3;
2042     else switch (Name.getNameKind()) {
2043       case DeclarationName::CXXConstructorName:
2044         InvalidDecl = 4;
2045         ShowDeclName = false;
2046         break;
2047 
2048       case DeclarationName::CXXDestructorName:
2049         InvalidDecl = 5;
2050         ShowDeclName = false;
2051         break;
2052 
2053       case DeclarationName::CXXOperatorName:
2054       case DeclarationName::CXXConversionFunctionName:
2055         InvalidDecl = 6;
2056         break;
2057 
2058       default:
2059         InvalidDecl = 0;
2060         break;
2061     }
2062 
2063     if (InvalidDecl) {
2064       if (ShowDeclName)
2065         Diag(Loc, diag::err_invalid_member_in_interface)
2066           << (InvalidDecl-1) << Name;
2067       else
2068         Diag(Loc, diag::err_invalid_member_in_interface)
2069           << (InvalidDecl-1) << "";
2070       return nullptr;
2071     }
2072   }
2073 
2074   // C++ 9.2p6: A member shall not be declared to have automatic storage
2075   // duration (auto, register) or with the extern storage-class-specifier.
2076   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2077   // data members and cannot be applied to names declared const or static,
2078   // and cannot be applied to reference members.
2079   switch (DS.getStorageClassSpec()) {
2080   case DeclSpec::SCS_unspecified:
2081   case DeclSpec::SCS_typedef:
2082   case DeclSpec::SCS_static:
2083     break;
2084   case DeclSpec::SCS_mutable:
2085     if (isFunc) {
2086       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2087 
2088       // FIXME: It would be nicer if the keyword was ignored only for this
2089       // declarator. Otherwise we could get follow-up errors.
2090       D.getMutableDeclSpec().ClearStorageClassSpecs();
2091     }
2092     break;
2093   default:
2094     Diag(DS.getStorageClassSpecLoc(),
2095          diag::err_storageclass_invalid_for_member);
2096     D.getMutableDeclSpec().ClearStorageClassSpecs();
2097     break;
2098   }
2099 
2100   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2101                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2102                       !isFunc);
2103 
2104   if (DS.isConstexprSpecified() && isInstField) {
2105     SemaDiagnosticBuilder B =
2106         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2107     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2108     if (InitStyle == ICIS_NoInit) {
2109       B << 0 << 0;
2110       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2111         B << FixItHint::CreateRemoval(ConstexprLoc);
2112       else {
2113         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2114         D.getMutableDeclSpec().ClearConstexprSpec();
2115         const char *PrevSpec;
2116         unsigned DiagID;
2117         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2118             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2119         (void)Failed;
2120         assert(!Failed && "Making a constexpr member const shouldn't fail");
2121       }
2122     } else {
2123       B << 1;
2124       const char *PrevSpec;
2125       unsigned DiagID;
2126       if (D.getMutableDeclSpec().SetStorageClassSpec(
2127           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2128           Context.getPrintingPolicy())) {
2129         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2130                "This is the only DeclSpec that should fail to be applied");
2131         B << 1;
2132       } else {
2133         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2134         isInstField = false;
2135       }
2136     }
2137   }
2138 
2139   NamedDecl *Member;
2140   if (isInstField) {
2141     CXXScopeSpec &SS = D.getCXXScopeSpec();
2142 
2143     // Data members must have identifiers for names.
2144     if (!Name.isIdentifier()) {
2145       Diag(Loc, diag::err_bad_variable_name)
2146         << Name;
2147       return nullptr;
2148     }
2149 
2150     IdentifierInfo *II = Name.getAsIdentifierInfo();
2151 
2152     // Member field could not be with "template" keyword.
2153     // So TemplateParameterLists should be empty in this case.
2154     if (TemplateParameterLists.size()) {
2155       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2156       if (TemplateParams->size()) {
2157         // There is no such thing as a member field template.
2158         Diag(D.getIdentifierLoc(), diag::err_template_member)
2159             << II
2160             << SourceRange(TemplateParams->getTemplateLoc(),
2161                 TemplateParams->getRAngleLoc());
2162       } else {
2163         // There is an extraneous 'template<>' for this member.
2164         Diag(TemplateParams->getTemplateLoc(),
2165             diag::err_template_member_noparams)
2166             << II
2167             << SourceRange(TemplateParams->getTemplateLoc(),
2168                 TemplateParams->getRAngleLoc());
2169       }
2170       return nullptr;
2171     }
2172 
2173     if (SS.isSet() && !SS.isInvalid()) {
2174       // The user provided a superfluous scope specifier inside a class
2175       // definition:
2176       //
2177       // class X {
2178       //   int X::member;
2179       // };
2180       if (DeclContext *DC = computeDeclContext(SS, false))
2181         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2182       else
2183         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2184           << Name << SS.getRange();
2185 
2186       SS.clear();
2187     }
2188 
2189     AttributeList *MSPropertyAttr =
2190       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2191     if (MSPropertyAttr) {
2192       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2193                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2194       if (!Member)
2195         return nullptr;
2196       isInstField = false;
2197     } else {
2198       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2199                                 BitWidth, InitStyle, AS);
2200       assert(Member && "HandleField never returns null");
2201     }
2202   } else {
2203     assert(InitStyle == ICIS_NoInit ||
2204            D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2205 
2206     Member = HandleDeclarator(S, D, TemplateParameterLists);
2207     if (!Member)
2208       return nullptr;
2209 
2210     // Non-instance-fields can't have a bitfield.
2211     if (BitWidth) {
2212       if (Member->isInvalidDecl()) {
2213         // don't emit another diagnostic.
2214       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2215         // C++ 9.6p3: A bit-field shall not be a static member.
2216         // "static member 'A' cannot be a bit-field"
2217         Diag(Loc, diag::err_static_not_bitfield)
2218           << Name << BitWidth->getSourceRange();
2219       } else if (isa<TypedefDecl>(Member)) {
2220         // "typedef member 'x' cannot be a bit-field"
2221         Diag(Loc, diag::err_typedef_not_bitfield)
2222           << Name << BitWidth->getSourceRange();
2223       } else {
2224         // A function typedef ("typedef int f(); f a;").
2225         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2226         Diag(Loc, diag::err_not_integral_type_bitfield)
2227           << Name << cast<ValueDecl>(Member)->getType()
2228           << BitWidth->getSourceRange();
2229       }
2230 
2231       BitWidth = nullptr;
2232       Member->setInvalidDecl();
2233     }
2234 
2235     Member->setAccess(AS);
2236 
2237     // If we have declared a member function template or static data member
2238     // template, set the access of the templated declaration as well.
2239     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2240       FunTmpl->getTemplatedDecl()->setAccess(AS);
2241     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2242       VarTmpl->getTemplatedDecl()->setAccess(AS);
2243   }
2244 
2245   if (VS.isOverrideSpecified())
2246     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2247   if (VS.isFinalSpecified())
2248     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2249                                             VS.isFinalSpelledSealed()));
2250 
2251   if (VS.getLastLocation().isValid()) {
2252     // Update the end location of a method that has a virt-specifiers.
2253     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2254       MD->setRangeEnd(VS.getLastLocation());
2255   }
2256 
2257   CheckOverrideControl(Member);
2258 
2259   assert((Name || isInstField) && "No identifier for non-field ?");
2260 
2261   if (isInstField) {
2262     FieldDecl *FD = cast<FieldDecl>(Member);
2263     FieldCollector->Add(FD);
2264 
2265     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2266       // Remember all explicit private FieldDecls that have a name, no side
2267       // effects and are not part of a dependent type declaration.
2268       if (!FD->isImplicit() && FD->getDeclName() &&
2269           FD->getAccess() == AS_private &&
2270           !FD->hasAttr<UnusedAttr>() &&
2271           !FD->getParent()->isDependentContext() &&
2272           !InitializationHasSideEffects(*FD))
2273         UnusedPrivateFields.insert(FD);
2274     }
2275   }
2276 
2277   return Member;
2278 }
2279 
2280 namespace {
2281   class UninitializedFieldVisitor
2282       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2283     Sema &S;
2284     // List of Decls to generate a warning on.  Also remove Decls that become
2285     // initialized.
2286     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2287     // List of base classes of the record.  Classes are removed after their
2288     // initializers.
2289     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
2290     // Vector of decls to be removed from the Decl set prior to visiting the
2291     // nodes.  These Decls may have been initialized in the prior initializer.
2292     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
2293     // If non-null, add a note to the warning pointing back to the constructor.
2294     const CXXConstructorDecl *Constructor;
2295     // Variables to hold state when processing an initializer list.  When
2296     // InitList is true, special case initialization of FieldDecls matching
2297     // InitListFieldDecl.
2298     bool InitList;
2299     FieldDecl *InitListFieldDecl;
2300     llvm::SmallVector<unsigned, 4> InitFieldIndex;
2301 
2302   public:
2303     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2304     UninitializedFieldVisitor(Sema &S,
2305                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2306                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2307       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2308         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
2309 
2310     // Returns true if the use of ME is not an uninitialized use.
2311     bool IsInitListMemberExprInitialized(MemberExpr *ME,
2312                                          bool CheckReferenceOnly) {
2313       llvm::SmallVector<FieldDecl*, 4> Fields;
2314       bool ReferenceField = false;
2315       while (ME) {
2316         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2317         if (!FD)
2318           return false;
2319         Fields.push_back(FD);
2320         if (FD->getType()->isReferenceType())
2321           ReferenceField = true;
2322         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2323       }
2324 
2325       // Binding a reference to an unintialized field is not an
2326       // uninitialized use.
2327       if (CheckReferenceOnly && !ReferenceField)
2328         return true;
2329 
2330       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2331       // Discard the first field since it is the field decl that is being
2332       // initialized.
2333       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2334         UsedFieldIndex.push_back((*I)->getFieldIndex());
2335       }
2336 
2337       for (auto UsedIter = UsedFieldIndex.begin(),
2338                 UsedEnd = UsedFieldIndex.end(),
2339                 OrigIter = InitFieldIndex.begin(),
2340                 OrigEnd = InitFieldIndex.end();
2341            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2342         if (*UsedIter < *OrigIter)
2343           return true;
2344         if (*UsedIter > *OrigIter)
2345           break;
2346       }
2347 
2348       return false;
2349     }
2350 
2351     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2352                           bool AddressOf) {
2353       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2354         return;
2355 
2356       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2357       // or union.
2358       MemberExpr *FieldME = ME;
2359 
2360       bool AllPODFields = FieldME->getType().isPODType(S.Context);
2361 
2362       Expr *Base = ME;
2363       while (MemberExpr *SubME =
2364                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
2365 
2366         if (isa<VarDecl>(SubME->getMemberDecl()))
2367           return;
2368 
2369         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
2370           if (!FD->isAnonymousStructOrUnion())
2371             FieldME = SubME;
2372 
2373         if (!FieldME->getType().isPODType(S.Context))
2374           AllPODFields = false;
2375 
2376         Base = SubME->getBase();
2377       }
2378 
2379       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
2380         return;
2381 
2382       if (AddressOf && AllPODFields)
2383         return;
2384 
2385       ValueDecl* FoundVD = FieldME->getMemberDecl();
2386 
2387       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2388         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2389           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2390         }
2391 
2392         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2393           QualType T = BaseCast->getType();
2394           if (T->isPointerType() &&
2395               BaseClasses.count(T->getPointeeType())) {
2396             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2397                 << T->getPointeeType() << FoundVD;
2398           }
2399         }
2400       }
2401 
2402       if (!Decls.count(FoundVD))
2403         return;
2404 
2405       const bool IsReference = FoundVD->getType()->isReferenceType();
2406 
2407       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2408         // Special checking for initializer lists.
2409         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2410           return;
2411         }
2412       } else {
2413         // Prevent double warnings on use of unbounded references.
2414         if (CheckReferenceOnly && !IsReference)
2415           return;
2416       }
2417 
2418       unsigned diag = IsReference
2419           ? diag::warn_reference_field_is_uninit
2420           : diag::warn_field_is_uninit;
2421       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2422       if (Constructor)
2423         S.Diag(Constructor->getLocation(),
2424                diag::note_uninit_in_this_constructor)
2425           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2426 
2427     }
2428 
2429     void HandleValue(Expr *E, bool AddressOf) {
2430       E = E->IgnoreParens();
2431 
2432       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2433         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2434                          AddressOf /*AddressOf*/);
2435         return;
2436       }
2437 
2438       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2439         Visit(CO->getCond());
2440         HandleValue(CO->getTrueExpr(), AddressOf);
2441         HandleValue(CO->getFalseExpr(), AddressOf);
2442         return;
2443       }
2444 
2445       if (BinaryConditionalOperator *BCO =
2446               dyn_cast<BinaryConditionalOperator>(E)) {
2447         Visit(BCO->getCond());
2448         HandleValue(BCO->getFalseExpr(), AddressOf);
2449         return;
2450       }
2451 
2452       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2453         HandleValue(OVE->getSourceExpr(), AddressOf);
2454         return;
2455       }
2456 
2457       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2458         switch (BO->getOpcode()) {
2459         default:
2460           break;
2461         case(BO_PtrMemD):
2462         case(BO_PtrMemI):
2463           HandleValue(BO->getLHS(), AddressOf);
2464           Visit(BO->getRHS());
2465           return;
2466         case(BO_Comma):
2467           Visit(BO->getLHS());
2468           HandleValue(BO->getRHS(), AddressOf);
2469           return;
2470         }
2471       }
2472 
2473       Visit(E);
2474     }
2475 
2476     void CheckInitListExpr(InitListExpr *ILE) {
2477       InitFieldIndex.push_back(0);
2478       for (auto Child : ILE->children()) {
2479         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2480           CheckInitListExpr(SubList);
2481         } else {
2482           Visit(Child);
2483         }
2484         ++InitFieldIndex.back();
2485       }
2486       InitFieldIndex.pop_back();
2487     }
2488 
2489     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2490                           FieldDecl *Field, const Type *BaseClass) {
2491       // Remove Decls that may have been initialized in the previous
2492       // initializer.
2493       for (ValueDecl* VD : DeclsToRemove)
2494         Decls.erase(VD);
2495       DeclsToRemove.clear();
2496 
2497       Constructor = FieldConstructor;
2498       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2499 
2500       if (ILE && Field) {
2501         InitList = true;
2502         InitListFieldDecl = Field;
2503         InitFieldIndex.clear();
2504         CheckInitListExpr(ILE);
2505       } else {
2506         InitList = false;
2507         Visit(E);
2508       }
2509 
2510       if (Field)
2511         Decls.erase(Field);
2512       if (BaseClass)
2513         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
2514     }
2515 
2516     void VisitMemberExpr(MemberExpr *ME) {
2517       // All uses of unbounded reference fields will warn.
2518       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
2519     }
2520 
2521     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2522       if (E->getCastKind() == CK_LValueToRValue) {
2523         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2524         return;
2525       }
2526 
2527       Inherited::VisitImplicitCastExpr(E);
2528     }
2529 
2530     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2531       if (E->getConstructor()->isCopyConstructor()) {
2532         Expr *ArgExpr = E->getArg(0);
2533         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2534           if (ILE->getNumInits() == 1)
2535             ArgExpr = ILE->getInit(0);
2536         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2537           if (ICE->getCastKind() == CK_NoOp)
2538             ArgExpr = ICE->getSubExpr();
2539         HandleValue(ArgExpr, false /*AddressOf*/);
2540         return;
2541       }
2542       Inherited::VisitCXXConstructExpr(E);
2543     }
2544 
2545     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2546       Expr *Callee = E->getCallee();
2547       if (isa<MemberExpr>(Callee)) {
2548         HandleValue(Callee, false /*AddressOf*/);
2549         for (auto Arg : E->arguments())
2550           Visit(Arg);
2551         return;
2552       }
2553 
2554       Inherited::VisitCXXMemberCallExpr(E);
2555     }
2556 
2557     void VisitCallExpr(CallExpr *E) {
2558       // Treat std::move as a use.
2559       if (E->getNumArgs() == 1) {
2560         if (FunctionDecl *FD = E->getDirectCallee()) {
2561           if (FD->isInStdNamespace() && FD->getIdentifier() &&
2562               FD->getIdentifier()->isStr("move")) {
2563             HandleValue(E->getArg(0), false /*AddressOf*/);
2564             return;
2565           }
2566         }
2567       }
2568 
2569       Inherited::VisitCallExpr(E);
2570     }
2571 
2572     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2573       Expr *Callee = E->getCallee();
2574 
2575       if (isa<UnresolvedLookupExpr>(Callee))
2576         return Inherited::VisitCXXOperatorCallExpr(E);
2577 
2578       Visit(Callee);
2579       for (auto Arg : E->arguments())
2580         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2581     }
2582 
2583     void VisitBinaryOperator(BinaryOperator *E) {
2584       // If a field assignment is detected, remove the field from the
2585       // uninitiailized field set.
2586       if (E->getOpcode() == BO_Assign)
2587         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2588           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2589             if (!FD->getType()->isReferenceType())
2590               DeclsToRemove.push_back(FD);
2591 
2592       if (E->isCompoundAssignmentOp()) {
2593         HandleValue(E->getLHS(), false /*AddressOf*/);
2594         Visit(E->getRHS());
2595         return;
2596       }
2597 
2598       Inherited::VisitBinaryOperator(E);
2599     }
2600 
2601     void VisitUnaryOperator(UnaryOperator *E) {
2602       if (E->isIncrementDecrementOp()) {
2603         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2604         return;
2605       }
2606       if (E->getOpcode() == UO_AddrOf) {
2607         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2608           HandleValue(ME->getBase(), true /*AddressOf*/);
2609           return;
2610         }
2611       }
2612 
2613       Inherited::VisitUnaryOperator(E);
2614     }
2615   };
2616 
2617   // Diagnose value-uses of fields to initialize themselves, e.g.
2618   //   foo(foo)
2619   // where foo is not also a parameter to the constructor.
2620   // Also diagnose across field uninitialized use such as
2621   //   x(y), y(x)
2622   // TODO: implement -Wuninitialized and fold this into that framework.
2623   static void DiagnoseUninitializedFields(
2624       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2625 
2626     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2627                                            Constructor->getLocation())) {
2628       return;
2629     }
2630 
2631     if (Constructor->isInvalidDecl())
2632       return;
2633 
2634     const CXXRecordDecl *RD = Constructor->getParent();
2635 
2636     if (RD->getDescribedClassTemplate())
2637       return;
2638 
2639     // Holds fields that are uninitialized.
2640     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2641 
2642     // At the beginning, all fields are uninitialized.
2643     for (auto *I : RD->decls()) {
2644       if (auto *FD = dyn_cast<FieldDecl>(I)) {
2645         UninitializedFields.insert(FD);
2646       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2647         UninitializedFields.insert(IFD->getAnonField());
2648       }
2649     }
2650 
2651     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2652     for (auto I : RD->bases())
2653       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2654 
2655     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2656       return;
2657 
2658     UninitializedFieldVisitor UninitializedChecker(SemaRef,
2659                                                    UninitializedFields,
2660                                                    UninitializedBaseClasses);
2661 
2662     for (const auto *FieldInit : Constructor->inits()) {
2663       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2664         break;
2665 
2666       Expr *InitExpr = FieldInit->getInit();
2667       if (!InitExpr)
2668         continue;
2669 
2670       if (CXXDefaultInitExpr *Default =
2671               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2672         InitExpr = Default->getExpr();
2673         if (!InitExpr)
2674           continue;
2675         // In class initializers will point to the constructor.
2676         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2677                                               FieldInit->getAnyMember(),
2678                                               FieldInit->getBaseClass());
2679       } else {
2680         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2681                                               FieldInit->getAnyMember(),
2682                                               FieldInit->getBaseClass());
2683       }
2684     }
2685   }
2686 } // namespace
2687 
2688 /// \brief Enter a new C++ default initializer scope. After calling this, the
2689 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2690 /// parsing or instantiating the initializer failed.
2691 void Sema::ActOnStartCXXInClassMemberInitializer() {
2692   // Create a synthetic function scope to represent the call to the constructor
2693   // that notionally surrounds a use of this initializer.
2694   PushFunctionScope();
2695 }
2696 
2697 /// \brief This is invoked after parsing an in-class initializer for a
2698 /// non-static C++ class member, and after instantiating an in-class initializer
2699 /// in a class template. Such actions are deferred until the class is complete.
2700 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2701                                                   SourceLocation InitLoc,
2702                                                   Expr *InitExpr) {
2703   // Pop the notional constructor scope we created earlier.
2704   PopFunctionScopeInfo(nullptr, D);
2705 
2706   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2707   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
2708          "must set init style when field is created");
2709 
2710   if (!InitExpr) {
2711     D->setInvalidDecl();
2712     if (FD)
2713       FD->removeInClassInitializer();
2714     return;
2715   }
2716 
2717   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2718     FD->setInvalidDecl();
2719     FD->removeInClassInitializer();
2720     return;
2721   }
2722 
2723   ExprResult Init = InitExpr;
2724   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2725     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2726     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2727         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2728         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2729     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2730     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2731     if (Init.isInvalid()) {
2732       FD->setInvalidDecl();
2733       return;
2734     }
2735   }
2736 
2737   // C++11 [class.base.init]p7:
2738   //   The initialization of each base and member constitutes a
2739   //   full-expression.
2740   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2741   if (Init.isInvalid()) {
2742     FD->setInvalidDecl();
2743     return;
2744   }
2745 
2746   InitExpr = Init.get();
2747 
2748   FD->setInClassInitializer(InitExpr);
2749 }
2750 
2751 /// \brief Find the direct and/or virtual base specifiers that
2752 /// correspond to the given base type, for use in base initialization
2753 /// within a constructor.
2754 static bool FindBaseInitializer(Sema &SemaRef,
2755                                 CXXRecordDecl *ClassDecl,
2756                                 QualType BaseType,
2757                                 const CXXBaseSpecifier *&DirectBaseSpec,
2758                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2759   // First, check for a direct base class.
2760   DirectBaseSpec = nullptr;
2761   for (const auto &Base : ClassDecl->bases()) {
2762     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2763       // We found a direct base of this type. That's what we're
2764       // initializing.
2765       DirectBaseSpec = &Base;
2766       break;
2767     }
2768   }
2769 
2770   // Check for a virtual base class.
2771   // FIXME: We might be able to short-circuit this if we know in advance that
2772   // there are no virtual bases.
2773   VirtualBaseSpec = nullptr;
2774   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2775     // We haven't found a base yet; search the class hierarchy for a
2776     // virtual base class.
2777     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2778                        /*DetectVirtual=*/false);
2779     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2780                               BaseType, Paths)) {
2781       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2782            Path != Paths.end(); ++Path) {
2783         if (Path->back().Base->isVirtual()) {
2784           VirtualBaseSpec = Path->back().Base;
2785           break;
2786         }
2787       }
2788     }
2789   }
2790 
2791   return DirectBaseSpec || VirtualBaseSpec;
2792 }
2793 
2794 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2795 MemInitResult
2796 Sema::ActOnMemInitializer(Decl *ConstructorD,
2797                           Scope *S,
2798                           CXXScopeSpec &SS,
2799                           IdentifierInfo *MemberOrBase,
2800                           ParsedType TemplateTypeTy,
2801                           const DeclSpec &DS,
2802                           SourceLocation IdLoc,
2803                           Expr *InitList,
2804                           SourceLocation EllipsisLoc) {
2805   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2806                              DS, IdLoc, InitList,
2807                              EllipsisLoc);
2808 }
2809 
2810 /// \brief Handle a C++ member initializer using parentheses syntax.
2811 MemInitResult
2812 Sema::ActOnMemInitializer(Decl *ConstructorD,
2813                           Scope *S,
2814                           CXXScopeSpec &SS,
2815                           IdentifierInfo *MemberOrBase,
2816                           ParsedType TemplateTypeTy,
2817                           const DeclSpec &DS,
2818                           SourceLocation IdLoc,
2819                           SourceLocation LParenLoc,
2820                           ArrayRef<Expr *> Args,
2821                           SourceLocation RParenLoc,
2822                           SourceLocation EllipsisLoc) {
2823   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2824                                            Args, RParenLoc);
2825   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2826                              DS, IdLoc, List, EllipsisLoc);
2827 }
2828 
2829 namespace {
2830 
2831 // Callback to only accept typo corrections that can be a valid C++ member
2832 // intializer: either a non-static field member or a base class.
2833 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2834 public:
2835   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2836       : ClassDecl(ClassDecl) {}
2837 
2838   bool ValidateCandidate(const TypoCorrection &candidate) override {
2839     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2840       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2841         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2842       return isa<TypeDecl>(ND);
2843     }
2844     return false;
2845   }
2846 
2847 private:
2848   CXXRecordDecl *ClassDecl;
2849 };
2850 
2851 }
2852 
2853 /// \brief Handle a C++ member initializer.
2854 MemInitResult
2855 Sema::BuildMemInitializer(Decl *ConstructorD,
2856                           Scope *S,
2857                           CXXScopeSpec &SS,
2858                           IdentifierInfo *MemberOrBase,
2859                           ParsedType TemplateTypeTy,
2860                           const DeclSpec &DS,
2861                           SourceLocation IdLoc,
2862                           Expr *Init,
2863                           SourceLocation EllipsisLoc) {
2864   ExprResult Res = CorrectDelayedTyposInExpr(Init);
2865   if (!Res.isUsable())
2866     return true;
2867   Init = Res.get();
2868 
2869   if (!ConstructorD)
2870     return true;
2871 
2872   AdjustDeclIfTemplate(ConstructorD);
2873 
2874   CXXConstructorDecl *Constructor
2875     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2876   if (!Constructor) {
2877     // The user wrote a constructor initializer on a function that is
2878     // not a C++ constructor. Ignore the error for now, because we may
2879     // have more member initializers coming; we'll diagnose it just
2880     // once in ActOnMemInitializers.
2881     return true;
2882   }
2883 
2884   CXXRecordDecl *ClassDecl = Constructor->getParent();
2885 
2886   // C++ [class.base.init]p2:
2887   //   Names in a mem-initializer-id are looked up in the scope of the
2888   //   constructor's class and, if not found in that scope, are looked
2889   //   up in the scope containing the constructor's definition.
2890   //   [Note: if the constructor's class contains a member with the
2891   //   same name as a direct or virtual base class of the class, a
2892   //   mem-initializer-id naming the member or base class and composed
2893   //   of a single identifier refers to the class member. A
2894   //   mem-initializer-id for the hidden base class may be specified
2895   //   using a qualified name. ]
2896   if (!SS.getScopeRep() && !TemplateTypeTy) {
2897     // Look for a member, first.
2898     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
2899     if (!Result.empty()) {
2900       ValueDecl *Member;
2901       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2902           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2903         if (EllipsisLoc.isValid())
2904           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2905             << MemberOrBase
2906             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2907 
2908         return BuildMemberInitializer(Member, Init, IdLoc);
2909       }
2910     }
2911   }
2912   // It didn't name a member, so see if it names a class.
2913   QualType BaseType;
2914   TypeSourceInfo *TInfo = nullptr;
2915 
2916   if (TemplateTypeTy) {
2917     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2918   } else if (DS.getTypeSpecType() == TST_decltype) {
2919     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2920   } else {
2921     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2922     LookupParsedName(R, S, &SS);
2923 
2924     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2925     if (!TyD) {
2926       if (R.isAmbiguous()) return true;
2927 
2928       // We don't want access-control diagnostics here.
2929       R.suppressDiagnostics();
2930 
2931       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2932         bool NotUnknownSpecialization = false;
2933         DeclContext *DC = computeDeclContext(SS, false);
2934         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2935           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2936 
2937         if (!NotUnknownSpecialization) {
2938           // When the scope specifier can refer to a member of an unknown
2939           // specialization, we take it as a type name.
2940           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2941                                        SS.getWithLocInContext(Context),
2942                                        *MemberOrBase, IdLoc);
2943           if (BaseType.isNull())
2944             return true;
2945 
2946           R.clear();
2947           R.setLookupName(MemberOrBase);
2948         }
2949       }
2950 
2951       // If no results were found, try to correct typos.
2952       TypoCorrection Corr;
2953       if (R.empty() && BaseType.isNull() &&
2954           (Corr = CorrectTypo(
2955                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2956                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2957                CTK_ErrorRecovery, ClassDecl))) {
2958         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2959           // We have found a non-static data member with a similar
2960           // name to what was typed; complain and initialize that
2961           // member.
2962           diagnoseTypo(Corr,
2963                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2964                          << MemberOrBase << true);
2965           return BuildMemberInitializer(Member, Init, IdLoc);
2966         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2967           const CXXBaseSpecifier *DirectBaseSpec;
2968           const CXXBaseSpecifier *VirtualBaseSpec;
2969           if (FindBaseInitializer(*this, ClassDecl,
2970                                   Context.getTypeDeclType(Type),
2971                                   DirectBaseSpec, VirtualBaseSpec)) {
2972             // We have found a direct or virtual base class with a
2973             // similar name to what was typed; complain and initialize
2974             // that base class.
2975             diagnoseTypo(Corr,
2976                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2977                            << MemberOrBase << false,
2978                          PDiag() /*Suppress note, we provide our own.*/);
2979 
2980             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2981                                                               : VirtualBaseSpec;
2982             Diag(BaseSpec->getLocStart(),
2983                  diag::note_base_class_specified_here)
2984               << BaseSpec->getType()
2985               << BaseSpec->getSourceRange();
2986 
2987             TyD = Type;
2988           }
2989         }
2990       }
2991 
2992       if (!TyD && BaseType.isNull()) {
2993         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2994           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2995         return true;
2996       }
2997     }
2998 
2999     if (BaseType.isNull()) {
3000       BaseType = Context.getTypeDeclType(TyD);
3001       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3002       if (SS.isSet())
3003         // FIXME: preserve source range information
3004         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3005                                              BaseType);
3006     }
3007   }
3008 
3009   if (!TInfo)
3010     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3011 
3012   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3013 }
3014 
3015 /// Checks a member initializer expression for cases where reference (or
3016 /// pointer) members are bound to by-value parameters (or their addresses).
3017 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3018                                                Expr *Init,
3019                                                SourceLocation IdLoc) {
3020   QualType MemberTy = Member->getType();
3021 
3022   // We only handle pointers and references currently.
3023   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3024   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3025     return;
3026 
3027   const bool IsPointer = MemberTy->isPointerType();
3028   if (IsPointer) {
3029     if (const UnaryOperator *Op
3030           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3031       // The only case we're worried about with pointers requires taking the
3032       // address.
3033       if (Op->getOpcode() != UO_AddrOf)
3034         return;
3035 
3036       Init = Op->getSubExpr();
3037     } else {
3038       // We only handle address-of expression initializers for pointers.
3039       return;
3040     }
3041   }
3042 
3043   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3044     // We only warn when referring to a non-reference parameter declaration.
3045     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3046     if (!Parameter || Parameter->getType()->isReferenceType())
3047       return;
3048 
3049     S.Diag(Init->getExprLoc(),
3050            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3051                      : diag::warn_bind_ref_member_to_parameter)
3052       << Member << Parameter << Init->getSourceRange();
3053   } else {
3054     // Other initializers are fine.
3055     return;
3056   }
3057 
3058   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3059     << (unsigned)IsPointer;
3060 }
3061 
3062 MemInitResult
3063 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3064                              SourceLocation IdLoc) {
3065   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3066   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3067   assert((DirectMember || IndirectMember) &&
3068          "Member must be a FieldDecl or IndirectFieldDecl");
3069 
3070   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3071     return true;
3072 
3073   if (Member->isInvalidDecl())
3074     return true;
3075 
3076   MultiExprArg Args;
3077   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3078     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3079   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3080     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3081   } else {
3082     // Template instantiation doesn't reconstruct ParenListExprs for us.
3083     Args = Init;
3084   }
3085 
3086   SourceRange InitRange = Init->getSourceRange();
3087 
3088   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3089     // Can't check initialization for a member of dependent type or when
3090     // any of the arguments are type-dependent expressions.
3091     DiscardCleanupsInEvaluationContext();
3092   } else {
3093     bool InitList = false;
3094     if (isa<InitListExpr>(Init)) {
3095       InitList = true;
3096       Args = Init;
3097     }
3098 
3099     // Initialize the member.
3100     InitializedEntity MemberEntity =
3101       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3102                    : InitializedEntity::InitializeMember(IndirectMember,
3103                                                          nullptr);
3104     InitializationKind Kind =
3105       InitList ? InitializationKind::CreateDirectList(IdLoc)
3106                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3107                                                   InitRange.getEnd());
3108 
3109     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3110     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3111                                             nullptr);
3112     if (MemberInit.isInvalid())
3113       return true;
3114 
3115     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3116 
3117     // C++11 [class.base.init]p7:
3118     //   The initialization of each base and member constitutes a
3119     //   full-expression.
3120     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3121     if (MemberInit.isInvalid())
3122       return true;
3123 
3124     Init = MemberInit.get();
3125   }
3126 
3127   if (DirectMember) {
3128     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3129                                             InitRange.getBegin(), Init,
3130                                             InitRange.getEnd());
3131   } else {
3132     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3133                                             InitRange.getBegin(), Init,
3134                                             InitRange.getEnd());
3135   }
3136 }
3137 
3138 MemInitResult
3139 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3140                                  CXXRecordDecl *ClassDecl) {
3141   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3142   if (!LangOpts.CPlusPlus11)
3143     return Diag(NameLoc, diag::err_delegating_ctor)
3144       << TInfo->getTypeLoc().getLocalSourceRange();
3145   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3146 
3147   bool InitList = true;
3148   MultiExprArg Args = Init;
3149   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3150     InitList = false;
3151     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3152   }
3153 
3154   SourceRange InitRange = Init->getSourceRange();
3155   // Initialize the object.
3156   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3157                                      QualType(ClassDecl->getTypeForDecl(), 0));
3158   InitializationKind Kind =
3159     InitList ? InitializationKind::CreateDirectList(NameLoc)
3160              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3161                                                 InitRange.getEnd());
3162   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3163   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3164                                               Args, nullptr);
3165   if (DelegationInit.isInvalid())
3166     return true;
3167 
3168   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3169          "Delegating constructor with no target?");
3170 
3171   // C++11 [class.base.init]p7:
3172   //   The initialization of each base and member constitutes a
3173   //   full-expression.
3174   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3175                                        InitRange.getBegin());
3176   if (DelegationInit.isInvalid())
3177     return true;
3178 
3179   // If we are in a dependent context, template instantiation will
3180   // perform this type-checking again. Just save the arguments that we
3181   // received in a ParenListExpr.
3182   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3183   // of the information that we have about the base
3184   // initializer. However, deconstructing the ASTs is a dicey process,
3185   // and this approach is far more likely to get the corner cases right.
3186   if (CurContext->isDependentContext())
3187     DelegationInit = Init;
3188 
3189   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3190                                           DelegationInit.getAs<Expr>(),
3191                                           InitRange.getEnd());
3192 }
3193 
3194 MemInitResult
3195 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3196                            Expr *Init, CXXRecordDecl *ClassDecl,
3197                            SourceLocation EllipsisLoc) {
3198   SourceLocation BaseLoc
3199     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3200 
3201   if (!BaseType->isDependentType() && !BaseType->isRecordType())
3202     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3203              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3204 
3205   // C++ [class.base.init]p2:
3206   //   [...] Unless the mem-initializer-id names a nonstatic data
3207   //   member of the constructor's class or a direct or virtual base
3208   //   of that class, the mem-initializer is ill-formed. A
3209   //   mem-initializer-list can initialize a base class using any
3210   //   name that denotes that base class type.
3211   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3212 
3213   SourceRange InitRange = Init->getSourceRange();
3214   if (EllipsisLoc.isValid()) {
3215     // This is a pack expansion.
3216     if (!BaseType->containsUnexpandedParameterPack())  {
3217       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3218         << SourceRange(BaseLoc, InitRange.getEnd());
3219 
3220       EllipsisLoc = SourceLocation();
3221     }
3222   } else {
3223     // Check for any unexpanded parameter packs.
3224     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3225       return true;
3226 
3227     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3228       return true;
3229   }
3230 
3231   // Check for direct and virtual base classes.
3232   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3233   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3234   if (!Dependent) {
3235     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3236                                        BaseType))
3237       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3238 
3239     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3240                         VirtualBaseSpec);
3241 
3242     // C++ [base.class.init]p2:
3243     // Unless the mem-initializer-id names a nonstatic data member of the
3244     // constructor's class or a direct or virtual base of that class, the
3245     // mem-initializer is ill-formed.
3246     if (!DirectBaseSpec && !VirtualBaseSpec) {
3247       // If the class has any dependent bases, then it's possible that
3248       // one of those types will resolve to the same type as
3249       // BaseType. Therefore, just treat this as a dependent base
3250       // class initialization.  FIXME: Should we try to check the
3251       // initialization anyway? It seems odd.
3252       if (ClassDecl->hasAnyDependentBases())
3253         Dependent = true;
3254       else
3255         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3256           << BaseType << Context.getTypeDeclType(ClassDecl)
3257           << BaseTInfo->getTypeLoc().getLocalSourceRange();
3258     }
3259   }
3260 
3261   if (Dependent) {
3262     DiscardCleanupsInEvaluationContext();
3263 
3264     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3265                                             /*IsVirtual=*/false,
3266                                             InitRange.getBegin(), Init,
3267                                             InitRange.getEnd(), EllipsisLoc);
3268   }
3269 
3270   // C++ [base.class.init]p2:
3271   //   If a mem-initializer-id is ambiguous because it designates both
3272   //   a direct non-virtual base class and an inherited virtual base
3273   //   class, the mem-initializer is ill-formed.
3274   if (DirectBaseSpec && VirtualBaseSpec)
3275     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3276       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3277 
3278   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3279   if (!BaseSpec)
3280     BaseSpec = VirtualBaseSpec;
3281 
3282   // Initialize the base.
3283   bool InitList = true;
3284   MultiExprArg Args = Init;
3285   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3286     InitList = false;
3287     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3288   }
3289 
3290   InitializedEntity BaseEntity =
3291     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3292   InitializationKind Kind =
3293     InitList ? InitializationKind::CreateDirectList(BaseLoc)
3294              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3295                                                 InitRange.getEnd());
3296   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3297   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3298   if (BaseInit.isInvalid())
3299     return true;
3300 
3301   // C++11 [class.base.init]p7:
3302   //   The initialization of each base and member constitutes a
3303   //   full-expression.
3304   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3305   if (BaseInit.isInvalid())
3306     return true;
3307 
3308   // If we are in a dependent context, template instantiation will
3309   // perform this type-checking again. Just save the arguments that we
3310   // received in a ParenListExpr.
3311   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3312   // of the information that we have about the base
3313   // initializer. However, deconstructing the ASTs is a dicey process,
3314   // and this approach is far more likely to get the corner cases right.
3315   if (CurContext->isDependentContext())
3316     BaseInit = Init;
3317 
3318   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3319                                           BaseSpec->isVirtual(),
3320                                           InitRange.getBegin(),
3321                                           BaseInit.getAs<Expr>(),
3322                                           InitRange.getEnd(), EllipsisLoc);
3323 }
3324 
3325 // Create a static_cast\<T&&>(expr).
3326 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3327   if (T.isNull()) T = E->getType();
3328   QualType TargetType = SemaRef.BuildReferenceType(
3329       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3330   SourceLocation ExprLoc = E->getLocStart();
3331   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3332       TargetType, ExprLoc);
3333 
3334   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3335                                    SourceRange(ExprLoc, ExprLoc),
3336                                    E->getSourceRange()).get();
3337 }
3338 
3339 /// ImplicitInitializerKind - How an implicit base or member initializer should
3340 /// initialize its base or member.
3341 enum ImplicitInitializerKind {
3342   IIK_Default,
3343   IIK_Copy,
3344   IIK_Move,
3345   IIK_Inherit
3346 };
3347 
3348 static bool
3349 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3350                              ImplicitInitializerKind ImplicitInitKind,
3351                              CXXBaseSpecifier *BaseSpec,
3352                              bool IsInheritedVirtualBase,
3353                              CXXCtorInitializer *&CXXBaseInit) {
3354   InitializedEntity InitEntity
3355     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3356                                         IsInheritedVirtualBase);
3357 
3358   ExprResult BaseInit;
3359 
3360   switch (ImplicitInitKind) {
3361   case IIK_Inherit: {
3362     const CXXRecordDecl *Inherited =
3363         Constructor->getInheritedConstructor()->getParent();
3364     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3365     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3366       // C++11 [class.inhctor]p8:
3367       //   Each expression in the expression-list is of the form
3368       //   static_cast<T&&>(p), where p is the name of the corresponding
3369       //   constructor parameter and T is the declared type of p.
3370       SmallVector<Expr*, 16> Args;
3371       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3372         ParmVarDecl *PD = Constructor->getParamDecl(I);
3373         ExprResult ArgExpr =
3374             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3375                                      VK_LValue, SourceLocation());
3376         if (ArgExpr.isInvalid())
3377           return true;
3378         Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3379       }
3380 
3381       InitializationKind InitKind = InitializationKind::CreateDirect(
3382           Constructor->getLocation(), SourceLocation(), SourceLocation());
3383       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3384       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3385       break;
3386     }
3387   }
3388   // Fall through.
3389   case IIK_Default: {
3390     InitializationKind InitKind
3391       = InitializationKind::CreateDefault(Constructor->getLocation());
3392     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3393     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3394     break;
3395   }
3396 
3397   case IIK_Move:
3398   case IIK_Copy: {
3399     bool Moving = ImplicitInitKind == IIK_Move;
3400     ParmVarDecl *Param = Constructor->getParamDecl(0);
3401     QualType ParamType = Param->getType().getNonReferenceType();
3402 
3403     Expr *CopyCtorArg =
3404       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3405                           SourceLocation(), Param, false,
3406                           Constructor->getLocation(), ParamType,
3407                           VK_LValue, nullptr);
3408 
3409     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3410 
3411     // Cast to the base class to avoid ambiguities.
3412     QualType ArgTy =
3413       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3414                                        ParamType.getQualifiers());
3415 
3416     if (Moving) {
3417       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3418     }
3419 
3420     CXXCastPath BasePath;
3421     BasePath.push_back(BaseSpec);
3422     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3423                                             CK_UncheckedDerivedToBase,
3424                                             Moving ? VK_XValue : VK_LValue,
3425                                             &BasePath).get();
3426 
3427     InitializationKind InitKind
3428       = InitializationKind::CreateDirect(Constructor->getLocation(),
3429                                          SourceLocation(), SourceLocation());
3430     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3431     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3432     break;
3433   }
3434   }
3435 
3436   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3437   if (BaseInit.isInvalid())
3438     return true;
3439 
3440   CXXBaseInit =
3441     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3442                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3443                                                         SourceLocation()),
3444                                              BaseSpec->isVirtual(),
3445                                              SourceLocation(),
3446                                              BaseInit.getAs<Expr>(),
3447                                              SourceLocation(),
3448                                              SourceLocation());
3449 
3450   return false;
3451 }
3452 
3453 static bool RefersToRValueRef(Expr *MemRef) {
3454   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3455   return Referenced->getType()->isRValueReferenceType();
3456 }
3457 
3458 static bool
3459 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3460                                ImplicitInitializerKind ImplicitInitKind,
3461                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3462                                CXXCtorInitializer *&CXXMemberInit) {
3463   if (Field->isInvalidDecl())
3464     return true;
3465 
3466   SourceLocation Loc = Constructor->getLocation();
3467 
3468   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3469     bool Moving = ImplicitInitKind == IIK_Move;
3470     ParmVarDecl *Param = Constructor->getParamDecl(0);
3471     QualType ParamType = Param->getType().getNonReferenceType();
3472 
3473     // Suppress copying zero-width bitfields.
3474     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3475       return false;
3476 
3477     Expr *MemberExprBase =
3478       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3479                           SourceLocation(), Param, false,
3480                           Loc, ParamType, VK_LValue, nullptr);
3481 
3482     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3483 
3484     if (Moving) {
3485       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3486     }
3487 
3488     // Build a reference to this field within the parameter.
3489     CXXScopeSpec SS;
3490     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3491                               Sema::LookupMemberName);
3492     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3493                                   : cast<ValueDecl>(Field), AS_public);
3494     MemberLookup.resolveKind();
3495     ExprResult CtorArg
3496       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3497                                          ParamType, Loc,
3498                                          /*IsArrow=*/false,
3499                                          SS,
3500                                          /*TemplateKWLoc=*/SourceLocation(),
3501                                          /*FirstQualifierInScope=*/nullptr,
3502                                          MemberLookup,
3503                                          /*TemplateArgs=*/nullptr);
3504     if (CtorArg.isInvalid())
3505       return true;
3506 
3507     // C++11 [class.copy]p15:
3508     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3509     //     with static_cast<T&&>(x.m);
3510     if (RefersToRValueRef(CtorArg.get())) {
3511       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3512     }
3513 
3514     // When the field we are copying is an array, create index variables for
3515     // each dimension of the array. We use these index variables to subscript
3516     // the source array, and other clients (e.g., CodeGen) will perform the
3517     // necessary iteration with these index variables.
3518     SmallVector<VarDecl *, 4> IndexVariables;
3519     QualType BaseType = Field->getType();
3520     QualType SizeType = SemaRef.Context.getSizeType();
3521     bool InitializingArray = false;
3522     while (const ConstantArrayType *Array
3523                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3524       InitializingArray = true;
3525       // Create the iteration variable for this array index.
3526       IdentifierInfo *IterationVarName = nullptr;
3527       {
3528         SmallString<8> Str;
3529         llvm::raw_svector_ostream OS(Str);
3530         OS << "__i" << IndexVariables.size();
3531         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3532       }
3533       VarDecl *IterationVar
3534         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3535                           IterationVarName, SizeType,
3536                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3537                           SC_None);
3538       IndexVariables.push_back(IterationVar);
3539 
3540       // Create a reference to the iteration variable.
3541       ExprResult IterationVarRef
3542         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3543       assert(!IterationVarRef.isInvalid() &&
3544              "Reference to invented variable cannot fail!");
3545       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3546       assert(!IterationVarRef.isInvalid() &&
3547              "Conversion of invented variable cannot fail!");
3548 
3549       // Subscript the array with this iteration variable.
3550       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3551                                                         IterationVarRef.get(),
3552                                                         Loc);
3553       if (CtorArg.isInvalid())
3554         return true;
3555 
3556       BaseType = Array->getElementType();
3557     }
3558 
3559     // The array subscript expression is an lvalue, which is wrong for moving.
3560     if (Moving && InitializingArray)
3561       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3562 
3563     // Construct the entity that we will be initializing. For an array, this
3564     // will be first element in the array, which may require several levels
3565     // of array-subscript entities.
3566     SmallVector<InitializedEntity, 4> Entities;
3567     Entities.reserve(1 + IndexVariables.size());
3568     if (Indirect)
3569       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3570     else
3571       Entities.push_back(InitializedEntity::InitializeMember(Field));
3572     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3573       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3574                                                               0,
3575                                                               Entities.back()));
3576 
3577     // Direct-initialize to use the copy constructor.
3578     InitializationKind InitKind =
3579       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3580 
3581     Expr *CtorArgE = CtorArg.getAs<Expr>();
3582     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3583 
3584     ExprResult MemberInit
3585       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3586                         MultiExprArg(&CtorArgE, 1));
3587     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3588     if (MemberInit.isInvalid())
3589       return true;
3590 
3591     if (Indirect) {
3592       assert(IndexVariables.size() == 0 &&
3593              "Indirect field improperly initialized");
3594       CXXMemberInit
3595         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3596                                                    Loc, Loc,
3597                                                    MemberInit.getAs<Expr>(),
3598                                                    Loc);
3599     } else
3600       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3601                                                  Loc, MemberInit.getAs<Expr>(),
3602                                                  Loc,
3603                                                  IndexVariables.data(),
3604                                                  IndexVariables.size());
3605     return false;
3606   }
3607 
3608   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3609          "Unhandled implicit init kind!");
3610 
3611   QualType FieldBaseElementType =
3612     SemaRef.Context.getBaseElementType(Field->getType());
3613 
3614   if (FieldBaseElementType->isRecordType()) {
3615     InitializedEntity InitEntity
3616       = Indirect? InitializedEntity::InitializeMember(Indirect)
3617                 : InitializedEntity::InitializeMember(Field);
3618     InitializationKind InitKind =
3619       InitializationKind::CreateDefault(Loc);
3620 
3621     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3622     ExprResult MemberInit =
3623       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3624 
3625     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3626     if (MemberInit.isInvalid())
3627       return true;
3628 
3629     if (Indirect)
3630       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3631                                                                Indirect, Loc,
3632                                                                Loc,
3633                                                                MemberInit.get(),
3634                                                                Loc);
3635     else
3636       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3637                                                                Field, Loc, Loc,
3638                                                                MemberInit.get(),
3639                                                                Loc);
3640     return false;
3641   }
3642 
3643   if (!Field->getParent()->isUnion()) {
3644     if (FieldBaseElementType->isReferenceType()) {
3645       SemaRef.Diag(Constructor->getLocation(),
3646                    diag::err_uninitialized_member_in_ctor)
3647       << (int)Constructor->isImplicit()
3648       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3649       << 0 << Field->getDeclName();
3650       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3651       return true;
3652     }
3653 
3654     if (FieldBaseElementType.isConstQualified()) {
3655       SemaRef.Diag(Constructor->getLocation(),
3656                    diag::err_uninitialized_member_in_ctor)
3657       << (int)Constructor->isImplicit()
3658       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3659       << 1 << Field->getDeclName();
3660       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3661       return true;
3662     }
3663   }
3664 
3665   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3666       FieldBaseElementType->isObjCRetainableType() &&
3667       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3668       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3669     // ARC:
3670     //   Default-initialize Objective-C pointers to NULL.
3671     CXXMemberInit
3672       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3673                                                  Loc, Loc,
3674                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3675                                                  Loc);
3676     return false;
3677   }
3678 
3679   // Nothing to initialize.
3680   CXXMemberInit = nullptr;
3681   return false;
3682 }
3683 
3684 namespace {
3685 struct BaseAndFieldInfo {
3686   Sema &S;
3687   CXXConstructorDecl *Ctor;
3688   bool AnyErrorsInInits;
3689   ImplicitInitializerKind IIK;
3690   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3691   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3692   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3693 
3694   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3695     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3696     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3697     if (Generated && Ctor->isCopyConstructor())
3698       IIK = IIK_Copy;
3699     else if (Generated && Ctor->isMoveConstructor())
3700       IIK = IIK_Move;
3701     else if (Ctor->getInheritedConstructor())
3702       IIK = IIK_Inherit;
3703     else
3704       IIK = IIK_Default;
3705   }
3706 
3707   bool isImplicitCopyOrMove() const {
3708     switch (IIK) {
3709     case IIK_Copy:
3710     case IIK_Move:
3711       return true;
3712 
3713     case IIK_Default:
3714     case IIK_Inherit:
3715       return false;
3716     }
3717 
3718     llvm_unreachable("Invalid ImplicitInitializerKind!");
3719   }
3720 
3721   bool addFieldInitializer(CXXCtorInitializer *Init) {
3722     AllToInit.push_back(Init);
3723 
3724     // Check whether this initializer makes the field "used".
3725     if (Init->getInit()->HasSideEffects(S.Context))
3726       S.UnusedPrivateFields.remove(Init->getAnyMember());
3727 
3728     return false;
3729   }
3730 
3731   bool isInactiveUnionMember(FieldDecl *Field) {
3732     RecordDecl *Record = Field->getParent();
3733     if (!Record->isUnion())
3734       return false;
3735 
3736     if (FieldDecl *Active =
3737             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3738       return Active != Field->getCanonicalDecl();
3739 
3740     // In an implicit copy or move constructor, ignore any in-class initializer.
3741     if (isImplicitCopyOrMove())
3742       return true;
3743 
3744     // If there's no explicit initialization, the field is active only if it
3745     // has an in-class initializer...
3746     if (Field->hasInClassInitializer())
3747       return false;
3748     // ... or it's an anonymous struct or union whose class has an in-class
3749     // initializer.
3750     if (!Field->isAnonymousStructOrUnion())
3751       return true;
3752     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3753     return !FieldRD->hasInClassInitializer();
3754   }
3755 
3756   /// \brief Determine whether the given field is, or is within, a union member
3757   /// that is inactive (because there was an initializer given for a different
3758   /// member of the union, or because the union was not initialized at all).
3759   bool isWithinInactiveUnionMember(FieldDecl *Field,
3760                                    IndirectFieldDecl *Indirect) {
3761     if (!Indirect)
3762       return isInactiveUnionMember(Field);
3763 
3764     for (auto *C : Indirect->chain()) {
3765       FieldDecl *Field = dyn_cast<FieldDecl>(C);
3766       if (Field && isInactiveUnionMember(Field))
3767         return true;
3768     }
3769     return false;
3770   }
3771 };
3772 }
3773 
3774 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3775 /// array type.
3776 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3777   if (T->isIncompleteArrayType())
3778     return true;
3779 
3780   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3781     if (!ArrayT->getSize())
3782       return true;
3783 
3784     T = ArrayT->getElementType();
3785   }
3786 
3787   return false;
3788 }
3789 
3790 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3791                                     FieldDecl *Field,
3792                                     IndirectFieldDecl *Indirect = nullptr) {
3793   if (Field->isInvalidDecl())
3794     return false;
3795 
3796   // Overwhelmingly common case: we have a direct initializer for this field.
3797   if (CXXCtorInitializer *Init =
3798           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3799     return Info.addFieldInitializer(Init);
3800 
3801   // C++11 [class.base.init]p8:
3802   //   if the entity is a non-static data member that has a
3803   //   brace-or-equal-initializer and either
3804   //   -- the constructor's class is a union and no other variant member of that
3805   //      union is designated by a mem-initializer-id or
3806   //   -- the constructor's class is not a union, and, if the entity is a member
3807   //      of an anonymous union, no other member of that union is designated by
3808   //      a mem-initializer-id,
3809   //   the entity is initialized as specified in [dcl.init].
3810   //
3811   // We also apply the same rules to handle anonymous structs within anonymous
3812   // unions.
3813   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3814     return false;
3815 
3816   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3817     ExprResult DIE =
3818         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3819     if (DIE.isInvalid())
3820       return true;
3821     CXXCtorInitializer *Init;
3822     if (Indirect)
3823       Init = new (SemaRef.Context)
3824           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3825                              SourceLocation(), DIE.get(), SourceLocation());
3826     else
3827       Init = new (SemaRef.Context)
3828           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3829                              SourceLocation(), DIE.get(), SourceLocation());
3830     return Info.addFieldInitializer(Init);
3831   }
3832 
3833   // Don't initialize incomplete or zero-length arrays.
3834   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3835     return false;
3836 
3837   // Don't try to build an implicit initializer if there were semantic
3838   // errors in any of the initializers (and therefore we might be
3839   // missing some that the user actually wrote).
3840   if (Info.AnyErrorsInInits)
3841     return false;
3842 
3843   CXXCtorInitializer *Init = nullptr;
3844   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3845                                      Indirect, Init))
3846     return true;
3847 
3848   if (!Init)
3849     return false;
3850 
3851   return Info.addFieldInitializer(Init);
3852 }
3853 
3854 bool
3855 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3856                                CXXCtorInitializer *Initializer) {
3857   assert(Initializer->isDelegatingInitializer());
3858   Constructor->setNumCtorInitializers(1);
3859   CXXCtorInitializer **initializer =
3860     new (Context) CXXCtorInitializer*[1];
3861   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3862   Constructor->setCtorInitializers(initializer);
3863 
3864   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3865     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3866     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3867   }
3868 
3869   DelegatingCtorDecls.push_back(Constructor);
3870 
3871   DiagnoseUninitializedFields(*this, Constructor);
3872 
3873   return false;
3874 }
3875 
3876 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3877                                ArrayRef<CXXCtorInitializer *> Initializers) {
3878   if (Constructor->isDependentContext()) {
3879     // Just store the initializers as written, they will be checked during
3880     // instantiation.
3881     if (!Initializers.empty()) {
3882       Constructor->setNumCtorInitializers(Initializers.size());
3883       CXXCtorInitializer **baseOrMemberInitializers =
3884         new (Context) CXXCtorInitializer*[Initializers.size()];
3885       memcpy(baseOrMemberInitializers, Initializers.data(),
3886              Initializers.size() * sizeof(CXXCtorInitializer*));
3887       Constructor->setCtorInitializers(baseOrMemberInitializers);
3888     }
3889 
3890     // Let template instantiation know whether we had errors.
3891     if (AnyErrors)
3892       Constructor->setInvalidDecl();
3893 
3894     return false;
3895   }
3896 
3897   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3898 
3899   // We need to build the initializer AST according to order of construction
3900   // and not what user specified in the Initializers list.
3901   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3902   if (!ClassDecl)
3903     return true;
3904 
3905   bool HadError = false;
3906 
3907   for (unsigned i = 0; i < Initializers.size(); i++) {
3908     CXXCtorInitializer *Member = Initializers[i];
3909 
3910     if (Member->isBaseInitializer())
3911       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3912     else {
3913       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3914 
3915       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3916         for (auto *C : F->chain()) {
3917           FieldDecl *FD = dyn_cast<FieldDecl>(C);
3918           if (FD && FD->getParent()->isUnion())
3919             Info.ActiveUnionMember.insert(std::make_pair(
3920                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3921         }
3922       } else if (FieldDecl *FD = Member->getMember()) {
3923         if (FD->getParent()->isUnion())
3924           Info.ActiveUnionMember.insert(std::make_pair(
3925               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3926       }
3927     }
3928   }
3929 
3930   // Keep track of the direct virtual bases.
3931   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3932   for (auto &I : ClassDecl->bases()) {
3933     if (I.isVirtual())
3934       DirectVBases.insert(&I);
3935   }
3936 
3937   // Push virtual bases before others.
3938   for (auto &VBase : ClassDecl->vbases()) {
3939     if (CXXCtorInitializer *Value
3940         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3941       // [class.base.init]p7, per DR257:
3942       //   A mem-initializer where the mem-initializer-id names a virtual base
3943       //   class is ignored during execution of a constructor of any class that
3944       //   is not the most derived class.
3945       if (ClassDecl->isAbstract()) {
3946         // FIXME: Provide a fixit to remove the base specifier. This requires
3947         // tracking the location of the associated comma for a base specifier.
3948         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3949           << VBase.getType() << ClassDecl;
3950         DiagnoseAbstractType(ClassDecl);
3951       }
3952 
3953       Info.AllToInit.push_back(Value);
3954     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3955       // [class.base.init]p8, per DR257:
3956       //   If a given [...] base class is not named by a mem-initializer-id
3957       //   [...] and the entity is not a virtual base class of an abstract
3958       //   class, then [...] the entity is default-initialized.
3959       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3960       CXXCtorInitializer *CXXBaseInit;
3961       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3962                                        &VBase, IsInheritedVirtualBase,
3963                                        CXXBaseInit)) {
3964         HadError = true;
3965         continue;
3966       }
3967 
3968       Info.AllToInit.push_back(CXXBaseInit);
3969     }
3970   }
3971 
3972   // Non-virtual bases.
3973   for (auto &Base : ClassDecl->bases()) {
3974     // Virtuals are in the virtual base list and already constructed.
3975     if (Base.isVirtual())
3976       continue;
3977 
3978     if (CXXCtorInitializer *Value
3979           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3980       Info.AllToInit.push_back(Value);
3981     } else if (!AnyErrors) {
3982       CXXCtorInitializer *CXXBaseInit;
3983       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3984                                        &Base, /*IsInheritedVirtualBase=*/false,
3985                                        CXXBaseInit)) {
3986         HadError = true;
3987         continue;
3988       }
3989 
3990       Info.AllToInit.push_back(CXXBaseInit);
3991     }
3992   }
3993 
3994   // Fields.
3995   for (auto *Mem : ClassDecl->decls()) {
3996     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3997       // C++ [class.bit]p2:
3998       //   A declaration for a bit-field that omits the identifier declares an
3999       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4000       //   initialized.
4001       if (F->isUnnamedBitfield())
4002         continue;
4003 
4004       // If we're not generating the implicit copy/move constructor, then we'll
4005       // handle anonymous struct/union fields based on their individual
4006       // indirect fields.
4007       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4008         continue;
4009 
4010       if (CollectFieldInitializer(*this, Info, F))
4011         HadError = true;
4012       continue;
4013     }
4014 
4015     // Beyond this point, we only consider default initialization.
4016     if (Info.isImplicitCopyOrMove())
4017       continue;
4018 
4019     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4020       if (F->getType()->isIncompleteArrayType()) {
4021         assert(ClassDecl->hasFlexibleArrayMember() &&
4022                "Incomplete array type is not valid");
4023         continue;
4024       }
4025 
4026       // Initialize each field of an anonymous struct individually.
4027       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4028         HadError = true;
4029 
4030       continue;
4031     }
4032   }
4033 
4034   unsigned NumInitializers = Info.AllToInit.size();
4035   if (NumInitializers > 0) {
4036     Constructor->setNumCtorInitializers(NumInitializers);
4037     CXXCtorInitializer **baseOrMemberInitializers =
4038       new (Context) CXXCtorInitializer*[NumInitializers];
4039     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4040            NumInitializers * sizeof(CXXCtorInitializer*));
4041     Constructor->setCtorInitializers(baseOrMemberInitializers);
4042 
4043     // Constructors implicitly reference the base and member
4044     // destructors.
4045     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4046                                            Constructor->getParent());
4047   }
4048 
4049   return HadError;
4050 }
4051 
4052 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4053   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4054     const RecordDecl *RD = RT->getDecl();
4055     if (RD->isAnonymousStructOrUnion()) {
4056       for (auto *Field : RD->fields())
4057         PopulateKeysForFields(Field, IdealInits);
4058       return;
4059     }
4060   }
4061   IdealInits.push_back(Field->getCanonicalDecl());
4062 }
4063 
4064 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4065   return Context.getCanonicalType(BaseType).getTypePtr();
4066 }
4067 
4068 static const void *GetKeyForMember(ASTContext &Context,
4069                                    CXXCtorInitializer *Member) {
4070   if (!Member->isAnyMemberInitializer())
4071     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4072 
4073   return Member->getAnyMember()->getCanonicalDecl();
4074 }
4075 
4076 static void DiagnoseBaseOrMemInitializerOrder(
4077     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4078     ArrayRef<CXXCtorInitializer *> Inits) {
4079   if (Constructor->getDeclContext()->isDependentContext())
4080     return;
4081 
4082   // Don't check initializers order unless the warning is enabled at the
4083   // location of at least one initializer.
4084   bool ShouldCheckOrder = false;
4085   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4086     CXXCtorInitializer *Init = Inits[InitIndex];
4087     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4088                                  Init->getSourceLocation())) {
4089       ShouldCheckOrder = true;
4090       break;
4091     }
4092   }
4093   if (!ShouldCheckOrder)
4094     return;
4095 
4096   // Build the list of bases and members in the order that they'll
4097   // actually be initialized.  The explicit initializers should be in
4098   // this same order but may be missing things.
4099   SmallVector<const void*, 32> IdealInitKeys;
4100 
4101   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4102 
4103   // 1. Virtual bases.
4104   for (const auto &VBase : ClassDecl->vbases())
4105     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4106 
4107   // 2. Non-virtual bases.
4108   for (const auto &Base : ClassDecl->bases()) {
4109     if (Base.isVirtual())
4110       continue;
4111     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4112   }
4113 
4114   // 3. Direct fields.
4115   for (auto *Field : ClassDecl->fields()) {
4116     if (Field->isUnnamedBitfield())
4117       continue;
4118 
4119     PopulateKeysForFields(Field, IdealInitKeys);
4120   }
4121 
4122   unsigned NumIdealInits = IdealInitKeys.size();
4123   unsigned IdealIndex = 0;
4124 
4125   CXXCtorInitializer *PrevInit = nullptr;
4126   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4127     CXXCtorInitializer *Init = Inits[InitIndex];
4128     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4129 
4130     // Scan forward to try to find this initializer in the idealized
4131     // initializers list.
4132     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4133       if (InitKey == IdealInitKeys[IdealIndex])
4134         break;
4135 
4136     // If we didn't find this initializer, it must be because we
4137     // scanned past it on a previous iteration.  That can only
4138     // happen if we're out of order;  emit a warning.
4139     if (IdealIndex == NumIdealInits && PrevInit) {
4140       Sema::SemaDiagnosticBuilder D =
4141         SemaRef.Diag(PrevInit->getSourceLocation(),
4142                      diag::warn_initializer_out_of_order);
4143 
4144       if (PrevInit->isAnyMemberInitializer())
4145         D << 0 << PrevInit->getAnyMember()->getDeclName();
4146       else
4147         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4148 
4149       if (Init->isAnyMemberInitializer())
4150         D << 0 << Init->getAnyMember()->getDeclName();
4151       else
4152         D << 1 << Init->getTypeSourceInfo()->getType();
4153 
4154       // Move back to the initializer's location in the ideal list.
4155       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4156         if (InitKey == IdealInitKeys[IdealIndex])
4157           break;
4158 
4159       assert(IdealIndex != NumIdealInits &&
4160              "initializer not found in initializer list");
4161     }
4162 
4163     PrevInit = Init;
4164   }
4165 }
4166 
4167 namespace {
4168 bool CheckRedundantInit(Sema &S,
4169                         CXXCtorInitializer *Init,
4170                         CXXCtorInitializer *&PrevInit) {
4171   if (!PrevInit) {
4172     PrevInit = Init;
4173     return false;
4174   }
4175 
4176   if (FieldDecl *Field = Init->getAnyMember())
4177     S.Diag(Init->getSourceLocation(),
4178            diag::err_multiple_mem_initialization)
4179       << Field->getDeclName()
4180       << Init->getSourceRange();
4181   else {
4182     const Type *BaseClass = Init->getBaseClass();
4183     assert(BaseClass && "neither field nor base");
4184     S.Diag(Init->getSourceLocation(),
4185            diag::err_multiple_base_initialization)
4186       << QualType(BaseClass, 0)
4187       << Init->getSourceRange();
4188   }
4189   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4190     << 0 << PrevInit->getSourceRange();
4191 
4192   return true;
4193 }
4194 
4195 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4196 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4197 
4198 bool CheckRedundantUnionInit(Sema &S,
4199                              CXXCtorInitializer *Init,
4200                              RedundantUnionMap &Unions) {
4201   FieldDecl *Field = Init->getAnyMember();
4202   RecordDecl *Parent = Field->getParent();
4203   NamedDecl *Child = Field;
4204 
4205   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4206     if (Parent->isUnion()) {
4207       UnionEntry &En = Unions[Parent];
4208       if (En.first && En.first != Child) {
4209         S.Diag(Init->getSourceLocation(),
4210                diag::err_multiple_mem_union_initialization)
4211           << Field->getDeclName()
4212           << Init->getSourceRange();
4213         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4214           << 0 << En.second->getSourceRange();
4215         return true;
4216       }
4217       if (!En.first) {
4218         En.first = Child;
4219         En.second = Init;
4220       }
4221       if (!Parent->isAnonymousStructOrUnion())
4222         return false;
4223     }
4224 
4225     Child = Parent;
4226     Parent = cast<RecordDecl>(Parent->getDeclContext());
4227   }
4228 
4229   return false;
4230 }
4231 }
4232 
4233 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4234 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4235                                 SourceLocation ColonLoc,
4236                                 ArrayRef<CXXCtorInitializer*> MemInits,
4237                                 bool AnyErrors) {
4238   if (!ConstructorDecl)
4239     return;
4240 
4241   AdjustDeclIfTemplate(ConstructorDecl);
4242 
4243   CXXConstructorDecl *Constructor
4244     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4245 
4246   if (!Constructor) {
4247     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4248     return;
4249   }
4250 
4251   // Mapping for the duplicate initializers check.
4252   // For member initializers, this is keyed with a FieldDecl*.
4253   // For base initializers, this is keyed with a Type*.
4254   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4255 
4256   // Mapping for the inconsistent anonymous-union initializers check.
4257   RedundantUnionMap MemberUnions;
4258 
4259   bool HadError = false;
4260   for (unsigned i = 0; i < MemInits.size(); i++) {
4261     CXXCtorInitializer *Init = MemInits[i];
4262 
4263     // Set the source order index.
4264     Init->setSourceOrder(i);
4265 
4266     if (Init->isAnyMemberInitializer()) {
4267       const void *Key = GetKeyForMember(Context, Init);
4268       if (CheckRedundantInit(*this, Init, Members[Key]) ||
4269           CheckRedundantUnionInit(*this, Init, MemberUnions))
4270         HadError = true;
4271     } else if (Init->isBaseInitializer()) {
4272       const void *Key = GetKeyForMember(Context, Init);
4273       if (CheckRedundantInit(*this, Init, Members[Key]))
4274         HadError = true;
4275     } else {
4276       assert(Init->isDelegatingInitializer());
4277       // This must be the only initializer
4278       if (MemInits.size() != 1) {
4279         Diag(Init->getSourceLocation(),
4280              diag::err_delegating_initializer_alone)
4281           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4282         // We will treat this as being the only initializer.
4283       }
4284       SetDelegatingInitializer(Constructor, MemInits[i]);
4285       // Return immediately as the initializer is set.
4286       return;
4287     }
4288   }
4289 
4290   if (HadError)
4291     return;
4292 
4293   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4294 
4295   SetCtorInitializers(Constructor, AnyErrors, MemInits);
4296 
4297   DiagnoseUninitializedFields(*this, Constructor);
4298 }
4299 
4300 void
4301 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4302                                              CXXRecordDecl *ClassDecl) {
4303   // Ignore dependent contexts. Also ignore unions, since their members never
4304   // have destructors implicitly called.
4305   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4306     return;
4307 
4308   // FIXME: all the access-control diagnostics are positioned on the
4309   // field/base declaration.  That's probably good; that said, the
4310   // user might reasonably want to know why the destructor is being
4311   // emitted, and we currently don't say.
4312 
4313   // Non-static data members.
4314   for (auto *Field : ClassDecl->fields()) {
4315     if (Field->isInvalidDecl())
4316       continue;
4317 
4318     // Don't destroy incomplete or zero-length arrays.
4319     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4320       continue;
4321 
4322     QualType FieldType = Context.getBaseElementType(Field->getType());
4323 
4324     const RecordType* RT = FieldType->getAs<RecordType>();
4325     if (!RT)
4326       continue;
4327 
4328     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4329     if (FieldClassDecl->isInvalidDecl())
4330       continue;
4331     if (FieldClassDecl->hasIrrelevantDestructor())
4332       continue;
4333     // The destructor for an implicit anonymous union member is never invoked.
4334     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4335       continue;
4336 
4337     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4338     assert(Dtor && "No dtor found for FieldClassDecl!");
4339     CheckDestructorAccess(Field->getLocation(), Dtor,
4340                           PDiag(diag::err_access_dtor_field)
4341                             << Field->getDeclName()
4342                             << FieldType);
4343 
4344     MarkFunctionReferenced(Location, Dtor);
4345     DiagnoseUseOfDecl(Dtor, Location);
4346   }
4347 
4348   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4349 
4350   // Bases.
4351   for (const auto &Base : ClassDecl->bases()) {
4352     // Bases are always records in a well-formed non-dependent class.
4353     const RecordType *RT = Base.getType()->getAs<RecordType>();
4354 
4355     // Remember direct virtual bases.
4356     if (Base.isVirtual())
4357       DirectVirtualBases.insert(RT);
4358 
4359     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4360     // If our base class is invalid, we probably can't get its dtor anyway.
4361     if (BaseClassDecl->isInvalidDecl())
4362       continue;
4363     if (BaseClassDecl->hasIrrelevantDestructor())
4364       continue;
4365 
4366     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4367     assert(Dtor && "No dtor found for BaseClassDecl!");
4368 
4369     // FIXME: caret should be on the start of the class name
4370     CheckDestructorAccess(Base.getLocStart(), Dtor,
4371                           PDiag(diag::err_access_dtor_base)
4372                             << Base.getType()
4373                             << Base.getSourceRange(),
4374                           Context.getTypeDeclType(ClassDecl));
4375 
4376     MarkFunctionReferenced(Location, Dtor);
4377     DiagnoseUseOfDecl(Dtor, Location);
4378   }
4379 
4380   // Virtual bases.
4381   for (const auto &VBase : ClassDecl->vbases()) {
4382     // Bases are always records in a well-formed non-dependent class.
4383     const RecordType *RT = VBase.getType()->castAs<RecordType>();
4384 
4385     // Ignore direct virtual bases.
4386     if (DirectVirtualBases.count(RT))
4387       continue;
4388 
4389     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4390     // If our base class is invalid, we probably can't get its dtor anyway.
4391     if (BaseClassDecl->isInvalidDecl())
4392       continue;
4393     if (BaseClassDecl->hasIrrelevantDestructor())
4394       continue;
4395 
4396     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4397     assert(Dtor && "No dtor found for BaseClassDecl!");
4398     if (CheckDestructorAccess(
4399             ClassDecl->getLocation(), Dtor,
4400             PDiag(diag::err_access_dtor_vbase)
4401                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4402             Context.getTypeDeclType(ClassDecl)) ==
4403         AR_accessible) {
4404       CheckDerivedToBaseConversion(
4405           Context.getTypeDeclType(ClassDecl), VBase.getType(),
4406           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4407           SourceRange(), DeclarationName(), nullptr);
4408     }
4409 
4410     MarkFunctionReferenced(Location, Dtor);
4411     DiagnoseUseOfDecl(Dtor, Location);
4412   }
4413 }
4414 
4415 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4416   if (!CDtorDecl)
4417     return;
4418 
4419   if (CXXConstructorDecl *Constructor
4420       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4421     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4422     DiagnoseUninitializedFields(*this, Constructor);
4423   }
4424 }
4425 
4426 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4427                                   unsigned DiagID, AbstractDiagSelID SelID) {
4428   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4429     unsigned DiagID;
4430     AbstractDiagSelID SelID;
4431 
4432   public:
4433     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4434       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4435 
4436     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4437       if (Suppressed) return;
4438       if (SelID == -1)
4439         S.Diag(Loc, DiagID) << T;
4440       else
4441         S.Diag(Loc, DiagID) << SelID << T;
4442     }
4443   } Diagnoser(DiagID, SelID);
4444 
4445   return RequireNonAbstractType(Loc, T, Diagnoser);
4446 }
4447 
4448 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4449                                   TypeDiagnoser &Diagnoser) {
4450   if (!getLangOpts().CPlusPlus)
4451     return false;
4452 
4453   if (const ArrayType *AT = Context.getAsArrayType(T))
4454     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4455 
4456   if (const PointerType *PT = T->getAs<PointerType>()) {
4457     // Find the innermost pointer type.
4458     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4459       PT = T;
4460 
4461     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4462       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4463   }
4464 
4465   const RecordType *RT = T->getAs<RecordType>();
4466   if (!RT)
4467     return false;
4468 
4469   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4470 
4471   // We can't answer whether something is abstract until it has a
4472   // definition.  If it's currently being defined, we'll walk back
4473   // over all the declarations when we have a full definition.
4474   const CXXRecordDecl *Def = RD->getDefinition();
4475   if (!Def || Def->isBeingDefined())
4476     return false;
4477 
4478   if (!RD->isAbstract())
4479     return false;
4480 
4481   Diagnoser.diagnose(*this, Loc, T);
4482   DiagnoseAbstractType(RD);
4483 
4484   return true;
4485 }
4486 
4487 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4488   // Check if we've already emitted the list of pure virtual functions
4489   // for this class.
4490   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4491     return;
4492 
4493   // If the diagnostic is suppressed, don't emit the notes. We're only
4494   // going to emit them once, so try to attach them to a diagnostic we're
4495   // actually going to show.
4496   if (Diags.isLastDiagnosticIgnored())
4497     return;
4498 
4499   CXXFinalOverriderMap FinalOverriders;
4500   RD->getFinalOverriders(FinalOverriders);
4501 
4502   // Keep a set of seen pure methods so we won't diagnose the same method
4503   // more than once.
4504   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4505 
4506   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4507                                    MEnd = FinalOverriders.end();
4508        M != MEnd;
4509        ++M) {
4510     for (OverridingMethods::iterator SO = M->second.begin(),
4511                                   SOEnd = M->second.end();
4512          SO != SOEnd; ++SO) {
4513       // C++ [class.abstract]p4:
4514       //   A class is abstract if it contains or inherits at least one
4515       //   pure virtual function for which the final overrider is pure
4516       //   virtual.
4517 
4518       //
4519       if (SO->second.size() != 1)
4520         continue;
4521 
4522       if (!SO->second.front().Method->isPure())
4523         continue;
4524 
4525       if (!SeenPureMethods.insert(SO->second.front().Method).second)
4526         continue;
4527 
4528       Diag(SO->second.front().Method->getLocation(),
4529            diag::note_pure_virtual_function)
4530         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4531     }
4532   }
4533 
4534   if (!PureVirtualClassDiagSet)
4535     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4536   PureVirtualClassDiagSet->insert(RD);
4537 }
4538 
4539 namespace {
4540 struct AbstractUsageInfo {
4541   Sema &S;
4542   CXXRecordDecl *Record;
4543   CanQualType AbstractType;
4544   bool Invalid;
4545 
4546   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4547     : S(S), Record(Record),
4548       AbstractType(S.Context.getCanonicalType(
4549                    S.Context.getTypeDeclType(Record))),
4550       Invalid(false) {}
4551 
4552   void DiagnoseAbstractType() {
4553     if (Invalid) return;
4554     S.DiagnoseAbstractType(Record);
4555     Invalid = true;
4556   }
4557 
4558   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4559 };
4560 
4561 struct CheckAbstractUsage {
4562   AbstractUsageInfo &Info;
4563   const NamedDecl *Ctx;
4564 
4565   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4566     : Info(Info), Ctx(Ctx) {}
4567 
4568   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4569     switch (TL.getTypeLocClass()) {
4570 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4571 #define TYPELOC(CLASS, PARENT) \
4572     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4573 #include "clang/AST/TypeLocNodes.def"
4574     }
4575   }
4576 
4577   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4578     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4579     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4580       if (!TL.getParam(I))
4581         continue;
4582 
4583       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4584       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4585     }
4586   }
4587 
4588   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4589     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4590   }
4591 
4592   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4593     // Visit the type parameters from a permissive context.
4594     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4595       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4596       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4597         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4598           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4599       // TODO: other template argument types?
4600     }
4601   }
4602 
4603   // Visit pointee types from a permissive context.
4604 #define CheckPolymorphic(Type) \
4605   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4606     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4607   }
4608   CheckPolymorphic(PointerTypeLoc)
4609   CheckPolymorphic(ReferenceTypeLoc)
4610   CheckPolymorphic(MemberPointerTypeLoc)
4611   CheckPolymorphic(BlockPointerTypeLoc)
4612   CheckPolymorphic(AtomicTypeLoc)
4613 
4614   /// Handle all the types we haven't given a more specific
4615   /// implementation for above.
4616   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4617     // Every other kind of type that we haven't called out already
4618     // that has an inner type is either (1) sugar or (2) contains that
4619     // inner type in some way as a subobject.
4620     if (TypeLoc Next = TL.getNextTypeLoc())
4621       return Visit(Next, Sel);
4622 
4623     // If there's no inner type and we're in a permissive context,
4624     // don't diagnose.
4625     if (Sel == Sema::AbstractNone) return;
4626 
4627     // Check whether the type matches the abstract type.
4628     QualType T = TL.getType();
4629     if (T->isArrayType()) {
4630       Sel = Sema::AbstractArrayType;
4631       T = Info.S.Context.getBaseElementType(T);
4632     }
4633     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4634     if (CT != Info.AbstractType) return;
4635 
4636     // It matched; do some magic.
4637     if (Sel == Sema::AbstractArrayType) {
4638       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4639         << T << TL.getSourceRange();
4640     } else {
4641       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4642         << Sel << T << TL.getSourceRange();
4643     }
4644     Info.DiagnoseAbstractType();
4645   }
4646 };
4647 
4648 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4649                                   Sema::AbstractDiagSelID Sel) {
4650   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4651 }
4652 
4653 }
4654 
4655 /// Check for invalid uses of an abstract type in a method declaration.
4656 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4657                                     CXXMethodDecl *MD) {
4658   // No need to do the check on definitions, which require that
4659   // the return/param types be complete.
4660   if (MD->doesThisDeclarationHaveABody())
4661     return;
4662 
4663   // For safety's sake, just ignore it if we don't have type source
4664   // information.  This should never happen for non-implicit methods,
4665   // but...
4666   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4667     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4668 }
4669 
4670 /// Check for invalid uses of an abstract type within a class definition.
4671 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4672                                     CXXRecordDecl *RD) {
4673   for (auto *D : RD->decls()) {
4674     if (D->isImplicit()) continue;
4675 
4676     // Methods and method templates.
4677     if (isa<CXXMethodDecl>(D)) {
4678       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4679     } else if (isa<FunctionTemplateDecl>(D)) {
4680       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4681       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4682 
4683     // Fields and static variables.
4684     } else if (isa<FieldDecl>(D)) {
4685       FieldDecl *FD = cast<FieldDecl>(D);
4686       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4687         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4688     } else if (isa<VarDecl>(D)) {
4689       VarDecl *VD = cast<VarDecl>(D);
4690       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4691         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4692 
4693     // Nested classes and class templates.
4694     } else if (isa<CXXRecordDecl>(D)) {
4695       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4696     } else if (isa<ClassTemplateDecl>(D)) {
4697       CheckAbstractClassUsage(Info,
4698                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4699     }
4700   }
4701 }
4702 
4703 /// \brief Check class-level dllimport/dllexport attribute.
4704 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4705   Attr *ClassAttr = getDLLAttr(Class);
4706 
4707   // MSVC inherits DLL attributes to partial class template specializations.
4708   if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4709     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4710       if (Attr *TemplateAttr =
4711               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4712         auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4713         A->setInherited(true);
4714         ClassAttr = A;
4715       }
4716     }
4717   }
4718 
4719   if (!ClassAttr)
4720     return;
4721 
4722   if (!Class->isExternallyVisible()) {
4723     S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4724         << Class << ClassAttr;
4725     return;
4726   }
4727 
4728   if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4729       !ClassAttr->isInherited()) {
4730     // Diagnose dll attributes on members of class with dll attribute.
4731     for (Decl *Member : Class->decls()) {
4732       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4733         continue;
4734       InheritableAttr *MemberAttr = getDLLAttr(Member);
4735       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4736         continue;
4737 
4738       S.Diag(MemberAttr->getLocation(),
4739              diag::err_attribute_dll_member_of_dll_class)
4740           << MemberAttr << ClassAttr;
4741       S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4742       Member->setInvalidDecl();
4743     }
4744   }
4745 
4746   if (Class->getDescribedClassTemplate())
4747     // Don't inherit dll attribute until the template is instantiated.
4748     return;
4749 
4750   // The class is either imported or exported.
4751   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4752   const bool ClassImported = !ClassExported;
4753 
4754   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4755 
4756   // Don't dllexport explicit class template instantiation declarations.
4757   if (ClassExported && TSK == TSK_ExplicitInstantiationDeclaration) {
4758     Class->dropAttr<DLLExportAttr>();
4759     return;
4760   }
4761 
4762   // Force declaration of implicit members so they can inherit the attribute.
4763   S.ForceDeclarationOfImplicitMembers(Class);
4764 
4765   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4766   // seem to be true in practice?
4767 
4768   for (Decl *Member : Class->decls()) {
4769     VarDecl *VD = dyn_cast<VarDecl>(Member);
4770     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4771 
4772     // Only methods and static fields inherit the attributes.
4773     if (!VD && !MD)
4774       continue;
4775 
4776     if (MD) {
4777       // Don't process deleted methods.
4778       if (MD->isDeleted())
4779         continue;
4780 
4781       if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) {
4782         // Current MSVC versions don't export the move assignment operators, so
4783         // don't attempt to import them if we have a definition.
4784         continue;
4785       }
4786 
4787       if (MD->isInlined() && ClassImported &&
4788           !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4789         // MinGW does not import inline functions.
4790         continue;
4791       }
4792     }
4793 
4794     if (!getDLLAttr(Member)) {
4795       auto *NewAttr =
4796           cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4797       NewAttr->setInherited(true);
4798       Member->addAttr(NewAttr);
4799     }
4800 
4801     if (MD && ClassExported) {
4802       if (MD->isUserProvided()) {
4803         // Instantiate non-default class member functions ...
4804 
4805         // .. except for certain kinds of template specializations.
4806         if (TSK == TSK_ExplicitInstantiationDeclaration)
4807           continue;
4808         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4809           continue;
4810 
4811         S.MarkFunctionReferenced(Class->getLocation(), MD);
4812 
4813         // The function will be passed to the consumer when its definition is
4814         // encountered.
4815       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4816                  MD->isCopyAssignmentOperator() ||
4817                  MD->isMoveAssignmentOperator()) {
4818         // Synthesize and instantiate non-trivial implicit methods, explicitly
4819         // defaulted methods, and the copy and move assignment operators. The
4820         // latter are exported even if they are trivial, because the address of
4821         // an operator can be taken and should compare equal accross libraries.
4822         S.MarkFunctionReferenced(Class->getLocation(), MD);
4823 
4824         // There is no later point when we will see the definition of this
4825         // function, so pass it to the consumer now.
4826         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
4827       }
4828     }
4829   }
4830 }
4831 
4832 /// \brief Perform semantic checks on a class definition that has been
4833 /// completing, introducing implicitly-declared members, checking for
4834 /// abstract types, etc.
4835 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4836   if (!Record)
4837     return;
4838 
4839   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4840     AbstractUsageInfo Info(*this, Record);
4841     CheckAbstractClassUsage(Info, Record);
4842   }
4843 
4844   // If this is not an aggregate type and has no user-declared constructor,
4845   // complain about any non-static data members of reference or const scalar
4846   // type, since they will never get initializers.
4847   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4848       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4849       !Record->isLambda()) {
4850     bool Complained = false;
4851     for (const auto *F : Record->fields()) {
4852       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4853         continue;
4854 
4855       if (F->getType()->isReferenceType() ||
4856           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4857         if (!Complained) {
4858           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4859             << Record->getTagKind() << Record;
4860           Complained = true;
4861         }
4862 
4863         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4864           << F->getType()->isReferenceType()
4865           << F->getDeclName();
4866       }
4867     }
4868   }
4869 
4870   if (Record->isDynamicClass() && !Record->isDependentType())
4871     DynamicClasses.push_back(Record);
4872 
4873   if (Record->getIdentifier()) {
4874     // C++ [class.mem]p13:
4875     //   If T is the name of a class, then each of the following shall have a
4876     //   name different from T:
4877     //     - every member of every anonymous union that is a member of class T.
4878     //
4879     // C++ [class.mem]p14:
4880     //   In addition, if class T has a user-declared constructor (12.1), every
4881     //   non-static data member of class T shall have a name different from T.
4882     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4883     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4884          ++I) {
4885       NamedDecl *D = *I;
4886       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4887           isa<IndirectFieldDecl>(D)) {
4888         Diag(D->getLocation(), diag::err_member_name_of_class)
4889           << D->getDeclName();
4890         break;
4891       }
4892     }
4893   }
4894 
4895   // Warn if the class has virtual methods but non-virtual public destructor.
4896   if (Record->isPolymorphic() && !Record->isDependentType()) {
4897     CXXDestructorDecl *dtor = Record->getDestructor();
4898     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4899         !Record->hasAttr<FinalAttr>())
4900       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4901            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4902   }
4903 
4904   if (Record->isAbstract()) {
4905     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4906       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4907         << FA->isSpelledAsSealed();
4908       DiagnoseAbstractType(Record);
4909     }
4910   }
4911 
4912   bool HasMethodWithOverrideControl = false,
4913        HasOverridingMethodWithoutOverrideControl = false;
4914   if (!Record->isDependentType()) {
4915     for (auto *M : Record->methods()) {
4916       // See if a method overloads virtual methods in a base
4917       // class without overriding any.
4918       if (!M->isStatic())
4919         DiagnoseHiddenVirtualMethods(M);
4920       if (M->hasAttr<OverrideAttr>())
4921         HasMethodWithOverrideControl = true;
4922       else if (M->size_overridden_methods() > 0)
4923         HasOverridingMethodWithoutOverrideControl = true;
4924       // Check whether the explicitly-defaulted special members are valid.
4925       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4926         CheckExplicitlyDefaultedSpecialMember(M);
4927 
4928       // For an explicitly defaulted or deleted special member, we defer
4929       // determining triviality until the class is complete. That time is now!
4930       if (!M->isImplicit() && !M->isUserProvided()) {
4931         CXXSpecialMember CSM = getSpecialMember(M);
4932         if (CSM != CXXInvalid) {
4933           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4934 
4935           // Inform the class that we've finished declaring this member.
4936           Record->finishedDefaultedOrDeletedMember(M);
4937         }
4938       }
4939     }
4940   }
4941 
4942   if (HasMethodWithOverrideControl &&
4943       HasOverridingMethodWithoutOverrideControl) {
4944     // At least one method has the 'override' control declared.
4945     // Diagnose all other overridden methods which do not have 'override' specified on them.
4946     for (auto *M : Record->methods())
4947       DiagnoseAbsenceOfOverrideControl(M);
4948   }
4949 
4950   // ms_struct is a request to use the same ABI rules as MSVC.  Check
4951   // whether this class uses any C++ features that are implemented
4952   // completely differently in MSVC, and if so, emit a diagnostic.
4953   // That diagnostic defaults to an error, but we allow projects to
4954   // map it down to a warning (or ignore it).  It's a fairly common
4955   // practice among users of the ms_struct pragma to mass-annotate
4956   // headers, sweeping up a bunch of types that the project doesn't
4957   // really rely on MSVC-compatible layout for.  We must therefore
4958   // support "ms_struct except for C++ stuff" as a secondary ABI.
4959   if (Record->isMsStruct(Context) &&
4960       (Record->isPolymorphic() || Record->getNumBases())) {
4961     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
4962   }
4963 
4964   // Declare inheriting constructors. We do this eagerly here because:
4965   // - The standard requires an eager diagnostic for conflicting inheriting
4966   //   constructors from different classes.
4967   // - The lazy declaration of the other implicit constructors is so as to not
4968   //   waste space and performance on classes that are not meant to be
4969   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4970   //   have inheriting constructors.
4971   DeclareInheritingConstructors(Record);
4972 
4973   checkDLLAttribute(*this, Record);
4974 }
4975 
4976 /// Look up the special member function that would be called by a special
4977 /// member function for a subobject of class type.
4978 ///
4979 /// \param Class The class type of the subobject.
4980 /// \param CSM The kind of special member function.
4981 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4982 /// \param ConstRHS True if this is a copy operation with a const object
4983 ///        on its RHS, that is, if the argument to the outer special member
4984 ///        function is 'const' and this is not a field marked 'mutable'.
4985 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4986     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4987     unsigned FieldQuals, bool ConstRHS) {
4988   unsigned LHSQuals = 0;
4989   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4990     LHSQuals = FieldQuals;
4991 
4992   unsigned RHSQuals = FieldQuals;
4993   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4994     RHSQuals = 0;
4995   else if (ConstRHS)
4996     RHSQuals |= Qualifiers::Const;
4997 
4998   return S.LookupSpecialMember(Class, CSM,
4999                                RHSQuals & Qualifiers::Const,
5000                                RHSQuals & Qualifiers::Volatile,
5001                                false,
5002                                LHSQuals & Qualifiers::Const,
5003                                LHSQuals & Qualifiers::Volatile);
5004 }
5005 
5006 /// Is the special member function which would be selected to perform the
5007 /// specified operation on the specified class type a constexpr constructor?
5008 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5009                                      Sema::CXXSpecialMember CSM,
5010                                      unsigned Quals, bool ConstRHS) {
5011   Sema::SpecialMemberOverloadResult *SMOR =
5012       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5013   if (!SMOR || !SMOR->getMethod())
5014     // A constructor we wouldn't select can't be "involved in initializing"
5015     // anything.
5016     return true;
5017   return SMOR->getMethod()->isConstexpr();
5018 }
5019 
5020 /// Determine whether the specified special member function would be constexpr
5021 /// if it were implicitly defined.
5022 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5023                                               Sema::CXXSpecialMember CSM,
5024                                               bool ConstArg) {
5025   if (!S.getLangOpts().CPlusPlus11)
5026     return false;
5027 
5028   // C++11 [dcl.constexpr]p4:
5029   // In the definition of a constexpr constructor [...]
5030   bool Ctor = true;
5031   switch (CSM) {
5032   case Sema::CXXDefaultConstructor:
5033     // Since default constructor lookup is essentially trivial (and cannot
5034     // involve, for instance, template instantiation), we compute whether a
5035     // defaulted default constructor is constexpr directly within CXXRecordDecl.
5036     //
5037     // This is important for performance; we need to know whether the default
5038     // constructor is constexpr to determine whether the type is a literal type.
5039     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5040 
5041   case Sema::CXXCopyConstructor:
5042   case Sema::CXXMoveConstructor:
5043     // For copy or move constructors, we need to perform overload resolution.
5044     break;
5045 
5046   case Sema::CXXCopyAssignment:
5047   case Sema::CXXMoveAssignment:
5048     if (!S.getLangOpts().CPlusPlus14)
5049       return false;
5050     // In C++1y, we need to perform overload resolution.
5051     Ctor = false;
5052     break;
5053 
5054   case Sema::CXXDestructor:
5055   case Sema::CXXInvalid:
5056     return false;
5057   }
5058 
5059   //   -- if the class is a non-empty union, or for each non-empty anonymous
5060   //      union member of a non-union class, exactly one non-static data member
5061   //      shall be initialized; [DR1359]
5062   //
5063   // If we squint, this is guaranteed, since exactly one non-static data member
5064   // will be initialized (if the constructor isn't deleted), we just don't know
5065   // which one.
5066   if (Ctor && ClassDecl->isUnion())
5067     return true;
5068 
5069   //   -- the class shall not have any virtual base classes;
5070   if (Ctor && ClassDecl->getNumVBases())
5071     return false;
5072 
5073   // C++1y [class.copy]p26:
5074   //   -- [the class] is a literal type, and
5075   if (!Ctor && !ClassDecl->isLiteral())
5076     return false;
5077 
5078   //   -- every constructor involved in initializing [...] base class
5079   //      sub-objects shall be a constexpr constructor;
5080   //   -- the assignment operator selected to copy/move each direct base
5081   //      class is a constexpr function, and
5082   for (const auto &B : ClassDecl->bases()) {
5083     const RecordType *BaseType = B.getType()->getAs<RecordType>();
5084     if (!BaseType) continue;
5085 
5086     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5087     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
5088       return false;
5089   }
5090 
5091   //   -- every constructor involved in initializing non-static data members
5092   //      [...] shall be a constexpr constructor;
5093   //   -- every non-static data member and base class sub-object shall be
5094   //      initialized
5095   //   -- for each non-static data member of X that is of class type (or array
5096   //      thereof), the assignment operator selected to copy/move that member is
5097   //      a constexpr function
5098   for (const auto *F : ClassDecl->fields()) {
5099     if (F->isInvalidDecl())
5100       continue;
5101     QualType BaseType = S.Context.getBaseElementType(F->getType());
5102     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
5103       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5104       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5105                                     BaseType.getCVRQualifiers(),
5106                                     ConstArg && !F->isMutable()))
5107         return false;
5108     }
5109   }
5110 
5111   // All OK, it's constexpr!
5112   return true;
5113 }
5114 
5115 static Sema::ImplicitExceptionSpecification
5116 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5117   switch (S.getSpecialMember(MD)) {
5118   case Sema::CXXDefaultConstructor:
5119     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5120   case Sema::CXXCopyConstructor:
5121     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5122   case Sema::CXXCopyAssignment:
5123     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5124   case Sema::CXXMoveConstructor:
5125     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5126   case Sema::CXXMoveAssignment:
5127     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5128   case Sema::CXXDestructor:
5129     return S.ComputeDefaultedDtorExceptionSpec(MD);
5130   case Sema::CXXInvalid:
5131     break;
5132   }
5133   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5134          "only special members have implicit exception specs");
5135   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
5136 }
5137 
5138 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5139                                                             CXXMethodDecl *MD) {
5140   FunctionProtoType::ExtProtoInfo EPI;
5141 
5142   // Build an exception specification pointing back at this member.
5143   EPI.ExceptionSpec.Type = EST_Unevaluated;
5144   EPI.ExceptionSpec.SourceDecl = MD;
5145 
5146   // Set the calling convention to the default for C++ instance methods.
5147   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5148       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5149                                             /*IsCXXMethod=*/true));
5150   return EPI;
5151 }
5152 
5153 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5154   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5155   if (FPT->getExceptionSpecType() != EST_Unevaluated)
5156     return;
5157 
5158   // Evaluate the exception specification.
5159   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
5160 
5161   // Update the type of the special member to use it.
5162   UpdateExceptionSpec(MD, ESI);
5163 
5164   // A user-provided destructor can be defined outside the class. When that
5165   // happens, be sure to update the exception specification on both
5166   // declarations.
5167   const FunctionProtoType *CanonicalFPT =
5168     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5169   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
5170     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
5171 }
5172 
5173 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5174   CXXRecordDecl *RD = MD->getParent();
5175   CXXSpecialMember CSM = getSpecialMember(MD);
5176 
5177   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5178          "not an explicitly-defaulted special member");
5179 
5180   // Whether this was the first-declared instance of the constructor.
5181   // This affects whether we implicitly add an exception spec and constexpr.
5182   bool First = MD == MD->getCanonicalDecl();
5183 
5184   bool HadError = false;
5185 
5186   // C++11 [dcl.fct.def.default]p1:
5187   //   A function that is explicitly defaulted shall
5188   //     -- be a special member function (checked elsewhere),
5189   //     -- have the same type (except for ref-qualifiers, and except that a
5190   //        copy operation can take a non-const reference) as an implicit
5191   //        declaration, and
5192   //     -- not have default arguments.
5193   unsigned ExpectedParams = 1;
5194   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5195     ExpectedParams = 0;
5196   if (MD->getNumParams() != ExpectedParams) {
5197     // This also checks for default arguments: a copy or move constructor with a
5198     // default argument is classified as a default constructor, and assignment
5199     // operations and destructors can't have default arguments.
5200     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5201       << CSM << MD->getSourceRange();
5202     HadError = true;
5203   } else if (MD->isVariadic()) {
5204     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5205       << CSM << MD->getSourceRange();
5206     HadError = true;
5207   }
5208 
5209   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
5210 
5211   bool CanHaveConstParam = false;
5212   if (CSM == CXXCopyConstructor)
5213     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
5214   else if (CSM == CXXCopyAssignment)
5215     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
5216 
5217   QualType ReturnType = Context.VoidTy;
5218   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5219     // Check for return type matching.
5220     ReturnType = Type->getReturnType();
5221     QualType ExpectedReturnType =
5222         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5223     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5224       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5225         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5226       HadError = true;
5227     }
5228 
5229     // A defaulted special member cannot have cv-qualifiers.
5230     if (Type->getTypeQuals()) {
5231       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
5232         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
5233       HadError = true;
5234     }
5235   }
5236 
5237   // Check for parameter type matching.
5238   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
5239   bool HasConstParam = false;
5240   if (ExpectedParams && ArgType->isReferenceType()) {
5241     // Argument must be reference to possibly-const T.
5242     QualType ReferentType = ArgType->getPointeeType();
5243     HasConstParam = ReferentType.isConstQualified();
5244 
5245     if (ReferentType.isVolatileQualified()) {
5246       Diag(MD->getLocation(),
5247            diag::err_defaulted_special_member_volatile_param) << CSM;
5248       HadError = true;
5249     }
5250 
5251     if (HasConstParam && !CanHaveConstParam) {
5252       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5253         Diag(MD->getLocation(),
5254              diag::err_defaulted_special_member_copy_const_param)
5255           << (CSM == CXXCopyAssignment);
5256         // FIXME: Explain why this special member can't be const.
5257       } else {
5258         Diag(MD->getLocation(),
5259              diag::err_defaulted_special_member_move_const_param)
5260           << (CSM == CXXMoveAssignment);
5261       }
5262       HadError = true;
5263     }
5264   } else if (ExpectedParams) {
5265     // A copy assignment operator can take its argument by value, but a
5266     // defaulted one cannot.
5267     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5268     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5269     HadError = true;
5270   }
5271 
5272   // C++11 [dcl.fct.def.default]p2:
5273   //   An explicitly-defaulted function may be declared constexpr only if it
5274   //   would have been implicitly declared as constexpr,
5275   // Do not apply this rule to members of class templates, since core issue 1358
5276   // makes such functions always instantiate to constexpr functions. For
5277   // functions which cannot be constexpr (for non-constructors in C++11 and for
5278   // destructors in C++1y), this is checked elsewhere.
5279   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5280                                                      HasConstParam);
5281   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5282                                  : isa<CXXConstructorDecl>(MD)) &&
5283       MD->isConstexpr() && !Constexpr &&
5284       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5285     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5286     // FIXME: Explain why the special member can't be constexpr.
5287     HadError = true;
5288   }
5289 
5290   //   and may have an explicit exception-specification only if it is compatible
5291   //   with the exception-specification on the implicit declaration.
5292   if (Type->hasExceptionSpec()) {
5293     // Delay the check if this is the first declaration of the special member,
5294     // since we may not have parsed some necessary in-class initializers yet.
5295     if (First) {
5296       // If the exception specification needs to be instantiated, do so now,
5297       // before we clobber it with an EST_Unevaluated specification below.
5298       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5299         InstantiateExceptionSpec(MD->getLocStart(), MD);
5300         Type = MD->getType()->getAs<FunctionProtoType>();
5301       }
5302       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5303     } else
5304       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5305   }
5306 
5307   //   If a function is explicitly defaulted on its first declaration,
5308   if (First) {
5309     //  -- it is implicitly considered to be constexpr if the implicit
5310     //     definition would be,
5311     MD->setConstexpr(Constexpr);
5312 
5313     //  -- it is implicitly considered to have the same exception-specification
5314     //     as if it had been implicitly declared,
5315     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5316     EPI.ExceptionSpec.Type = EST_Unevaluated;
5317     EPI.ExceptionSpec.SourceDecl = MD;
5318     MD->setType(Context.getFunctionType(ReturnType,
5319                                         llvm::makeArrayRef(&ArgType,
5320                                                            ExpectedParams),
5321                                         EPI));
5322   }
5323 
5324   if (ShouldDeleteSpecialMember(MD, CSM)) {
5325     if (First) {
5326       SetDeclDeleted(MD, MD->getLocation());
5327     } else {
5328       // C++11 [dcl.fct.def.default]p4:
5329       //   [For a] user-provided explicitly-defaulted function [...] if such a
5330       //   function is implicitly defined as deleted, the program is ill-formed.
5331       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5332       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5333       HadError = true;
5334     }
5335   }
5336 
5337   if (HadError)
5338     MD->setInvalidDecl();
5339 }
5340 
5341 /// Check whether the exception specification provided for an
5342 /// explicitly-defaulted special member matches the exception specification
5343 /// that would have been generated for an implicit special member, per
5344 /// C++11 [dcl.fct.def.default]p2.
5345 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5346     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5347   // If the exception specification was explicitly specified but hadn't been
5348   // parsed when the method was defaulted, grab it now.
5349   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5350     SpecifiedType =
5351         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5352 
5353   // Compute the implicit exception specification.
5354   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5355                                                        /*IsCXXMethod=*/true);
5356   FunctionProtoType::ExtProtoInfo EPI(CC);
5357   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5358                           .getExceptionSpec();
5359   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5360     Context.getFunctionType(Context.VoidTy, None, EPI));
5361 
5362   // Ensure that it matches.
5363   CheckEquivalentExceptionSpec(
5364     PDiag(diag::err_incorrect_defaulted_exception_spec)
5365       << getSpecialMember(MD), PDiag(),
5366     ImplicitType, SourceLocation(),
5367     SpecifiedType, MD->getLocation());
5368 }
5369 
5370 void Sema::CheckDelayedMemberExceptionSpecs() {
5371   decltype(DelayedExceptionSpecChecks) Checks;
5372   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
5373 
5374   std::swap(Checks, DelayedExceptionSpecChecks);
5375   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5376 
5377   // Perform any deferred checking of exception specifications for virtual
5378   // destructors.
5379   for (auto &Check : Checks)
5380     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
5381 
5382   // Check that any explicitly-defaulted methods have exception specifications
5383   // compatible with their implicit exception specifications.
5384   for (auto &Spec : Specs)
5385     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
5386 }
5387 
5388 namespace {
5389 struct SpecialMemberDeletionInfo {
5390   Sema &S;
5391   CXXMethodDecl *MD;
5392   Sema::CXXSpecialMember CSM;
5393   bool Diagnose;
5394 
5395   // Properties of the special member, computed for convenience.
5396   bool IsConstructor, IsAssignment, IsMove, ConstArg;
5397   SourceLocation Loc;
5398 
5399   bool AllFieldsAreConst;
5400 
5401   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5402                             Sema::CXXSpecialMember CSM, bool Diagnose)
5403     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5404       IsConstructor(false), IsAssignment(false), IsMove(false),
5405       ConstArg(false), Loc(MD->getLocation()),
5406       AllFieldsAreConst(true) {
5407     switch (CSM) {
5408       case Sema::CXXDefaultConstructor:
5409       case Sema::CXXCopyConstructor:
5410         IsConstructor = true;
5411         break;
5412       case Sema::CXXMoveConstructor:
5413         IsConstructor = true;
5414         IsMove = true;
5415         break;
5416       case Sema::CXXCopyAssignment:
5417         IsAssignment = true;
5418         break;
5419       case Sema::CXXMoveAssignment:
5420         IsAssignment = true;
5421         IsMove = true;
5422         break;
5423       case Sema::CXXDestructor:
5424         break;
5425       case Sema::CXXInvalid:
5426         llvm_unreachable("invalid special member kind");
5427     }
5428 
5429     if (MD->getNumParams()) {
5430       if (const ReferenceType *RT =
5431               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5432         ConstArg = RT->getPointeeType().isConstQualified();
5433     }
5434   }
5435 
5436   bool inUnion() const { return MD->getParent()->isUnion(); }
5437 
5438   /// Look up the corresponding special member in the given class.
5439   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5440                                               unsigned Quals, bool IsMutable) {
5441     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5442                                        ConstArg && !IsMutable);
5443   }
5444 
5445   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5446 
5447   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5448   bool shouldDeleteForField(FieldDecl *FD);
5449   bool shouldDeleteForAllConstMembers();
5450 
5451   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5452                                      unsigned Quals);
5453   bool shouldDeleteForSubobjectCall(Subobject Subobj,
5454                                     Sema::SpecialMemberOverloadResult *SMOR,
5455                                     bool IsDtorCallInCtor);
5456 
5457   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5458 };
5459 }
5460 
5461 /// Is the given special member inaccessible when used on the given
5462 /// sub-object.
5463 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5464                                              CXXMethodDecl *target) {
5465   /// If we're operating on a base class, the object type is the
5466   /// type of this special member.
5467   QualType objectTy;
5468   AccessSpecifier access = target->getAccess();
5469   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5470     objectTy = S.Context.getTypeDeclType(MD->getParent());
5471     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5472 
5473   // If we're operating on a field, the object type is the type of the field.
5474   } else {
5475     objectTy = S.Context.getTypeDeclType(target->getParent());
5476   }
5477 
5478   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5479 }
5480 
5481 /// Check whether we should delete a special member due to the implicit
5482 /// definition containing a call to a special member of a subobject.
5483 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5484     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5485     bool IsDtorCallInCtor) {
5486   CXXMethodDecl *Decl = SMOR->getMethod();
5487   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5488 
5489   int DiagKind = -1;
5490 
5491   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5492     DiagKind = !Decl ? 0 : 1;
5493   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5494     DiagKind = 2;
5495   else if (!isAccessible(Subobj, Decl))
5496     DiagKind = 3;
5497   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5498            !Decl->isTrivial()) {
5499     // A member of a union must have a trivial corresponding special member.
5500     // As a weird special case, a destructor call from a union's constructor
5501     // must be accessible and non-deleted, but need not be trivial. Such a
5502     // destructor is never actually called, but is semantically checked as
5503     // if it were.
5504     DiagKind = 4;
5505   }
5506 
5507   if (DiagKind == -1)
5508     return false;
5509 
5510   if (Diagnose) {
5511     if (Field) {
5512       S.Diag(Field->getLocation(),
5513              diag::note_deleted_special_member_class_subobject)
5514         << CSM << MD->getParent() << /*IsField*/true
5515         << Field << DiagKind << IsDtorCallInCtor;
5516     } else {
5517       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5518       S.Diag(Base->getLocStart(),
5519              diag::note_deleted_special_member_class_subobject)
5520         << CSM << MD->getParent() << /*IsField*/false
5521         << Base->getType() << DiagKind << IsDtorCallInCtor;
5522     }
5523 
5524     if (DiagKind == 1)
5525       S.NoteDeletedFunction(Decl);
5526     // FIXME: Explain inaccessibility if DiagKind == 3.
5527   }
5528 
5529   return true;
5530 }
5531 
5532 /// Check whether we should delete a special member function due to having a
5533 /// direct or virtual base class or non-static data member of class type M.
5534 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5535     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5536   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5537   bool IsMutable = Field && Field->isMutable();
5538 
5539   // C++11 [class.ctor]p5:
5540   // -- any direct or virtual base class, or non-static data member with no
5541   //    brace-or-equal-initializer, has class type M (or array thereof) and
5542   //    either M has no default constructor or overload resolution as applied
5543   //    to M's default constructor results in an ambiguity or in a function
5544   //    that is deleted or inaccessible
5545   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5546   // -- a direct or virtual base class B that cannot be copied/moved because
5547   //    overload resolution, as applied to B's corresponding special member,
5548   //    results in an ambiguity or a function that is deleted or inaccessible
5549   //    from the defaulted special member
5550   // C++11 [class.dtor]p5:
5551   // -- any direct or virtual base class [...] has a type with a destructor
5552   //    that is deleted or inaccessible
5553   if (!(CSM == Sema::CXXDefaultConstructor &&
5554         Field && Field->hasInClassInitializer()) &&
5555       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5556                                    false))
5557     return true;
5558 
5559   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5560   // -- any direct or virtual base class or non-static data member has a
5561   //    type with a destructor that is deleted or inaccessible
5562   if (IsConstructor) {
5563     Sema::SpecialMemberOverloadResult *SMOR =
5564         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5565                               false, false, false, false, false);
5566     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5567       return true;
5568   }
5569 
5570   return false;
5571 }
5572 
5573 /// Check whether we should delete a special member function due to the class
5574 /// having a particular direct or virtual base class.
5575 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5576   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5577   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5578 }
5579 
5580 /// Check whether we should delete a special member function due to the class
5581 /// having a particular non-static data member.
5582 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5583   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5584   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5585 
5586   if (CSM == Sema::CXXDefaultConstructor) {
5587     // For a default constructor, all references must be initialized in-class
5588     // and, if a union, it must have a non-const member.
5589     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5590       if (Diagnose)
5591         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5592           << MD->getParent() << FD << FieldType << /*Reference*/0;
5593       return true;
5594     }
5595     // C++11 [class.ctor]p5: any non-variant non-static data member of
5596     // const-qualified type (or array thereof) with no
5597     // brace-or-equal-initializer does not have a user-provided default
5598     // constructor.
5599     if (!inUnion() && FieldType.isConstQualified() &&
5600         !FD->hasInClassInitializer() &&
5601         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5602       if (Diagnose)
5603         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5604           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5605       return true;
5606     }
5607 
5608     if (inUnion() && !FieldType.isConstQualified())
5609       AllFieldsAreConst = false;
5610   } else if (CSM == Sema::CXXCopyConstructor) {
5611     // For a copy constructor, data members must not be of rvalue reference
5612     // type.
5613     if (FieldType->isRValueReferenceType()) {
5614       if (Diagnose)
5615         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5616           << MD->getParent() << FD << FieldType;
5617       return true;
5618     }
5619   } else if (IsAssignment) {
5620     // For an assignment operator, data members must not be of reference type.
5621     if (FieldType->isReferenceType()) {
5622       if (Diagnose)
5623         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5624           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5625       return true;
5626     }
5627     if (!FieldRecord && FieldType.isConstQualified()) {
5628       // C++11 [class.copy]p23:
5629       // -- a non-static data member of const non-class type (or array thereof)
5630       if (Diagnose)
5631         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5632           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5633       return true;
5634     }
5635   }
5636 
5637   if (FieldRecord) {
5638     // Some additional restrictions exist on the variant members.
5639     if (!inUnion() && FieldRecord->isUnion() &&
5640         FieldRecord->isAnonymousStructOrUnion()) {
5641       bool AllVariantFieldsAreConst = true;
5642 
5643       // FIXME: Handle anonymous unions declared within anonymous unions.
5644       for (auto *UI : FieldRecord->fields()) {
5645         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5646 
5647         if (!UnionFieldType.isConstQualified())
5648           AllVariantFieldsAreConst = false;
5649 
5650         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5651         if (UnionFieldRecord &&
5652             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5653                                           UnionFieldType.getCVRQualifiers()))
5654           return true;
5655       }
5656 
5657       // At least one member in each anonymous union must be non-const
5658       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5659           !FieldRecord->field_empty()) {
5660         if (Diagnose)
5661           S.Diag(FieldRecord->getLocation(),
5662                  diag::note_deleted_default_ctor_all_const)
5663             << MD->getParent() << /*anonymous union*/1;
5664         return true;
5665       }
5666 
5667       // Don't check the implicit member of the anonymous union type.
5668       // This is technically non-conformant, but sanity demands it.
5669       return false;
5670     }
5671 
5672     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5673                                       FieldType.getCVRQualifiers()))
5674       return true;
5675   }
5676 
5677   return false;
5678 }
5679 
5680 /// C++11 [class.ctor] p5:
5681 ///   A defaulted default constructor for a class X is defined as deleted if
5682 /// X is a union and all of its variant members are of const-qualified type.
5683 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5684   // This is a silly definition, because it gives an empty union a deleted
5685   // default constructor. Don't do that.
5686   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5687       !MD->getParent()->field_empty()) {
5688     if (Diagnose)
5689       S.Diag(MD->getParent()->getLocation(),
5690              diag::note_deleted_default_ctor_all_const)
5691         << MD->getParent() << /*not anonymous union*/0;
5692     return true;
5693   }
5694   return false;
5695 }
5696 
5697 /// Determine whether a defaulted special member function should be defined as
5698 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5699 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5700 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5701                                      bool Diagnose) {
5702   if (MD->isInvalidDecl())
5703     return false;
5704   CXXRecordDecl *RD = MD->getParent();
5705   assert(!RD->isDependentType() && "do deletion after instantiation");
5706   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5707     return false;
5708 
5709   // C++11 [expr.lambda.prim]p19:
5710   //   The closure type associated with a lambda-expression has a
5711   //   deleted (8.4.3) default constructor and a deleted copy
5712   //   assignment operator.
5713   if (RD->isLambda() &&
5714       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5715     if (Diagnose)
5716       Diag(RD->getLocation(), diag::note_lambda_decl);
5717     return true;
5718   }
5719 
5720   // For an anonymous struct or union, the copy and assignment special members
5721   // will never be used, so skip the check. For an anonymous union declared at
5722   // namespace scope, the constructor and destructor are used.
5723   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5724       RD->isAnonymousStructOrUnion())
5725     return false;
5726 
5727   // C++11 [class.copy]p7, p18:
5728   //   If the class definition declares a move constructor or move assignment
5729   //   operator, an implicitly declared copy constructor or copy assignment
5730   //   operator is defined as deleted.
5731   if (MD->isImplicit() &&
5732       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5733     CXXMethodDecl *UserDeclaredMove = nullptr;
5734 
5735     // In Microsoft mode, a user-declared move only causes the deletion of the
5736     // corresponding copy operation, not both copy operations.
5737     if (RD->hasUserDeclaredMoveConstructor() &&
5738         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5739       if (!Diagnose) return true;
5740 
5741       // Find any user-declared move constructor.
5742       for (auto *I : RD->ctors()) {
5743         if (I->isMoveConstructor()) {
5744           UserDeclaredMove = I;
5745           break;
5746         }
5747       }
5748       assert(UserDeclaredMove);
5749     } else if (RD->hasUserDeclaredMoveAssignment() &&
5750                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5751       if (!Diagnose) return true;
5752 
5753       // Find any user-declared move assignment operator.
5754       for (auto *I : RD->methods()) {
5755         if (I->isMoveAssignmentOperator()) {
5756           UserDeclaredMove = I;
5757           break;
5758         }
5759       }
5760       assert(UserDeclaredMove);
5761     }
5762 
5763     if (UserDeclaredMove) {
5764       Diag(UserDeclaredMove->getLocation(),
5765            diag::note_deleted_copy_user_declared_move)
5766         << (CSM == CXXCopyAssignment) << RD
5767         << UserDeclaredMove->isMoveAssignmentOperator();
5768       return true;
5769     }
5770   }
5771 
5772   // Do access control from the special member function
5773   ContextRAII MethodContext(*this, MD);
5774 
5775   // C++11 [class.dtor]p5:
5776   // -- for a virtual destructor, lookup of the non-array deallocation function
5777   //    results in an ambiguity or in a function that is deleted or inaccessible
5778   if (CSM == CXXDestructor && MD->isVirtual()) {
5779     FunctionDecl *OperatorDelete = nullptr;
5780     DeclarationName Name =
5781       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5782     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5783                                  OperatorDelete, false)) {
5784       if (Diagnose)
5785         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5786       return true;
5787     }
5788   }
5789 
5790   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5791 
5792   for (auto &BI : RD->bases())
5793     if (!BI.isVirtual() &&
5794         SMI.shouldDeleteForBase(&BI))
5795       return true;
5796 
5797   // Per DR1611, do not consider virtual bases of constructors of abstract
5798   // classes, since we are not going to construct them.
5799   if (!RD->isAbstract() || !SMI.IsConstructor) {
5800     for (auto &BI : RD->vbases())
5801       if (SMI.shouldDeleteForBase(&BI))
5802         return true;
5803   }
5804 
5805   for (auto *FI : RD->fields())
5806     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5807         SMI.shouldDeleteForField(FI))
5808       return true;
5809 
5810   if (SMI.shouldDeleteForAllConstMembers())
5811     return true;
5812 
5813   if (getLangOpts().CUDA) {
5814     // We should delete the special member in CUDA mode if target inference
5815     // failed.
5816     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5817                                                    Diagnose);
5818   }
5819 
5820   return false;
5821 }
5822 
5823 /// Perform lookup for a special member of the specified kind, and determine
5824 /// whether it is trivial. If the triviality can be determined without the
5825 /// lookup, skip it. This is intended for use when determining whether a
5826 /// special member of a containing object is trivial, and thus does not ever
5827 /// perform overload resolution for default constructors.
5828 ///
5829 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5830 /// member that was most likely to be intended to be trivial, if any.
5831 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5832                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5833                                      bool ConstRHS, CXXMethodDecl **Selected) {
5834   if (Selected)
5835     *Selected = nullptr;
5836 
5837   switch (CSM) {
5838   case Sema::CXXInvalid:
5839     llvm_unreachable("not a special member");
5840 
5841   case Sema::CXXDefaultConstructor:
5842     // C++11 [class.ctor]p5:
5843     //   A default constructor is trivial if:
5844     //    - all the [direct subobjects] have trivial default constructors
5845     //
5846     // Note, no overload resolution is performed in this case.
5847     if (RD->hasTrivialDefaultConstructor())
5848       return true;
5849 
5850     if (Selected) {
5851       // If there's a default constructor which could have been trivial, dig it
5852       // out. Otherwise, if there's any user-provided default constructor, point
5853       // to that as an example of why there's not a trivial one.
5854       CXXConstructorDecl *DefCtor = nullptr;
5855       if (RD->needsImplicitDefaultConstructor())
5856         S.DeclareImplicitDefaultConstructor(RD);
5857       for (auto *CI : RD->ctors()) {
5858         if (!CI->isDefaultConstructor())
5859           continue;
5860         DefCtor = CI;
5861         if (!DefCtor->isUserProvided())
5862           break;
5863       }
5864 
5865       *Selected = DefCtor;
5866     }
5867 
5868     return false;
5869 
5870   case Sema::CXXDestructor:
5871     // C++11 [class.dtor]p5:
5872     //   A destructor is trivial if:
5873     //    - all the direct [subobjects] have trivial destructors
5874     if (RD->hasTrivialDestructor())
5875       return true;
5876 
5877     if (Selected) {
5878       if (RD->needsImplicitDestructor())
5879         S.DeclareImplicitDestructor(RD);
5880       *Selected = RD->getDestructor();
5881     }
5882 
5883     return false;
5884 
5885   case Sema::CXXCopyConstructor:
5886     // C++11 [class.copy]p12:
5887     //   A copy constructor is trivial if:
5888     //    - the constructor selected to copy each direct [subobject] is trivial
5889     if (RD->hasTrivialCopyConstructor()) {
5890       if (Quals == Qualifiers::Const)
5891         // We must either select the trivial copy constructor or reach an
5892         // ambiguity; no need to actually perform overload resolution.
5893         return true;
5894     } else if (!Selected) {
5895       return false;
5896     }
5897     // In C++98, we are not supposed to perform overload resolution here, but we
5898     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5899     // cases like B as having a non-trivial copy constructor:
5900     //   struct A { template<typename T> A(T&); };
5901     //   struct B { mutable A a; };
5902     goto NeedOverloadResolution;
5903 
5904   case Sema::CXXCopyAssignment:
5905     // C++11 [class.copy]p25:
5906     //   A copy assignment operator is trivial if:
5907     //    - the assignment operator selected to copy each direct [subobject] is
5908     //      trivial
5909     if (RD->hasTrivialCopyAssignment()) {
5910       if (Quals == Qualifiers::Const)
5911         return true;
5912     } else if (!Selected) {
5913       return false;
5914     }
5915     // In C++98, we are not supposed to perform overload resolution here, but we
5916     // treat that as a language defect.
5917     goto NeedOverloadResolution;
5918 
5919   case Sema::CXXMoveConstructor:
5920   case Sema::CXXMoveAssignment:
5921   NeedOverloadResolution:
5922     Sema::SpecialMemberOverloadResult *SMOR =
5923         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5924 
5925     // The standard doesn't describe how to behave if the lookup is ambiguous.
5926     // We treat it as not making the member non-trivial, just like the standard
5927     // mandates for the default constructor. This should rarely matter, because
5928     // the member will also be deleted.
5929     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5930       return true;
5931 
5932     if (!SMOR->getMethod()) {
5933       assert(SMOR->getKind() ==
5934              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5935       return false;
5936     }
5937 
5938     // We deliberately don't check if we found a deleted special member. We're
5939     // not supposed to!
5940     if (Selected)
5941       *Selected = SMOR->getMethod();
5942     return SMOR->getMethod()->isTrivial();
5943   }
5944 
5945   llvm_unreachable("unknown special method kind");
5946 }
5947 
5948 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5949   for (auto *CI : RD->ctors())
5950     if (!CI->isImplicit())
5951       return CI;
5952 
5953   // Look for constructor templates.
5954   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5955   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5956     if (CXXConstructorDecl *CD =
5957           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5958       return CD;
5959   }
5960 
5961   return nullptr;
5962 }
5963 
5964 /// The kind of subobject we are checking for triviality. The values of this
5965 /// enumeration are used in diagnostics.
5966 enum TrivialSubobjectKind {
5967   /// The subobject is a base class.
5968   TSK_BaseClass,
5969   /// The subobject is a non-static data member.
5970   TSK_Field,
5971   /// The object is actually the complete object.
5972   TSK_CompleteObject
5973 };
5974 
5975 /// Check whether the special member selected for a given type would be trivial.
5976 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5977                                       QualType SubType, bool ConstRHS,
5978                                       Sema::CXXSpecialMember CSM,
5979                                       TrivialSubobjectKind Kind,
5980                                       bool Diagnose) {
5981   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5982   if (!SubRD)
5983     return true;
5984 
5985   CXXMethodDecl *Selected;
5986   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5987                                ConstRHS, Diagnose ? &Selected : nullptr))
5988     return true;
5989 
5990   if (Diagnose) {
5991     if (ConstRHS)
5992       SubType.addConst();
5993 
5994     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5995       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5996         << Kind << SubType.getUnqualifiedType();
5997       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5998         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5999     } else if (!Selected)
6000       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6001         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6002     else if (Selected->isUserProvided()) {
6003       if (Kind == TSK_CompleteObject)
6004         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6005           << Kind << SubType.getUnqualifiedType() << CSM;
6006       else {
6007         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6008           << Kind << SubType.getUnqualifiedType() << CSM;
6009         S.Diag(Selected->getLocation(), diag::note_declared_at);
6010       }
6011     } else {
6012       if (Kind != TSK_CompleteObject)
6013         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6014           << Kind << SubType.getUnqualifiedType() << CSM;
6015 
6016       // Explain why the defaulted or deleted special member isn't trivial.
6017       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6018     }
6019   }
6020 
6021   return false;
6022 }
6023 
6024 /// Check whether the members of a class type allow a special member to be
6025 /// trivial.
6026 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6027                                      Sema::CXXSpecialMember CSM,
6028                                      bool ConstArg, bool Diagnose) {
6029   for (const auto *FI : RD->fields()) {
6030     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6031       continue;
6032 
6033     QualType FieldType = S.Context.getBaseElementType(FI->getType());
6034 
6035     // Pretend anonymous struct or union members are members of this class.
6036     if (FI->isAnonymousStructOrUnion()) {
6037       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6038                                     CSM, ConstArg, Diagnose))
6039         return false;
6040       continue;
6041     }
6042 
6043     // C++11 [class.ctor]p5:
6044     //   A default constructor is trivial if [...]
6045     //    -- no non-static data member of its class has a
6046     //       brace-or-equal-initializer
6047     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6048       if (Diagnose)
6049         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
6050       return false;
6051     }
6052 
6053     // Objective C ARC 4.3.5:
6054     //   [...] nontrivally ownership-qualified types are [...] not trivially
6055     //   default constructible, copy constructible, move constructible, copy
6056     //   assignable, move assignable, or destructible [...]
6057     if (S.getLangOpts().ObjCAutoRefCount &&
6058         FieldType.hasNonTrivialObjCLifetime()) {
6059       if (Diagnose)
6060         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6061           << RD << FieldType.getObjCLifetime();
6062       return false;
6063     }
6064 
6065     bool ConstRHS = ConstArg && !FI->isMutable();
6066     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6067                                    CSM, TSK_Field, Diagnose))
6068       return false;
6069   }
6070 
6071   return true;
6072 }
6073 
6074 /// Diagnose why the specified class does not have a trivial special member of
6075 /// the given kind.
6076 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6077   QualType Ty = Context.getRecordType(RD);
6078 
6079   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6080   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
6081                             TSK_CompleteObject, /*Diagnose*/true);
6082 }
6083 
6084 /// Determine whether a defaulted or deleted special member function is trivial,
6085 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6086 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6087 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6088                                   bool Diagnose) {
6089   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6090 
6091   CXXRecordDecl *RD = MD->getParent();
6092 
6093   bool ConstArg = false;
6094 
6095   // C++11 [class.copy]p12, p25: [DR1593]
6096   //   A [special member] is trivial if [...] its parameter-type-list is
6097   //   equivalent to the parameter-type-list of an implicit declaration [...]
6098   switch (CSM) {
6099   case CXXDefaultConstructor:
6100   case CXXDestructor:
6101     // Trivial default constructors and destructors cannot have parameters.
6102     break;
6103 
6104   case CXXCopyConstructor:
6105   case CXXCopyAssignment: {
6106     // Trivial copy operations always have const, non-volatile parameter types.
6107     ConstArg = true;
6108     const ParmVarDecl *Param0 = MD->getParamDecl(0);
6109     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6110     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6111       if (Diagnose)
6112         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6113           << Param0->getSourceRange() << Param0->getType()
6114           << Context.getLValueReferenceType(
6115                Context.getRecordType(RD).withConst());
6116       return false;
6117     }
6118     break;
6119   }
6120 
6121   case CXXMoveConstructor:
6122   case CXXMoveAssignment: {
6123     // Trivial move operations always have non-cv-qualified parameters.
6124     const ParmVarDecl *Param0 = MD->getParamDecl(0);
6125     const RValueReferenceType *RT =
6126       Param0->getType()->getAs<RValueReferenceType>();
6127     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6128       if (Diagnose)
6129         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6130           << Param0->getSourceRange() << Param0->getType()
6131           << Context.getRValueReferenceType(Context.getRecordType(RD));
6132       return false;
6133     }
6134     break;
6135   }
6136 
6137   case CXXInvalid:
6138     llvm_unreachable("not a special member");
6139   }
6140 
6141   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6142     if (Diagnose)
6143       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6144            diag::note_nontrivial_default_arg)
6145         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6146     return false;
6147   }
6148   if (MD->isVariadic()) {
6149     if (Diagnose)
6150       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6151     return false;
6152   }
6153 
6154   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6155   //   A copy/move [constructor or assignment operator] is trivial if
6156   //    -- the [member] selected to copy/move each direct base class subobject
6157   //       is trivial
6158   //
6159   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6160   //   A [default constructor or destructor] is trivial if
6161   //    -- all the direct base classes have trivial [default constructors or
6162   //       destructors]
6163   for (const auto &BI : RD->bases())
6164     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
6165                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
6166       return false;
6167 
6168   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6169   //   A copy/move [constructor or assignment operator] for a class X is
6170   //   trivial if
6171   //    -- for each non-static data member of X that is of class type (or array
6172   //       thereof), the constructor selected to copy/move that member is
6173   //       trivial
6174   //
6175   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6176   //   A [default constructor or destructor] is trivial if
6177   //    -- for all of the non-static data members of its class that are of class
6178   //       type (or array thereof), each such class has a trivial [default
6179   //       constructor or destructor]
6180   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6181     return false;
6182 
6183   // C++11 [class.dtor]p5:
6184   //   A destructor is trivial if [...]
6185   //    -- the destructor is not virtual
6186   if (CSM == CXXDestructor && MD->isVirtual()) {
6187     if (Diagnose)
6188       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6189     return false;
6190   }
6191 
6192   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6193   //   A [special member] for class X is trivial if [...]
6194   //    -- class X has no virtual functions and no virtual base classes
6195   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6196     if (!Diagnose)
6197       return false;
6198 
6199     if (RD->getNumVBases()) {
6200       // Check for virtual bases. We already know that the corresponding
6201       // member in all bases is trivial, so vbases must all be direct.
6202       CXXBaseSpecifier &BS = *RD->vbases_begin();
6203       assert(BS.isVirtual());
6204       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6205       return false;
6206     }
6207 
6208     // Must have a virtual method.
6209     for (const auto *MI : RD->methods()) {
6210       if (MI->isVirtual()) {
6211         SourceLocation MLoc = MI->getLocStart();
6212         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6213         return false;
6214       }
6215     }
6216 
6217     llvm_unreachable("dynamic class with no vbases and no virtual functions");
6218   }
6219 
6220   // Looks like it's trivial!
6221   return true;
6222 }
6223 
6224 /// \brief Data used with FindHiddenVirtualMethod
6225 namespace {
6226   struct FindHiddenVirtualMethodData {
6227     Sema *S;
6228     CXXMethodDecl *Method;
6229     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6230     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6231   };
6232 }
6233 
6234 /// \brief Check whether any most overriden method from MD in Methods
6235 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
6236                   const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6237   if (MD->size_overridden_methods() == 0)
6238     return Methods.count(MD->getCanonicalDecl());
6239   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6240                                       E = MD->end_overridden_methods();
6241        I != E; ++I)
6242     if (CheckMostOverridenMethods(*I, Methods))
6243       return true;
6244   return false;
6245 }
6246 
6247 /// \brief Member lookup function that determines whether a given C++
6248 /// method overloads virtual methods in a base class without overriding any,
6249 /// to be used with CXXRecordDecl::lookupInBases().
6250 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6251                                     CXXBasePath &Path,
6252                                     void *UserData) {
6253   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6254 
6255   FindHiddenVirtualMethodData &Data
6256     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6257 
6258   DeclarationName Name = Data.Method->getDeclName();
6259   assert(Name.getNameKind() == DeclarationName::Identifier);
6260 
6261   bool foundSameNameMethod = false;
6262   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6263   for (Path.Decls = BaseRecord->lookup(Name);
6264        !Path.Decls.empty();
6265        Path.Decls = Path.Decls.slice(1)) {
6266     NamedDecl *D = Path.Decls.front();
6267     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6268       MD = MD->getCanonicalDecl();
6269       foundSameNameMethod = true;
6270       // Interested only in hidden virtual methods.
6271       if (!MD->isVirtual())
6272         continue;
6273       // If the method we are checking overrides a method from its base
6274       // don't warn about the other overloaded methods. Clang deviates from GCC
6275       // by only diagnosing overloads of inherited virtual functions that do not
6276       // override any other virtual functions in the base. GCC's
6277       // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6278       // function from a base class. These cases may be better served by a
6279       // warning (not specific to virtual functions) on call sites when the call
6280       // would select a different function from the base class, were it visible.
6281       // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6282       if (!Data.S->IsOverload(Data.Method, MD, false))
6283         return true;
6284       // Collect the overload only if its hidden.
6285       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
6286         overloadedMethods.push_back(MD);
6287     }
6288   }
6289 
6290   if (foundSameNameMethod)
6291     Data.OverloadedMethods.append(overloadedMethods.begin(),
6292                                    overloadedMethods.end());
6293   return foundSameNameMethod;
6294 }
6295 
6296 /// \brief Add the most overriden methods from MD to Methods
6297 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6298                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6299   if (MD->size_overridden_methods() == 0)
6300     Methods.insert(MD->getCanonicalDecl());
6301   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6302                                       E = MD->end_overridden_methods();
6303        I != E; ++I)
6304     AddMostOverridenMethods(*I, Methods);
6305 }
6306 
6307 /// \brief Check if a method overloads virtual methods in a base class without
6308 /// overriding any.
6309 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6310                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6311   if (!MD->getDeclName().isIdentifier())
6312     return;
6313 
6314   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6315                      /*bool RecordPaths=*/false,
6316                      /*bool DetectVirtual=*/false);
6317   FindHiddenVirtualMethodData Data;
6318   Data.Method = MD;
6319   Data.S = this;
6320 
6321   // Keep the base methods that were overriden or introduced in the subclass
6322   // by 'using' in a set. A base method not in this set is hidden.
6323   CXXRecordDecl *DC = MD->getParent();
6324   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6325   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6326     NamedDecl *ND = *I;
6327     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6328       ND = shad->getTargetDecl();
6329     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6330       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
6331   }
6332 
6333   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6334     OverloadedMethods = Data.OverloadedMethods;
6335 }
6336 
6337 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6338                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6339   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6340     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6341     PartialDiagnostic PD = PDiag(
6342          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6343     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6344     Diag(overloadedMD->getLocation(), PD);
6345   }
6346 }
6347 
6348 /// \brief Diagnose methods which overload virtual methods in a base class
6349 /// without overriding any.
6350 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6351   if (MD->isInvalidDecl())
6352     return;
6353 
6354   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6355     return;
6356 
6357   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6358   FindHiddenVirtualMethods(MD, OverloadedMethods);
6359   if (!OverloadedMethods.empty()) {
6360     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6361       << MD << (OverloadedMethods.size() > 1);
6362 
6363     NoteHiddenVirtualMethods(MD, OverloadedMethods);
6364   }
6365 }
6366 
6367 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6368                                              Decl *TagDecl,
6369                                              SourceLocation LBrac,
6370                                              SourceLocation RBrac,
6371                                              AttributeList *AttrList) {
6372   if (!TagDecl)
6373     return;
6374 
6375   AdjustDeclIfTemplate(TagDecl);
6376 
6377   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6378     if (l->getKind() != AttributeList::AT_Visibility)
6379       continue;
6380     l->setInvalid();
6381     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6382       l->getName();
6383   }
6384 
6385   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6386               // strict aliasing violation!
6387               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6388               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6389 
6390   CheckCompletedCXXClass(
6391                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6392 }
6393 
6394 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6395 /// special functions, such as the default constructor, copy
6396 /// constructor, or destructor, to the given C++ class (C++
6397 /// [special]p1).  This routine can only be executed just before the
6398 /// definition of the class is complete.
6399 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6400   if (!ClassDecl->hasUserDeclaredConstructor())
6401     ++ASTContext::NumImplicitDefaultConstructors;
6402 
6403   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6404     ++ASTContext::NumImplicitCopyConstructors;
6405 
6406     // If the properties or semantics of the copy constructor couldn't be
6407     // determined while the class was being declared, force a declaration
6408     // of it now.
6409     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6410       DeclareImplicitCopyConstructor(ClassDecl);
6411   }
6412 
6413   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6414     ++ASTContext::NumImplicitMoveConstructors;
6415 
6416     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6417       DeclareImplicitMoveConstructor(ClassDecl);
6418   }
6419 
6420   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6421     ++ASTContext::NumImplicitCopyAssignmentOperators;
6422 
6423     // If we have a dynamic class, then the copy assignment operator may be
6424     // virtual, so we have to declare it immediately. This ensures that, e.g.,
6425     // it shows up in the right place in the vtable and that we diagnose
6426     // problems with the implicit exception specification.
6427     if (ClassDecl->isDynamicClass() ||
6428         ClassDecl->needsOverloadResolutionForCopyAssignment())
6429       DeclareImplicitCopyAssignment(ClassDecl);
6430   }
6431 
6432   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6433     ++ASTContext::NumImplicitMoveAssignmentOperators;
6434 
6435     // Likewise for the move assignment operator.
6436     if (ClassDecl->isDynamicClass() ||
6437         ClassDecl->needsOverloadResolutionForMoveAssignment())
6438       DeclareImplicitMoveAssignment(ClassDecl);
6439   }
6440 
6441   if (!ClassDecl->hasUserDeclaredDestructor()) {
6442     ++ASTContext::NumImplicitDestructors;
6443 
6444     // If we have a dynamic class, then the destructor may be virtual, so we
6445     // have to declare the destructor immediately. This ensures that, e.g., it
6446     // shows up in the right place in the vtable and that we diagnose problems
6447     // with the implicit exception specification.
6448     if (ClassDecl->isDynamicClass() ||
6449         ClassDecl->needsOverloadResolutionForDestructor())
6450       DeclareImplicitDestructor(ClassDecl);
6451   }
6452 }
6453 
6454 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6455   if (!D)
6456     return 0;
6457 
6458   // The order of template parameters is not important here. All names
6459   // get added to the same scope.
6460   SmallVector<TemplateParameterList *, 4> ParameterLists;
6461 
6462   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6463     D = TD->getTemplatedDecl();
6464 
6465   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6466     ParameterLists.push_back(PSD->getTemplateParameters());
6467 
6468   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6469     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6470       ParameterLists.push_back(DD->getTemplateParameterList(i));
6471 
6472     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6473       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6474         ParameterLists.push_back(FTD->getTemplateParameters());
6475     }
6476   }
6477 
6478   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6479     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6480       ParameterLists.push_back(TD->getTemplateParameterList(i));
6481 
6482     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6483       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6484         ParameterLists.push_back(CTD->getTemplateParameters());
6485     }
6486   }
6487 
6488   unsigned Count = 0;
6489   for (TemplateParameterList *Params : ParameterLists) {
6490     if (Params->size() > 0)
6491       // Ignore explicit specializations; they don't contribute to the template
6492       // depth.
6493       ++Count;
6494     for (NamedDecl *Param : *Params) {
6495       if (Param->getDeclName()) {
6496         S->AddDecl(Param);
6497         IdResolver.AddDecl(Param);
6498       }
6499     }
6500   }
6501 
6502   return Count;
6503 }
6504 
6505 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6506   if (!RecordD) return;
6507   AdjustDeclIfTemplate(RecordD);
6508   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6509   PushDeclContext(S, Record);
6510 }
6511 
6512 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6513   if (!RecordD) return;
6514   PopDeclContext();
6515 }
6516 
6517 /// This is used to implement the constant expression evaluation part of the
6518 /// attribute enable_if extension. There is nothing in standard C++ which would
6519 /// require reentering parameters.
6520 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6521   if (!Param)
6522     return;
6523 
6524   S->AddDecl(Param);
6525   if (Param->getDeclName())
6526     IdResolver.AddDecl(Param);
6527 }
6528 
6529 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6530 /// parsing a top-level (non-nested) C++ class, and we are now
6531 /// parsing those parts of the given Method declaration that could
6532 /// not be parsed earlier (C++ [class.mem]p2), such as default
6533 /// arguments. This action should enter the scope of the given
6534 /// Method declaration as if we had just parsed the qualified method
6535 /// name. However, it should not bring the parameters into scope;
6536 /// that will be performed by ActOnDelayedCXXMethodParameter.
6537 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6538 }
6539 
6540 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6541 /// C++ method declaration. We're (re-)introducing the given
6542 /// function parameter into scope for use in parsing later parts of
6543 /// the method declaration. For example, we could see an
6544 /// ActOnParamDefaultArgument event for this parameter.
6545 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6546   if (!ParamD)
6547     return;
6548 
6549   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6550 
6551   // If this parameter has an unparsed default argument, clear it out
6552   // to make way for the parsed default argument.
6553   if (Param->hasUnparsedDefaultArg())
6554     Param->setDefaultArg(nullptr);
6555 
6556   S->AddDecl(Param);
6557   if (Param->getDeclName())
6558     IdResolver.AddDecl(Param);
6559 }
6560 
6561 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6562 /// processing the delayed method declaration for Method. The method
6563 /// declaration is now considered finished. There may be a separate
6564 /// ActOnStartOfFunctionDef action later (not necessarily
6565 /// immediately!) for this method, if it was also defined inside the
6566 /// class body.
6567 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6568   if (!MethodD)
6569     return;
6570 
6571   AdjustDeclIfTemplate(MethodD);
6572 
6573   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6574 
6575   // Now that we have our default arguments, check the constructor
6576   // again. It could produce additional diagnostics or affect whether
6577   // the class has implicitly-declared destructors, among other
6578   // things.
6579   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6580     CheckConstructor(Constructor);
6581 
6582   // Check the default arguments, which we may have added.
6583   if (!Method->isInvalidDecl())
6584     CheckCXXDefaultArguments(Method);
6585 }
6586 
6587 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6588 /// the well-formedness of the constructor declarator @p D with type @p
6589 /// R. If there are any errors in the declarator, this routine will
6590 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6591 /// will be updated to reflect a well-formed type for the constructor and
6592 /// returned.
6593 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6594                                           StorageClass &SC) {
6595   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6596 
6597   // C++ [class.ctor]p3:
6598   //   A constructor shall not be virtual (10.3) or static (9.4). A
6599   //   constructor can be invoked for a const, volatile or const
6600   //   volatile object. A constructor shall not be declared const,
6601   //   volatile, or const volatile (9.3.2).
6602   if (isVirtual) {
6603     if (!D.isInvalidType())
6604       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6605         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6606         << SourceRange(D.getIdentifierLoc());
6607     D.setInvalidType();
6608   }
6609   if (SC == SC_Static) {
6610     if (!D.isInvalidType())
6611       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6612         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6613         << SourceRange(D.getIdentifierLoc());
6614     D.setInvalidType();
6615     SC = SC_None;
6616   }
6617 
6618   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6619     diagnoseIgnoredQualifiers(
6620         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6621         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6622         D.getDeclSpec().getRestrictSpecLoc(),
6623         D.getDeclSpec().getAtomicSpecLoc());
6624     D.setInvalidType();
6625   }
6626 
6627   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6628   if (FTI.TypeQuals != 0) {
6629     if (FTI.TypeQuals & Qualifiers::Const)
6630       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6631         << "const" << SourceRange(D.getIdentifierLoc());
6632     if (FTI.TypeQuals & Qualifiers::Volatile)
6633       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6634         << "volatile" << SourceRange(D.getIdentifierLoc());
6635     if (FTI.TypeQuals & Qualifiers::Restrict)
6636       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6637         << "restrict" << SourceRange(D.getIdentifierLoc());
6638     D.setInvalidType();
6639   }
6640 
6641   // C++0x [class.ctor]p4:
6642   //   A constructor shall not be declared with a ref-qualifier.
6643   if (FTI.hasRefQualifier()) {
6644     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6645       << FTI.RefQualifierIsLValueRef
6646       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6647     D.setInvalidType();
6648   }
6649 
6650   // Rebuild the function type "R" without any type qualifiers (in
6651   // case any of the errors above fired) and with "void" as the
6652   // return type, since constructors don't have return types.
6653   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6654   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6655     return R;
6656 
6657   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6658   EPI.TypeQuals = 0;
6659   EPI.RefQualifier = RQ_None;
6660 
6661   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6662 }
6663 
6664 /// CheckConstructor - Checks a fully-formed constructor for
6665 /// well-formedness, issuing any diagnostics required. Returns true if
6666 /// the constructor declarator is invalid.
6667 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6668   CXXRecordDecl *ClassDecl
6669     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6670   if (!ClassDecl)
6671     return Constructor->setInvalidDecl();
6672 
6673   // C++ [class.copy]p3:
6674   //   A declaration of a constructor for a class X is ill-formed if
6675   //   its first parameter is of type (optionally cv-qualified) X and
6676   //   either there are no other parameters or else all other
6677   //   parameters have default arguments.
6678   if (!Constructor->isInvalidDecl() &&
6679       ((Constructor->getNumParams() == 1) ||
6680        (Constructor->getNumParams() > 1 &&
6681         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6682       Constructor->getTemplateSpecializationKind()
6683                                               != TSK_ImplicitInstantiation) {
6684     QualType ParamType = Constructor->getParamDecl(0)->getType();
6685     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6686     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6687       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6688       const char *ConstRef
6689         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6690                                                         : " const &";
6691       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6692         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6693 
6694       // FIXME: Rather that making the constructor invalid, we should endeavor
6695       // to fix the type.
6696       Constructor->setInvalidDecl();
6697     }
6698   }
6699 }
6700 
6701 /// CheckDestructor - Checks a fully-formed destructor definition for
6702 /// well-formedness, issuing any diagnostics required.  Returns true
6703 /// on error.
6704 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6705   CXXRecordDecl *RD = Destructor->getParent();
6706 
6707   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6708     SourceLocation Loc;
6709 
6710     if (!Destructor->isImplicit())
6711       Loc = Destructor->getLocation();
6712     else
6713       Loc = RD->getLocation();
6714 
6715     // If we have a virtual destructor, look up the deallocation function
6716     FunctionDecl *OperatorDelete = nullptr;
6717     DeclarationName Name =
6718     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6719     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6720       return true;
6721     // If there's no class-specific operator delete, look up the global
6722     // non-array delete.
6723     if (!OperatorDelete)
6724       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6725 
6726     MarkFunctionReferenced(Loc, OperatorDelete);
6727 
6728     Destructor->setOperatorDelete(OperatorDelete);
6729   }
6730 
6731   return false;
6732 }
6733 
6734 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6735 /// the well-formednes of the destructor declarator @p D with type @p
6736 /// R. If there are any errors in the declarator, this routine will
6737 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6738 /// will be updated to reflect a well-formed type for the destructor and
6739 /// returned.
6740 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6741                                          StorageClass& SC) {
6742   // C++ [class.dtor]p1:
6743   //   [...] A typedef-name that names a class is a class-name
6744   //   (7.1.3); however, a typedef-name that names a class shall not
6745   //   be used as the identifier in the declarator for a destructor
6746   //   declaration.
6747   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6748   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6749     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6750       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6751   else if (const TemplateSpecializationType *TST =
6752              DeclaratorType->getAs<TemplateSpecializationType>())
6753     if (TST->isTypeAlias())
6754       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6755         << DeclaratorType << 1;
6756 
6757   // C++ [class.dtor]p2:
6758   //   A destructor is used to destroy objects of its class type. A
6759   //   destructor takes no parameters, and no return type can be
6760   //   specified for it (not even void). The address of a destructor
6761   //   shall not be taken. A destructor shall not be static. A
6762   //   destructor can be invoked for a const, volatile or const
6763   //   volatile object. A destructor shall not be declared const,
6764   //   volatile or const volatile (9.3.2).
6765   if (SC == SC_Static) {
6766     if (!D.isInvalidType())
6767       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6768         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6769         << SourceRange(D.getIdentifierLoc())
6770         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6771 
6772     SC = SC_None;
6773   }
6774   if (!D.isInvalidType()) {
6775     // Destructors don't have return types, but the parser will
6776     // happily parse something like:
6777     //
6778     //   class X {
6779     //     float ~X();
6780     //   };
6781     //
6782     // The return type will be eliminated later.
6783     if (D.getDeclSpec().hasTypeSpecifier())
6784       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6785         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6786         << SourceRange(D.getIdentifierLoc());
6787     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6788       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6789                                 SourceLocation(),
6790                                 D.getDeclSpec().getConstSpecLoc(),
6791                                 D.getDeclSpec().getVolatileSpecLoc(),
6792                                 D.getDeclSpec().getRestrictSpecLoc(),
6793                                 D.getDeclSpec().getAtomicSpecLoc());
6794       D.setInvalidType();
6795     }
6796   }
6797 
6798   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6799   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6800     if (FTI.TypeQuals & Qualifiers::Const)
6801       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6802         << "const" << SourceRange(D.getIdentifierLoc());
6803     if (FTI.TypeQuals & Qualifiers::Volatile)
6804       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6805         << "volatile" << SourceRange(D.getIdentifierLoc());
6806     if (FTI.TypeQuals & Qualifiers::Restrict)
6807       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6808         << "restrict" << SourceRange(D.getIdentifierLoc());
6809     D.setInvalidType();
6810   }
6811 
6812   // C++0x [class.dtor]p2:
6813   //   A destructor shall not be declared with a ref-qualifier.
6814   if (FTI.hasRefQualifier()) {
6815     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6816       << FTI.RefQualifierIsLValueRef
6817       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6818     D.setInvalidType();
6819   }
6820 
6821   // Make sure we don't have any parameters.
6822   if (FTIHasNonVoidParameters(FTI)) {
6823     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6824 
6825     // Delete the parameters.
6826     FTI.freeParams();
6827     D.setInvalidType();
6828   }
6829 
6830   // Make sure the destructor isn't variadic.
6831   if (FTI.isVariadic) {
6832     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6833     D.setInvalidType();
6834   }
6835 
6836   // Rebuild the function type "R" without any type qualifiers or
6837   // parameters (in case any of the errors above fired) and with
6838   // "void" as the return type, since destructors don't have return
6839   // types.
6840   if (!D.isInvalidType())
6841     return R;
6842 
6843   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6844   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6845   EPI.Variadic = false;
6846   EPI.TypeQuals = 0;
6847   EPI.RefQualifier = RQ_None;
6848   return Context.getFunctionType(Context.VoidTy, None, EPI);
6849 }
6850 
6851 static void extendLeft(SourceRange &R, const SourceRange &Before) {
6852   if (Before.isInvalid())
6853     return;
6854   R.setBegin(Before.getBegin());
6855   if (R.getEnd().isInvalid())
6856     R.setEnd(Before.getEnd());
6857 }
6858 
6859 static void extendRight(SourceRange &R, const SourceRange &After) {
6860   if (After.isInvalid())
6861     return;
6862   if (R.getBegin().isInvalid())
6863     R.setBegin(After.getBegin());
6864   R.setEnd(After.getEnd());
6865 }
6866 
6867 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6868 /// well-formednes of the conversion function declarator @p D with
6869 /// type @p R. If there are any errors in the declarator, this routine
6870 /// will emit diagnostics and return true. Otherwise, it will return
6871 /// false. Either way, the type @p R will be updated to reflect a
6872 /// well-formed type for the conversion operator.
6873 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6874                                      StorageClass& SC) {
6875   // C++ [class.conv.fct]p1:
6876   //   Neither parameter types nor return type can be specified. The
6877   //   type of a conversion function (8.3.5) is "function taking no
6878   //   parameter returning conversion-type-id."
6879   if (SC == SC_Static) {
6880     if (!D.isInvalidType())
6881       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6882         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6883         << D.getName().getSourceRange();
6884     D.setInvalidType();
6885     SC = SC_None;
6886   }
6887 
6888   TypeSourceInfo *ConvTSI = nullptr;
6889   QualType ConvType =
6890       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
6891 
6892   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6893     // Conversion functions don't have return types, but the parser will
6894     // happily parse something like:
6895     //
6896     //   class X {
6897     //     float operator bool();
6898     //   };
6899     //
6900     // The return type will be changed later anyway.
6901     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6902       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6903       << SourceRange(D.getIdentifierLoc());
6904     D.setInvalidType();
6905   }
6906 
6907   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6908 
6909   // Make sure we don't have any parameters.
6910   if (Proto->getNumParams() > 0) {
6911     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6912 
6913     // Delete the parameters.
6914     D.getFunctionTypeInfo().freeParams();
6915     D.setInvalidType();
6916   } else if (Proto->isVariadic()) {
6917     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6918     D.setInvalidType();
6919   }
6920 
6921   // Diagnose "&operator bool()" and other such nonsense.  This
6922   // is actually a gcc extension which we don't support.
6923   if (Proto->getReturnType() != ConvType) {
6924     bool NeedsTypedef = false;
6925     SourceRange Before, After;
6926 
6927     // Walk the chunks and extract information on them for our diagnostic.
6928     bool PastFunctionChunk = false;
6929     for (auto &Chunk : D.type_objects()) {
6930       switch (Chunk.Kind) {
6931       case DeclaratorChunk::Function:
6932         if (!PastFunctionChunk) {
6933           if (Chunk.Fun.HasTrailingReturnType) {
6934             TypeSourceInfo *TRT = nullptr;
6935             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6936             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6937           }
6938           PastFunctionChunk = true;
6939           break;
6940         }
6941         // Fall through.
6942       case DeclaratorChunk::Array:
6943         NeedsTypedef = true;
6944         extendRight(After, Chunk.getSourceRange());
6945         break;
6946 
6947       case DeclaratorChunk::Pointer:
6948       case DeclaratorChunk::BlockPointer:
6949       case DeclaratorChunk::Reference:
6950       case DeclaratorChunk::MemberPointer:
6951         extendLeft(Before, Chunk.getSourceRange());
6952         break;
6953 
6954       case DeclaratorChunk::Paren:
6955         extendLeft(Before, Chunk.Loc);
6956         extendRight(After, Chunk.EndLoc);
6957         break;
6958       }
6959     }
6960 
6961     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
6962                          After.isValid()  ? After.getBegin() :
6963                                             D.getIdentifierLoc();
6964     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
6965     DB << Before << After;
6966 
6967     if (!NeedsTypedef) {
6968       DB << /*don't need a typedef*/0;
6969 
6970       // If we can provide a correct fix-it hint, do so.
6971       if (After.isInvalid() && ConvTSI) {
6972         SourceLocation InsertLoc =
6973             PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
6974         DB << FixItHint::CreateInsertion(InsertLoc, " ")
6975            << FixItHint::CreateInsertionFromRange(
6976                   InsertLoc, CharSourceRange::getTokenRange(Before))
6977            << FixItHint::CreateRemoval(Before);
6978       }
6979     } else if (!Proto->getReturnType()->isDependentType()) {
6980       DB << /*typedef*/1 << Proto->getReturnType();
6981     } else if (getLangOpts().CPlusPlus11) {
6982       DB << /*alias template*/2 << Proto->getReturnType();
6983     } else {
6984       DB << /*might not be fixable*/3;
6985     }
6986 
6987     // Recover by incorporating the other type chunks into the result type.
6988     // Note, this does *not* change the name of the function. This is compatible
6989     // with the GCC extension:
6990     //   struct S { &operator int(); } s;
6991     //   int &r = s.operator int(); // ok in GCC
6992     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
6993     ConvType = Proto->getReturnType();
6994   }
6995 
6996   // C++ [class.conv.fct]p4:
6997   //   The conversion-type-id shall not represent a function type nor
6998   //   an array type.
6999   if (ConvType->isArrayType()) {
7000     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7001     ConvType = Context.getPointerType(ConvType);
7002     D.setInvalidType();
7003   } else if (ConvType->isFunctionType()) {
7004     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7005     ConvType = Context.getPointerType(ConvType);
7006     D.setInvalidType();
7007   }
7008 
7009   // Rebuild the function type "R" without any parameters (in case any
7010   // of the errors above fired) and with the conversion type as the
7011   // return type.
7012   if (D.isInvalidType())
7013     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7014 
7015   // C++0x explicit conversion operators.
7016   if (D.getDeclSpec().isExplicitSpecified())
7017     Diag(D.getDeclSpec().getExplicitSpecLoc(),
7018          getLangOpts().CPlusPlus11 ?
7019            diag::warn_cxx98_compat_explicit_conversion_functions :
7020            diag::ext_explicit_conversion_functions)
7021       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
7022 }
7023 
7024 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7025 /// the declaration of the given C++ conversion function. This routine
7026 /// is responsible for recording the conversion function in the C++
7027 /// class, if possible.
7028 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
7029   assert(Conversion && "Expected to receive a conversion function declaration");
7030 
7031   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
7032 
7033   // Make sure we aren't redeclaring the conversion function.
7034   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
7035 
7036   // C++ [class.conv.fct]p1:
7037   //   [...] A conversion function is never used to convert a
7038   //   (possibly cv-qualified) object to the (possibly cv-qualified)
7039   //   same object type (or a reference to it), to a (possibly
7040   //   cv-qualified) base class of that type (or a reference to it),
7041   //   or to (possibly cv-qualified) void.
7042   // FIXME: Suppress this warning if the conversion function ends up being a
7043   // virtual function that overrides a virtual function in a base class.
7044   QualType ClassType
7045     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7046   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
7047     ConvType = ConvTypeRef->getPointeeType();
7048   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7049       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
7050     /* Suppress diagnostics for instantiations. */;
7051   else if (ConvType->isRecordType()) {
7052     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7053     if (ConvType == ClassType)
7054       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
7055         << ClassType;
7056     else if (IsDerivedFrom(ClassType, ConvType))
7057       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
7058         <<  ClassType << ConvType;
7059   } else if (ConvType->isVoidType()) {
7060     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
7061       << ClassType << ConvType;
7062   }
7063 
7064   if (FunctionTemplateDecl *ConversionTemplate
7065                                 = Conversion->getDescribedFunctionTemplate())
7066     return ConversionTemplate;
7067 
7068   return Conversion;
7069 }
7070 
7071 //===----------------------------------------------------------------------===//
7072 // Namespace Handling
7073 //===----------------------------------------------------------------------===//
7074 
7075 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7076 /// reopened.
7077 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7078                                             SourceLocation Loc,
7079                                             IdentifierInfo *II, bool *IsInline,
7080                                             NamespaceDecl *PrevNS) {
7081   assert(*IsInline != PrevNS->isInline());
7082 
7083   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7084   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7085   // inline namespaces, with the intention of bringing names into namespace std.
7086   //
7087   // We support this just well enough to get that case working; this is not
7088   // sufficient to support reopening namespaces as inline in general.
7089   if (*IsInline && II && II->getName().startswith("__atomic") &&
7090       S.getSourceManager().isInSystemHeader(Loc)) {
7091     // Mark all prior declarations of the namespace as inline.
7092     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7093          NS = NS->getPreviousDecl())
7094       NS->setInline(*IsInline);
7095     // Patch up the lookup table for the containing namespace. This isn't really
7096     // correct, but it's good enough for this particular case.
7097     for (auto *I : PrevNS->decls())
7098       if (auto *ND = dyn_cast<NamedDecl>(I))
7099         PrevNS->getParent()->makeDeclVisibleInContext(ND);
7100     return;
7101   }
7102 
7103   if (PrevNS->isInline())
7104     // The user probably just forgot the 'inline', so suggest that it
7105     // be added back.
7106     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7107       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7108   else
7109     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
7110 
7111   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7112   *IsInline = PrevNS->isInline();
7113 }
7114 
7115 /// ActOnStartNamespaceDef - This is called at the start of a namespace
7116 /// definition.
7117 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
7118                                    SourceLocation InlineLoc,
7119                                    SourceLocation NamespaceLoc,
7120                                    SourceLocation IdentLoc,
7121                                    IdentifierInfo *II,
7122                                    SourceLocation LBrace,
7123                                    AttributeList *AttrList) {
7124   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7125   // For anonymous namespace, take the location of the left brace.
7126   SourceLocation Loc = II ? IdentLoc : LBrace;
7127   bool IsInline = InlineLoc.isValid();
7128   bool IsInvalid = false;
7129   bool IsStd = false;
7130   bool AddToKnown = false;
7131   Scope *DeclRegionScope = NamespcScope->getParent();
7132 
7133   NamespaceDecl *PrevNS = nullptr;
7134   if (II) {
7135     // C++ [namespace.def]p2:
7136     //   The identifier in an original-namespace-definition shall not
7137     //   have been previously defined in the declarative region in
7138     //   which the original-namespace-definition appears. The
7139     //   identifier in an original-namespace-definition is the name of
7140     //   the namespace. Subsequently in that declarative region, it is
7141     //   treated as an original-namespace-name.
7142     //
7143     // Since namespace names are unique in their scope, and we don't
7144     // look through using directives, just look for any ordinary names.
7145 
7146     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
7147     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7148     Decl::IDNS_Namespace;
7149     NamedDecl *PrevDecl = nullptr;
7150     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7151     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7152          ++I) {
7153       if ((*I)->getIdentifierNamespace() & IDNS) {
7154         PrevDecl = *I;
7155         break;
7156       }
7157     }
7158 
7159     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7160 
7161     if (PrevNS) {
7162       // This is an extended namespace definition.
7163       if (IsInline != PrevNS->isInline())
7164         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7165                                         &IsInline, PrevNS);
7166     } else if (PrevDecl) {
7167       // This is an invalid name redefinition.
7168       Diag(Loc, diag::err_redefinition_different_kind)
7169         << II;
7170       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7171       IsInvalid = true;
7172       // Continue on to push Namespc as current DeclContext and return it.
7173     } else if (II->isStr("std") &&
7174                CurContext->getRedeclContext()->isTranslationUnit()) {
7175       // This is the first "real" definition of the namespace "std", so update
7176       // our cache of the "std" namespace to point at this definition.
7177       PrevNS = getStdNamespace();
7178       IsStd = true;
7179       AddToKnown = !IsInline;
7180     } else {
7181       // We've seen this namespace for the first time.
7182       AddToKnown = !IsInline;
7183     }
7184   } else {
7185     // Anonymous namespaces.
7186 
7187     // Determine whether the parent already has an anonymous namespace.
7188     DeclContext *Parent = CurContext->getRedeclContext();
7189     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7190       PrevNS = TU->getAnonymousNamespace();
7191     } else {
7192       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
7193       PrevNS = ND->getAnonymousNamespace();
7194     }
7195 
7196     if (PrevNS && IsInline != PrevNS->isInline())
7197       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7198                                       &IsInline, PrevNS);
7199   }
7200 
7201   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7202                                                  StartLoc, Loc, II, PrevNS);
7203   if (IsInvalid)
7204     Namespc->setInvalidDecl();
7205 
7206   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
7207 
7208   // FIXME: Should we be merging attributes?
7209   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
7210     PushNamespaceVisibilityAttr(Attr, Loc);
7211 
7212   if (IsStd)
7213     StdNamespace = Namespc;
7214   if (AddToKnown)
7215     KnownNamespaces[Namespc] = false;
7216 
7217   if (II) {
7218     PushOnScopeChains(Namespc, DeclRegionScope);
7219   } else {
7220     // Link the anonymous namespace into its parent.
7221     DeclContext *Parent = CurContext->getRedeclContext();
7222     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7223       TU->setAnonymousNamespace(Namespc);
7224     } else {
7225       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
7226     }
7227 
7228     CurContext->addDecl(Namespc);
7229 
7230     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
7231     //   behaves as if it were replaced by
7232     //     namespace unique { /* empty body */ }
7233     //     using namespace unique;
7234     //     namespace unique { namespace-body }
7235     //   where all occurrences of 'unique' in a translation unit are
7236     //   replaced by the same identifier and this identifier differs
7237     //   from all other identifiers in the entire program.
7238 
7239     // We just create the namespace with an empty name and then add an
7240     // implicit using declaration, just like the standard suggests.
7241     //
7242     // CodeGen enforces the "universally unique" aspect by giving all
7243     // declarations semantically contained within an anonymous
7244     // namespace internal linkage.
7245 
7246     if (!PrevNS) {
7247       UsingDirectiveDecl* UD
7248         = UsingDirectiveDecl::Create(Context, Parent,
7249                                      /* 'using' */ LBrace,
7250                                      /* 'namespace' */ SourceLocation(),
7251                                      /* qualifier */ NestedNameSpecifierLoc(),
7252                                      /* identifier */ SourceLocation(),
7253                                      Namespc,
7254                                      /* Ancestor */ Parent);
7255       UD->setImplicit();
7256       Parent->addDecl(UD);
7257     }
7258   }
7259 
7260   ActOnDocumentableDecl(Namespc);
7261 
7262   // Although we could have an invalid decl (i.e. the namespace name is a
7263   // redefinition), push it as current DeclContext and try to continue parsing.
7264   // FIXME: We should be able to push Namespc here, so that the each DeclContext
7265   // for the namespace has the declarations that showed up in that particular
7266   // namespace definition.
7267   PushDeclContext(NamespcScope, Namespc);
7268   return Namespc;
7269 }
7270 
7271 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7272 /// is a namespace alias, returns the namespace it points to.
7273 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7274   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7275     return AD->getNamespace();
7276   return dyn_cast_or_null<NamespaceDecl>(D);
7277 }
7278 
7279 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
7280 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
7281 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
7282   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7283   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
7284   Namespc->setRBraceLoc(RBrace);
7285   PopDeclContext();
7286   if (Namespc->hasAttr<VisibilityAttr>())
7287     PopPragmaVisibility(true, RBrace);
7288 }
7289 
7290 CXXRecordDecl *Sema::getStdBadAlloc() const {
7291   return cast_or_null<CXXRecordDecl>(
7292                                   StdBadAlloc.get(Context.getExternalSource()));
7293 }
7294 
7295 NamespaceDecl *Sema::getStdNamespace() const {
7296   return cast_or_null<NamespaceDecl>(
7297                                  StdNamespace.get(Context.getExternalSource()));
7298 }
7299 
7300 /// \brief Retrieve the special "std" namespace, which may require us to
7301 /// implicitly define the namespace.
7302 NamespaceDecl *Sema::getOrCreateStdNamespace() {
7303   if (!StdNamespace) {
7304     // The "std" namespace has not yet been defined, so build one implicitly.
7305     StdNamespace = NamespaceDecl::Create(Context,
7306                                          Context.getTranslationUnitDecl(),
7307                                          /*Inline=*/false,
7308                                          SourceLocation(), SourceLocation(),
7309                                          &PP.getIdentifierTable().get("std"),
7310                                          /*PrevDecl=*/nullptr);
7311     getStdNamespace()->setImplicit(true);
7312   }
7313 
7314   return getStdNamespace();
7315 }
7316 
7317 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
7318   assert(getLangOpts().CPlusPlus &&
7319          "Looking for std::initializer_list outside of C++.");
7320 
7321   // We're looking for implicit instantiations of
7322   // template <typename E> class std::initializer_list.
7323 
7324   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7325     return false;
7326 
7327   ClassTemplateDecl *Template = nullptr;
7328   const TemplateArgument *Arguments = nullptr;
7329 
7330   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7331 
7332     ClassTemplateSpecializationDecl *Specialization =
7333         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7334     if (!Specialization)
7335       return false;
7336 
7337     Template = Specialization->getSpecializedTemplate();
7338     Arguments = Specialization->getTemplateArgs().data();
7339   } else if (const TemplateSpecializationType *TST =
7340                  Ty->getAs<TemplateSpecializationType>()) {
7341     Template = dyn_cast_or_null<ClassTemplateDecl>(
7342         TST->getTemplateName().getAsTemplateDecl());
7343     Arguments = TST->getArgs();
7344   }
7345   if (!Template)
7346     return false;
7347 
7348   if (!StdInitializerList) {
7349     // Haven't recognized std::initializer_list yet, maybe this is it.
7350     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7351     if (TemplateClass->getIdentifier() !=
7352             &PP.getIdentifierTable().get("initializer_list") ||
7353         !getStdNamespace()->InEnclosingNamespaceSetOf(
7354             TemplateClass->getDeclContext()))
7355       return false;
7356     // This is a template called std::initializer_list, but is it the right
7357     // template?
7358     TemplateParameterList *Params = Template->getTemplateParameters();
7359     if (Params->getMinRequiredArguments() != 1)
7360       return false;
7361     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7362       return false;
7363 
7364     // It's the right template.
7365     StdInitializerList = Template;
7366   }
7367 
7368   if (Template != StdInitializerList)
7369     return false;
7370 
7371   // This is an instance of std::initializer_list. Find the argument type.
7372   if (Element)
7373     *Element = Arguments[0].getAsType();
7374   return true;
7375 }
7376 
7377 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7378   NamespaceDecl *Std = S.getStdNamespace();
7379   if (!Std) {
7380     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7381     return nullptr;
7382   }
7383 
7384   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7385                       Loc, Sema::LookupOrdinaryName);
7386   if (!S.LookupQualifiedName(Result, Std)) {
7387     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7388     return nullptr;
7389   }
7390   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7391   if (!Template) {
7392     Result.suppressDiagnostics();
7393     // We found something weird. Complain about the first thing we found.
7394     NamedDecl *Found = *Result.begin();
7395     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7396     return nullptr;
7397   }
7398 
7399   // We found some template called std::initializer_list. Now verify that it's
7400   // correct.
7401   TemplateParameterList *Params = Template->getTemplateParameters();
7402   if (Params->getMinRequiredArguments() != 1 ||
7403       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7404     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7405     return nullptr;
7406   }
7407 
7408   return Template;
7409 }
7410 
7411 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7412   if (!StdInitializerList) {
7413     StdInitializerList = LookupStdInitializerList(*this, Loc);
7414     if (!StdInitializerList)
7415       return QualType();
7416   }
7417 
7418   TemplateArgumentListInfo Args(Loc, Loc);
7419   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7420                                        Context.getTrivialTypeSourceInfo(Element,
7421                                                                         Loc)));
7422   return Context.getCanonicalType(
7423       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7424 }
7425 
7426 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7427   // C++ [dcl.init.list]p2:
7428   //   A constructor is an initializer-list constructor if its first parameter
7429   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
7430   //   std::initializer_list<E> for some type E, and either there are no other
7431   //   parameters or else all other parameters have default arguments.
7432   if (Ctor->getNumParams() < 1 ||
7433       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7434     return false;
7435 
7436   QualType ArgType = Ctor->getParamDecl(0)->getType();
7437   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7438     ArgType = RT->getPointeeType().getUnqualifiedType();
7439 
7440   return isStdInitializerList(ArgType, nullptr);
7441 }
7442 
7443 /// \brief Determine whether a using statement is in a context where it will be
7444 /// apply in all contexts.
7445 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7446   switch (CurContext->getDeclKind()) {
7447     case Decl::TranslationUnit:
7448       return true;
7449     case Decl::LinkageSpec:
7450       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7451     default:
7452       return false;
7453   }
7454 }
7455 
7456 namespace {
7457 
7458 // Callback to only accept typo corrections that are namespaces.
7459 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7460 public:
7461   bool ValidateCandidate(const TypoCorrection &candidate) override {
7462     if (NamedDecl *ND = candidate.getCorrectionDecl())
7463       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7464     return false;
7465   }
7466 };
7467 
7468 }
7469 
7470 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7471                                        CXXScopeSpec &SS,
7472                                        SourceLocation IdentLoc,
7473                                        IdentifierInfo *Ident) {
7474   R.clear();
7475   if (TypoCorrection Corrected =
7476           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7477                         llvm::make_unique<NamespaceValidatorCCC>(),
7478                         Sema::CTK_ErrorRecovery)) {
7479     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7480       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7481       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7482                               Ident->getName().equals(CorrectedStr);
7483       S.diagnoseTypo(Corrected,
7484                      S.PDiag(diag::err_using_directive_member_suggest)
7485                        << Ident << DC << DroppedSpecifier << SS.getRange(),
7486                      S.PDiag(diag::note_namespace_defined_here));
7487     } else {
7488       S.diagnoseTypo(Corrected,
7489                      S.PDiag(diag::err_using_directive_suggest) << Ident,
7490                      S.PDiag(diag::note_namespace_defined_here));
7491     }
7492     R.addDecl(Corrected.getCorrectionDecl());
7493     return true;
7494   }
7495   return false;
7496 }
7497 
7498 Decl *Sema::ActOnUsingDirective(Scope *S,
7499                                           SourceLocation UsingLoc,
7500                                           SourceLocation NamespcLoc,
7501                                           CXXScopeSpec &SS,
7502                                           SourceLocation IdentLoc,
7503                                           IdentifierInfo *NamespcName,
7504                                           AttributeList *AttrList) {
7505   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7506   assert(NamespcName && "Invalid NamespcName.");
7507   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7508 
7509   // This can only happen along a recovery path.
7510   while (S->getFlags() & Scope::TemplateParamScope)
7511     S = S->getParent();
7512   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7513 
7514   UsingDirectiveDecl *UDir = nullptr;
7515   NestedNameSpecifier *Qualifier = nullptr;
7516   if (SS.isSet())
7517     Qualifier = SS.getScopeRep();
7518 
7519   // Lookup namespace name.
7520   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7521   LookupParsedName(R, S, &SS);
7522   if (R.isAmbiguous())
7523     return nullptr;
7524 
7525   if (R.empty()) {
7526     R.clear();
7527     // Allow "using namespace std;" or "using namespace ::std;" even if
7528     // "std" hasn't been defined yet, for GCC compatibility.
7529     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7530         NamespcName->isStr("std")) {
7531       Diag(IdentLoc, diag::ext_using_undefined_std);
7532       R.addDecl(getOrCreateStdNamespace());
7533       R.resolveKind();
7534     }
7535     // Otherwise, attempt typo correction.
7536     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7537   }
7538 
7539   if (!R.empty()) {
7540     NamedDecl *Named = R.getFoundDecl();
7541     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7542         && "expected namespace decl");
7543 
7544     // The use of a nested name specifier may trigger deprecation warnings.
7545     DiagnoseUseOfDecl(Named, IdentLoc);
7546 
7547     // C++ [namespace.udir]p1:
7548     //   A using-directive specifies that the names in the nominated
7549     //   namespace can be used in the scope in which the
7550     //   using-directive appears after the using-directive. During
7551     //   unqualified name lookup (3.4.1), the names appear as if they
7552     //   were declared in the nearest enclosing namespace which
7553     //   contains both the using-directive and the nominated
7554     //   namespace. [Note: in this context, "contains" means "contains
7555     //   directly or indirectly". ]
7556 
7557     // Find enclosing context containing both using-directive and
7558     // nominated namespace.
7559     NamespaceDecl *NS = getNamespaceDecl(Named);
7560     DeclContext *CommonAncestor = cast<DeclContext>(NS);
7561     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7562       CommonAncestor = CommonAncestor->getParent();
7563 
7564     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7565                                       SS.getWithLocInContext(Context),
7566                                       IdentLoc, Named, CommonAncestor);
7567 
7568     if (IsUsingDirectiveInToplevelContext(CurContext) &&
7569         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7570       Diag(IdentLoc, diag::warn_using_directive_in_header);
7571     }
7572 
7573     PushUsingDirective(S, UDir);
7574   } else {
7575     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7576   }
7577 
7578   if (UDir)
7579     ProcessDeclAttributeList(S, UDir, AttrList);
7580 
7581   return UDir;
7582 }
7583 
7584 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7585   // If the scope has an associated entity and the using directive is at
7586   // namespace or translation unit scope, add the UsingDirectiveDecl into
7587   // its lookup structure so qualified name lookup can find it.
7588   DeclContext *Ctx = S->getEntity();
7589   if (Ctx && !Ctx->isFunctionOrMethod())
7590     Ctx->addDecl(UDir);
7591   else
7592     // Otherwise, it is at block scope. The using-directives will affect lookup
7593     // only to the end of the scope.
7594     S->PushUsingDirective(UDir);
7595 }
7596 
7597 
7598 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7599                                   AccessSpecifier AS,
7600                                   bool HasUsingKeyword,
7601                                   SourceLocation UsingLoc,
7602                                   CXXScopeSpec &SS,
7603                                   UnqualifiedId &Name,
7604                                   AttributeList *AttrList,
7605                                   bool HasTypenameKeyword,
7606                                   SourceLocation TypenameLoc) {
7607   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7608 
7609   switch (Name.getKind()) {
7610   case UnqualifiedId::IK_ImplicitSelfParam:
7611   case UnqualifiedId::IK_Identifier:
7612   case UnqualifiedId::IK_OperatorFunctionId:
7613   case UnqualifiedId::IK_LiteralOperatorId:
7614   case UnqualifiedId::IK_ConversionFunctionId:
7615     break;
7616 
7617   case UnqualifiedId::IK_ConstructorName:
7618   case UnqualifiedId::IK_ConstructorTemplateId:
7619     // C++11 inheriting constructors.
7620     Diag(Name.getLocStart(),
7621          getLangOpts().CPlusPlus11 ?
7622            diag::warn_cxx98_compat_using_decl_constructor :
7623            diag::err_using_decl_constructor)
7624       << SS.getRange();
7625 
7626     if (getLangOpts().CPlusPlus11) break;
7627 
7628     return nullptr;
7629 
7630   case UnqualifiedId::IK_DestructorName:
7631     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7632       << SS.getRange();
7633     return nullptr;
7634 
7635   case UnqualifiedId::IK_TemplateId:
7636     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7637       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7638     return nullptr;
7639   }
7640 
7641   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7642   DeclarationName TargetName = TargetNameInfo.getName();
7643   if (!TargetName)
7644     return nullptr;
7645 
7646   // Warn about access declarations.
7647   if (!HasUsingKeyword) {
7648     Diag(Name.getLocStart(),
7649          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7650                                    : diag::warn_access_decl_deprecated)
7651       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7652   }
7653 
7654   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7655       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7656     return nullptr;
7657 
7658   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7659                                         TargetNameInfo, AttrList,
7660                                         /* IsInstantiation */ false,
7661                                         HasTypenameKeyword, TypenameLoc);
7662   if (UD)
7663     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7664 
7665   return UD;
7666 }
7667 
7668 /// \brief Determine whether a using declaration considers the given
7669 /// declarations as "equivalent", e.g., if they are redeclarations of
7670 /// the same entity or are both typedefs of the same type.
7671 static bool
7672 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7673   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7674     return true;
7675 
7676   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7677     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7678       return Context.hasSameType(TD1->getUnderlyingType(),
7679                                  TD2->getUnderlyingType());
7680 
7681   return false;
7682 }
7683 
7684 
7685 /// Determines whether to create a using shadow decl for a particular
7686 /// decl, given the set of decls existing prior to this using lookup.
7687 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7688                                 const LookupResult &Previous,
7689                                 UsingShadowDecl *&PrevShadow) {
7690   // Diagnose finding a decl which is not from a base class of the
7691   // current class.  We do this now because there are cases where this
7692   // function will silently decide not to build a shadow decl, which
7693   // will pre-empt further diagnostics.
7694   //
7695   // We don't need to do this in C++0x because we do the check once on
7696   // the qualifier.
7697   //
7698   // FIXME: diagnose the following if we care enough:
7699   //   struct A { int foo; };
7700   //   struct B : A { using A::foo; };
7701   //   template <class T> struct C : A {};
7702   //   template <class T> struct D : C<T> { using B::foo; } // <---
7703   // This is invalid (during instantiation) in C++03 because B::foo
7704   // resolves to the using decl in B, which is not a base class of D<T>.
7705   // We can't diagnose it immediately because C<T> is an unknown
7706   // specialization.  The UsingShadowDecl in D<T> then points directly
7707   // to A::foo, which will look well-formed when we instantiate.
7708   // The right solution is to not collapse the shadow-decl chain.
7709   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7710     DeclContext *OrigDC = Orig->getDeclContext();
7711 
7712     // Handle enums and anonymous structs.
7713     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7714     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7715     while (OrigRec->isAnonymousStructOrUnion())
7716       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7717 
7718     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7719       if (OrigDC == CurContext) {
7720         Diag(Using->getLocation(),
7721              diag::err_using_decl_nested_name_specifier_is_current_class)
7722           << Using->getQualifierLoc().getSourceRange();
7723         Diag(Orig->getLocation(), diag::note_using_decl_target);
7724         return true;
7725       }
7726 
7727       Diag(Using->getQualifierLoc().getBeginLoc(),
7728            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7729         << Using->getQualifier()
7730         << cast<CXXRecordDecl>(CurContext)
7731         << Using->getQualifierLoc().getSourceRange();
7732       Diag(Orig->getLocation(), diag::note_using_decl_target);
7733       return true;
7734     }
7735   }
7736 
7737   if (Previous.empty()) return false;
7738 
7739   NamedDecl *Target = Orig;
7740   if (isa<UsingShadowDecl>(Target))
7741     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7742 
7743   // If the target happens to be one of the previous declarations, we
7744   // don't have a conflict.
7745   //
7746   // FIXME: but we might be increasing its access, in which case we
7747   // should redeclare it.
7748   NamedDecl *NonTag = nullptr, *Tag = nullptr;
7749   bool FoundEquivalentDecl = false;
7750   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7751          I != E; ++I) {
7752     NamedDecl *D = (*I)->getUnderlyingDecl();
7753     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7754       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7755         PrevShadow = Shadow;
7756       FoundEquivalentDecl = true;
7757     }
7758 
7759     (isa<TagDecl>(D) ? Tag : NonTag) = D;
7760   }
7761 
7762   if (FoundEquivalentDecl)
7763     return false;
7764 
7765   if (FunctionDecl *FD = Target->getAsFunction()) {
7766     NamedDecl *OldDecl = nullptr;
7767     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7768                           /*IsForUsingDecl*/ true)) {
7769     case Ovl_Overload:
7770       return false;
7771 
7772     case Ovl_NonFunction:
7773       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7774       break;
7775 
7776     // We found a decl with the exact signature.
7777     case Ovl_Match:
7778       // If we're in a record, we want to hide the target, so we
7779       // return true (without a diagnostic) to tell the caller not to
7780       // build a shadow decl.
7781       if (CurContext->isRecord())
7782         return true;
7783 
7784       // If we're not in a record, this is an error.
7785       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7786       break;
7787     }
7788 
7789     Diag(Target->getLocation(), diag::note_using_decl_target);
7790     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7791     return true;
7792   }
7793 
7794   // Target is not a function.
7795 
7796   if (isa<TagDecl>(Target)) {
7797     // No conflict between a tag and a non-tag.
7798     if (!Tag) return false;
7799 
7800     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7801     Diag(Target->getLocation(), diag::note_using_decl_target);
7802     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7803     return true;
7804   }
7805 
7806   // No conflict between a tag and a non-tag.
7807   if (!NonTag) return false;
7808 
7809   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7810   Diag(Target->getLocation(), diag::note_using_decl_target);
7811   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7812   return true;
7813 }
7814 
7815 /// Builds a shadow declaration corresponding to a 'using' declaration.
7816 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7817                                             UsingDecl *UD,
7818                                             NamedDecl *Orig,
7819                                             UsingShadowDecl *PrevDecl) {
7820 
7821   // If we resolved to another shadow declaration, just coalesce them.
7822   NamedDecl *Target = Orig;
7823   if (isa<UsingShadowDecl>(Target)) {
7824     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7825     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7826   }
7827 
7828   UsingShadowDecl *Shadow
7829     = UsingShadowDecl::Create(Context, CurContext,
7830                               UD->getLocation(), UD, Target);
7831   UD->addShadowDecl(Shadow);
7832 
7833   Shadow->setAccess(UD->getAccess());
7834   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7835     Shadow->setInvalidDecl();
7836 
7837   Shadow->setPreviousDecl(PrevDecl);
7838 
7839   if (S)
7840     PushOnScopeChains(Shadow, S);
7841   else
7842     CurContext->addDecl(Shadow);
7843 
7844 
7845   return Shadow;
7846 }
7847 
7848 /// Hides a using shadow declaration.  This is required by the current
7849 /// using-decl implementation when a resolvable using declaration in a
7850 /// class is followed by a declaration which would hide or override
7851 /// one or more of the using decl's targets; for example:
7852 ///
7853 ///   struct Base { void foo(int); };
7854 ///   struct Derived : Base {
7855 ///     using Base::foo;
7856 ///     void foo(int);
7857 ///   };
7858 ///
7859 /// The governing language is C++03 [namespace.udecl]p12:
7860 ///
7861 ///   When a using-declaration brings names from a base class into a
7862 ///   derived class scope, member functions in the derived class
7863 ///   override and/or hide member functions with the same name and
7864 ///   parameter types in a base class (rather than conflicting).
7865 ///
7866 /// There are two ways to implement this:
7867 ///   (1) optimistically create shadow decls when they're not hidden
7868 ///       by existing declarations, or
7869 ///   (2) don't create any shadow decls (or at least don't make them
7870 ///       visible) until we've fully parsed/instantiated the class.
7871 /// The problem with (1) is that we might have to retroactively remove
7872 /// a shadow decl, which requires several O(n) operations because the
7873 /// decl structures are (very reasonably) not designed for removal.
7874 /// (2) avoids this but is very fiddly and phase-dependent.
7875 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7876   if (Shadow->getDeclName().getNameKind() ==
7877         DeclarationName::CXXConversionFunctionName)
7878     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7879 
7880   // Remove it from the DeclContext...
7881   Shadow->getDeclContext()->removeDecl(Shadow);
7882 
7883   // ...and the scope, if applicable...
7884   if (S) {
7885     S->RemoveDecl(Shadow);
7886     IdResolver.RemoveDecl(Shadow);
7887   }
7888 
7889   // ...and the using decl.
7890   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7891 
7892   // TODO: complain somehow if Shadow was used.  It shouldn't
7893   // be possible for this to happen, because...?
7894 }
7895 
7896 /// Find the base specifier for a base class with the given type.
7897 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7898                                                 QualType DesiredBase,
7899                                                 bool &AnyDependentBases) {
7900   // Check whether the named type is a direct base class.
7901   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7902   for (auto &Base : Derived->bases()) {
7903     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7904     if (CanonicalDesiredBase == BaseType)
7905       return &Base;
7906     if (BaseType->isDependentType())
7907       AnyDependentBases = true;
7908   }
7909   return nullptr;
7910 }
7911 
7912 namespace {
7913 class UsingValidatorCCC : public CorrectionCandidateCallback {
7914 public:
7915   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7916                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7917       : HasTypenameKeyword(HasTypenameKeyword),
7918         IsInstantiation(IsInstantiation), OldNNS(NNS),
7919         RequireMemberOf(RequireMemberOf) {}
7920 
7921   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7922     NamedDecl *ND = Candidate.getCorrectionDecl();
7923 
7924     // Keywords are not valid here.
7925     if (!ND || isa<NamespaceDecl>(ND))
7926       return false;
7927 
7928     // Completely unqualified names are invalid for a 'using' declaration.
7929     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7930       return false;
7931 
7932     if (RequireMemberOf) {
7933       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7934       if (FoundRecord && FoundRecord->isInjectedClassName()) {
7935         // No-one ever wants a using-declaration to name an injected-class-name
7936         // of a base class, unless they're declaring an inheriting constructor.
7937         ASTContext &Ctx = ND->getASTContext();
7938         if (!Ctx.getLangOpts().CPlusPlus11)
7939           return false;
7940         QualType FoundType = Ctx.getRecordType(FoundRecord);
7941 
7942         // Check that the injected-class-name is named as a member of its own
7943         // type; we don't want to suggest 'using Derived::Base;', since that
7944         // means something else.
7945         NestedNameSpecifier *Specifier =
7946             Candidate.WillReplaceSpecifier()
7947                 ? Candidate.getCorrectionSpecifier()
7948                 : OldNNS;
7949         if (!Specifier->getAsType() ||
7950             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7951           return false;
7952 
7953         // Check that this inheriting constructor declaration actually names a
7954         // direct base class of the current class.
7955         bool AnyDependentBases = false;
7956         if (!findDirectBaseWithType(RequireMemberOf,
7957                                     Ctx.getRecordType(FoundRecord),
7958                                     AnyDependentBases) &&
7959             !AnyDependentBases)
7960           return false;
7961       } else {
7962         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7963         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7964           return false;
7965 
7966         // FIXME: Check that the base class member is accessible?
7967       }
7968     }
7969 
7970     if (isa<TypeDecl>(ND))
7971       return HasTypenameKeyword || !IsInstantiation;
7972 
7973     return !HasTypenameKeyword;
7974   }
7975 
7976 private:
7977   bool HasTypenameKeyword;
7978   bool IsInstantiation;
7979   NestedNameSpecifier *OldNNS;
7980   CXXRecordDecl *RequireMemberOf;
7981 };
7982 } // end anonymous namespace
7983 
7984 /// Builds a using declaration.
7985 ///
7986 /// \param IsInstantiation - Whether this call arises from an
7987 ///   instantiation of an unresolved using declaration.  We treat
7988 ///   the lookup differently for these declarations.
7989 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7990                                        SourceLocation UsingLoc,
7991                                        CXXScopeSpec &SS,
7992                                        DeclarationNameInfo NameInfo,
7993                                        AttributeList *AttrList,
7994                                        bool IsInstantiation,
7995                                        bool HasTypenameKeyword,
7996                                        SourceLocation TypenameLoc) {
7997   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7998   SourceLocation IdentLoc = NameInfo.getLoc();
7999   assert(IdentLoc.isValid() && "Invalid TargetName location.");
8000 
8001   // FIXME: We ignore attributes for now.
8002 
8003   if (SS.isEmpty()) {
8004     Diag(IdentLoc, diag::err_using_requires_qualname);
8005     return nullptr;
8006   }
8007 
8008   // Do the redeclaration lookup in the current scope.
8009   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
8010                         ForRedeclaration);
8011   Previous.setHideTags(false);
8012   if (S) {
8013     LookupName(Previous, S);
8014 
8015     // It is really dumb that we have to do this.
8016     LookupResult::Filter F = Previous.makeFilter();
8017     while (F.hasNext()) {
8018       NamedDecl *D = F.next();
8019       if (!isDeclInScope(D, CurContext, S))
8020         F.erase();
8021       // If we found a local extern declaration that's not ordinarily visible,
8022       // and this declaration is being added to a non-block scope, ignore it.
8023       // We're only checking for scope conflicts here, not also for violations
8024       // of the linkage rules.
8025       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8026                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8027         F.erase();
8028     }
8029     F.done();
8030   } else {
8031     assert(IsInstantiation && "no scope in non-instantiation");
8032     assert(CurContext->isRecord() && "scope not record in instantiation");
8033     LookupQualifiedName(Previous, CurContext);
8034   }
8035 
8036   // Check for invalid redeclarations.
8037   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8038                                   SS, IdentLoc, Previous))
8039     return nullptr;
8040 
8041   // Check for bad qualifiers.
8042   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
8043     return nullptr;
8044 
8045   DeclContext *LookupContext = computeDeclContext(SS);
8046   NamedDecl *D;
8047   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8048   if (!LookupContext) {
8049     if (HasTypenameKeyword) {
8050       // FIXME: not all declaration name kinds are legal here
8051       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8052                                               UsingLoc, TypenameLoc,
8053                                               QualifierLoc,
8054                                               IdentLoc, NameInfo.getName());
8055     } else {
8056       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8057                                            QualifierLoc, NameInfo);
8058     }
8059     D->setAccess(AS);
8060     CurContext->addDecl(D);
8061     return D;
8062   }
8063 
8064   auto Build = [&](bool Invalid) {
8065     UsingDecl *UD =
8066         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8067                           HasTypenameKeyword);
8068     UD->setAccess(AS);
8069     CurContext->addDecl(UD);
8070     UD->setInvalidDecl(Invalid);
8071     return UD;
8072   };
8073   auto BuildInvalid = [&]{ return Build(true); };
8074   auto BuildValid = [&]{ return Build(false); };
8075 
8076   if (RequireCompleteDeclContext(SS, LookupContext))
8077     return BuildInvalid();
8078 
8079   // The normal rules do not apply to inheriting constructor declarations.
8080   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
8081     UsingDecl *UD = BuildValid();
8082     CheckInheritingConstructorUsingDecl(UD);
8083     return UD;
8084   }
8085 
8086   // Otherwise, look up the target name.
8087 
8088   LookupResult R(*this, NameInfo, LookupOrdinaryName);
8089 
8090   // Unlike most lookups, we don't always want to hide tag
8091   // declarations: tag names are visible through the using declaration
8092   // even if hidden by ordinary names, *except* in a dependent context
8093   // where it's important for the sanity of two-phase lookup.
8094   if (!IsInstantiation)
8095     R.setHideTags(false);
8096 
8097   // For the purposes of this lookup, we have a base object type
8098   // equal to that of the current context.
8099   if (CurContext->isRecord()) {
8100     R.setBaseObjectType(
8101                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8102   }
8103 
8104   LookupQualifiedName(R, LookupContext);
8105 
8106   // Try to correct typos if possible.
8107   if (R.empty()) {
8108     if (TypoCorrection Corrected = CorrectTypo(
8109             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8110             llvm::make_unique<UsingValidatorCCC>(
8111                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8112                 dyn_cast<CXXRecordDecl>(CurContext)),
8113             CTK_ErrorRecovery)) {
8114       // We reject any correction for which ND would be NULL.
8115       NamedDecl *ND = Corrected.getCorrectionDecl();
8116 
8117       // We reject candidates where DroppedSpecifier == true, hence the
8118       // literal '0' below.
8119       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8120                                 << NameInfo.getName() << LookupContext << 0
8121                                 << SS.getRange());
8122 
8123       // If we corrected to an inheriting constructor, handle it as one.
8124       auto *RD = dyn_cast<CXXRecordDecl>(ND);
8125       if (RD && RD->isInjectedClassName()) {
8126         // Fix up the information we'll use to build the using declaration.
8127         if (Corrected.WillReplaceSpecifier()) {
8128           NestedNameSpecifierLocBuilder Builder;
8129           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8130                               QualifierLoc.getSourceRange());
8131           QualifierLoc = Builder.getWithLocInContext(Context);
8132         }
8133 
8134         NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8135             Context.getCanonicalType(Context.getRecordType(RD))));
8136         NameInfo.setNamedTypeInfo(nullptr);
8137 
8138         // Build it and process it as an inheriting constructor.
8139         UsingDecl *UD = BuildValid();
8140         CheckInheritingConstructorUsingDecl(UD);
8141         return UD;
8142       }
8143 
8144       // FIXME: Pick up all the declarations if we found an overloaded function.
8145       R.setLookupName(Corrected.getCorrection());
8146       R.addDecl(ND);
8147     } else {
8148       Diag(IdentLoc, diag::err_no_member)
8149         << NameInfo.getName() << LookupContext << SS.getRange();
8150       return BuildInvalid();
8151     }
8152   }
8153 
8154   if (R.isAmbiguous())
8155     return BuildInvalid();
8156 
8157   if (HasTypenameKeyword) {
8158     // If we asked for a typename and got a non-type decl, error out.
8159     if (!R.getAsSingle<TypeDecl>()) {
8160       Diag(IdentLoc, diag::err_using_typename_non_type);
8161       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8162         Diag((*I)->getUnderlyingDecl()->getLocation(),
8163              diag::note_using_decl_target);
8164       return BuildInvalid();
8165     }
8166   } else {
8167     // If we asked for a non-typename and we got a type, error out,
8168     // but only if this is an instantiation of an unresolved using
8169     // decl.  Otherwise just silently find the type name.
8170     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
8171       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8172       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
8173       return BuildInvalid();
8174     }
8175   }
8176 
8177   // C++0x N2914 [namespace.udecl]p6:
8178   // A using-declaration shall not name a namespace.
8179   if (R.getAsSingle<NamespaceDecl>()) {
8180     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8181       << SS.getRange();
8182     return BuildInvalid();
8183   }
8184 
8185   UsingDecl *UD = BuildValid();
8186   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8187     UsingShadowDecl *PrevDecl = nullptr;
8188     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8189       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
8190   }
8191 
8192   return UD;
8193 }
8194 
8195 /// Additional checks for a using declaration referring to a constructor name.
8196 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
8197   assert(!UD->hasTypename() && "expecting a constructor name");
8198 
8199   const Type *SourceType = UD->getQualifier()->getAsType();
8200   assert(SourceType &&
8201          "Using decl naming constructor doesn't have type in scope spec.");
8202   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8203 
8204   // Check whether the named type is a direct base class.
8205   bool AnyDependentBases = false;
8206   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8207                                       AnyDependentBases);
8208   if (!Base && !AnyDependentBases) {
8209     Diag(UD->getUsingLoc(),
8210          diag::err_using_decl_constructor_not_in_direct_base)
8211       << UD->getNameInfo().getSourceRange()
8212       << QualType(SourceType, 0) << TargetClass;
8213     UD->setInvalidDecl();
8214     return true;
8215   }
8216 
8217   if (Base)
8218     Base->setInheritConstructors();
8219 
8220   return false;
8221 }
8222 
8223 /// Checks that the given using declaration is not an invalid
8224 /// redeclaration.  Note that this is checking only for the using decl
8225 /// itself, not for any ill-formedness among the UsingShadowDecls.
8226 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
8227                                        bool HasTypenameKeyword,
8228                                        const CXXScopeSpec &SS,
8229                                        SourceLocation NameLoc,
8230                                        const LookupResult &Prev) {
8231   // C++03 [namespace.udecl]p8:
8232   // C++0x [namespace.udecl]p10:
8233   //   A using-declaration is a declaration and can therefore be used
8234   //   repeatedly where (and only where) multiple declarations are
8235   //   allowed.
8236   //
8237   // That's in non-member contexts.
8238   if (!CurContext->getRedeclContext()->isRecord())
8239     return false;
8240 
8241   NestedNameSpecifier *Qual = SS.getScopeRep();
8242 
8243   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8244     NamedDecl *D = *I;
8245 
8246     bool DTypename;
8247     NestedNameSpecifier *DQual;
8248     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
8249       DTypename = UD->hasTypename();
8250       DQual = UD->getQualifier();
8251     } else if (UnresolvedUsingValueDecl *UD
8252                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8253       DTypename = false;
8254       DQual = UD->getQualifier();
8255     } else if (UnresolvedUsingTypenameDecl *UD
8256                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8257       DTypename = true;
8258       DQual = UD->getQualifier();
8259     } else continue;
8260 
8261     // using decls differ if one says 'typename' and the other doesn't.
8262     // FIXME: non-dependent using decls?
8263     if (HasTypenameKeyword != DTypename) continue;
8264 
8265     // using decls differ if they name different scopes (but note that
8266     // template instantiation can cause this check to trigger when it
8267     // didn't before instantiation).
8268     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8269         Context.getCanonicalNestedNameSpecifier(DQual))
8270       continue;
8271 
8272     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
8273     Diag(D->getLocation(), diag::note_using_decl) << 1;
8274     return true;
8275   }
8276 
8277   return false;
8278 }
8279 
8280 
8281 /// Checks that the given nested-name qualifier used in a using decl
8282 /// in the current context is appropriately related to the current
8283 /// scope.  If an error is found, diagnoses it and returns true.
8284 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8285                                    const CXXScopeSpec &SS,
8286                                    const DeclarationNameInfo &NameInfo,
8287                                    SourceLocation NameLoc) {
8288   DeclContext *NamedContext = computeDeclContext(SS);
8289 
8290   if (!CurContext->isRecord()) {
8291     // C++03 [namespace.udecl]p3:
8292     // C++0x [namespace.udecl]p8:
8293     //   A using-declaration for a class member shall be a member-declaration.
8294 
8295     // If we weren't able to compute a valid scope, it must be a
8296     // dependent class scope.
8297     if (!NamedContext || NamedContext->isRecord()) {
8298       auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
8299       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
8300         RD = nullptr;
8301 
8302       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8303         << SS.getRange();
8304 
8305       // If we have a complete, non-dependent source type, try to suggest a
8306       // way to get the same effect.
8307       if (!RD)
8308         return true;
8309 
8310       // Find what this using-declaration was referring to.
8311       LookupResult R(*this, NameInfo, LookupOrdinaryName);
8312       R.setHideTags(false);
8313       R.suppressDiagnostics();
8314       LookupQualifiedName(R, RD);
8315 
8316       if (R.getAsSingle<TypeDecl>()) {
8317         if (getLangOpts().CPlusPlus11) {
8318           // Convert 'using X::Y;' to 'using Y = X::Y;'.
8319           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8320             << 0 // alias declaration
8321             << FixItHint::CreateInsertion(SS.getBeginLoc(),
8322                                           NameInfo.getName().getAsString() +
8323                                               " = ");
8324         } else {
8325           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8326           SourceLocation InsertLoc =
8327               PP.getLocForEndOfToken(NameInfo.getLocEnd());
8328           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8329             << 1 // typedef declaration
8330             << FixItHint::CreateReplacement(UsingLoc, "typedef")
8331             << FixItHint::CreateInsertion(
8332                    InsertLoc, " " + NameInfo.getName().getAsString());
8333         }
8334       } else if (R.getAsSingle<VarDecl>()) {
8335         // Don't provide a fixit outside C++11 mode; we don't want to suggest
8336         // repeating the type of the static data member here.
8337         FixItHint FixIt;
8338         if (getLangOpts().CPlusPlus11) {
8339           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8340           FixIt = FixItHint::CreateReplacement(
8341               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8342         }
8343 
8344         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8345           << 2 // reference declaration
8346           << FixIt;
8347       }
8348       return true;
8349     }
8350 
8351     // Otherwise, everything is known to be fine.
8352     return false;
8353   }
8354 
8355   // The current scope is a record.
8356 
8357   // If the named context is dependent, we can't decide much.
8358   if (!NamedContext) {
8359     // FIXME: in C++0x, we can diagnose if we can prove that the
8360     // nested-name-specifier does not refer to a base class, which is
8361     // still possible in some cases.
8362 
8363     // Otherwise we have to conservatively report that things might be
8364     // okay.
8365     return false;
8366   }
8367 
8368   if (!NamedContext->isRecord()) {
8369     // Ideally this would point at the last name in the specifier,
8370     // but we don't have that level of source info.
8371     Diag(SS.getRange().getBegin(),
8372          diag::err_using_decl_nested_name_specifier_is_not_class)
8373       << SS.getScopeRep() << SS.getRange();
8374     return true;
8375   }
8376 
8377   if (!NamedContext->isDependentContext() &&
8378       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8379     return true;
8380 
8381   if (getLangOpts().CPlusPlus11) {
8382     // C++0x [namespace.udecl]p3:
8383     //   In a using-declaration used as a member-declaration, the
8384     //   nested-name-specifier shall name a base class of the class
8385     //   being defined.
8386 
8387     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8388                                  cast<CXXRecordDecl>(NamedContext))) {
8389       if (CurContext == NamedContext) {
8390         Diag(NameLoc,
8391              diag::err_using_decl_nested_name_specifier_is_current_class)
8392           << SS.getRange();
8393         return true;
8394       }
8395 
8396       Diag(SS.getRange().getBegin(),
8397            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8398         << SS.getScopeRep()
8399         << cast<CXXRecordDecl>(CurContext)
8400         << SS.getRange();
8401       return true;
8402     }
8403 
8404     return false;
8405   }
8406 
8407   // C++03 [namespace.udecl]p4:
8408   //   A using-declaration used as a member-declaration shall refer
8409   //   to a member of a base class of the class being defined [etc.].
8410 
8411   // Salient point: SS doesn't have to name a base class as long as
8412   // lookup only finds members from base classes.  Therefore we can
8413   // diagnose here only if we can prove that that can't happen,
8414   // i.e. if the class hierarchies provably don't intersect.
8415 
8416   // TODO: it would be nice if "definitely valid" results were cached
8417   // in the UsingDecl and UsingShadowDecl so that these checks didn't
8418   // need to be repeated.
8419 
8420   struct UserData {
8421     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
8422 
8423     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8424       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8425       Data->Bases.insert(Base);
8426       return true;
8427     }
8428 
8429     bool hasDependentBases(const CXXRecordDecl *Class) {
8430       return !Class->forallBases(collect, this);
8431     }
8432 
8433     /// Returns true if the base is dependent or is one of the
8434     /// accumulated base classes.
8435     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8436       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8437       return !Data->Bases.count(Base);
8438     }
8439 
8440     bool mightShareBases(const CXXRecordDecl *Class) {
8441       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8442     }
8443   };
8444 
8445   UserData Data;
8446 
8447   // Returns false if we find a dependent base.
8448   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8449     return false;
8450 
8451   // Returns false if the class has a dependent base or if it or one
8452   // of its bases is present in the base set of the current context.
8453   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8454     return false;
8455 
8456   Diag(SS.getRange().getBegin(),
8457        diag::err_using_decl_nested_name_specifier_is_not_base_class)
8458     << SS.getScopeRep()
8459     << cast<CXXRecordDecl>(CurContext)
8460     << SS.getRange();
8461 
8462   return true;
8463 }
8464 
8465 Decl *Sema::ActOnAliasDeclaration(Scope *S,
8466                                   AccessSpecifier AS,
8467                                   MultiTemplateParamsArg TemplateParamLists,
8468                                   SourceLocation UsingLoc,
8469                                   UnqualifiedId &Name,
8470                                   AttributeList *AttrList,
8471                                   TypeResult Type) {
8472   // Skip up to the relevant declaration scope.
8473   while (S->getFlags() & Scope::TemplateParamScope)
8474     S = S->getParent();
8475   assert((S->getFlags() & Scope::DeclScope) &&
8476          "got alias-declaration outside of declaration scope");
8477 
8478   if (Type.isInvalid())
8479     return nullptr;
8480 
8481   bool Invalid = false;
8482   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8483   TypeSourceInfo *TInfo = nullptr;
8484   GetTypeFromParser(Type.get(), &TInfo);
8485 
8486   if (DiagnoseClassNameShadow(CurContext, NameInfo))
8487     return nullptr;
8488 
8489   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8490                                       UPPC_DeclarationType)) {
8491     Invalid = true;
8492     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8493                                              TInfo->getTypeLoc().getBeginLoc());
8494   }
8495 
8496   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8497   LookupName(Previous, S);
8498 
8499   // Warn about shadowing the name of a template parameter.
8500   if (Previous.isSingleResult() &&
8501       Previous.getFoundDecl()->isTemplateParameter()) {
8502     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8503     Previous.clear();
8504   }
8505 
8506   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8507          "name in alias declaration must be an identifier");
8508   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8509                                                Name.StartLocation,
8510                                                Name.Identifier, TInfo);
8511 
8512   NewTD->setAccess(AS);
8513 
8514   if (Invalid)
8515     NewTD->setInvalidDecl();
8516 
8517   ProcessDeclAttributeList(S, NewTD, AttrList);
8518 
8519   CheckTypedefForVariablyModifiedType(S, NewTD);
8520   Invalid |= NewTD->isInvalidDecl();
8521 
8522   bool Redeclaration = false;
8523 
8524   NamedDecl *NewND;
8525   if (TemplateParamLists.size()) {
8526     TypeAliasTemplateDecl *OldDecl = nullptr;
8527     TemplateParameterList *OldTemplateParams = nullptr;
8528 
8529     if (TemplateParamLists.size() != 1) {
8530       Diag(UsingLoc, diag::err_alias_template_extra_headers)
8531         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8532          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8533     }
8534     TemplateParameterList *TemplateParams = TemplateParamLists[0];
8535 
8536     // Only consider previous declarations in the same scope.
8537     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8538                          /*ExplicitInstantiationOrSpecialization*/false);
8539     if (!Previous.empty()) {
8540       Redeclaration = true;
8541 
8542       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8543       if (!OldDecl && !Invalid) {
8544         Diag(UsingLoc, diag::err_redefinition_different_kind)
8545           << Name.Identifier;
8546 
8547         NamedDecl *OldD = Previous.getRepresentativeDecl();
8548         if (OldD->getLocation().isValid())
8549           Diag(OldD->getLocation(), diag::note_previous_definition);
8550 
8551         Invalid = true;
8552       }
8553 
8554       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8555         if (TemplateParameterListsAreEqual(TemplateParams,
8556                                            OldDecl->getTemplateParameters(),
8557                                            /*Complain=*/true,
8558                                            TPL_TemplateMatch))
8559           OldTemplateParams = OldDecl->getTemplateParameters();
8560         else
8561           Invalid = true;
8562 
8563         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8564         if (!Invalid &&
8565             !Context.hasSameType(OldTD->getUnderlyingType(),
8566                                  NewTD->getUnderlyingType())) {
8567           // FIXME: The C++0x standard does not clearly say this is ill-formed,
8568           // but we can't reasonably accept it.
8569           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8570             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8571           if (OldTD->getLocation().isValid())
8572             Diag(OldTD->getLocation(), diag::note_previous_definition);
8573           Invalid = true;
8574         }
8575       }
8576     }
8577 
8578     // Merge any previous default template arguments into our parameters,
8579     // and check the parameter list.
8580     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8581                                    TPC_TypeAliasTemplate))
8582       return nullptr;
8583 
8584     TypeAliasTemplateDecl *NewDecl =
8585       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8586                                     Name.Identifier, TemplateParams,
8587                                     NewTD);
8588     NewTD->setDescribedAliasTemplate(NewDecl);
8589 
8590     NewDecl->setAccess(AS);
8591 
8592     if (Invalid)
8593       NewDecl->setInvalidDecl();
8594     else if (OldDecl)
8595       NewDecl->setPreviousDecl(OldDecl);
8596 
8597     NewND = NewDecl;
8598   } else {
8599     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8600     NewND = NewTD;
8601   }
8602 
8603   if (!Redeclaration)
8604     PushOnScopeChains(NewND, S);
8605 
8606   ActOnDocumentableDecl(NewND);
8607   return NewND;
8608 }
8609 
8610 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8611                                    SourceLocation AliasLoc,
8612                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
8613                                    SourceLocation IdentLoc,
8614                                    IdentifierInfo *Ident) {
8615 
8616   // Lookup the namespace name.
8617   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8618   LookupParsedName(R, S, &SS);
8619 
8620   if (R.isAmbiguous())
8621     return nullptr;
8622 
8623   if (R.empty()) {
8624     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8625       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8626       return nullptr;
8627     }
8628   }
8629   assert(!R.isAmbiguous() && !R.empty());
8630 
8631   // Check if we have a previous declaration with the same name.
8632   NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8633                                          ForRedeclaration);
8634   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8635     PrevDecl = nullptr;
8636 
8637   NamedDecl *ND = R.getFoundDecl();
8638 
8639   if (PrevDecl) {
8640     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8641       // We already have an alias with the same name that points to the same
8642       // namespace; check that it matches.
8643       if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8644         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8645           << Alias;
8646         Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8647           << AD->getNamespace();
8648         return nullptr;
8649       }
8650     } else {
8651       unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8652                             ? diag::err_redefinition
8653                             : diag::err_redefinition_different_kind;
8654       Diag(AliasLoc, DiagID) << Alias;
8655       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8656       return nullptr;
8657     }
8658   }
8659 
8660   // The use of a nested name specifier may trigger deprecation warnings.
8661   DiagnoseUseOfDecl(ND, IdentLoc);
8662 
8663   NamespaceAliasDecl *AliasDecl =
8664     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8665                                Alias, SS.getWithLocInContext(Context),
8666                                IdentLoc, ND);
8667   if (PrevDecl)
8668     AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
8669 
8670   PushOnScopeChains(AliasDecl, S);
8671   return AliasDecl;
8672 }
8673 
8674 Sema::ImplicitExceptionSpecification
8675 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8676                                                CXXMethodDecl *MD) {
8677   CXXRecordDecl *ClassDecl = MD->getParent();
8678 
8679   // C++ [except.spec]p14:
8680   //   An implicitly declared special member function (Clause 12) shall have an
8681   //   exception-specification. [...]
8682   ImplicitExceptionSpecification ExceptSpec(*this);
8683   if (ClassDecl->isInvalidDecl())
8684     return ExceptSpec;
8685 
8686   // Direct base-class constructors.
8687   for (const auto &B : ClassDecl->bases()) {
8688     if (B.isVirtual()) // Handled below.
8689       continue;
8690 
8691     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8692       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8693       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8694       // If this is a deleted function, add it anyway. This might be conformant
8695       // with the standard. This might not. I'm not sure. It might not matter.
8696       if (Constructor)
8697         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8698     }
8699   }
8700 
8701   // Virtual base-class constructors.
8702   for (const auto &B : ClassDecl->vbases()) {
8703     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8704       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8705       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8706       // If this is a deleted function, add it anyway. This might be conformant
8707       // with the standard. This might not. I'm not sure. It might not matter.
8708       if (Constructor)
8709         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8710     }
8711   }
8712 
8713   // Field constructors.
8714   for (const auto *F : ClassDecl->fields()) {
8715     if (F->hasInClassInitializer()) {
8716       if (Expr *E = F->getInClassInitializer())
8717         ExceptSpec.CalledExpr(E);
8718     } else if (const RecordType *RecordTy
8719               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8720       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8721       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8722       // If this is a deleted function, add it anyway. This might be conformant
8723       // with the standard. This might not. I'm not sure. It might not matter.
8724       // In particular, the problem is that this function never gets called. It
8725       // might just be ill-formed because this function attempts to refer to
8726       // a deleted function here.
8727       if (Constructor)
8728         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8729     }
8730   }
8731 
8732   return ExceptSpec;
8733 }
8734 
8735 Sema::ImplicitExceptionSpecification
8736 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8737   CXXRecordDecl *ClassDecl = CD->getParent();
8738 
8739   // C++ [except.spec]p14:
8740   //   An inheriting constructor [...] shall have an exception-specification. [...]
8741   ImplicitExceptionSpecification ExceptSpec(*this);
8742   if (ClassDecl->isInvalidDecl())
8743     return ExceptSpec;
8744 
8745   // Inherited constructor.
8746   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8747   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8748   // FIXME: Copying or moving the parameters could add extra exceptions to the
8749   // set, as could the default arguments for the inherited constructor. This
8750   // will be addressed when we implement the resolution of core issue 1351.
8751   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8752 
8753   // Direct base-class constructors.
8754   for (const auto &B : ClassDecl->bases()) {
8755     if (B.isVirtual()) // Handled below.
8756       continue;
8757 
8758     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8759       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8760       if (BaseClassDecl == InheritedDecl)
8761         continue;
8762       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8763       if (Constructor)
8764         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8765     }
8766   }
8767 
8768   // Virtual base-class constructors.
8769   for (const auto &B : ClassDecl->vbases()) {
8770     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8771       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8772       if (BaseClassDecl == InheritedDecl)
8773         continue;
8774       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8775       if (Constructor)
8776         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8777     }
8778   }
8779 
8780   // Field constructors.
8781   for (const auto *F : ClassDecl->fields()) {
8782     if (F->hasInClassInitializer()) {
8783       if (Expr *E = F->getInClassInitializer())
8784         ExceptSpec.CalledExpr(E);
8785     } else if (const RecordType *RecordTy
8786               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8787       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8788       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8789       if (Constructor)
8790         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8791     }
8792   }
8793 
8794   return ExceptSpec;
8795 }
8796 
8797 namespace {
8798 /// RAII object to register a special member as being currently declared.
8799 struct DeclaringSpecialMember {
8800   Sema &S;
8801   Sema::SpecialMemberDecl D;
8802   bool WasAlreadyBeingDeclared;
8803 
8804   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8805     : S(S), D(RD, CSM) {
8806     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
8807     if (WasAlreadyBeingDeclared)
8808       // This almost never happens, but if it does, ensure that our cache
8809       // doesn't contain a stale result.
8810       S.SpecialMemberCache.clear();
8811 
8812     // FIXME: Register a note to be produced if we encounter an error while
8813     // declaring the special member.
8814   }
8815   ~DeclaringSpecialMember() {
8816     if (!WasAlreadyBeingDeclared)
8817       S.SpecialMembersBeingDeclared.erase(D);
8818   }
8819 
8820   /// \brief Are we already trying to declare this special member?
8821   bool isAlreadyBeingDeclared() const {
8822     return WasAlreadyBeingDeclared;
8823   }
8824 };
8825 }
8826 
8827 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8828                                                      CXXRecordDecl *ClassDecl) {
8829   // C++ [class.ctor]p5:
8830   //   A default constructor for a class X is a constructor of class X
8831   //   that can be called without an argument. If there is no
8832   //   user-declared constructor for class X, a default constructor is
8833   //   implicitly declared. An implicitly-declared default constructor
8834   //   is an inline public member of its class.
8835   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8836          "Should not build implicit default constructor!");
8837 
8838   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8839   if (DSM.isAlreadyBeingDeclared())
8840     return nullptr;
8841 
8842   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8843                                                      CXXDefaultConstructor,
8844                                                      false);
8845 
8846   // Create the actual constructor declaration.
8847   CanQualType ClassType
8848     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8849   SourceLocation ClassLoc = ClassDecl->getLocation();
8850   DeclarationName Name
8851     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8852   DeclarationNameInfo NameInfo(Name, ClassLoc);
8853   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8854       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8855       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8856       /*isImplicitlyDeclared=*/true, Constexpr);
8857   DefaultCon->setAccess(AS_public);
8858   DefaultCon->setDefaulted();
8859 
8860   if (getLangOpts().CUDA) {
8861     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8862                                             DefaultCon,
8863                                             /* ConstRHS */ false,
8864                                             /* Diagnose */ false);
8865   }
8866 
8867   // Build an exception specification pointing back at this constructor.
8868   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8869   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8870 
8871   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8872   // constructors is easy to compute.
8873   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8874 
8875   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8876     SetDeclDeleted(DefaultCon, ClassLoc);
8877 
8878   // Note that we have declared this constructor.
8879   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8880 
8881   if (Scope *S = getScopeForContext(ClassDecl))
8882     PushOnScopeChains(DefaultCon, S, false);
8883   ClassDecl->addDecl(DefaultCon);
8884 
8885   return DefaultCon;
8886 }
8887 
8888 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8889                                             CXXConstructorDecl *Constructor) {
8890   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8891           !Constructor->doesThisDeclarationHaveABody() &&
8892           !Constructor->isDeleted()) &&
8893     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8894 
8895   CXXRecordDecl *ClassDecl = Constructor->getParent();
8896   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8897 
8898   SynthesizedFunctionScope Scope(*this, Constructor);
8899   DiagnosticErrorTrap Trap(Diags);
8900   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8901       Trap.hasErrorOccurred()) {
8902     Diag(CurrentLocation, diag::note_member_synthesized_at)
8903       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8904     Constructor->setInvalidDecl();
8905     return;
8906   }
8907 
8908   // The exception specification is needed because we are defining the
8909   // function.
8910   ResolveExceptionSpec(CurrentLocation,
8911                        Constructor->getType()->castAs<FunctionProtoType>());
8912 
8913   SourceLocation Loc = Constructor->getLocEnd().isValid()
8914                            ? Constructor->getLocEnd()
8915                            : Constructor->getLocation();
8916   Constructor->setBody(new (Context) CompoundStmt(Loc));
8917 
8918   Constructor->markUsed(Context);
8919   MarkVTableUsed(CurrentLocation, ClassDecl);
8920 
8921   if (ASTMutationListener *L = getASTMutationListener()) {
8922     L->CompletedImplicitDefinition(Constructor);
8923   }
8924 
8925   DiagnoseUninitializedFields(*this, Constructor);
8926 }
8927 
8928 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8929   // Perform any delayed checks on exception specifications.
8930   CheckDelayedMemberExceptionSpecs();
8931 }
8932 
8933 namespace {
8934 /// Information on inheriting constructors to declare.
8935 class InheritingConstructorInfo {
8936 public:
8937   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8938       : SemaRef(SemaRef), Derived(Derived) {
8939     // Mark the constructors that we already have in the derived class.
8940     //
8941     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8942     //   unless there is a user-declared constructor with the same signature in
8943     //   the class where the using-declaration appears.
8944     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8945   }
8946 
8947   void inheritAll(CXXRecordDecl *RD) {
8948     visitAll(RD, &InheritingConstructorInfo::inherit);
8949   }
8950 
8951 private:
8952   /// Information about an inheriting constructor.
8953   struct InheritingConstructor {
8954     InheritingConstructor()
8955       : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
8956 
8957     /// If \c true, a constructor with this signature is already declared
8958     /// in the derived class.
8959     bool DeclaredInDerived;
8960 
8961     /// The constructor which is inherited.
8962     const CXXConstructorDecl *BaseCtor;
8963 
8964     /// The derived constructor we declared.
8965     CXXConstructorDecl *DerivedCtor;
8966   };
8967 
8968   /// Inheriting constructors with a given canonical type. There can be at
8969   /// most one such non-template constructor, and any number of templated
8970   /// constructors.
8971   struct InheritingConstructorsForType {
8972     InheritingConstructor NonTemplate;
8973     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8974         Templates;
8975 
8976     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8977       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8978         TemplateParameterList *ParamList = FTD->getTemplateParameters();
8979         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8980           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8981                                                false, S.TPL_TemplateMatch))
8982             return Templates[I].second;
8983         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8984         return Templates.back().second;
8985       }
8986 
8987       return NonTemplate;
8988     }
8989   };
8990 
8991   /// Get or create the inheriting constructor record for a constructor.
8992   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8993                                   QualType CtorType) {
8994     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8995         .getEntry(SemaRef, Ctor);
8996   }
8997 
8998   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8999 
9000   /// Process all constructors for a class.
9001   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
9002     for (const auto *Ctor : RD->ctors())
9003       (this->*Callback)(Ctor);
9004     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9005              I(RD->decls_begin()), E(RD->decls_end());
9006          I != E; ++I) {
9007       const FunctionDecl *FD = (*I)->getTemplatedDecl();
9008       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9009         (this->*Callback)(CD);
9010     }
9011   }
9012 
9013   /// Note that a constructor (or constructor template) was declared in Derived.
9014   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9015     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9016   }
9017 
9018   /// Inherit a single constructor.
9019   void inherit(const CXXConstructorDecl *Ctor) {
9020     const FunctionProtoType *CtorType =
9021         Ctor->getType()->castAs<FunctionProtoType>();
9022     ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
9023     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9024 
9025     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9026 
9027     // Core issue (no number yet): the ellipsis is always discarded.
9028     if (EPI.Variadic) {
9029       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9030       SemaRef.Diag(Ctor->getLocation(),
9031                    diag::note_using_decl_constructor_ellipsis);
9032       EPI.Variadic = false;
9033     }
9034 
9035     // Declare a constructor for each number of parameters.
9036     //
9037     // C++11 [class.inhctor]p1:
9038     //   The candidate set of inherited constructors from the class X named in
9039     //   the using-declaration consists of [... modulo defects ...] for each
9040     //   constructor or constructor template of X, the set of constructors or
9041     //   constructor templates that results from omitting any ellipsis parameter
9042     //   specification and successively omitting parameters with a default
9043     //   argument from the end of the parameter-type-list
9044     unsigned MinParams = minParamsToInherit(Ctor);
9045     unsigned Params = Ctor->getNumParams();
9046     if (Params >= MinParams) {
9047       do
9048         declareCtor(UsingLoc, Ctor,
9049                     SemaRef.Context.getFunctionType(
9050                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
9051       while (Params > MinParams &&
9052              Ctor->getParamDecl(--Params)->hasDefaultArg());
9053     }
9054   }
9055 
9056   /// Find the using-declaration which specified that we should inherit the
9057   /// constructors of \p Base.
9058   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9059     // No fancy lookup required; just look for the base constructor name
9060     // directly within the derived class.
9061     ASTContext &Context = SemaRef.Context;
9062     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9063         Context.getCanonicalType(Context.getRecordType(Base)));
9064     DeclContext::lookup_const_result Decls = Derived->lookup(Name);
9065     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9066   }
9067 
9068   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9069     // C++11 [class.inhctor]p3:
9070     //   [F]or each constructor template in the candidate set of inherited
9071     //   constructors, a constructor template is implicitly declared
9072     if (Ctor->getDescribedFunctionTemplate())
9073       return 0;
9074 
9075     //   For each non-template constructor in the candidate set of inherited
9076     //   constructors other than a constructor having no parameters or a
9077     //   copy/move constructor having a single parameter, a constructor is
9078     //   implicitly declared [...]
9079     if (Ctor->getNumParams() == 0)
9080       return 1;
9081     if (Ctor->isCopyOrMoveConstructor())
9082       return 2;
9083 
9084     // Per discussion on core reflector, never inherit a constructor which
9085     // would become a default, copy, or move constructor of Derived either.
9086     const ParmVarDecl *PD = Ctor->getParamDecl(0);
9087     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9088     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9089   }
9090 
9091   /// Declare a single inheriting constructor, inheriting the specified
9092   /// constructor, with the given type.
9093   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9094                    QualType DerivedType) {
9095     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9096 
9097     // C++11 [class.inhctor]p3:
9098     //   ... a constructor is implicitly declared with the same constructor
9099     //   characteristics unless there is a user-declared constructor with
9100     //   the same signature in the class where the using-declaration appears
9101     if (Entry.DeclaredInDerived)
9102       return;
9103 
9104     // C++11 [class.inhctor]p7:
9105     //   If two using-declarations declare inheriting constructors with the
9106     //   same signature, the program is ill-formed
9107     if (Entry.DerivedCtor) {
9108       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9109         // Only diagnose this once per constructor.
9110         if (Entry.DerivedCtor->isInvalidDecl())
9111           return;
9112         Entry.DerivedCtor->setInvalidDecl();
9113 
9114         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9115         SemaRef.Diag(BaseCtor->getLocation(),
9116                      diag::note_using_decl_constructor_conflict_current_ctor);
9117         SemaRef.Diag(Entry.BaseCtor->getLocation(),
9118                      diag::note_using_decl_constructor_conflict_previous_ctor);
9119         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9120                      diag::note_using_decl_constructor_conflict_previous_using);
9121       } else {
9122         // Core issue (no number): if the same inheriting constructor is
9123         // produced by multiple base class constructors from the same base
9124         // class, the inheriting constructor is defined as deleted.
9125         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9126       }
9127 
9128       return;
9129     }
9130 
9131     ASTContext &Context = SemaRef.Context;
9132     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9133         Context.getCanonicalType(Context.getRecordType(Derived)));
9134     DeclarationNameInfo NameInfo(Name, UsingLoc);
9135 
9136     TemplateParameterList *TemplateParams = nullptr;
9137     if (const FunctionTemplateDecl *FTD =
9138             BaseCtor->getDescribedFunctionTemplate()) {
9139       TemplateParams = FTD->getTemplateParameters();
9140       // We're reusing template parameters from a different DeclContext. This
9141       // is questionable at best, but works out because the template depth in
9142       // both places is guaranteed to be 0.
9143       // FIXME: Rebuild the template parameters in the new context, and
9144       // transform the function type to refer to them.
9145     }
9146 
9147     // Build type source info pointing at the using-declaration. This is
9148     // required by template instantiation.
9149     TypeSourceInfo *TInfo =
9150         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9151     FunctionProtoTypeLoc ProtoLoc =
9152         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9153 
9154     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9155         Context, Derived, UsingLoc, NameInfo, DerivedType,
9156         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9157         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9158 
9159     // Build an unevaluated exception specification for this constructor.
9160     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9161     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9162     EPI.ExceptionSpec.Type = EST_Unevaluated;
9163     EPI.ExceptionSpec.SourceDecl = DerivedCtor;
9164     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
9165                                                  FPT->getParamTypes(), EPI));
9166 
9167     // Build the parameter declarations.
9168     SmallVector<ParmVarDecl *, 16> ParamDecls;
9169     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
9170       TypeSourceInfo *TInfo =
9171           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
9172       ParmVarDecl *PD = ParmVarDecl::Create(
9173           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9174           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
9175       PD->setScopeInfo(0, I);
9176       PD->setImplicit();
9177       ParamDecls.push_back(PD);
9178       ProtoLoc.setParam(I, PD);
9179     }
9180 
9181     // Set up the new constructor.
9182     DerivedCtor->setAccess(BaseCtor->getAccess());
9183     DerivedCtor->setParams(ParamDecls);
9184     DerivedCtor->setInheritedConstructor(BaseCtor);
9185     if (BaseCtor->isDeleted())
9186       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9187 
9188     // If this is a constructor template, build the template declaration.
9189     if (TemplateParams) {
9190       FunctionTemplateDecl *DerivedTemplate =
9191           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9192                                        TemplateParams, DerivedCtor);
9193       DerivedTemplate->setAccess(BaseCtor->getAccess());
9194       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9195       Derived->addDecl(DerivedTemplate);
9196     } else {
9197       Derived->addDecl(DerivedCtor);
9198     }
9199 
9200     Entry.BaseCtor = BaseCtor;
9201     Entry.DerivedCtor = DerivedCtor;
9202   }
9203 
9204   Sema &SemaRef;
9205   CXXRecordDecl *Derived;
9206   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9207   MapType Map;
9208 };
9209 }
9210 
9211 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9212   // Defer declaring the inheriting constructors until the class is
9213   // instantiated.
9214   if (ClassDecl->isDependentContext())
9215     return;
9216 
9217   // Find base classes from which we might inherit constructors.
9218   SmallVector<CXXRecordDecl*, 4> InheritedBases;
9219   for (const auto &BaseIt : ClassDecl->bases())
9220     if (BaseIt.getInheritConstructors())
9221       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
9222 
9223   // Go no further if we're not inheriting any constructors.
9224   if (InheritedBases.empty())
9225     return;
9226 
9227   // Declare the inherited constructors.
9228   InheritingConstructorInfo ICI(*this, ClassDecl);
9229   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9230     ICI.inheritAll(InheritedBases[I]);
9231 }
9232 
9233 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9234                                        CXXConstructorDecl *Constructor) {
9235   CXXRecordDecl *ClassDecl = Constructor->getParent();
9236   assert(Constructor->getInheritedConstructor() &&
9237          !Constructor->doesThisDeclarationHaveABody() &&
9238          !Constructor->isDeleted());
9239 
9240   SynthesizedFunctionScope Scope(*this, Constructor);
9241   DiagnosticErrorTrap Trap(Diags);
9242   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9243       Trap.hasErrorOccurred()) {
9244     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9245       << Context.getTagDeclType(ClassDecl);
9246     Constructor->setInvalidDecl();
9247     return;
9248   }
9249 
9250   SourceLocation Loc = Constructor->getLocation();
9251   Constructor->setBody(new (Context) CompoundStmt(Loc));
9252 
9253   Constructor->markUsed(Context);
9254   MarkVTableUsed(CurrentLocation, ClassDecl);
9255 
9256   if (ASTMutationListener *L = getASTMutationListener()) {
9257     L->CompletedImplicitDefinition(Constructor);
9258   }
9259 }
9260 
9261 
9262 Sema::ImplicitExceptionSpecification
9263 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9264   CXXRecordDecl *ClassDecl = MD->getParent();
9265 
9266   // C++ [except.spec]p14:
9267   //   An implicitly declared special member function (Clause 12) shall have
9268   //   an exception-specification.
9269   ImplicitExceptionSpecification ExceptSpec(*this);
9270   if (ClassDecl->isInvalidDecl())
9271     return ExceptSpec;
9272 
9273   // Direct base-class destructors.
9274   for (const auto &B : ClassDecl->bases()) {
9275     if (B.isVirtual()) // Handled below.
9276       continue;
9277 
9278     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9279       ExceptSpec.CalledDecl(B.getLocStart(),
9280                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9281   }
9282 
9283   // Virtual base-class destructors.
9284   for (const auto &B : ClassDecl->vbases()) {
9285     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9286       ExceptSpec.CalledDecl(B.getLocStart(),
9287                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9288   }
9289 
9290   // Field destructors.
9291   for (const auto *F : ClassDecl->fields()) {
9292     if (const RecordType *RecordTy
9293         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
9294       ExceptSpec.CalledDecl(F->getLocation(),
9295                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
9296   }
9297 
9298   return ExceptSpec;
9299 }
9300 
9301 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9302   // C++ [class.dtor]p2:
9303   //   If a class has no user-declared destructor, a destructor is
9304   //   declared implicitly. An implicitly-declared destructor is an
9305   //   inline public member of its class.
9306   assert(ClassDecl->needsImplicitDestructor());
9307 
9308   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9309   if (DSM.isAlreadyBeingDeclared())
9310     return nullptr;
9311 
9312   // Create the actual destructor declaration.
9313   CanQualType ClassType
9314     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9315   SourceLocation ClassLoc = ClassDecl->getLocation();
9316   DeclarationName Name
9317     = Context.DeclarationNames.getCXXDestructorName(ClassType);
9318   DeclarationNameInfo NameInfo(Name, ClassLoc);
9319   CXXDestructorDecl *Destructor
9320       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
9321                                   QualType(), nullptr, /*isInline=*/true,
9322                                   /*isImplicitlyDeclared=*/true);
9323   Destructor->setAccess(AS_public);
9324   Destructor->setDefaulted();
9325 
9326   if (getLangOpts().CUDA) {
9327     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9328                                             Destructor,
9329                                             /* ConstRHS */ false,
9330                                             /* Diagnose */ false);
9331   }
9332 
9333   // Build an exception specification pointing back at this destructor.
9334   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
9335   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9336 
9337   AddOverriddenMethods(ClassDecl, Destructor);
9338 
9339   // We don't need to use SpecialMemberIsTrivial here; triviality for
9340   // destructors is easy to compute.
9341   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9342 
9343   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
9344     SetDeclDeleted(Destructor, ClassLoc);
9345 
9346   // Note that we have declared this destructor.
9347   ++ASTContext::NumImplicitDestructorsDeclared;
9348 
9349   // Introduce this destructor into its scope.
9350   if (Scope *S = getScopeForContext(ClassDecl))
9351     PushOnScopeChains(Destructor, S, false);
9352   ClassDecl->addDecl(Destructor);
9353 
9354   return Destructor;
9355 }
9356 
9357 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
9358                                     CXXDestructorDecl *Destructor) {
9359   assert((Destructor->isDefaulted() &&
9360           !Destructor->doesThisDeclarationHaveABody() &&
9361           !Destructor->isDeleted()) &&
9362          "DefineImplicitDestructor - call it for implicit default dtor");
9363   CXXRecordDecl *ClassDecl = Destructor->getParent();
9364   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
9365 
9366   if (Destructor->isInvalidDecl())
9367     return;
9368 
9369   SynthesizedFunctionScope Scope(*this, Destructor);
9370 
9371   DiagnosticErrorTrap Trap(Diags);
9372   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9373                                          Destructor->getParent());
9374 
9375   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9376     Diag(CurrentLocation, diag::note_member_synthesized_at)
9377       << CXXDestructor << Context.getTagDeclType(ClassDecl);
9378 
9379     Destructor->setInvalidDecl();
9380     return;
9381   }
9382 
9383   // The exception specification is needed because we are defining the
9384   // function.
9385   ResolveExceptionSpec(CurrentLocation,
9386                        Destructor->getType()->castAs<FunctionProtoType>());
9387 
9388   SourceLocation Loc = Destructor->getLocEnd().isValid()
9389                            ? Destructor->getLocEnd()
9390                            : Destructor->getLocation();
9391   Destructor->setBody(new (Context) CompoundStmt(Loc));
9392   Destructor->markUsed(Context);
9393   MarkVTableUsed(CurrentLocation, ClassDecl);
9394 
9395   if (ASTMutationListener *L = getASTMutationListener()) {
9396     L->CompletedImplicitDefinition(Destructor);
9397   }
9398 }
9399 
9400 /// \brief Perform any semantic analysis which needs to be delayed until all
9401 /// pending class member declarations have been parsed.
9402 void Sema::ActOnFinishCXXMemberDecls() {
9403   // If the context is an invalid C++ class, just suppress these checks.
9404   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9405     if (Record->isInvalidDecl()) {
9406       DelayedDefaultedMemberExceptionSpecs.clear();
9407       DelayedExceptionSpecChecks.clear();
9408       return;
9409     }
9410   }
9411 }
9412 
9413 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9414                                          CXXDestructorDecl *Destructor) {
9415   assert(getLangOpts().CPlusPlus11 &&
9416          "adjusting dtor exception specs was introduced in c++11");
9417 
9418   // C++11 [class.dtor]p3:
9419   //   A declaration of a destructor that does not have an exception-
9420   //   specification is implicitly considered to have the same exception-
9421   //   specification as an implicit declaration.
9422   const FunctionProtoType *DtorType = Destructor->getType()->
9423                                         getAs<FunctionProtoType>();
9424   if (DtorType->hasExceptionSpec())
9425     return;
9426 
9427   // Replace the destructor's type, building off the existing one. Fortunately,
9428   // the only thing of interest in the destructor type is its extended info.
9429   // The return and arguments are fixed.
9430   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9431   EPI.ExceptionSpec.Type = EST_Unevaluated;
9432   EPI.ExceptionSpec.SourceDecl = Destructor;
9433   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9434 
9435   // FIXME: If the destructor has a body that could throw, and the newly created
9436   // spec doesn't allow exceptions, we should emit a warning, because this
9437   // change in behavior can break conforming C++03 programs at runtime.
9438   // However, we don't have a body or an exception specification yet, so it
9439   // needs to be done somewhere else.
9440 }
9441 
9442 namespace {
9443 /// \brief An abstract base class for all helper classes used in building the
9444 //  copy/move operators. These classes serve as factory functions and help us
9445 //  avoid using the same Expr* in the AST twice.
9446 class ExprBuilder {
9447   ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9448   ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9449 
9450 protected:
9451   static Expr *assertNotNull(Expr *E) {
9452     assert(E && "Expression construction must not fail.");
9453     return E;
9454   }
9455 
9456 public:
9457   ExprBuilder() {}
9458   virtual ~ExprBuilder() {}
9459 
9460   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9461 };
9462 
9463 class RefBuilder: public ExprBuilder {
9464   VarDecl *Var;
9465   QualType VarType;
9466 
9467 public:
9468   Expr *build(Sema &S, SourceLocation Loc) const override {
9469     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9470   }
9471 
9472   RefBuilder(VarDecl *Var, QualType VarType)
9473       : Var(Var), VarType(VarType) {}
9474 };
9475 
9476 class ThisBuilder: public ExprBuilder {
9477 public:
9478   Expr *build(Sema &S, SourceLocation Loc) const override {
9479     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9480   }
9481 };
9482 
9483 class CastBuilder: public ExprBuilder {
9484   const ExprBuilder &Builder;
9485   QualType Type;
9486   ExprValueKind Kind;
9487   const CXXCastPath &Path;
9488 
9489 public:
9490   Expr *build(Sema &S, SourceLocation Loc) const override {
9491     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9492                                              CK_UncheckedDerivedToBase, Kind,
9493                                              &Path).get());
9494   }
9495 
9496   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9497               const CXXCastPath &Path)
9498       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9499 };
9500 
9501 class DerefBuilder: public ExprBuilder {
9502   const ExprBuilder &Builder;
9503 
9504 public:
9505   Expr *build(Sema &S, SourceLocation Loc) const override {
9506     return assertNotNull(
9507         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9508   }
9509 
9510   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9511 };
9512 
9513 class MemberBuilder: public ExprBuilder {
9514   const ExprBuilder &Builder;
9515   QualType Type;
9516   CXXScopeSpec SS;
9517   bool IsArrow;
9518   LookupResult &MemberLookup;
9519 
9520 public:
9521   Expr *build(Sema &S, SourceLocation Loc) const override {
9522     return assertNotNull(S.BuildMemberReferenceExpr(
9523         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9524         nullptr, MemberLookup, nullptr).get());
9525   }
9526 
9527   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9528                 LookupResult &MemberLookup)
9529       : Builder(Builder), Type(Type), IsArrow(IsArrow),
9530         MemberLookup(MemberLookup) {}
9531 };
9532 
9533 class MoveCastBuilder: public ExprBuilder {
9534   const ExprBuilder &Builder;
9535 
9536 public:
9537   Expr *build(Sema &S, SourceLocation Loc) const override {
9538     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9539   }
9540 
9541   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9542 };
9543 
9544 class LvalueConvBuilder: public ExprBuilder {
9545   const ExprBuilder &Builder;
9546 
9547 public:
9548   Expr *build(Sema &S, SourceLocation Loc) const override {
9549     return assertNotNull(
9550         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9551   }
9552 
9553   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9554 };
9555 
9556 class SubscriptBuilder: public ExprBuilder {
9557   const ExprBuilder &Base;
9558   const ExprBuilder &Index;
9559 
9560 public:
9561   Expr *build(Sema &S, SourceLocation Loc) const override {
9562     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9563         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9564   }
9565 
9566   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9567       : Base(Base), Index(Index) {}
9568 };
9569 
9570 } // end anonymous namespace
9571 
9572 /// When generating a defaulted copy or move assignment operator, if a field
9573 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9574 /// do so. This optimization only applies for arrays of scalars, and for arrays
9575 /// of class type where the selected copy/move-assignment operator is trivial.
9576 static StmtResult
9577 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9578                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
9579   // Compute the size of the memory buffer to be copied.
9580   QualType SizeType = S.Context.getSizeType();
9581   llvm::APInt Size(S.Context.getTypeSize(SizeType),
9582                    S.Context.getTypeSizeInChars(T).getQuantity());
9583 
9584   // Take the address of the field references for "from" and "to". We
9585   // directly construct UnaryOperators here because semantic analysis
9586   // does not permit us to take the address of an xvalue.
9587   Expr *From = FromB.build(S, Loc);
9588   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9589                          S.Context.getPointerType(From->getType()),
9590                          VK_RValue, OK_Ordinary, Loc);
9591   Expr *To = ToB.build(S, Loc);
9592   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9593                        S.Context.getPointerType(To->getType()),
9594                        VK_RValue, OK_Ordinary, Loc);
9595 
9596   const Type *E = T->getBaseElementTypeUnsafe();
9597   bool NeedsCollectableMemCpy =
9598     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9599 
9600   // Create a reference to the __builtin_objc_memmove_collectable function
9601   StringRef MemCpyName = NeedsCollectableMemCpy ?
9602     "__builtin_objc_memmove_collectable" :
9603     "__builtin_memcpy";
9604   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9605                  Sema::LookupOrdinaryName);
9606   S.LookupName(R, S.TUScope, true);
9607 
9608   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9609   if (!MemCpy)
9610     // Something went horribly wrong earlier, and we will have complained
9611     // about it.
9612     return StmtError();
9613 
9614   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9615                                             VK_RValue, Loc, nullptr);
9616   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9617 
9618   Expr *CallArgs[] = {
9619     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9620   };
9621   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9622                                     Loc, CallArgs, Loc);
9623 
9624   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9625   return Call.getAs<Stmt>();
9626 }
9627 
9628 /// \brief Builds a statement that copies/moves the given entity from \p From to
9629 /// \c To.
9630 ///
9631 /// This routine is used to copy/move the members of a class with an
9632 /// implicitly-declared copy/move assignment operator. When the entities being
9633 /// copied are arrays, this routine builds for loops to copy them.
9634 ///
9635 /// \param S The Sema object used for type-checking.
9636 ///
9637 /// \param Loc The location where the implicit copy/move is being generated.
9638 ///
9639 /// \param T The type of the expressions being copied/moved. Both expressions
9640 /// must have this type.
9641 ///
9642 /// \param To The expression we are copying/moving to.
9643 ///
9644 /// \param From The expression we are copying/moving from.
9645 ///
9646 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9647 /// Otherwise, it's a non-static member subobject.
9648 ///
9649 /// \param Copying Whether we're copying or moving.
9650 ///
9651 /// \param Depth Internal parameter recording the depth of the recursion.
9652 ///
9653 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9654 /// if a memcpy should be used instead.
9655 static StmtResult
9656 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9657                                  const ExprBuilder &To, const ExprBuilder &From,
9658                                  bool CopyingBaseSubobject, bool Copying,
9659                                  unsigned Depth = 0) {
9660   // C++11 [class.copy]p28:
9661   //   Each subobject is assigned in the manner appropriate to its type:
9662   //
9663   //     - if the subobject is of class type, as if by a call to operator= with
9664   //       the subobject as the object expression and the corresponding
9665   //       subobject of x as a single function argument (as if by explicit
9666   //       qualification; that is, ignoring any possible virtual overriding
9667   //       functions in more derived classes);
9668   //
9669   // C++03 [class.copy]p13:
9670   //     - if the subobject is of class type, the copy assignment operator for
9671   //       the class is used (as if by explicit qualification; that is,
9672   //       ignoring any possible virtual overriding functions in more derived
9673   //       classes);
9674   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9675     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9676 
9677     // Look for operator=.
9678     DeclarationName Name
9679       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9680     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9681     S.LookupQualifiedName(OpLookup, ClassDecl, false);
9682 
9683     // Prior to C++11, filter out any result that isn't a copy/move-assignment
9684     // operator.
9685     if (!S.getLangOpts().CPlusPlus11) {
9686       LookupResult::Filter F = OpLookup.makeFilter();
9687       while (F.hasNext()) {
9688         NamedDecl *D = F.next();
9689         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9690           if (Method->isCopyAssignmentOperator() ||
9691               (!Copying && Method->isMoveAssignmentOperator()))
9692             continue;
9693 
9694         F.erase();
9695       }
9696       F.done();
9697     }
9698 
9699     // Suppress the protected check (C++ [class.protected]) for each of the
9700     // assignment operators we found. This strange dance is required when
9701     // we're assigning via a base classes's copy-assignment operator. To
9702     // ensure that we're getting the right base class subobject (without
9703     // ambiguities), we need to cast "this" to that subobject type; to
9704     // ensure that we don't go through the virtual call mechanism, we need
9705     // to qualify the operator= name with the base class (see below). However,
9706     // this means that if the base class has a protected copy assignment
9707     // operator, the protected member access check will fail. So, we
9708     // rewrite "protected" access to "public" access in this case, since we
9709     // know by construction that we're calling from a derived class.
9710     if (CopyingBaseSubobject) {
9711       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9712            L != LEnd; ++L) {
9713         if (L.getAccess() == AS_protected)
9714           L.setAccess(AS_public);
9715       }
9716     }
9717 
9718     // Create the nested-name-specifier that will be used to qualify the
9719     // reference to operator=; this is required to suppress the virtual
9720     // call mechanism.
9721     CXXScopeSpec SS;
9722     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9723     SS.MakeTrivial(S.Context,
9724                    NestedNameSpecifier::Create(S.Context, nullptr, false,
9725                                                CanonicalT),
9726                    Loc);
9727 
9728     // Create the reference to operator=.
9729     ExprResult OpEqualRef
9730       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9731                                    SS, /*TemplateKWLoc=*/SourceLocation(),
9732                                    /*FirstQualifierInScope=*/nullptr,
9733                                    OpLookup,
9734                                    /*TemplateArgs=*/nullptr,
9735                                    /*SuppressQualifierCheck=*/true);
9736     if (OpEqualRef.isInvalid())
9737       return StmtError();
9738 
9739     // Build the call to the assignment operator.
9740 
9741     Expr *FromInst = From.build(S, Loc);
9742     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9743                                                   OpEqualRef.getAs<Expr>(),
9744                                                   Loc, FromInst, Loc);
9745     if (Call.isInvalid())
9746       return StmtError();
9747 
9748     // If we built a call to a trivial 'operator=' while copying an array,
9749     // bail out. We'll replace the whole shebang with a memcpy.
9750     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9751     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9752       return StmtResult((Stmt*)nullptr);
9753 
9754     // Convert to an expression-statement, and clean up any produced
9755     // temporaries.
9756     return S.ActOnExprStmt(Call);
9757   }
9758 
9759   //     - if the subobject is of scalar type, the built-in assignment
9760   //       operator is used.
9761   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9762   if (!ArrayTy) {
9763     ExprResult Assignment = S.CreateBuiltinBinOp(
9764         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9765     if (Assignment.isInvalid())
9766       return StmtError();
9767     return S.ActOnExprStmt(Assignment);
9768   }
9769 
9770   //     - if the subobject is an array, each element is assigned, in the
9771   //       manner appropriate to the element type;
9772 
9773   // Construct a loop over the array bounds, e.g.,
9774   //
9775   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9776   //
9777   // that will copy each of the array elements.
9778   QualType SizeType = S.Context.getSizeType();
9779 
9780   // Create the iteration variable.
9781   IdentifierInfo *IterationVarName = nullptr;
9782   {
9783     SmallString<8> Str;
9784     llvm::raw_svector_ostream OS(Str);
9785     OS << "__i" << Depth;
9786     IterationVarName = &S.Context.Idents.get(OS.str());
9787   }
9788   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9789                                           IterationVarName, SizeType,
9790                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9791                                           SC_None);
9792 
9793   // Initialize the iteration variable to zero.
9794   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9795   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9796 
9797   // Creates a reference to the iteration variable.
9798   RefBuilder IterationVarRef(IterationVar, SizeType);
9799   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9800 
9801   // Create the DeclStmt that holds the iteration variable.
9802   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9803 
9804   // Subscript the "from" and "to" expressions with the iteration variable.
9805   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9806   MoveCastBuilder FromIndexMove(FromIndexCopy);
9807   const ExprBuilder *FromIndex;
9808   if (Copying)
9809     FromIndex = &FromIndexCopy;
9810   else
9811     FromIndex = &FromIndexMove;
9812 
9813   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9814 
9815   // Build the copy/move for an individual element of the array.
9816   StmtResult Copy =
9817     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9818                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9819                                      Copying, Depth + 1);
9820   // Bail out if copying fails or if we determined that we should use memcpy.
9821   if (Copy.isInvalid() || !Copy.get())
9822     return Copy;
9823 
9824   // Create the comparison against the array bound.
9825   llvm::APInt Upper
9826     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9827   Expr *Comparison
9828     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9829                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9830                                      BO_NE, S.Context.BoolTy,
9831                                      VK_RValue, OK_Ordinary, Loc, false);
9832 
9833   // Create the pre-increment of the iteration variable.
9834   Expr *Increment
9835     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9836                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9837 
9838   // Construct the loop that copies all elements of this array.
9839   return S.ActOnForStmt(Loc, Loc, InitStmt,
9840                         S.MakeFullExpr(Comparison),
9841                         nullptr, S.MakeFullDiscardedValueExpr(Increment),
9842                         Loc, Copy.get());
9843 }
9844 
9845 static StmtResult
9846 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9847                       const ExprBuilder &To, const ExprBuilder &From,
9848                       bool CopyingBaseSubobject, bool Copying) {
9849   // Maybe we should use a memcpy?
9850   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9851       T.isTriviallyCopyableType(S.Context))
9852     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9853 
9854   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9855                                                      CopyingBaseSubobject,
9856                                                      Copying, 0));
9857 
9858   // If we ended up picking a trivial assignment operator for an array of a
9859   // non-trivially-copyable class type, just emit a memcpy.
9860   if (!Result.isInvalid() && !Result.get())
9861     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9862 
9863   return Result;
9864 }
9865 
9866 Sema::ImplicitExceptionSpecification
9867 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9868   CXXRecordDecl *ClassDecl = MD->getParent();
9869 
9870   ImplicitExceptionSpecification ExceptSpec(*this);
9871   if (ClassDecl->isInvalidDecl())
9872     return ExceptSpec;
9873 
9874   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9875   assert(T->getNumParams() == 1 && "not a copy assignment op");
9876   unsigned ArgQuals =
9877       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9878 
9879   // C++ [except.spec]p14:
9880   //   An implicitly declared special member function (Clause 12) shall have an
9881   //   exception-specification. [...]
9882 
9883   // It is unspecified whether or not an implicit copy assignment operator
9884   // attempts to deduplicate calls to assignment operators of virtual bases are
9885   // made. As such, this exception specification is effectively unspecified.
9886   // Based on a similar decision made for constness in C++0x, we're erring on
9887   // the side of assuming such calls to be made regardless of whether they
9888   // actually happen.
9889   for (const auto &Base : ClassDecl->bases()) {
9890     if (Base.isVirtual())
9891       continue;
9892 
9893     CXXRecordDecl *BaseClassDecl
9894       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9895     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9896                                                             ArgQuals, false, 0))
9897       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9898   }
9899 
9900   for (const auto &Base : ClassDecl->vbases()) {
9901     CXXRecordDecl *BaseClassDecl
9902       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9903     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9904                                                             ArgQuals, false, 0))
9905       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9906   }
9907 
9908   for (const auto *Field : ClassDecl->fields()) {
9909     QualType FieldType = Context.getBaseElementType(Field->getType());
9910     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9911       if (CXXMethodDecl *CopyAssign =
9912           LookupCopyingAssignment(FieldClassDecl,
9913                                   ArgQuals | FieldType.getCVRQualifiers(),
9914                                   false, 0))
9915         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
9916     }
9917   }
9918 
9919   return ExceptSpec;
9920 }
9921 
9922 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9923   // Note: The following rules are largely analoguous to the copy
9924   // constructor rules. Note that virtual bases are not taken into account
9925   // for determining the argument type of the operator. Note also that
9926   // operators taking an object instead of a reference are allowed.
9927   assert(ClassDecl->needsImplicitCopyAssignment());
9928 
9929   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9930   if (DSM.isAlreadyBeingDeclared())
9931     return nullptr;
9932 
9933   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9934   QualType RetType = Context.getLValueReferenceType(ArgType);
9935   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9936   if (Const)
9937     ArgType = ArgType.withConst();
9938   ArgType = Context.getLValueReferenceType(ArgType);
9939 
9940   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9941                                                      CXXCopyAssignment,
9942                                                      Const);
9943 
9944   //   An implicitly-declared copy assignment operator is an inline public
9945   //   member of its class.
9946   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9947   SourceLocation ClassLoc = ClassDecl->getLocation();
9948   DeclarationNameInfo NameInfo(Name, ClassLoc);
9949   CXXMethodDecl *CopyAssignment =
9950       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9951                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9952                             /*isInline=*/true, Constexpr, SourceLocation());
9953   CopyAssignment->setAccess(AS_public);
9954   CopyAssignment->setDefaulted();
9955   CopyAssignment->setImplicit();
9956 
9957   if (getLangOpts().CUDA) {
9958     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
9959                                             CopyAssignment,
9960                                             /* ConstRHS */ Const,
9961                                             /* Diagnose */ false);
9962   }
9963 
9964   // Build an exception specification pointing back at this member.
9965   FunctionProtoType::ExtProtoInfo EPI =
9966       getImplicitMethodEPI(*this, CopyAssignment);
9967   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9968 
9969   // Add the parameter to the operator.
9970   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
9971                                                ClassLoc, ClassLoc,
9972                                                /*Id=*/nullptr, ArgType,
9973                                                /*TInfo=*/nullptr, SC_None,
9974                                                nullptr);
9975   CopyAssignment->setParams(FromParam);
9976 
9977   AddOverriddenMethods(ClassDecl, CopyAssignment);
9978 
9979   CopyAssignment->setTrivial(
9980     ClassDecl->needsOverloadResolutionForCopyAssignment()
9981       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9982       : ClassDecl->hasTrivialCopyAssignment());
9983 
9984   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
9985     SetDeclDeleted(CopyAssignment, ClassLoc);
9986 
9987   // Note that we have added this copy-assignment operator.
9988   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9989 
9990   if (Scope *S = getScopeForContext(ClassDecl))
9991     PushOnScopeChains(CopyAssignment, S, false);
9992   ClassDecl->addDecl(CopyAssignment);
9993 
9994   return CopyAssignment;
9995 }
9996 
9997 /// Diagnose an implicit copy operation for a class which is odr-used, but
9998 /// which is deprecated because the class has a user-declared copy constructor,
9999 /// copy assignment operator, or destructor.
10000 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10001                                             SourceLocation UseLoc) {
10002   assert(CopyOp->isImplicit());
10003 
10004   CXXRecordDecl *RD = CopyOp->getParent();
10005   CXXMethodDecl *UserDeclaredOperation = nullptr;
10006 
10007   // In Microsoft mode, assignment operations don't affect constructors and
10008   // vice versa.
10009   if (RD->hasUserDeclaredDestructor()) {
10010     UserDeclaredOperation = RD->getDestructor();
10011   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10012              RD->hasUserDeclaredCopyConstructor() &&
10013              !S.getLangOpts().MSVCCompat) {
10014     // Find any user-declared copy constructor.
10015     for (auto *I : RD->ctors()) {
10016       if (I->isCopyConstructor()) {
10017         UserDeclaredOperation = I;
10018         break;
10019       }
10020     }
10021     assert(UserDeclaredOperation);
10022   } else if (isa<CXXConstructorDecl>(CopyOp) &&
10023              RD->hasUserDeclaredCopyAssignment() &&
10024              !S.getLangOpts().MSVCCompat) {
10025     // Find any user-declared move assignment operator.
10026     for (auto *I : RD->methods()) {
10027       if (I->isCopyAssignmentOperator()) {
10028         UserDeclaredOperation = I;
10029         break;
10030       }
10031     }
10032     assert(UserDeclaredOperation);
10033   }
10034 
10035   if (UserDeclaredOperation) {
10036     S.Diag(UserDeclaredOperation->getLocation(),
10037          diag::warn_deprecated_copy_operation)
10038       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10039       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10040     S.Diag(UseLoc, diag::note_member_synthesized_at)
10041       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10042                                           : Sema::CXXCopyAssignment)
10043       << RD;
10044   }
10045 }
10046 
10047 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10048                                         CXXMethodDecl *CopyAssignOperator) {
10049   assert((CopyAssignOperator->isDefaulted() &&
10050           CopyAssignOperator->isOverloadedOperator() &&
10051           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
10052           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10053           !CopyAssignOperator->isDeleted()) &&
10054          "DefineImplicitCopyAssignment called for wrong function");
10055 
10056   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10057 
10058   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10059     CopyAssignOperator->setInvalidDecl();
10060     return;
10061   }
10062 
10063   // C++11 [class.copy]p18:
10064   //   The [definition of an implicitly declared copy assignment operator] is
10065   //   deprecated if the class has a user-declared copy constructor or a
10066   //   user-declared destructor.
10067   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10068     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10069 
10070   CopyAssignOperator->markUsed(Context);
10071 
10072   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
10073   DiagnosticErrorTrap Trap(Diags);
10074 
10075   // C++0x [class.copy]p30:
10076   //   The implicitly-defined or explicitly-defaulted copy assignment operator
10077   //   for a non-union class X performs memberwise copy assignment of its
10078   //   subobjects. The direct base classes of X are assigned first, in the
10079   //   order of their declaration in the base-specifier-list, and then the
10080   //   immediate non-static data members of X are assigned, in the order in
10081   //   which they were declared in the class definition.
10082 
10083   // The statements that form the synthesized function body.
10084   SmallVector<Stmt*, 8> Statements;
10085 
10086   // The parameter for the "other" object, which we are copying from.
10087   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10088   Qualifiers OtherQuals = Other->getType().getQualifiers();
10089   QualType OtherRefType = Other->getType();
10090   if (const LValueReferenceType *OtherRef
10091                                 = OtherRefType->getAs<LValueReferenceType>()) {
10092     OtherRefType = OtherRef->getPointeeType();
10093     OtherQuals = OtherRefType.getQualifiers();
10094   }
10095 
10096   // Our location for everything implicitly-generated.
10097   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10098                            ? CopyAssignOperator->getLocEnd()
10099                            : CopyAssignOperator->getLocation();
10100 
10101   // Builds a DeclRefExpr for the "other" object.
10102   RefBuilder OtherRef(Other, OtherRefType);
10103 
10104   // Builds the "this" pointer.
10105   ThisBuilder This;
10106 
10107   // Assign base classes.
10108   bool Invalid = false;
10109   for (auto &Base : ClassDecl->bases()) {
10110     // Form the assignment:
10111     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
10112     QualType BaseType = Base.getType().getUnqualifiedType();
10113     if (!BaseType->isRecordType()) {
10114       Invalid = true;
10115       continue;
10116     }
10117 
10118     CXXCastPath BasePath;
10119     BasePath.push_back(&Base);
10120 
10121     // Construct the "from" expression, which is an implicit cast to the
10122     // appropriately-qualified base type.
10123     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10124                      VK_LValue, BasePath);
10125 
10126     // Dereference "this".
10127     DerefBuilder DerefThis(This);
10128     CastBuilder To(DerefThis,
10129                    Context.getCVRQualifiedType(
10130                        BaseType, CopyAssignOperator->getTypeQualifiers()),
10131                    VK_LValue, BasePath);
10132 
10133     // Build the copy.
10134     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
10135                                             To, From,
10136                                             /*CopyingBaseSubobject=*/true,
10137                                             /*Copying=*/true);
10138     if (Copy.isInvalid()) {
10139       Diag(CurrentLocation, diag::note_member_synthesized_at)
10140         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10141       CopyAssignOperator->setInvalidDecl();
10142       return;
10143     }
10144 
10145     // Success! Record the copy.
10146     Statements.push_back(Copy.getAs<Expr>());
10147   }
10148 
10149   // Assign non-static members.
10150   for (auto *Field : ClassDecl->fields()) {
10151     if (Field->isUnnamedBitfield())
10152       continue;
10153 
10154     if (Field->isInvalidDecl()) {
10155       Invalid = true;
10156       continue;
10157     }
10158 
10159     // Check for members of reference type; we can't copy those.
10160     if (Field->getType()->isReferenceType()) {
10161       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10162         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10163       Diag(Field->getLocation(), diag::note_declared_at);
10164       Diag(CurrentLocation, diag::note_member_synthesized_at)
10165         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10166       Invalid = true;
10167       continue;
10168     }
10169 
10170     // Check for members of const-qualified, non-class type.
10171     QualType BaseType = Context.getBaseElementType(Field->getType());
10172     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10173       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10174         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10175       Diag(Field->getLocation(), diag::note_declared_at);
10176       Diag(CurrentLocation, diag::note_member_synthesized_at)
10177         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10178       Invalid = true;
10179       continue;
10180     }
10181 
10182     // Suppress assigning zero-width bitfields.
10183     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10184       continue;
10185 
10186     QualType FieldType = Field->getType().getNonReferenceType();
10187     if (FieldType->isIncompleteArrayType()) {
10188       assert(ClassDecl->hasFlexibleArrayMember() &&
10189              "Incomplete array type is not valid");
10190       continue;
10191     }
10192 
10193     // Build references to the field in the object we're copying from and to.
10194     CXXScopeSpec SS; // Intentionally empty
10195     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10196                               LookupMemberName);
10197     MemberLookup.addDecl(Field);
10198     MemberLookup.resolveKind();
10199 
10200     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10201 
10202     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
10203 
10204     // Build the copy of this field.
10205     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
10206                                             To, From,
10207                                             /*CopyingBaseSubobject=*/false,
10208                                             /*Copying=*/true);
10209     if (Copy.isInvalid()) {
10210       Diag(CurrentLocation, diag::note_member_synthesized_at)
10211         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10212       CopyAssignOperator->setInvalidDecl();
10213       return;
10214     }
10215 
10216     // Success! Record the copy.
10217     Statements.push_back(Copy.getAs<Stmt>());
10218   }
10219 
10220   if (!Invalid) {
10221     // Add a "return *this;"
10222     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10223 
10224     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10225     if (Return.isInvalid())
10226       Invalid = true;
10227     else {
10228       Statements.push_back(Return.getAs<Stmt>());
10229 
10230       if (Trap.hasErrorOccurred()) {
10231         Diag(CurrentLocation, diag::note_member_synthesized_at)
10232           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10233         Invalid = true;
10234       }
10235     }
10236   }
10237 
10238   // The exception specification is needed because we are defining the
10239   // function.
10240   ResolveExceptionSpec(CurrentLocation,
10241                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10242 
10243   if (Invalid) {
10244     CopyAssignOperator->setInvalidDecl();
10245     return;
10246   }
10247 
10248   StmtResult Body;
10249   {
10250     CompoundScopeRAII CompoundScope(*this);
10251     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10252                              /*isStmtExpr=*/false);
10253     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10254   }
10255   CopyAssignOperator->setBody(Body.getAs<Stmt>());
10256 
10257   if (ASTMutationListener *L = getASTMutationListener()) {
10258     L->CompletedImplicitDefinition(CopyAssignOperator);
10259   }
10260 }
10261 
10262 Sema::ImplicitExceptionSpecification
10263 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10264   CXXRecordDecl *ClassDecl = MD->getParent();
10265 
10266   ImplicitExceptionSpecification ExceptSpec(*this);
10267   if (ClassDecl->isInvalidDecl())
10268     return ExceptSpec;
10269 
10270   // C++0x [except.spec]p14:
10271   //   An implicitly declared special member function (Clause 12) shall have an
10272   //   exception-specification. [...]
10273 
10274   // It is unspecified whether or not an implicit move assignment operator
10275   // attempts to deduplicate calls to assignment operators of virtual bases are
10276   // made. As such, this exception specification is effectively unspecified.
10277   // Based on a similar decision made for constness in C++0x, we're erring on
10278   // the side of assuming such calls to be made regardless of whether they
10279   // actually happen.
10280   // Note that a move constructor is not implicitly declared when there are
10281   // virtual bases, but it can still be user-declared and explicitly defaulted.
10282   for (const auto &Base : ClassDecl->bases()) {
10283     if (Base.isVirtual())
10284       continue;
10285 
10286     CXXRecordDecl *BaseClassDecl
10287       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10288     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10289                                                            0, false, 0))
10290       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10291   }
10292 
10293   for (const auto &Base : ClassDecl->vbases()) {
10294     CXXRecordDecl *BaseClassDecl
10295       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10296     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10297                                                            0, false, 0))
10298       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10299   }
10300 
10301   for (const auto *Field : ClassDecl->fields()) {
10302     QualType FieldType = Context.getBaseElementType(Field->getType());
10303     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10304       if (CXXMethodDecl *MoveAssign =
10305               LookupMovingAssignment(FieldClassDecl,
10306                                      FieldType.getCVRQualifiers(),
10307                                      false, 0))
10308         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
10309     }
10310   }
10311 
10312   return ExceptSpec;
10313 }
10314 
10315 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
10316   assert(ClassDecl->needsImplicitMoveAssignment());
10317 
10318   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10319   if (DSM.isAlreadyBeingDeclared())
10320     return nullptr;
10321 
10322   // Note: The following rules are largely analoguous to the move
10323   // constructor rules.
10324 
10325   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10326   QualType RetType = Context.getLValueReferenceType(ArgType);
10327   ArgType = Context.getRValueReferenceType(ArgType);
10328 
10329   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10330                                                      CXXMoveAssignment,
10331                                                      false);
10332 
10333   //   An implicitly-declared move assignment operator is an inline public
10334   //   member of its class.
10335   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10336   SourceLocation ClassLoc = ClassDecl->getLocation();
10337   DeclarationNameInfo NameInfo(Name, ClassLoc);
10338   CXXMethodDecl *MoveAssignment =
10339       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10340                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10341                             /*isInline=*/true, Constexpr, SourceLocation());
10342   MoveAssignment->setAccess(AS_public);
10343   MoveAssignment->setDefaulted();
10344   MoveAssignment->setImplicit();
10345 
10346   if (getLangOpts().CUDA) {
10347     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10348                                             MoveAssignment,
10349                                             /* ConstRHS */ false,
10350                                             /* Diagnose */ false);
10351   }
10352 
10353   // Build an exception specification pointing back at this member.
10354   FunctionProtoType::ExtProtoInfo EPI =
10355       getImplicitMethodEPI(*this, MoveAssignment);
10356   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10357 
10358   // Add the parameter to the operator.
10359   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
10360                                                ClassLoc, ClassLoc,
10361                                                /*Id=*/nullptr, ArgType,
10362                                                /*TInfo=*/nullptr, SC_None,
10363                                                nullptr);
10364   MoveAssignment->setParams(FromParam);
10365 
10366   AddOverriddenMethods(ClassDecl, MoveAssignment);
10367 
10368   MoveAssignment->setTrivial(
10369     ClassDecl->needsOverloadResolutionForMoveAssignment()
10370       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10371       : ClassDecl->hasTrivialMoveAssignment());
10372 
10373   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10374     ClassDecl->setImplicitMoveAssignmentIsDeleted();
10375     SetDeclDeleted(MoveAssignment, ClassLoc);
10376   }
10377 
10378   // Note that we have added this copy-assignment operator.
10379   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10380 
10381   if (Scope *S = getScopeForContext(ClassDecl))
10382     PushOnScopeChains(MoveAssignment, S, false);
10383   ClassDecl->addDecl(MoveAssignment);
10384 
10385   return MoveAssignment;
10386 }
10387 
10388 /// Check if we're implicitly defining a move assignment operator for a class
10389 /// with virtual bases. Such a move assignment might move-assign the virtual
10390 /// base multiple times.
10391 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10392                                                SourceLocation CurrentLocation) {
10393   assert(!Class->isDependentContext() && "should not define dependent move");
10394 
10395   // Only a virtual base could get implicitly move-assigned multiple times.
10396   // Only a non-trivial move assignment can observe this. We only want to
10397   // diagnose if we implicitly define an assignment operator that assigns
10398   // two base classes, both of which move-assign the same virtual base.
10399   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10400       Class->getNumBases() < 2)
10401     return;
10402 
10403   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10404   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10405   VBaseMap VBases;
10406 
10407   for (auto &BI : Class->bases()) {
10408     Worklist.push_back(&BI);
10409     while (!Worklist.empty()) {
10410       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10411       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10412 
10413       // If the base has no non-trivial move assignment operators,
10414       // we don't care about moves from it.
10415       if (!Base->hasNonTrivialMoveAssignment())
10416         continue;
10417 
10418       // If there's nothing virtual here, skip it.
10419       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10420         continue;
10421 
10422       // If we're not actually going to call a move assignment for this base,
10423       // or the selected move assignment is trivial, skip it.
10424       Sema::SpecialMemberOverloadResult *SMOR =
10425         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10426                               /*ConstArg*/false, /*VolatileArg*/false,
10427                               /*RValueThis*/true, /*ConstThis*/false,
10428                               /*VolatileThis*/false);
10429       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10430           !SMOR->getMethod()->isMoveAssignmentOperator())
10431         continue;
10432 
10433       if (BaseSpec->isVirtual()) {
10434         // We're going to move-assign this virtual base, and its move
10435         // assignment operator is not trivial. If this can happen for
10436         // multiple distinct direct bases of Class, diagnose it. (If it
10437         // only happens in one base, we'll diagnose it when synthesizing
10438         // that base class's move assignment operator.)
10439         CXXBaseSpecifier *&Existing =
10440             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10441                 .first->second;
10442         if (Existing && Existing != &BI) {
10443           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10444             << Class << Base;
10445           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10446             << (Base->getCanonicalDecl() ==
10447                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10448             << Base << Existing->getType() << Existing->getSourceRange();
10449           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10450             << (Base->getCanonicalDecl() ==
10451                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10452             << Base << BI.getType() << BaseSpec->getSourceRange();
10453 
10454           // Only diagnose each vbase once.
10455           Existing = nullptr;
10456         }
10457       } else {
10458         // Only walk over bases that have defaulted move assignment operators.
10459         // We assume that any user-provided move assignment operator handles
10460         // the multiple-moves-of-vbase case itself somehow.
10461         if (!SMOR->getMethod()->isDefaulted())
10462           continue;
10463 
10464         // We're going to move the base classes of Base. Add them to the list.
10465         for (auto &BI : Base->bases())
10466           Worklist.push_back(&BI);
10467       }
10468     }
10469   }
10470 }
10471 
10472 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10473                                         CXXMethodDecl *MoveAssignOperator) {
10474   assert((MoveAssignOperator->isDefaulted() &&
10475           MoveAssignOperator->isOverloadedOperator() &&
10476           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10477           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10478           !MoveAssignOperator->isDeleted()) &&
10479          "DefineImplicitMoveAssignment called for wrong function");
10480 
10481   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10482 
10483   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10484     MoveAssignOperator->setInvalidDecl();
10485     return;
10486   }
10487 
10488   MoveAssignOperator->markUsed(Context);
10489 
10490   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10491   DiagnosticErrorTrap Trap(Diags);
10492 
10493   // C++0x [class.copy]p28:
10494   //   The implicitly-defined or move assignment operator for a non-union class
10495   //   X performs memberwise move assignment of its subobjects. The direct base
10496   //   classes of X are assigned first, in the order of their declaration in the
10497   //   base-specifier-list, and then the immediate non-static data members of X
10498   //   are assigned, in the order in which they were declared in the class
10499   //   definition.
10500 
10501   // Issue a warning if our implicit move assignment operator will move
10502   // from a virtual base more than once.
10503   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10504 
10505   // The statements that form the synthesized function body.
10506   SmallVector<Stmt*, 8> Statements;
10507 
10508   // The parameter for the "other" object, which we are move from.
10509   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10510   QualType OtherRefType = Other->getType()->
10511       getAs<RValueReferenceType>()->getPointeeType();
10512   assert(!OtherRefType.getQualifiers() &&
10513          "Bad argument type of defaulted move assignment");
10514 
10515   // Our location for everything implicitly-generated.
10516   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10517                            ? MoveAssignOperator->getLocEnd()
10518                            : MoveAssignOperator->getLocation();
10519 
10520   // Builds a reference to the "other" object.
10521   RefBuilder OtherRef(Other, OtherRefType);
10522   // Cast to rvalue.
10523   MoveCastBuilder MoveOther(OtherRef);
10524 
10525   // Builds the "this" pointer.
10526   ThisBuilder This;
10527 
10528   // Assign base classes.
10529   bool Invalid = false;
10530   for (auto &Base : ClassDecl->bases()) {
10531     // C++11 [class.copy]p28:
10532     //   It is unspecified whether subobjects representing virtual base classes
10533     //   are assigned more than once by the implicitly-defined copy assignment
10534     //   operator.
10535     // FIXME: Do not assign to a vbase that will be assigned by some other base
10536     // class. For a move-assignment, this can result in the vbase being moved
10537     // multiple times.
10538 
10539     // Form the assignment:
10540     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10541     QualType BaseType = Base.getType().getUnqualifiedType();
10542     if (!BaseType->isRecordType()) {
10543       Invalid = true;
10544       continue;
10545     }
10546 
10547     CXXCastPath BasePath;
10548     BasePath.push_back(&Base);
10549 
10550     // Construct the "from" expression, which is an implicit cast to the
10551     // appropriately-qualified base type.
10552     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10553 
10554     // Dereference "this".
10555     DerefBuilder DerefThis(This);
10556 
10557     // Implicitly cast "this" to the appropriately-qualified base type.
10558     CastBuilder To(DerefThis,
10559                    Context.getCVRQualifiedType(
10560                        BaseType, MoveAssignOperator->getTypeQualifiers()),
10561                    VK_LValue, BasePath);
10562 
10563     // Build the move.
10564     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10565                                             To, From,
10566                                             /*CopyingBaseSubobject=*/true,
10567                                             /*Copying=*/false);
10568     if (Move.isInvalid()) {
10569       Diag(CurrentLocation, diag::note_member_synthesized_at)
10570         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10571       MoveAssignOperator->setInvalidDecl();
10572       return;
10573     }
10574 
10575     // Success! Record the move.
10576     Statements.push_back(Move.getAs<Expr>());
10577   }
10578 
10579   // Assign non-static members.
10580   for (auto *Field : ClassDecl->fields()) {
10581     if (Field->isUnnamedBitfield())
10582       continue;
10583 
10584     if (Field->isInvalidDecl()) {
10585       Invalid = true;
10586       continue;
10587     }
10588 
10589     // Check for members of reference type; we can't move those.
10590     if (Field->getType()->isReferenceType()) {
10591       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10592         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10593       Diag(Field->getLocation(), diag::note_declared_at);
10594       Diag(CurrentLocation, diag::note_member_synthesized_at)
10595         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10596       Invalid = true;
10597       continue;
10598     }
10599 
10600     // Check for members of const-qualified, non-class type.
10601     QualType BaseType = Context.getBaseElementType(Field->getType());
10602     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10603       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10604         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10605       Diag(Field->getLocation(), diag::note_declared_at);
10606       Diag(CurrentLocation, diag::note_member_synthesized_at)
10607         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10608       Invalid = true;
10609       continue;
10610     }
10611 
10612     // Suppress assigning zero-width bitfields.
10613     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10614       continue;
10615 
10616     QualType FieldType = Field->getType().getNonReferenceType();
10617     if (FieldType->isIncompleteArrayType()) {
10618       assert(ClassDecl->hasFlexibleArrayMember() &&
10619              "Incomplete array type is not valid");
10620       continue;
10621     }
10622 
10623     // Build references to the field in the object we're copying from and to.
10624     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10625                               LookupMemberName);
10626     MemberLookup.addDecl(Field);
10627     MemberLookup.resolveKind();
10628     MemberBuilder From(MoveOther, OtherRefType,
10629                        /*IsArrow=*/false, MemberLookup);
10630     MemberBuilder To(This, getCurrentThisType(),
10631                      /*IsArrow=*/true, MemberLookup);
10632 
10633     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10634         "Member reference with rvalue base must be rvalue except for reference "
10635         "members, which aren't allowed for move assignment.");
10636 
10637     // Build the move of this field.
10638     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10639                                             To, From,
10640                                             /*CopyingBaseSubobject=*/false,
10641                                             /*Copying=*/false);
10642     if (Move.isInvalid()) {
10643       Diag(CurrentLocation, diag::note_member_synthesized_at)
10644         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10645       MoveAssignOperator->setInvalidDecl();
10646       return;
10647     }
10648 
10649     // Success! Record the copy.
10650     Statements.push_back(Move.getAs<Stmt>());
10651   }
10652 
10653   if (!Invalid) {
10654     // Add a "return *this;"
10655     ExprResult ThisObj =
10656         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10657 
10658     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10659     if (Return.isInvalid())
10660       Invalid = true;
10661     else {
10662       Statements.push_back(Return.getAs<Stmt>());
10663 
10664       if (Trap.hasErrorOccurred()) {
10665         Diag(CurrentLocation, diag::note_member_synthesized_at)
10666           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10667         Invalid = true;
10668       }
10669     }
10670   }
10671 
10672   // The exception specification is needed because we are defining the
10673   // function.
10674   ResolveExceptionSpec(CurrentLocation,
10675                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10676 
10677   if (Invalid) {
10678     MoveAssignOperator->setInvalidDecl();
10679     return;
10680   }
10681 
10682   StmtResult Body;
10683   {
10684     CompoundScopeRAII CompoundScope(*this);
10685     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10686                              /*isStmtExpr=*/false);
10687     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10688   }
10689   MoveAssignOperator->setBody(Body.getAs<Stmt>());
10690 
10691   if (ASTMutationListener *L = getASTMutationListener()) {
10692     L->CompletedImplicitDefinition(MoveAssignOperator);
10693   }
10694 }
10695 
10696 Sema::ImplicitExceptionSpecification
10697 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10698   CXXRecordDecl *ClassDecl = MD->getParent();
10699 
10700   ImplicitExceptionSpecification ExceptSpec(*this);
10701   if (ClassDecl->isInvalidDecl())
10702     return ExceptSpec;
10703 
10704   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10705   assert(T->getNumParams() >= 1 && "not a copy ctor");
10706   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10707 
10708   // C++ [except.spec]p14:
10709   //   An implicitly declared special member function (Clause 12) shall have an
10710   //   exception-specification. [...]
10711   for (const auto &Base : ClassDecl->bases()) {
10712     // Virtual bases are handled below.
10713     if (Base.isVirtual())
10714       continue;
10715 
10716     CXXRecordDecl *BaseClassDecl
10717       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10718     if (CXXConstructorDecl *CopyConstructor =
10719           LookupCopyingConstructor(BaseClassDecl, Quals))
10720       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10721   }
10722   for (const auto &Base : ClassDecl->vbases()) {
10723     CXXRecordDecl *BaseClassDecl
10724       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10725     if (CXXConstructorDecl *CopyConstructor =
10726           LookupCopyingConstructor(BaseClassDecl, Quals))
10727       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10728   }
10729   for (const auto *Field : ClassDecl->fields()) {
10730     QualType FieldType = Context.getBaseElementType(Field->getType());
10731     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10732       if (CXXConstructorDecl *CopyConstructor =
10733               LookupCopyingConstructor(FieldClassDecl,
10734                                        Quals | FieldType.getCVRQualifiers()))
10735       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10736     }
10737   }
10738 
10739   return ExceptSpec;
10740 }
10741 
10742 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10743                                                     CXXRecordDecl *ClassDecl) {
10744   // C++ [class.copy]p4:
10745   //   If the class definition does not explicitly declare a copy
10746   //   constructor, one is declared implicitly.
10747   assert(ClassDecl->needsImplicitCopyConstructor());
10748 
10749   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10750   if (DSM.isAlreadyBeingDeclared())
10751     return nullptr;
10752 
10753   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10754   QualType ArgType = ClassType;
10755   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10756   if (Const)
10757     ArgType = ArgType.withConst();
10758   ArgType = Context.getLValueReferenceType(ArgType);
10759 
10760   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10761                                                      CXXCopyConstructor,
10762                                                      Const);
10763 
10764   DeclarationName Name
10765     = Context.DeclarationNames.getCXXConstructorName(
10766                                            Context.getCanonicalType(ClassType));
10767   SourceLocation ClassLoc = ClassDecl->getLocation();
10768   DeclarationNameInfo NameInfo(Name, ClassLoc);
10769 
10770   //   An implicitly-declared copy constructor is an inline public
10771   //   member of its class.
10772   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10773       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10774       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10775       Constexpr);
10776   CopyConstructor->setAccess(AS_public);
10777   CopyConstructor->setDefaulted();
10778 
10779   if (getLangOpts().CUDA) {
10780     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10781                                             CopyConstructor,
10782                                             /* ConstRHS */ Const,
10783                                             /* Diagnose */ false);
10784   }
10785 
10786   // Build an exception specification pointing back at this member.
10787   FunctionProtoType::ExtProtoInfo EPI =
10788       getImplicitMethodEPI(*this, CopyConstructor);
10789   CopyConstructor->setType(
10790       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10791 
10792   // Add the parameter to the constructor.
10793   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10794                                                ClassLoc, ClassLoc,
10795                                                /*IdentifierInfo=*/nullptr,
10796                                                ArgType, /*TInfo=*/nullptr,
10797                                                SC_None, nullptr);
10798   CopyConstructor->setParams(FromParam);
10799 
10800   CopyConstructor->setTrivial(
10801     ClassDecl->needsOverloadResolutionForCopyConstructor()
10802       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10803       : ClassDecl->hasTrivialCopyConstructor());
10804 
10805   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10806     SetDeclDeleted(CopyConstructor, ClassLoc);
10807 
10808   // Note that we have declared this constructor.
10809   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10810 
10811   if (Scope *S = getScopeForContext(ClassDecl))
10812     PushOnScopeChains(CopyConstructor, S, false);
10813   ClassDecl->addDecl(CopyConstructor);
10814 
10815   return CopyConstructor;
10816 }
10817 
10818 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10819                                    CXXConstructorDecl *CopyConstructor) {
10820   assert((CopyConstructor->isDefaulted() &&
10821           CopyConstructor->isCopyConstructor() &&
10822           !CopyConstructor->doesThisDeclarationHaveABody() &&
10823           !CopyConstructor->isDeleted()) &&
10824          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10825 
10826   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10827   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10828 
10829   // C++11 [class.copy]p7:
10830   //   The [definition of an implicitly declared copy constructor] is
10831   //   deprecated if the class has a user-declared copy assignment operator
10832   //   or a user-declared destructor.
10833   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10834     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10835 
10836   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10837   DiagnosticErrorTrap Trap(Diags);
10838 
10839   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10840       Trap.hasErrorOccurred()) {
10841     Diag(CurrentLocation, diag::note_member_synthesized_at)
10842       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10843     CopyConstructor->setInvalidDecl();
10844   }  else {
10845     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10846                              ? CopyConstructor->getLocEnd()
10847                              : CopyConstructor->getLocation();
10848     Sema::CompoundScopeRAII CompoundScope(*this);
10849     CopyConstructor->setBody(
10850         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
10851   }
10852 
10853   // The exception specification is needed because we are defining the
10854   // function.
10855   ResolveExceptionSpec(CurrentLocation,
10856                        CopyConstructor->getType()->castAs<FunctionProtoType>());
10857 
10858   CopyConstructor->markUsed(Context);
10859   MarkVTableUsed(CurrentLocation, ClassDecl);
10860 
10861   if (ASTMutationListener *L = getASTMutationListener()) {
10862     L->CompletedImplicitDefinition(CopyConstructor);
10863   }
10864 }
10865 
10866 Sema::ImplicitExceptionSpecification
10867 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10868   CXXRecordDecl *ClassDecl = MD->getParent();
10869 
10870   // C++ [except.spec]p14:
10871   //   An implicitly declared special member function (Clause 12) shall have an
10872   //   exception-specification. [...]
10873   ImplicitExceptionSpecification ExceptSpec(*this);
10874   if (ClassDecl->isInvalidDecl())
10875     return ExceptSpec;
10876 
10877   // Direct base-class constructors.
10878   for (const auto &B : ClassDecl->bases()) {
10879     if (B.isVirtual()) // Handled below.
10880       continue;
10881 
10882     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10883       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10884       CXXConstructorDecl *Constructor =
10885           LookupMovingConstructor(BaseClassDecl, 0);
10886       // If this is a deleted function, add it anyway. This might be conformant
10887       // with the standard. This might not. I'm not sure. It might not matter.
10888       if (Constructor)
10889         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10890     }
10891   }
10892 
10893   // Virtual base-class constructors.
10894   for (const auto &B : ClassDecl->vbases()) {
10895     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10896       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10897       CXXConstructorDecl *Constructor =
10898           LookupMovingConstructor(BaseClassDecl, 0);
10899       // If this is a deleted function, add it anyway. This might be conformant
10900       // with the standard. This might not. I'm not sure. It might not matter.
10901       if (Constructor)
10902         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10903     }
10904   }
10905 
10906   // Field constructors.
10907   for (const auto *F : ClassDecl->fields()) {
10908     QualType FieldType = Context.getBaseElementType(F->getType());
10909     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10910       CXXConstructorDecl *Constructor =
10911           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10912       // If this is a deleted function, add it anyway. This might be conformant
10913       // with the standard. This might not. I'm not sure. It might not matter.
10914       // In particular, the problem is that this function never gets called. It
10915       // might just be ill-formed because this function attempts to refer to
10916       // a deleted function here.
10917       if (Constructor)
10918         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10919     }
10920   }
10921 
10922   return ExceptSpec;
10923 }
10924 
10925 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10926                                                     CXXRecordDecl *ClassDecl) {
10927   assert(ClassDecl->needsImplicitMoveConstructor());
10928 
10929   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10930   if (DSM.isAlreadyBeingDeclared())
10931     return nullptr;
10932 
10933   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10934   QualType ArgType = Context.getRValueReferenceType(ClassType);
10935 
10936   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10937                                                      CXXMoveConstructor,
10938                                                      false);
10939 
10940   DeclarationName Name
10941     = Context.DeclarationNames.getCXXConstructorName(
10942                                            Context.getCanonicalType(ClassType));
10943   SourceLocation ClassLoc = ClassDecl->getLocation();
10944   DeclarationNameInfo NameInfo(Name, ClassLoc);
10945 
10946   // C++11 [class.copy]p11:
10947   //   An implicitly-declared copy/move constructor is an inline public
10948   //   member of its class.
10949   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10950       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10951       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10952       Constexpr);
10953   MoveConstructor->setAccess(AS_public);
10954   MoveConstructor->setDefaulted();
10955 
10956   if (getLangOpts().CUDA) {
10957     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
10958                                             MoveConstructor,
10959                                             /* ConstRHS */ false,
10960                                             /* Diagnose */ false);
10961   }
10962 
10963   // Build an exception specification pointing back at this member.
10964   FunctionProtoType::ExtProtoInfo EPI =
10965       getImplicitMethodEPI(*this, MoveConstructor);
10966   MoveConstructor->setType(
10967       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10968 
10969   // Add the parameter to the constructor.
10970   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10971                                                ClassLoc, ClassLoc,
10972                                                /*IdentifierInfo=*/nullptr,
10973                                                ArgType, /*TInfo=*/nullptr,
10974                                                SC_None, nullptr);
10975   MoveConstructor->setParams(FromParam);
10976 
10977   MoveConstructor->setTrivial(
10978     ClassDecl->needsOverloadResolutionForMoveConstructor()
10979       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10980       : ClassDecl->hasTrivialMoveConstructor());
10981 
10982   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10983     ClassDecl->setImplicitMoveConstructorIsDeleted();
10984     SetDeclDeleted(MoveConstructor, ClassLoc);
10985   }
10986 
10987   // Note that we have declared this constructor.
10988   ++ASTContext::NumImplicitMoveConstructorsDeclared;
10989 
10990   if (Scope *S = getScopeForContext(ClassDecl))
10991     PushOnScopeChains(MoveConstructor, S, false);
10992   ClassDecl->addDecl(MoveConstructor);
10993 
10994   return MoveConstructor;
10995 }
10996 
10997 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10998                                    CXXConstructorDecl *MoveConstructor) {
10999   assert((MoveConstructor->isDefaulted() &&
11000           MoveConstructor->isMoveConstructor() &&
11001           !MoveConstructor->doesThisDeclarationHaveABody() &&
11002           !MoveConstructor->isDeleted()) &&
11003          "DefineImplicitMoveConstructor - call it for implicit move ctor");
11004 
11005   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11006   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11007 
11008   SynthesizedFunctionScope Scope(*this, MoveConstructor);
11009   DiagnosticErrorTrap Trap(Diags);
11010 
11011   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
11012       Trap.hasErrorOccurred()) {
11013     Diag(CurrentLocation, diag::note_member_synthesized_at)
11014       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11015     MoveConstructor->setInvalidDecl();
11016   }  else {
11017     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11018                              ? MoveConstructor->getLocEnd()
11019                              : MoveConstructor->getLocation();
11020     Sema::CompoundScopeRAII CompoundScope(*this);
11021     MoveConstructor->setBody(ActOnCompoundStmt(
11022         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
11023   }
11024 
11025   // The exception specification is needed because we are defining the
11026   // function.
11027   ResolveExceptionSpec(CurrentLocation,
11028                        MoveConstructor->getType()->castAs<FunctionProtoType>());
11029 
11030   MoveConstructor->markUsed(Context);
11031   MarkVTableUsed(CurrentLocation, ClassDecl);
11032 
11033   if (ASTMutationListener *L = getASTMutationListener()) {
11034     L->CompletedImplicitDefinition(MoveConstructor);
11035   }
11036 }
11037 
11038 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
11039   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
11040 }
11041 
11042 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
11043                             SourceLocation CurrentLocation,
11044                             CXXConversionDecl *Conv) {
11045   CXXRecordDecl *Lambda = Conv->getParent();
11046   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11047   // If we are defining a specialization of a conversion to function-ptr
11048   // cache the deduced template arguments for this specialization
11049   // so that we can use them to retrieve the corresponding call-operator
11050   // and static-invoker.
11051   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11052 
11053   // Retrieve the corresponding call-operator specialization.
11054   if (Lambda->isGenericLambda()) {
11055     assert(Conv->isFunctionTemplateSpecialization());
11056     FunctionTemplateDecl *CallOpTemplate =
11057         CallOp->getDescribedFunctionTemplate();
11058     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
11059     void *InsertPos = nullptr;
11060     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
11061                                                 DeducedTemplateArgs->asArray(),
11062                                                 InsertPos);
11063     assert(CallOpSpec &&
11064           "Conversion operator must have a corresponding call operator");
11065     CallOp = cast<CXXMethodDecl>(CallOpSpec);
11066   }
11067   // Mark the call operator referenced (and add to pending instantiations
11068   // if necessary).
11069   // For both the conversion and static-invoker template specializations
11070   // we construct their body's in this function, so no need to add them
11071   // to the PendingInstantiations.
11072   MarkFunctionReferenced(CurrentLocation, CallOp);
11073 
11074   SynthesizedFunctionScope Scope(*this, Conv);
11075   DiagnosticErrorTrap Trap(Diags);
11076 
11077   // Retrieve the static invoker...
11078   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11079   // ... and get the corresponding specialization for a generic lambda.
11080   if (Lambda->isGenericLambda()) {
11081     assert(DeducedTemplateArgs &&
11082       "Must have deduced template arguments from Conversion Operator");
11083     FunctionTemplateDecl *InvokeTemplate =
11084                           Invoker->getDescribedFunctionTemplate();
11085     void *InsertPos = nullptr;
11086     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
11087                                                 DeducedTemplateArgs->asArray(),
11088                                                 InsertPos);
11089     assert(InvokeSpec &&
11090       "Must have a corresponding static invoker specialization");
11091     Invoker = cast<CXXMethodDecl>(InvokeSpec);
11092   }
11093   // Construct the body of the conversion function { return __invoke; }.
11094   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
11095                                         VK_LValue, Conv->getLocation()).get();
11096    assert(FunctionRef && "Can't refer to __invoke function?");
11097    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
11098    Conv->setBody(new (Context) CompoundStmt(Context, Return,
11099                                             Conv->getLocation(),
11100                                             Conv->getLocation()));
11101 
11102   Conv->markUsed(Context);
11103   Conv->setReferenced();
11104 
11105   // Fill in the __invoke function with a dummy implementation. IR generation
11106   // will fill in the actual details.
11107   Invoker->markUsed(Context);
11108   Invoker->setReferenced();
11109   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11110 
11111   if (ASTMutationListener *L = getASTMutationListener()) {
11112     L->CompletedImplicitDefinition(Conv);
11113     L->CompletedImplicitDefinition(Invoker);
11114    }
11115 }
11116 
11117 
11118 
11119 void Sema::DefineImplicitLambdaToBlockPointerConversion(
11120        SourceLocation CurrentLocation,
11121        CXXConversionDecl *Conv)
11122 {
11123   assert(!Conv->getParent()->isGenericLambda());
11124 
11125   Conv->markUsed(Context);
11126 
11127   SynthesizedFunctionScope Scope(*this, Conv);
11128   DiagnosticErrorTrap Trap(Diags);
11129 
11130   // Copy-initialize the lambda object as needed to capture it.
11131   Expr *This = ActOnCXXThis(CurrentLocation).get();
11132   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
11133 
11134   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11135                                                         Conv->getLocation(),
11136                                                         Conv, DerefThis);
11137 
11138   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11139   // behavior.  Note that only the general conversion function does this
11140   // (since it's unusable otherwise); in the case where we inline the
11141   // block literal, it has block literal lifetime semantics.
11142   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
11143     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11144                                           CK_CopyAndAutoreleaseBlockObject,
11145                                           BuildBlock.get(), nullptr, VK_RValue);
11146 
11147   if (BuildBlock.isInvalid()) {
11148     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11149     Conv->setInvalidDecl();
11150     return;
11151   }
11152 
11153   // Create the return statement that returns the block from the conversion
11154   // function.
11155   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
11156   if (Return.isInvalid()) {
11157     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11158     Conv->setInvalidDecl();
11159     return;
11160   }
11161 
11162   // Set the body of the conversion function.
11163   Stmt *ReturnS = Return.get();
11164   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
11165                                            Conv->getLocation(),
11166                                            Conv->getLocation()));
11167 
11168   // We're done; notify the mutation listener, if any.
11169   if (ASTMutationListener *L = getASTMutationListener()) {
11170     L->CompletedImplicitDefinition(Conv);
11171   }
11172 }
11173 
11174 /// \brief Determine whether the given list arguments contains exactly one
11175 /// "real" (non-default) argument.
11176 static bool hasOneRealArgument(MultiExprArg Args) {
11177   switch (Args.size()) {
11178   case 0:
11179     return false;
11180 
11181   default:
11182     if (!Args[1]->isDefaultArgument())
11183       return false;
11184 
11185     // fall through
11186   case 1:
11187     return !Args[0]->isDefaultArgument();
11188   }
11189 
11190   return false;
11191 }
11192 
11193 ExprResult
11194 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11195                             CXXConstructorDecl *Constructor,
11196                             MultiExprArg ExprArgs,
11197                             bool HadMultipleCandidates,
11198                             bool IsListInitialization,
11199                             bool IsStdInitListInitialization,
11200                             bool RequiresZeroInit,
11201                             unsigned ConstructKind,
11202                             SourceRange ParenRange) {
11203   bool Elidable = false;
11204 
11205   // C++0x [class.copy]p34:
11206   //   When certain criteria are met, an implementation is allowed to
11207   //   omit the copy/move construction of a class object, even if the
11208   //   copy/move constructor and/or destructor for the object have
11209   //   side effects. [...]
11210   //     - when a temporary class object that has not been bound to a
11211   //       reference (12.2) would be copied/moved to a class object
11212   //       with the same cv-unqualified type, the copy/move operation
11213   //       can be omitted by constructing the temporary object
11214   //       directly into the target of the omitted copy/move
11215   if (ConstructKind == CXXConstructExpr::CK_Complete &&
11216       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
11217     Expr *SubExpr = ExprArgs[0];
11218     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
11219   }
11220 
11221   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
11222                                Elidable, ExprArgs, HadMultipleCandidates,
11223                                IsListInitialization,
11224                                IsStdInitListInitialization, RequiresZeroInit,
11225                                ConstructKind, ParenRange);
11226 }
11227 
11228 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
11229 /// including handling of its default argument expressions.
11230 ExprResult
11231 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11232                             CXXConstructorDecl *Constructor, bool Elidable,
11233                             MultiExprArg ExprArgs,
11234                             bool HadMultipleCandidates,
11235                             bool IsListInitialization,
11236                             bool IsStdInitListInitialization,
11237                             bool RequiresZeroInit,
11238                             unsigned ConstructKind,
11239                             SourceRange ParenRange) {
11240   MarkFunctionReferenced(ConstructLoc, Constructor);
11241   return CXXConstructExpr::Create(
11242       Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
11243       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11244       RequiresZeroInit,
11245       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11246       ParenRange);
11247 }
11248 
11249 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11250   assert(Field->hasInClassInitializer());
11251 
11252   // If we already have the in-class initializer nothing needs to be done.
11253   if (Field->getInClassInitializer())
11254     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11255 
11256   // Maybe we haven't instantiated the in-class initializer. Go check the
11257   // pattern FieldDecl to see if it has one.
11258   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11259 
11260   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11261     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11262     DeclContext::lookup_result Lookup =
11263         ClassPattern->lookup(Field->getDeclName());
11264     assert(Lookup.size() == 1);
11265     FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11266     if (InstantiateInClassInitializer(Loc, Field, Pattern,
11267                                       getTemplateInstantiationArgs(Field)))
11268       return ExprError();
11269     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11270   }
11271 
11272   // DR1351:
11273   //   If the brace-or-equal-initializer of a non-static data member
11274   //   invokes a defaulted default constructor of its class or of an
11275   //   enclosing class in a potentially evaluated subexpression, the
11276   //   program is ill-formed.
11277   //
11278   // This resolution is unworkable: the exception specification of the
11279   // default constructor can be needed in an unevaluated context, in
11280   // particular, in the operand of a noexcept-expression, and we can be
11281   // unable to compute an exception specification for an enclosed class.
11282   //
11283   // Any attempt to resolve the exception specification of a defaulted default
11284   // constructor before the initializer is lexically complete will ultimately
11285   // come here at which point we can diagnose it.
11286   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11287   if (OutermostClass == ParentRD) {
11288     Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11289         << ParentRD << Field;
11290   } else {
11291     Diag(Field->getLocEnd(),
11292          diag::err_in_class_initializer_not_yet_parsed_outer_class)
11293         << ParentRD << OutermostClass << Field;
11294   }
11295 
11296   return ExprError();
11297 }
11298 
11299 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
11300   if (VD->isInvalidDecl()) return;
11301 
11302   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
11303   if (ClassDecl->isInvalidDecl()) return;
11304   if (ClassDecl->hasIrrelevantDestructor()) return;
11305   if (ClassDecl->isDependentContext()) return;
11306 
11307   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11308   MarkFunctionReferenced(VD->getLocation(), Destructor);
11309   CheckDestructorAccess(VD->getLocation(), Destructor,
11310                         PDiag(diag::err_access_dtor_var)
11311                         << VD->getDeclName()
11312                         << VD->getType());
11313   DiagnoseUseOfDecl(Destructor, VD->getLocation());
11314 
11315   if (Destructor->isTrivial()) return;
11316   if (!VD->hasGlobalStorage()) return;
11317 
11318   // Emit warning for non-trivial dtor in global scope (a real global,
11319   // class-static, function-static).
11320   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11321 
11322   // TODO: this should be re-enabled for static locals by !CXAAtExit
11323   if (!VD->isStaticLocal())
11324     Diag(VD->getLocation(), diag::warn_global_destructor);
11325 }
11326 
11327 /// \brief Given a constructor and the set of arguments provided for the
11328 /// constructor, convert the arguments and add any required default arguments
11329 /// to form a proper call to this constructor.
11330 ///
11331 /// \returns true if an error occurred, false otherwise.
11332 bool
11333 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11334                               MultiExprArg ArgsPtr,
11335                               SourceLocation Loc,
11336                               SmallVectorImpl<Expr*> &ConvertedArgs,
11337                               bool AllowExplicit,
11338                               bool IsListInitialization) {
11339   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11340   unsigned NumArgs = ArgsPtr.size();
11341   Expr **Args = ArgsPtr.data();
11342 
11343   const FunctionProtoType *Proto
11344     = Constructor->getType()->getAs<FunctionProtoType>();
11345   assert(Proto && "Constructor without a prototype?");
11346   unsigned NumParams = Proto->getNumParams();
11347 
11348   // If too few arguments are available, we'll fill in the rest with defaults.
11349   if (NumArgs < NumParams)
11350     ConvertedArgs.reserve(NumParams);
11351   else
11352     ConvertedArgs.reserve(NumArgs);
11353 
11354   VariadicCallType CallType =
11355     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
11356   SmallVector<Expr *, 8> AllArgs;
11357   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
11358                                         Proto, 0,
11359                                         llvm::makeArrayRef(Args, NumArgs),
11360                                         AllArgs,
11361                                         CallType, AllowExplicit,
11362                                         IsListInitialization);
11363   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
11364 
11365   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
11366 
11367   CheckConstructorCall(Constructor,
11368                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
11369                        Proto, Loc);
11370 
11371   return Invalid;
11372 }
11373 
11374 static inline bool
11375 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11376                                        const FunctionDecl *FnDecl) {
11377   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
11378   if (isa<NamespaceDecl>(DC)) {
11379     return SemaRef.Diag(FnDecl->getLocation(),
11380                         diag::err_operator_new_delete_declared_in_namespace)
11381       << FnDecl->getDeclName();
11382   }
11383 
11384   if (isa<TranslationUnitDecl>(DC) &&
11385       FnDecl->getStorageClass() == SC_Static) {
11386     return SemaRef.Diag(FnDecl->getLocation(),
11387                         diag::err_operator_new_delete_declared_static)
11388       << FnDecl->getDeclName();
11389   }
11390 
11391   return false;
11392 }
11393 
11394 static inline bool
11395 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11396                             CanQualType ExpectedResultType,
11397                             CanQualType ExpectedFirstParamType,
11398                             unsigned DependentParamTypeDiag,
11399                             unsigned InvalidParamTypeDiag) {
11400   QualType ResultType =
11401       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
11402 
11403   // Check that the result type is not dependent.
11404   if (ResultType->isDependentType())
11405     return SemaRef.Diag(FnDecl->getLocation(),
11406                         diag::err_operator_new_delete_dependent_result_type)
11407     << FnDecl->getDeclName() << ExpectedResultType;
11408 
11409   // Check that the result type is what we expect.
11410   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11411     return SemaRef.Diag(FnDecl->getLocation(),
11412                         diag::err_operator_new_delete_invalid_result_type)
11413     << FnDecl->getDeclName() << ExpectedResultType;
11414 
11415   // A function template must have at least 2 parameters.
11416   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11417     return SemaRef.Diag(FnDecl->getLocation(),
11418                       diag::err_operator_new_delete_template_too_few_parameters)
11419         << FnDecl->getDeclName();
11420 
11421   // The function decl must have at least 1 parameter.
11422   if (FnDecl->getNumParams() == 0)
11423     return SemaRef.Diag(FnDecl->getLocation(),
11424                         diag::err_operator_new_delete_too_few_parameters)
11425       << FnDecl->getDeclName();
11426 
11427   // Check the first parameter type is not dependent.
11428   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11429   if (FirstParamType->isDependentType())
11430     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11431       << FnDecl->getDeclName() << ExpectedFirstParamType;
11432 
11433   // Check that the first parameter type is what we expect.
11434   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
11435       ExpectedFirstParamType)
11436     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11437     << FnDecl->getDeclName() << ExpectedFirstParamType;
11438 
11439   return false;
11440 }
11441 
11442 static bool
11443 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
11444   // C++ [basic.stc.dynamic.allocation]p1:
11445   //   A program is ill-formed if an allocation function is declared in a
11446   //   namespace scope other than global scope or declared static in global
11447   //   scope.
11448   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11449     return true;
11450 
11451   CanQualType SizeTy =
11452     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11453 
11454   // C++ [basic.stc.dynamic.allocation]p1:
11455   //  The return type shall be void*. The first parameter shall have type
11456   //  std::size_t.
11457   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11458                                   SizeTy,
11459                                   diag::err_operator_new_dependent_param_type,
11460                                   diag::err_operator_new_param_type))
11461     return true;
11462 
11463   // C++ [basic.stc.dynamic.allocation]p1:
11464   //  The first parameter shall not have an associated default argument.
11465   if (FnDecl->getParamDecl(0)->hasDefaultArg())
11466     return SemaRef.Diag(FnDecl->getLocation(),
11467                         diag::err_operator_new_default_arg)
11468       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11469 
11470   return false;
11471 }
11472 
11473 static bool
11474 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11475   // C++ [basic.stc.dynamic.deallocation]p1:
11476   //   A program is ill-formed if deallocation functions are declared in a
11477   //   namespace scope other than global scope or declared static in global
11478   //   scope.
11479   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11480     return true;
11481 
11482   // C++ [basic.stc.dynamic.deallocation]p2:
11483   //   Each deallocation function shall return void and its first parameter
11484   //   shall be void*.
11485   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11486                                   SemaRef.Context.VoidPtrTy,
11487                                  diag::err_operator_delete_dependent_param_type,
11488                                  diag::err_operator_delete_param_type))
11489     return true;
11490 
11491   return false;
11492 }
11493 
11494 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11495 /// of this overloaded operator is well-formed. If so, returns false;
11496 /// otherwise, emits appropriate diagnostics and returns true.
11497 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11498   assert(FnDecl && FnDecl->isOverloadedOperator() &&
11499          "Expected an overloaded operator declaration");
11500 
11501   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11502 
11503   // C++ [over.oper]p5:
11504   //   The allocation and deallocation functions, operator new,
11505   //   operator new[], operator delete and operator delete[], are
11506   //   described completely in 3.7.3. The attributes and restrictions
11507   //   found in the rest of this subclause do not apply to them unless
11508   //   explicitly stated in 3.7.3.
11509   if (Op == OO_Delete || Op == OO_Array_Delete)
11510     return CheckOperatorDeleteDeclaration(*this, FnDecl);
11511 
11512   if (Op == OO_New || Op == OO_Array_New)
11513     return CheckOperatorNewDeclaration(*this, FnDecl);
11514 
11515   // C++ [over.oper]p6:
11516   //   An operator function shall either be a non-static member
11517   //   function or be a non-member function and have at least one
11518   //   parameter whose type is a class, a reference to a class, an
11519   //   enumeration, or a reference to an enumeration.
11520   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11521     if (MethodDecl->isStatic())
11522       return Diag(FnDecl->getLocation(),
11523                   diag::err_operator_overload_static) << FnDecl->getDeclName();
11524   } else {
11525     bool ClassOrEnumParam = false;
11526     for (auto Param : FnDecl->params()) {
11527       QualType ParamType = Param->getType().getNonReferenceType();
11528       if (ParamType->isDependentType() || ParamType->isRecordType() ||
11529           ParamType->isEnumeralType()) {
11530         ClassOrEnumParam = true;
11531         break;
11532       }
11533     }
11534 
11535     if (!ClassOrEnumParam)
11536       return Diag(FnDecl->getLocation(),
11537                   diag::err_operator_overload_needs_class_or_enum)
11538         << FnDecl->getDeclName();
11539   }
11540 
11541   // C++ [over.oper]p8:
11542   //   An operator function cannot have default arguments (8.3.6),
11543   //   except where explicitly stated below.
11544   //
11545   // Only the function-call operator allows default arguments
11546   // (C++ [over.call]p1).
11547   if (Op != OO_Call) {
11548     for (auto Param : FnDecl->params()) {
11549       if (Param->hasDefaultArg())
11550         return Diag(Param->getLocation(),
11551                     diag::err_operator_overload_default_arg)
11552           << FnDecl->getDeclName() << Param->getDefaultArgRange();
11553     }
11554   }
11555 
11556   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11557     { false, false, false }
11558 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11559     , { Unary, Binary, MemberOnly }
11560 #include "clang/Basic/OperatorKinds.def"
11561   };
11562 
11563   bool CanBeUnaryOperator = OperatorUses[Op][0];
11564   bool CanBeBinaryOperator = OperatorUses[Op][1];
11565   bool MustBeMemberOperator = OperatorUses[Op][2];
11566 
11567   // C++ [over.oper]p8:
11568   //   [...] Operator functions cannot have more or fewer parameters
11569   //   than the number required for the corresponding operator, as
11570   //   described in the rest of this subclause.
11571   unsigned NumParams = FnDecl->getNumParams()
11572                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11573   if (Op != OO_Call &&
11574       ((NumParams == 1 && !CanBeUnaryOperator) ||
11575        (NumParams == 2 && !CanBeBinaryOperator) ||
11576        (NumParams < 1) || (NumParams > 2))) {
11577     // We have the wrong number of parameters.
11578     unsigned ErrorKind;
11579     if (CanBeUnaryOperator && CanBeBinaryOperator) {
11580       ErrorKind = 2;  // 2 -> unary or binary.
11581     } else if (CanBeUnaryOperator) {
11582       ErrorKind = 0;  // 0 -> unary
11583     } else {
11584       assert(CanBeBinaryOperator &&
11585              "All non-call overloaded operators are unary or binary!");
11586       ErrorKind = 1;  // 1 -> binary
11587     }
11588 
11589     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11590       << FnDecl->getDeclName() << NumParams << ErrorKind;
11591   }
11592 
11593   // Overloaded operators other than operator() cannot be variadic.
11594   if (Op != OO_Call &&
11595       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11596     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11597       << FnDecl->getDeclName();
11598   }
11599 
11600   // Some operators must be non-static member functions.
11601   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11602     return Diag(FnDecl->getLocation(),
11603                 diag::err_operator_overload_must_be_member)
11604       << FnDecl->getDeclName();
11605   }
11606 
11607   // C++ [over.inc]p1:
11608   //   The user-defined function called operator++ implements the
11609   //   prefix and postfix ++ operator. If this function is a member
11610   //   function with no parameters, or a non-member function with one
11611   //   parameter of class or enumeration type, it defines the prefix
11612   //   increment operator ++ for objects of that type. If the function
11613   //   is a member function with one parameter (which shall be of type
11614   //   int) or a non-member function with two parameters (the second
11615   //   of which shall be of type int), it defines the postfix
11616   //   increment operator ++ for objects of that type.
11617   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11618     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11619     QualType ParamType = LastParam->getType();
11620 
11621     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11622         !ParamType->isDependentType())
11623       return Diag(LastParam->getLocation(),
11624                   diag::err_operator_overload_post_incdec_must_be_int)
11625         << LastParam->getType() << (Op == OO_MinusMinus);
11626   }
11627 
11628   return false;
11629 }
11630 
11631 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11632 /// of this literal operator function is well-formed. If so, returns
11633 /// false; otherwise, emits appropriate diagnostics and returns true.
11634 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11635   if (isa<CXXMethodDecl>(FnDecl)) {
11636     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11637       << FnDecl->getDeclName();
11638     return true;
11639   }
11640 
11641   if (FnDecl->isExternC()) {
11642     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11643     return true;
11644   }
11645 
11646   bool Valid = false;
11647 
11648   // This might be the definition of a literal operator template.
11649   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11650   // This might be a specialization of a literal operator template.
11651   if (!TpDecl)
11652     TpDecl = FnDecl->getPrimaryTemplate();
11653 
11654   // template <char...> type operator "" name() and
11655   // template <class T, T...> type operator "" name() are the only valid
11656   // template signatures, and the only valid signatures with no parameters.
11657   if (TpDecl) {
11658     if (FnDecl->param_size() == 0) {
11659       // Must have one or two template parameters
11660       TemplateParameterList *Params = TpDecl->getTemplateParameters();
11661       if (Params->size() == 1) {
11662         NonTypeTemplateParmDecl *PmDecl =
11663           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11664 
11665         // The template parameter must be a char parameter pack.
11666         if (PmDecl && PmDecl->isTemplateParameterPack() &&
11667             Context.hasSameType(PmDecl->getType(), Context.CharTy))
11668           Valid = true;
11669       } else if (Params->size() == 2) {
11670         TemplateTypeParmDecl *PmType =
11671           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11672         NonTypeTemplateParmDecl *PmArgs =
11673           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11674 
11675         // The second template parameter must be a parameter pack with the
11676         // first template parameter as its type.
11677         if (PmType && PmArgs &&
11678             !PmType->isTemplateParameterPack() &&
11679             PmArgs->isTemplateParameterPack()) {
11680           const TemplateTypeParmType *TArgs =
11681             PmArgs->getType()->getAs<TemplateTypeParmType>();
11682           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11683               TArgs->getIndex() == PmType->getIndex()) {
11684             Valid = true;
11685             if (ActiveTemplateInstantiations.empty())
11686               Diag(FnDecl->getLocation(),
11687                    diag::ext_string_literal_operator_template);
11688           }
11689         }
11690       }
11691     }
11692   } else if (FnDecl->param_size()) {
11693     // Check the first parameter
11694     FunctionDecl::param_iterator Param = FnDecl->param_begin();
11695 
11696     QualType T = (*Param)->getType().getUnqualifiedType();
11697 
11698     // unsigned long long int, long double, and any character type are allowed
11699     // as the only parameters.
11700     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11701         Context.hasSameType(T, Context.LongDoubleTy) ||
11702         Context.hasSameType(T, Context.CharTy) ||
11703         Context.hasSameType(T, Context.WideCharTy) ||
11704         Context.hasSameType(T, Context.Char16Ty) ||
11705         Context.hasSameType(T, Context.Char32Ty)) {
11706       if (++Param == FnDecl->param_end())
11707         Valid = true;
11708       goto FinishedParams;
11709     }
11710 
11711     // Otherwise it must be a pointer to const; let's strip those qualifiers.
11712     const PointerType *PT = T->getAs<PointerType>();
11713     if (!PT)
11714       goto FinishedParams;
11715     T = PT->getPointeeType();
11716     if (!T.isConstQualified() || T.isVolatileQualified())
11717       goto FinishedParams;
11718     T = T.getUnqualifiedType();
11719 
11720     // Move on to the second parameter;
11721     ++Param;
11722 
11723     // If there is no second parameter, the first must be a const char *
11724     if (Param == FnDecl->param_end()) {
11725       if (Context.hasSameType(T, Context.CharTy))
11726         Valid = true;
11727       goto FinishedParams;
11728     }
11729 
11730     // const char *, const wchar_t*, const char16_t*, and const char32_t*
11731     // are allowed as the first parameter to a two-parameter function
11732     if (!(Context.hasSameType(T, Context.CharTy) ||
11733           Context.hasSameType(T, Context.WideCharTy) ||
11734           Context.hasSameType(T, Context.Char16Ty) ||
11735           Context.hasSameType(T, Context.Char32Ty)))
11736       goto FinishedParams;
11737 
11738     // The second and final parameter must be an std::size_t
11739     T = (*Param)->getType().getUnqualifiedType();
11740     if (Context.hasSameType(T, Context.getSizeType()) &&
11741         ++Param == FnDecl->param_end())
11742       Valid = true;
11743   }
11744 
11745   // FIXME: This diagnostic is absolutely terrible.
11746 FinishedParams:
11747   if (!Valid) {
11748     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11749       << FnDecl->getDeclName();
11750     return true;
11751   }
11752 
11753   // A parameter-declaration-clause containing a default argument is not
11754   // equivalent to any of the permitted forms.
11755   for (auto Param : FnDecl->params()) {
11756     if (Param->hasDefaultArg()) {
11757       Diag(Param->getDefaultArgRange().getBegin(),
11758            diag::err_literal_operator_default_argument)
11759         << Param->getDefaultArgRange();
11760       break;
11761     }
11762   }
11763 
11764   StringRef LiteralName
11765     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11766   if (LiteralName[0] != '_') {
11767     // C++11 [usrlit.suffix]p1:
11768     //   Literal suffix identifiers that do not start with an underscore
11769     //   are reserved for future standardization.
11770     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11771       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11772   }
11773 
11774   return false;
11775 }
11776 
11777 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11778 /// linkage specification, including the language and (if present)
11779 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11780 /// language string literal. LBraceLoc, if valid, provides the location of
11781 /// the '{' brace. Otherwise, this linkage specification does not
11782 /// have any braces.
11783 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11784                                            Expr *LangStr,
11785                                            SourceLocation LBraceLoc) {
11786   StringLiteral *Lit = cast<StringLiteral>(LangStr);
11787   if (!Lit->isAscii()) {
11788     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11789       << LangStr->getSourceRange();
11790     return nullptr;
11791   }
11792 
11793   StringRef Lang = Lit->getString();
11794   LinkageSpecDecl::LanguageIDs Language;
11795   if (Lang == "C")
11796     Language = LinkageSpecDecl::lang_c;
11797   else if (Lang == "C++")
11798     Language = LinkageSpecDecl::lang_cxx;
11799   else {
11800     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11801       << LangStr->getSourceRange();
11802     return nullptr;
11803   }
11804 
11805   // FIXME: Add all the various semantics of linkage specifications
11806 
11807   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11808                                                LangStr->getExprLoc(), Language,
11809                                                LBraceLoc.isValid());
11810   CurContext->addDecl(D);
11811   PushDeclContext(S, D);
11812   return D;
11813 }
11814 
11815 /// ActOnFinishLinkageSpecification - Complete the definition of
11816 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11817 /// valid, it's the position of the closing '}' brace in a linkage
11818 /// specification that uses braces.
11819 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11820                                             Decl *LinkageSpec,
11821                                             SourceLocation RBraceLoc) {
11822   if (RBraceLoc.isValid()) {
11823     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11824     LSDecl->setRBraceLoc(RBraceLoc);
11825   }
11826   PopDeclContext();
11827   return LinkageSpec;
11828 }
11829 
11830 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11831                                   AttributeList *AttrList,
11832                                   SourceLocation SemiLoc) {
11833   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11834   // Attribute declarations appertain to empty declaration so we handle
11835   // them here.
11836   if (AttrList)
11837     ProcessDeclAttributeList(S, ED, AttrList);
11838 
11839   CurContext->addDecl(ED);
11840   return ED;
11841 }
11842 
11843 /// \brief Perform semantic analysis for the variable declaration that
11844 /// occurs within a C++ catch clause, returning the newly-created
11845 /// variable.
11846 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11847                                          TypeSourceInfo *TInfo,
11848                                          SourceLocation StartLoc,
11849                                          SourceLocation Loc,
11850                                          IdentifierInfo *Name) {
11851   bool Invalid = false;
11852   QualType ExDeclType = TInfo->getType();
11853 
11854   // Arrays and functions decay.
11855   if (ExDeclType->isArrayType())
11856     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11857   else if (ExDeclType->isFunctionType())
11858     ExDeclType = Context.getPointerType(ExDeclType);
11859 
11860   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11861   // The exception-declaration shall not denote a pointer or reference to an
11862   // incomplete type, other than [cv] void*.
11863   // N2844 forbids rvalue references.
11864   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11865     Diag(Loc, diag::err_catch_rvalue_ref);
11866     Invalid = true;
11867   }
11868 
11869   QualType BaseType = ExDeclType;
11870   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11871   unsigned DK = diag::err_catch_incomplete;
11872   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11873     BaseType = Ptr->getPointeeType();
11874     Mode = 1;
11875     DK = diag::err_catch_incomplete_ptr;
11876   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11877     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11878     BaseType = Ref->getPointeeType();
11879     Mode = 2;
11880     DK = diag::err_catch_incomplete_ref;
11881   }
11882   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11883       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11884     Invalid = true;
11885 
11886   if (!Invalid && !ExDeclType->isDependentType() &&
11887       RequireNonAbstractType(Loc, ExDeclType,
11888                              diag::err_abstract_type_in_decl,
11889                              AbstractVariableType))
11890     Invalid = true;
11891 
11892   // Only the non-fragile NeXT runtime currently supports C++ catches
11893   // of ObjC types, and no runtime supports catching ObjC types by value.
11894   if (!Invalid && getLangOpts().ObjC1) {
11895     QualType T = ExDeclType;
11896     if (const ReferenceType *RT = T->getAs<ReferenceType>())
11897       T = RT->getPointeeType();
11898 
11899     if (T->isObjCObjectType()) {
11900       Diag(Loc, diag::err_objc_object_catch);
11901       Invalid = true;
11902     } else if (T->isObjCObjectPointerType()) {
11903       // FIXME: should this be a test for macosx-fragile specifically?
11904       if (getLangOpts().ObjCRuntime.isFragile())
11905         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
11906     }
11907   }
11908 
11909   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
11910                                     ExDeclType, TInfo, SC_None);
11911   ExDecl->setExceptionVariable(true);
11912 
11913   // In ARC, infer 'retaining' for variables of retainable type.
11914   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
11915     Invalid = true;
11916 
11917   if (!Invalid && !ExDeclType->isDependentType()) {
11918     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
11919       // Insulate this from anything else we might currently be parsing.
11920       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11921 
11922       // C++ [except.handle]p16:
11923       //   The object declared in an exception-declaration or, if the
11924       //   exception-declaration does not specify a name, a temporary (12.2) is
11925       //   copy-initialized (8.5) from the exception object. [...]
11926       //   The object is destroyed when the handler exits, after the destruction
11927       //   of any automatic objects initialized within the handler.
11928       //
11929       // We just pretend to initialize the object with itself, then make sure
11930       // it can be destroyed later.
11931       QualType initType = ExDeclType;
11932 
11933       InitializedEntity entity =
11934         InitializedEntity::InitializeVariable(ExDecl);
11935       InitializationKind initKind =
11936         InitializationKind::CreateCopy(Loc, SourceLocation());
11937 
11938       Expr *opaqueValue =
11939         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
11940       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11941       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
11942       if (result.isInvalid())
11943         Invalid = true;
11944       else {
11945         // If the constructor used was non-trivial, set this as the
11946         // "initializer".
11947         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
11948         if (!construct->getConstructor()->isTrivial()) {
11949           Expr *init = MaybeCreateExprWithCleanups(construct);
11950           ExDecl->setInit(init);
11951         }
11952 
11953         // And make sure it's destructable.
11954         FinalizeVarWithDestructor(ExDecl, recordType);
11955       }
11956     }
11957   }
11958 
11959   if (Invalid)
11960     ExDecl->setInvalidDecl();
11961 
11962   return ExDecl;
11963 }
11964 
11965 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11966 /// handler.
11967 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
11968   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11969   bool Invalid = D.isInvalidType();
11970 
11971   // Check for unexpanded parameter packs.
11972   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11973                                       UPPC_ExceptionType)) {
11974     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11975                                              D.getIdentifierLoc());
11976     Invalid = true;
11977   }
11978 
11979   IdentifierInfo *II = D.getIdentifier();
11980   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11981                                              LookupOrdinaryName,
11982                                              ForRedeclaration)) {
11983     // The scope should be freshly made just for us. There is just no way
11984     // it contains any previous declaration, except for function parameters in
11985     // a function-try-block's catch statement.
11986     assert(!S->isDeclScope(PrevDecl));
11987     if (isDeclInScope(PrevDecl, CurContext, S)) {
11988       Diag(D.getIdentifierLoc(), diag::err_redefinition)
11989         << D.getIdentifier();
11990       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11991       Invalid = true;
11992     } else if (PrevDecl->isTemplateParameter())
11993       // Maybe we will complain about the shadowed template parameter.
11994       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11995   }
11996 
11997   if (D.getCXXScopeSpec().isSet() && !Invalid) {
11998     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11999       << D.getCXXScopeSpec().getRange();
12000     Invalid = true;
12001   }
12002 
12003   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
12004                                               D.getLocStart(),
12005                                               D.getIdentifierLoc(),
12006                                               D.getIdentifier());
12007   if (Invalid)
12008     ExDecl->setInvalidDecl();
12009 
12010   // Add the exception declaration into this scope.
12011   if (II)
12012     PushOnScopeChains(ExDecl, S);
12013   else
12014     CurContext->addDecl(ExDecl);
12015 
12016   ProcessDeclAttributes(S, ExDecl, D);
12017   return ExDecl;
12018 }
12019 
12020 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12021                                          Expr *AssertExpr,
12022                                          Expr *AssertMessageExpr,
12023                                          SourceLocation RParenLoc) {
12024   StringLiteral *AssertMessage =
12025       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
12026 
12027   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
12028     return nullptr;
12029 
12030   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12031                                       AssertMessage, RParenLoc, false);
12032 }
12033 
12034 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12035                                          Expr *AssertExpr,
12036                                          StringLiteral *AssertMessage,
12037                                          SourceLocation RParenLoc,
12038                                          bool Failed) {
12039   assert(AssertExpr != nullptr && "Expected non-null condition");
12040   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12041       !Failed) {
12042     // In a static_assert-declaration, the constant-expression shall be a
12043     // constant expression that can be contextually converted to bool.
12044     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12045     if (Converted.isInvalid())
12046       Failed = true;
12047 
12048     llvm::APSInt Cond;
12049     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
12050           diag::err_static_assert_expression_is_not_constant,
12051           /*AllowFold=*/false).isInvalid())
12052       Failed = true;
12053 
12054     if (!Failed && !Cond) {
12055       SmallString<256> MsgBuffer;
12056       llvm::raw_svector_ostream Msg(MsgBuffer);
12057       if (AssertMessage)
12058         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
12059       Diag(StaticAssertLoc, diag::err_static_assert_failed)
12060         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
12061       Failed = true;
12062     }
12063   }
12064 
12065   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
12066                                         AssertExpr, AssertMessage, RParenLoc,
12067                                         Failed);
12068 
12069   CurContext->addDecl(Decl);
12070   return Decl;
12071 }
12072 
12073 /// \brief Perform semantic analysis of the given friend type declaration.
12074 ///
12075 /// \returns A friend declaration that.
12076 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
12077                                       SourceLocation FriendLoc,
12078                                       TypeSourceInfo *TSInfo) {
12079   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12080 
12081   QualType T = TSInfo->getType();
12082   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
12083 
12084   // C++03 [class.friend]p2:
12085   //   An elaborated-type-specifier shall be used in a friend declaration
12086   //   for a class.*
12087   //
12088   //   * The class-key of the elaborated-type-specifier is required.
12089   if (!ActiveTemplateInstantiations.empty()) {
12090     // Do not complain about the form of friend template types during
12091     // template instantiation; we will already have complained when the
12092     // template was declared.
12093   } else {
12094     if (!T->isElaboratedTypeSpecifier()) {
12095       // If we evaluated the type to a record type, suggest putting
12096       // a tag in front.
12097       if (const RecordType *RT = T->getAs<RecordType>()) {
12098         RecordDecl *RD = RT->getDecl();
12099 
12100         SmallString<16> InsertionText(" ");
12101         InsertionText += RD->getKindName();
12102 
12103         Diag(TypeRange.getBegin(),
12104              getLangOpts().CPlusPlus11 ?
12105                diag::warn_cxx98_compat_unelaborated_friend_type :
12106                diag::ext_unelaborated_friend_type)
12107           << (unsigned) RD->getTagKind()
12108           << T
12109           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
12110                                         InsertionText);
12111       } else {
12112         Diag(FriendLoc,
12113              getLangOpts().CPlusPlus11 ?
12114                diag::warn_cxx98_compat_nonclass_type_friend :
12115                diag::ext_nonclass_type_friend)
12116           << T
12117           << TypeRange;
12118       }
12119     } else if (T->getAs<EnumType>()) {
12120       Diag(FriendLoc,
12121            getLangOpts().CPlusPlus11 ?
12122              diag::warn_cxx98_compat_enum_friend :
12123              diag::ext_enum_friend)
12124         << T
12125         << TypeRange;
12126     }
12127 
12128     // C++11 [class.friend]p3:
12129     //   A friend declaration that does not declare a function shall have one
12130     //   of the following forms:
12131     //     friend elaborated-type-specifier ;
12132     //     friend simple-type-specifier ;
12133     //     friend typename-specifier ;
12134     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12135       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12136   }
12137 
12138   //   If the type specifier in a friend declaration designates a (possibly
12139   //   cv-qualified) class type, that class is declared as a friend; otherwise,
12140   //   the friend declaration is ignored.
12141   return FriendDecl::Create(Context, CurContext,
12142                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
12143                             FriendLoc);
12144 }
12145 
12146 /// Handle a friend tag declaration where the scope specifier was
12147 /// templated.
12148 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12149                                     unsigned TagSpec, SourceLocation TagLoc,
12150                                     CXXScopeSpec &SS,
12151                                     IdentifierInfo *Name,
12152                                     SourceLocation NameLoc,
12153                                     AttributeList *Attr,
12154                                     MultiTemplateParamsArg TempParamLists) {
12155   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12156 
12157   bool isExplicitSpecialization = false;
12158   bool Invalid = false;
12159 
12160   if (TemplateParameterList *TemplateParams =
12161           MatchTemplateParametersToScopeSpecifier(
12162               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
12163               isExplicitSpecialization, Invalid)) {
12164     if (TemplateParams->size() > 0) {
12165       // This is a declaration of a class template.
12166       if (Invalid)
12167         return nullptr;
12168 
12169       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12170                                 NameLoc, Attr, TemplateParams, AS_public,
12171                                 /*ModulePrivateLoc=*/SourceLocation(),
12172                                 FriendLoc, TempParamLists.size() - 1,
12173                                 TempParamLists.data()).get();
12174     } else {
12175       // The "template<>" header is extraneous.
12176       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12177         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12178       isExplicitSpecialization = true;
12179     }
12180   }
12181 
12182   if (Invalid) return nullptr;
12183 
12184   bool isAllExplicitSpecializations = true;
12185   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
12186     if (TempParamLists[I]->size()) {
12187       isAllExplicitSpecializations = false;
12188       break;
12189     }
12190   }
12191 
12192   // FIXME: don't ignore attributes.
12193 
12194   // If it's explicit specializations all the way down, just forget
12195   // about the template header and build an appropriate non-templated
12196   // friend.  TODO: for source fidelity, remember the headers.
12197   if (isAllExplicitSpecializations) {
12198     if (SS.isEmpty()) {
12199       bool Owned = false;
12200       bool IsDependent = false;
12201       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
12202                       Attr, AS_public,
12203                       /*ModulePrivateLoc=*/SourceLocation(),
12204                       MultiTemplateParamsArg(), Owned, IsDependent,
12205                       /*ScopedEnumKWLoc=*/SourceLocation(),
12206                       /*ScopedEnumUsesClassTag=*/false,
12207                       /*UnderlyingType=*/TypeResult(),
12208                       /*IsTypeSpecifier=*/false);
12209     }
12210 
12211     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12212     ElaboratedTypeKeyword Keyword
12213       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12214     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
12215                                    *Name, NameLoc);
12216     if (T.isNull())
12217       return nullptr;
12218 
12219     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12220     if (isa<DependentNameType>(T)) {
12221       DependentNameTypeLoc TL =
12222           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12223       TL.setElaboratedKeywordLoc(TagLoc);
12224       TL.setQualifierLoc(QualifierLoc);
12225       TL.setNameLoc(NameLoc);
12226     } else {
12227       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
12228       TL.setElaboratedKeywordLoc(TagLoc);
12229       TL.setQualifierLoc(QualifierLoc);
12230       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
12231     }
12232 
12233     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12234                                             TSI, FriendLoc, TempParamLists);
12235     Friend->setAccess(AS_public);
12236     CurContext->addDecl(Friend);
12237     return Friend;
12238   }
12239 
12240   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12241 
12242 
12243 
12244   // Handle the case of a templated-scope friend class.  e.g.
12245   //   template <class T> class A<T>::B;
12246   // FIXME: we don't support these right now.
12247   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12248     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
12249   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12250   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12251   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12252   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12253   TL.setElaboratedKeywordLoc(TagLoc);
12254   TL.setQualifierLoc(SS.getWithLocInContext(Context));
12255   TL.setNameLoc(NameLoc);
12256 
12257   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12258                                           TSI, FriendLoc, TempParamLists);
12259   Friend->setAccess(AS_public);
12260   Friend->setUnsupportedFriend(true);
12261   CurContext->addDecl(Friend);
12262   return Friend;
12263 }
12264 
12265 
12266 /// Handle a friend type declaration.  This works in tandem with
12267 /// ActOnTag.
12268 ///
12269 /// Notes on friend class templates:
12270 ///
12271 /// We generally treat friend class declarations as if they were
12272 /// declaring a class.  So, for example, the elaborated type specifier
12273 /// in a friend declaration is required to obey the restrictions of a
12274 /// class-head (i.e. no typedefs in the scope chain), template
12275 /// parameters are required to match up with simple template-ids, &c.
12276 /// However, unlike when declaring a template specialization, it's
12277 /// okay to refer to a template specialization without an empty
12278 /// template parameter declaration, e.g.
12279 ///   friend class A<T>::B<unsigned>;
12280 /// We permit this as a special case; if there are any template
12281 /// parameters present at all, require proper matching, i.e.
12282 ///   template <> template \<class T> friend class A<int>::B;
12283 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
12284                                 MultiTemplateParamsArg TempParams) {
12285   SourceLocation Loc = DS.getLocStart();
12286 
12287   assert(DS.isFriendSpecified());
12288   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12289 
12290   // Try to convert the decl specifier to a type.  This works for
12291   // friend templates because ActOnTag never produces a ClassTemplateDecl
12292   // for a TUK_Friend.
12293   Declarator TheDeclarator(DS, Declarator::MemberContext);
12294   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12295   QualType T = TSI->getType();
12296   if (TheDeclarator.isInvalidType())
12297     return nullptr;
12298 
12299   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
12300     return nullptr;
12301 
12302   // This is definitely an error in C++98.  It's probably meant to
12303   // be forbidden in C++0x, too, but the specification is just
12304   // poorly written.
12305   //
12306   // The problem is with declarations like the following:
12307   //   template <T> friend A<T>::foo;
12308   // where deciding whether a class C is a friend or not now hinges
12309   // on whether there exists an instantiation of A that causes
12310   // 'foo' to equal C.  There are restrictions on class-heads
12311   // (which we declare (by fiat) elaborated friend declarations to
12312   // be) that makes this tractable.
12313   //
12314   // FIXME: handle "template <> friend class A<T>;", which
12315   // is possibly well-formed?  Who even knows?
12316   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
12317     Diag(Loc, diag::err_tagless_friend_type_template)
12318       << DS.getSourceRange();
12319     return nullptr;
12320   }
12321 
12322   // C++98 [class.friend]p1: A friend of a class is a function
12323   //   or class that is not a member of the class . . .
12324   // This is fixed in DR77, which just barely didn't make the C++03
12325   // deadline.  It's also a very silly restriction that seriously
12326   // affects inner classes and which nobody else seems to implement;
12327   // thus we never diagnose it, not even in -pedantic.
12328   //
12329   // But note that we could warn about it: it's always useless to
12330   // friend one of your own members (it's not, however, worthless to
12331   // friend a member of an arbitrary specialization of your template).
12332 
12333   Decl *D;
12334   if (unsigned NumTempParamLists = TempParams.size())
12335     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
12336                                    NumTempParamLists,
12337                                    TempParams.data(),
12338                                    TSI,
12339                                    DS.getFriendSpecLoc());
12340   else
12341     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
12342 
12343   if (!D)
12344     return nullptr;
12345 
12346   D->setAccess(AS_public);
12347   CurContext->addDecl(D);
12348 
12349   return D;
12350 }
12351 
12352 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12353                                         MultiTemplateParamsArg TemplateParams) {
12354   const DeclSpec &DS = D.getDeclSpec();
12355 
12356   assert(DS.isFriendSpecified());
12357   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12358 
12359   SourceLocation Loc = D.getIdentifierLoc();
12360   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12361 
12362   // C++ [class.friend]p1
12363   //   A friend of a class is a function or class....
12364   // Note that this sees through typedefs, which is intended.
12365   // It *doesn't* see through dependent types, which is correct
12366   // according to [temp.arg.type]p3:
12367   //   If a declaration acquires a function type through a
12368   //   type dependent on a template-parameter and this causes
12369   //   a declaration that does not use the syntactic form of a
12370   //   function declarator to have a function type, the program
12371   //   is ill-formed.
12372   if (!TInfo->getType()->isFunctionType()) {
12373     Diag(Loc, diag::err_unexpected_friend);
12374 
12375     // It might be worthwhile to try to recover by creating an
12376     // appropriate declaration.
12377     return nullptr;
12378   }
12379 
12380   // C++ [namespace.memdef]p3
12381   //  - If a friend declaration in a non-local class first declares a
12382   //    class or function, the friend class or function is a member
12383   //    of the innermost enclosing namespace.
12384   //  - The name of the friend is not found by simple name lookup
12385   //    until a matching declaration is provided in that namespace
12386   //    scope (either before or after the class declaration granting
12387   //    friendship).
12388   //  - If a friend function is called, its name may be found by the
12389   //    name lookup that considers functions from namespaces and
12390   //    classes associated with the types of the function arguments.
12391   //  - When looking for a prior declaration of a class or a function
12392   //    declared as a friend, scopes outside the innermost enclosing
12393   //    namespace scope are not considered.
12394 
12395   CXXScopeSpec &SS = D.getCXXScopeSpec();
12396   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12397   DeclarationName Name = NameInfo.getName();
12398   assert(Name);
12399 
12400   // Check for unexpanded parameter packs.
12401   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12402       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12403       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
12404     return nullptr;
12405 
12406   // The context we found the declaration in, or in which we should
12407   // create the declaration.
12408   DeclContext *DC;
12409   Scope *DCScope = S;
12410   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12411                         ForRedeclaration);
12412 
12413   // There are five cases here.
12414   //   - There's no scope specifier and we're in a local class. Only look
12415   //     for functions declared in the immediately-enclosing block scope.
12416   // We recover from invalid scope qualifiers as if they just weren't there.
12417   FunctionDecl *FunctionContainingLocalClass = nullptr;
12418   if ((SS.isInvalid() || !SS.isSet()) &&
12419       (FunctionContainingLocalClass =
12420            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12421     // C++11 [class.friend]p11:
12422     //   If a friend declaration appears in a local class and the name
12423     //   specified is an unqualified name, a prior declaration is
12424     //   looked up without considering scopes that are outside the
12425     //   innermost enclosing non-class scope. For a friend function
12426     //   declaration, if there is no prior declaration, the program is
12427     //   ill-formed.
12428 
12429     // Find the innermost enclosing non-class scope. This is the block
12430     // scope containing the local class definition (or for a nested class,
12431     // the outer local class).
12432     DCScope = S->getFnParent();
12433 
12434     // Look up the function name in the scope.
12435     Previous.clear(LookupLocalFriendName);
12436     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12437 
12438     if (!Previous.empty()) {
12439       // All possible previous declarations must have the same context:
12440       // either they were declared at block scope or they are members of
12441       // one of the enclosing local classes.
12442       DC = Previous.getRepresentativeDecl()->getDeclContext();
12443     } else {
12444       // This is ill-formed, but provide the context that we would have
12445       // declared the function in, if we were permitted to, for error recovery.
12446       DC = FunctionContainingLocalClass;
12447     }
12448     adjustContextForLocalExternDecl(DC);
12449 
12450     // C++ [class.friend]p6:
12451     //   A function can be defined in a friend declaration of a class if and
12452     //   only if the class is a non-local class (9.8), the function name is
12453     //   unqualified, and the function has namespace scope.
12454     if (D.isFunctionDefinition()) {
12455       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12456     }
12457 
12458   //   - There's no scope specifier, in which case we just go to the
12459   //     appropriate scope and look for a function or function template
12460   //     there as appropriate.
12461   } else if (SS.isInvalid() || !SS.isSet()) {
12462     // C++11 [namespace.memdef]p3:
12463     //   If the name in a friend declaration is neither qualified nor
12464     //   a template-id and the declaration is a function or an
12465     //   elaborated-type-specifier, the lookup to determine whether
12466     //   the entity has been previously declared shall not consider
12467     //   any scopes outside the innermost enclosing namespace.
12468     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12469 
12470     // Find the appropriate context according to the above.
12471     DC = CurContext;
12472 
12473     // Skip class contexts.  If someone can cite chapter and verse
12474     // for this behavior, that would be nice --- it's what GCC and
12475     // EDG do, and it seems like a reasonable intent, but the spec
12476     // really only says that checks for unqualified existing
12477     // declarations should stop at the nearest enclosing namespace,
12478     // not that they should only consider the nearest enclosing
12479     // namespace.
12480     while (DC->isRecord())
12481       DC = DC->getParent();
12482 
12483     DeclContext *LookupDC = DC;
12484     while (LookupDC->isTransparentContext())
12485       LookupDC = LookupDC->getParent();
12486 
12487     while (true) {
12488       LookupQualifiedName(Previous, LookupDC);
12489 
12490       if (!Previous.empty()) {
12491         DC = LookupDC;
12492         break;
12493       }
12494 
12495       if (isTemplateId) {
12496         if (isa<TranslationUnitDecl>(LookupDC)) break;
12497       } else {
12498         if (LookupDC->isFileContext()) break;
12499       }
12500       LookupDC = LookupDC->getParent();
12501     }
12502 
12503     DCScope = getScopeForDeclContext(S, DC);
12504 
12505   //   - There's a non-dependent scope specifier, in which case we
12506   //     compute it and do a previous lookup there for a function
12507   //     or function template.
12508   } else if (!SS.getScopeRep()->isDependent()) {
12509     DC = computeDeclContext(SS);
12510     if (!DC) return nullptr;
12511 
12512     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12513 
12514     LookupQualifiedName(Previous, DC);
12515 
12516     // Ignore things found implicitly in the wrong scope.
12517     // TODO: better diagnostics for this case.  Suggesting the right
12518     // qualified scope would be nice...
12519     LookupResult::Filter F = Previous.makeFilter();
12520     while (F.hasNext()) {
12521       NamedDecl *D = F.next();
12522       if (!DC->InEnclosingNamespaceSetOf(
12523               D->getDeclContext()->getRedeclContext()))
12524         F.erase();
12525     }
12526     F.done();
12527 
12528     if (Previous.empty()) {
12529       D.setInvalidType();
12530       Diag(Loc, diag::err_qualified_friend_not_found)
12531           << Name << TInfo->getType();
12532       return nullptr;
12533     }
12534 
12535     // C++ [class.friend]p1: A friend of a class is a function or
12536     //   class that is not a member of the class . . .
12537     if (DC->Equals(CurContext))
12538       Diag(DS.getFriendSpecLoc(),
12539            getLangOpts().CPlusPlus11 ?
12540              diag::warn_cxx98_compat_friend_is_member :
12541              diag::err_friend_is_member);
12542 
12543     if (D.isFunctionDefinition()) {
12544       // C++ [class.friend]p6:
12545       //   A function can be defined in a friend declaration of a class if and
12546       //   only if the class is a non-local class (9.8), the function name is
12547       //   unqualified, and the function has namespace scope.
12548       SemaDiagnosticBuilder DB
12549         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12550 
12551       DB << SS.getScopeRep();
12552       if (DC->isFileContext())
12553         DB << FixItHint::CreateRemoval(SS.getRange());
12554       SS.clear();
12555     }
12556 
12557   //   - There's a scope specifier that does not match any template
12558   //     parameter lists, in which case we use some arbitrary context,
12559   //     create a method or method template, and wait for instantiation.
12560   //   - There's a scope specifier that does match some template
12561   //     parameter lists, which we don't handle right now.
12562   } else {
12563     if (D.isFunctionDefinition()) {
12564       // C++ [class.friend]p6:
12565       //   A function can be defined in a friend declaration of a class if and
12566       //   only if the class is a non-local class (9.8), the function name is
12567       //   unqualified, and the function has namespace scope.
12568       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12569         << SS.getScopeRep();
12570     }
12571 
12572     DC = CurContext;
12573     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12574   }
12575 
12576   if (!DC->isRecord()) {
12577     // This implies that it has to be an operator or function.
12578     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12579         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12580         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
12581       Diag(Loc, diag::err_introducing_special_friend) <<
12582         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12583          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
12584       return nullptr;
12585     }
12586   }
12587 
12588   // FIXME: This is an egregious hack to cope with cases where the scope stack
12589   // does not contain the declaration context, i.e., in an out-of-line
12590   // definition of a class.
12591   Scope FakeDCScope(S, Scope::DeclScope, Diags);
12592   if (!DCScope) {
12593     FakeDCScope.setEntity(DC);
12594     DCScope = &FakeDCScope;
12595   }
12596 
12597   bool AddToScope = true;
12598   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12599                                           TemplateParams, AddToScope);
12600   if (!ND) return nullptr;
12601 
12602   assert(ND->getLexicalDeclContext() == CurContext);
12603 
12604   // If we performed typo correction, we might have added a scope specifier
12605   // and changed the decl context.
12606   DC = ND->getDeclContext();
12607 
12608   // Add the function declaration to the appropriate lookup tables,
12609   // adjusting the redeclarations list as necessary.  We don't
12610   // want to do this yet if the friending class is dependent.
12611   //
12612   // Also update the scope-based lookup if the target context's
12613   // lookup context is in lexical scope.
12614   if (!CurContext->isDependentContext()) {
12615     DC = DC->getRedeclContext();
12616     DC->makeDeclVisibleInContext(ND);
12617     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12618       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12619   }
12620 
12621   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12622                                        D.getIdentifierLoc(), ND,
12623                                        DS.getFriendSpecLoc());
12624   FrD->setAccess(AS_public);
12625   CurContext->addDecl(FrD);
12626 
12627   if (ND->isInvalidDecl()) {
12628     FrD->setInvalidDecl();
12629   } else {
12630     if (DC->isRecord()) CheckFriendAccess(ND);
12631 
12632     FunctionDecl *FD;
12633     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12634       FD = FTD->getTemplatedDecl();
12635     else
12636       FD = cast<FunctionDecl>(ND);
12637 
12638     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12639     // default argument expression, that declaration shall be a definition
12640     // and shall be the only declaration of the function or function
12641     // template in the translation unit.
12642     if (functionDeclHasDefaultArgument(FD)) {
12643       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12644         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12645         Diag(OldFD->getLocation(), diag::note_previous_declaration);
12646       } else if (!D.isFunctionDefinition())
12647         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12648     }
12649 
12650     // Mark templated-scope function declarations as unsupported.
12651     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12652       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12653         << SS.getScopeRep() << SS.getRange()
12654         << cast<CXXRecordDecl>(CurContext);
12655       FrD->setUnsupportedFriend(true);
12656     }
12657   }
12658 
12659   return ND;
12660 }
12661 
12662 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12663   AdjustDeclIfTemplate(Dcl);
12664 
12665   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12666   if (!Fn) {
12667     Diag(DelLoc, diag::err_deleted_non_function);
12668     return;
12669   }
12670 
12671   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12672     // Don't consider the implicit declaration we generate for explicit
12673     // specializations. FIXME: Do not generate these implicit declarations.
12674     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12675          Prev->getPreviousDecl()) &&
12676         !Prev->isDefined()) {
12677       Diag(DelLoc, diag::err_deleted_decl_not_first);
12678       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12679            Prev->isImplicit() ? diag::note_previous_implicit_declaration
12680                               : diag::note_previous_declaration);
12681     }
12682     // If the declaration wasn't the first, we delete the function anyway for
12683     // recovery.
12684     Fn = Fn->getCanonicalDecl();
12685   }
12686 
12687   // dllimport/dllexport cannot be deleted.
12688   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12689     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12690     Fn->setInvalidDecl();
12691   }
12692 
12693   if (Fn->isDeleted())
12694     return;
12695 
12696   // See if we're deleting a function which is already known to override a
12697   // non-deleted virtual function.
12698   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12699     bool IssuedDiagnostic = false;
12700     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12701                                         E = MD->end_overridden_methods();
12702          I != E; ++I) {
12703       if (!(*MD->begin_overridden_methods())->isDeleted()) {
12704         if (!IssuedDiagnostic) {
12705           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12706           IssuedDiagnostic = true;
12707         }
12708         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12709       }
12710     }
12711   }
12712 
12713   // C++11 [basic.start.main]p3:
12714   //   A program that defines main as deleted [...] is ill-formed.
12715   if (Fn->isMain())
12716     Diag(DelLoc, diag::err_deleted_main);
12717 
12718   Fn->setDeletedAsWritten();
12719 }
12720 
12721 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12722   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12723 
12724   if (MD) {
12725     if (MD->getParent()->isDependentType()) {
12726       MD->setDefaulted();
12727       MD->setExplicitlyDefaulted();
12728       return;
12729     }
12730 
12731     CXXSpecialMember Member = getSpecialMember(MD);
12732     if (Member == CXXInvalid) {
12733       if (!MD->isInvalidDecl())
12734         Diag(DefaultLoc, diag::err_default_special_members);
12735       return;
12736     }
12737 
12738     MD->setDefaulted();
12739     MD->setExplicitlyDefaulted();
12740 
12741     // If this definition appears within the record, do the checking when
12742     // the record is complete.
12743     const FunctionDecl *Primary = MD;
12744     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12745       // Find the uninstantiated declaration that actually had the '= default'
12746       // on it.
12747       Pattern->isDefined(Primary);
12748 
12749     // If the method was defaulted on its first declaration, we will have
12750     // already performed the checking in CheckCompletedCXXClass. Such a
12751     // declaration doesn't trigger an implicit definition.
12752     if (Primary == Primary->getCanonicalDecl())
12753       return;
12754 
12755     CheckExplicitlyDefaultedSpecialMember(MD);
12756 
12757     if (MD->isInvalidDecl())
12758       return;
12759 
12760     switch (Member) {
12761     case CXXDefaultConstructor:
12762       DefineImplicitDefaultConstructor(DefaultLoc,
12763                                        cast<CXXConstructorDecl>(MD));
12764       break;
12765     case CXXCopyConstructor:
12766       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12767       break;
12768     case CXXCopyAssignment:
12769       DefineImplicitCopyAssignment(DefaultLoc, MD);
12770       break;
12771     case CXXDestructor:
12772       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12773       break;
12774     case CXXMoveConstructor:
12775       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12776       break;
12777     case CXXMoveAssignment:
12778       DefineImplicitMoveAssignment(DefaultLoc, MD);
12779       break;
12780     case CXXInvalid:
12781       llvm_unreachable("Invalid special member.");
12782     }
12783   } else {
12784     Diag(DefaultLoc, diag::err_default_special_members);
12785   }
12786 }
12787 
12788 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12789   for (Stmt::child_range CI = S->children(); CI; ++CI) {
12790     Stmt *SubStmt = *CI;
12791     if (!SubStmt)
12792       continue;
12793     if (isa<ReturnStmt>(SubStmt))
12794       Self.Diag(SubStmt->getLocStart(),
12795            diag::err_return_in_constructor_handler);
12796     if (!isa<Expr>(SubStmt))
12797       SearchForReturnInStmt(Self, SubStmt);
12798   }
12799 }
12800 
12801 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12802   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12803     CXXCatchStmt *Handler = TryBlock->getHandler(I);
12804     SearchForReturnInStmt(*this, Handler);
12805   }
12806 }
12807 
12808 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12809                                              const CXXMethodDecl *Old) {
12810   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12811   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12812 
12813   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12814 
12815   // If the calling conventions match, everything is fine
12816   if (NewCC == OldCC)
12817     return false;
12818 
12819   // If the calling conventions mismatch because the new function is static,
12820   // suppress the calling convention mismatch error; the error about static
12821   // function override (err_static_overrides_virtual from
12822   // Sema::CheckFunctionDeclaration) is more clear.
12823   if (New->getStorageClass() == SC_Static)
12824     return false;
12825 
12826   Diag(New->getLocation(),
12827        diag::err_conflicting_overriding_cc_attributes)
12828     << New->getDeclName() << New->getType() << Old->getType();
12829   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12830   return true;
12831 }
12832 
12833 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12834                                              const CXXMethodDecl *Old) {
12835   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12836   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12837 
12838   if (Context.hasSameType(NewTy, OldTy) ||
12839       NewTy->isDependentType() || OldTy->isDependentType())
12840     return false;
12841 
12842   // Check if the return types are covariant
12843   QualType NewClassTy, OldClassTy;
12844 
12845   /// Both types must be pointers or references to classes.
12846   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12847     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12848       NewClassTy = NewPT->getPointeeType();
12849       OldClassTy = OldPT->getPointeeType();
12850     }
12851   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12852     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12853       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12854         NewClassTy = NewRT->getPointeeType();
12855         OldClassTy = OldRT->getPointeeType();
12856       }
12857     }
12858   }
12859 
12860   // The return types aren't either both pointers or references to a class type.
12861   if (NewClassTy.isNull()) {
12862     Diag(New->getLocation(),
12863          diag::err_different_return_type_for_overriding_virtual_function)
12864         << New->getDeclName() << NewTy << OldTy
12865         << New->getReturnTypeSourceRange();
12866     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12867         << Old->getReturnTypeSourceRange();
12868 
12869     return true;
12870   }
12871 
12872   // C++ [class.virtual]p6:
12873   //   If the return type of D::f differs from the return type of B::f, the
12874   //   class type in the return type of D::f shall be complete at the point of
12875   //   declaration of D::f or shall be the class type D.
12876   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12877     if (!RT->isBeingDefined() &&
12878         RequireCompleteType(New->getLocation(), NewClassTy,
12879                             diag::err_covariant_return_incomplete,
12880                             New->getDeclName()))
12881     return true;
12882   }
12883 
12884   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12885     // Check if the new class derives from the old class.
12886     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12887       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12888           << New->getDeclName() << NewTy << OldTy
12889           << New->getReturnTypeSourceRange();
12890       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12891           << Old->getReturnTypeSourceRange();
12892       return true;
12893     }
12894 
12895     // Check if we the conversion from derived to base is valid.
12896     if (CheckDerivedToBaseConversion(
12897             NewClassTy, OldClassTy,
12898             diag::err_covariant_return_inaccessible_base,
12899             diag::err_covariant_return_ambiguous_derived_to_base_conv,
12900             New->getLocation(), New->getReturnTypeSourceRange(),
12901             New->getDeclName(), nullptr)) {
12902       // FIXME: this note won't trigger for delayed access control
12903       // diagnostics, and it's impossible to get an undelayed error
12904       // here from access control during the original parse because
12905       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
12906       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12907           << Old->getReturnTypeSourceRange();
12908       return true;
12909     }
12910   }
12911 
12912   // The qualifiers of the return types must be the same.
12913   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
12914     Diag(New->getLocation(),
12915          diag::err_covariant_return_type_different_qualifications)
12916         << New->getDeclName() << NewTy << OldTy
12917         << New->getReturnTypeSourceRange();
12918     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12919         << Old->getReturnTypeSourceRange();
12920     return true;
12921   };
12922 
12923 
12924   // The new class type must have the same or less qualifiers as the old type.
12925   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12926     Diag(New->getLocation(),
12927          diag::err_covariant_return_type_class_type_more_qualified)
12928         << New->getDeclName() << NewTy << OldTy
12929         << New->getReturnTypeSourceRange();
12930     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12931         << Old->getReturnTypeSourceRange();
12932     return true;
12933   };
12934 
12935   return false;
12936 }
12937 
12938 /// \brief Mark the given method pure.
12939 ///
12940 /// \param Method the method to be marked pure.
12941 ///
12942 /// \param InitRange the source range that covers the "0" initializer.
12943 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
12944   SourceLocation EndLoc = InitRange.getEnd();
12945   if (EndLoc.isValid())
12946     Method->setRangeEnd(EndLoc);
12947 
12948   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12949     Method->setPure();
12950     return false;
12951   }
12952 
12953   if (!Method->isInvalidDecl())
12954     Diag(Method->getLocation(), diag::err_non_virtual_pure)
12955       << Method->getDeclName() << InitRange;
12956   return true;
12957 }
12958 
12959 /// \brief Determine whether the given declaration is a static data member.
12960 static bool isStaticDataMember(const Decl *D) {
12961   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12962     return Var->isStaticDataMember();
12963 
12964   return false;
12965 }
12966 
12967 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12968 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
12969 /// is a fresh scope pushed for just this purpose.
12970 ///
12971 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12972 /// static data member of class X, names should be looked up in the scope of
12973 /// class X.
12974 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
12975   // If there is no declaration, there was an error parsing it.
12976   if (!D || D->isInvalidDecl())
12977     return;
12978 
12979   // We will always have a nested name specifier here, but this declaration
12980   // might not be out of line if the specifier names the current namespace:
12981   //   extern int n;
12982   //   int ::n = 0;
12983   if (D->isOutOfLine())
12984     EnterDeclaratorContext(S, D->getDeclContext());
12985 
12986   // If we are parsing the initializer for a static data member, push a
12987   // new expression evaluation context that is associated with this static
12988   // data member.
12989   if (isStaticDataMember(D))
12990     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
12991 }
12992 
12993 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
12994 /// initializer for the out-of-line declaration 'D'.
12995 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
12996   // If there is no declaration, there was an error parsing it.
12997   if (!D || D->isInvalidDecl())
12998     return;
12999 
13000   if (isStaticDataMember(D))
13001     PopExpressionEvaluationContext();
13002 
13003   if (D->isOutOfLine())
13004     ExitDeclaratorContext(S);
13005 }
13006 
13007 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13008 /// C++ if/switch/while/for statement.
13009 /// e.g: "if (int x = f()) {...}"
13010 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
13011   // C++ 6.4p2:
13012   // The declarator shall not specify a function or an array.
13013   // The type-specifier-seq shall not contain typedef and shall not declare a
13014   // new class or enumeration.
13015   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13016          "Parser allowed 'typedef' as storage class of condition decl.");
13017 
13018   Decl *Dcl = ActOnDeclarator(S, D);
13019   if (!Dcl)
13020     return true;
13021 
13022   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13023     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
13024       << D.getSourceRange();
13025     return true;
13026   }
13027 
13028   return Dcl;
13029 }
13030 
13031 void Sema::LoadExternalVTableUses() {
13032   if (!ExternalSource)
13033     return;
13034 
13035   SmallVector<ExternalVTableUse, 4> VTables;
13036   ExternalSource->ReadUsedVTables(VTables);
13037   SmallVector<VTableUse, 4> NewUses;
13038   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13039     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13040       = VTablesUsed.find(VTables[I].Record);
13041     // Even if a definition wasn't required before, it may be required now.
13042     if (Pos != VTablesUsed.end()) {
13043       if (!Pos->second && VTables[I].DefinitionRequired)
13044         Pos->second = true;
13045       continue;
13046     }
13047 
13048     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13049     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13050   }
13051 
13052   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13053 }
13054 
13055 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13056                           bool DefinitionRequired) {
13057   // Ignore any vtable uses in unevaluated operands or for classes that do
13058   // not have a vtable.
13059   if (!Class->isDynamicClass() || Class->isDependentContext() ||
13060       CurContext->isDependentContext() || isUnevaluatedContext())
13061     return;
13062 
13063   // Try to insert this class into the map.
13064   LoadExternalVTableUses();
13065   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13066   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13067     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13068   if (!Pos.second) {
13069     // If we already had an entry, check to see if we are promoting this vtable
13070     // to require a definition. If so, we need to reappend to the VTableUses
13071     // list, since we may have already processed the first entry.
13072     if (DefinitionRequired && !Pos.first->second) {
13073       Pos.first->second = true;
13074     } else {
13075       // Otherwise, we can early exit.
13076       return;
13077     }
13078   } else {
13079     // The Microsoft ABI requires that we perform the destructor body
13080     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13081     // the deleting destructor is emitted with the vtable, not with the
13082     // destructor definition as in the Itanium ABI.
13083     // If it has a definition, we do the check at that point instead.
13084     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13085         Class->hasUserDeclaredDestructor() &&
13086         !Class->getDestructor()->isDefined() &&
13087         !Class->getDestructor()->isDeleted()) {
13088       CXXDestructorDecl *DD = Class->getDestructor();
13089       ContextRAII SavedContext(*this, DD);
13090       CheckDestructor(DD);
13091     }
13092   }
13093 
13094   // Local classes need to have their virtual members marked
13095   // immediately. For all other classes, we mark their virtual members
13096   // at the end of the translation unit.
13097   if (Class->isLocalClass())
13098     MarkVirtualMembersReferenced(Loc, Class);
13099   else
13100     VTableUses.push_back(std::make_pair(Class, Loc));
13101 }
13102 
13103 bool Sema::DefineUsedVTables() {
13104   LoadExternalVTableUses();
13105   if (VTableUses.empty())
13106     return false;
13107 
13108   // Note: The VTableUses vector could grow as a result of marking
13109   // the members of a class as "used", so we check the size each
13110   // time through the loop and prefer indices (which are stable) to
13111   // iterators (which are not).
13112   bool DefinedAnything = false;
13113   for (unsigned I = 0; I != VTableUses.size(); ++I) {
13114     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
13115     if (!Class)
13116       continue;
13117 
13118     SourceLocation Loc = VTableUses[I].second;
13119 
13120     bool DefineVTable = true;
13121 
13122     // If this class has a key function, but that key function is
13123     // defined in another translation unit, we don't need to emit the
13124     // vtable even though we're using it.
13125     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
13126     if (KeyFunction && !KeyFunction->hasBody()) {
13127       // The key function is in another translation unit.
13128       DefineVTable = false;
13129       TemplateSpecializationKind TSK =
13130           KeyFunction->getTemplateSpecializationKind();
13131       assert(TSK != TSK_ExplicitInstantiationDefinition &&
13132              TSK != TSK_ImplicitInstantiation &&
13133              "Instantiations don't have key functions");
13134       (void)TSK;
13135     } else if (!KeyFunction) {
13136       // If we have a class with no key function that is the subject
13137       // of an explicit instantiation declaration, suppress the
13138       // vtable; it will live with the explicit instantiation
13139       // definition.
13140       bool IsExplicitInstantiationDeclaration
13141         = Class->getTemplateSpecializationKind()
13142                                       == TSK_ExplicitInstantiationDeclaration;
13143       for (auto R : Class->redecls()) {
13144         TemplateSpecializationKind TSK
13145           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
13146         if (TSK == TSK_ExplicitInstantiationDeclaration)
13147           IsExplicitInstantiationDeclaration = true;
13148         else if (TSK == TSK_ExplicitInstantiationDefinition) {
13149           IsExplicitInstantiationDeclaration = false;
13150           break;
13151         }
13152       }
13153 
13154       if (IsExplicitInstantiationDeclaration)
13155         DefineVTable = false;
13156     }
13157 
13158     // The exception specifications for all virtual members may be needed even
13159     // if we are not providing an authoritative form of the vtable in this TU.
13160     // We may choose to emit it available_externally anyway.
13161     if (!DefineVTable) {
13162       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13163       continue;
13164     }
13165 
13166     // Mark all of the virtual members of this class as referenced, so
13167     // that we can build a vtable. Then, tell the AST consumer that a
13168     // vtable for this class is required.
13169     DefinedAnything = true;
13170     MarkVirtualMembersReferenced(Loc, Class);
13171     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13172     if (VTablesUsed[Canonical])
13173       Consumer.HandleVTable(Class);
13174 
13175     // Optionally warn if we're emitting a weak vtable.
13176     if (Class->isExternallyVisible() &&
13177         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
13178       const FunctionDecl *KeyFunctionDef = nullptr;
13179       if (!KeyFunction ||
13180           (KeyFunction->hasBody(KeyFunctionDef) &&
13181            KeyFunctionDef->isInlined()))
13182         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13183              TSK_ExplicitInstantiationDefinition
13184              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13185           << Class;
13186     }
13187   }
13188   VTableUses.clear();
13189 
13190   return DefinedAnything;
13191 }
13192 
13193 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13194                                                  const CXXRecordDecl *RD) {
13195   for (const auto *I : RD->methods())
13196     if (I->isVirtual() && !I->isPure())
13197       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
13198 }
13199 
13200 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13201                                         const CXXRecordDecl *RD) {
13202   // Mark all functions which will appear in RD's vtable as used.
13203   CXXFinalOverriderMap FinalOverriders;
13204   RD->getFinalOverriders(FinalOverriders);
13205   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13206                                             E = FinalOverriders.end();
13207        I != E; ++I) {
13208     for (OverridingMethods::const_iterator OI = I->second.begin(),
13209                                            OE = I->second.end();
13210          OI != OE; ++OI) {
13211       assert(OI->second.size() > 0 && "no final overrider");
13212       CXXMethodDecl *Overrider = OI->second.front().Method;
13213 
13214       // C++ [basic.def.odr]p2:
13215       //   [...] A virtual member function is used if it is not pure. [...]
13216       if (!Overrider->isPure())
13217         MarkFunctionReferenced(Loc, Overrider);
13218     }
13219   }
13220 
13221   // Only classes that have virtual bases need a VTT.
13222   if (RD->getNumVBases() == 0)
13223     return;
13224 
13225   for (const auto &I : RD->bases()) {
13226     const CXXRecordDecl *Base =
13227         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
13228     if (Base->getNumVBases() == 0)
13229       continue;
13230     MarkVirtualMembersReferenced(Loc, Base);
13231   }
13232 }
13233 
13234 /// SetIvarInitializers - This routine builds initialization ASTs for the
13235 /// Objective-C implementation whose ivars need be initialized.
13236 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
13237   if (!getLangOpts().CPlusPlus)
13238     return;
13239   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
13240     SmallVector<ObjCIvarDecl*, 8> ivars;
13241     CollectIvarsToConstructOrDestruct(OID, ivars);
13242     if (ivars.empty())
13243       return;
13244     SmallVector<CXXCtorInitializer*, 32> AllToInit;
13245     for (unsigned i = 0; i < ivars.size(); i++) {
13246       FieldDecl *Field = ivars[i];
13247       if (Field->isInvalidDecl())
13248         continue;
13249 
13250       CXXCtorInitializer *Member;
13251       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13252       InitializationKind InitKind =
13253         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
13254 
13255       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13256       ExprResult MemberInit =
13257         InitSeq.Perform(*this, InitEntity, InitKind, None);
13258       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
13259       // Note, MemberInit could actually come back empty if no initialization
13260       // is required (e.g., because it would call a trivial default constructor)
13261       if (!MemberInit.get() || MemberInit.isInvalid())
13262         continue;
13263 
13264       Member =
13265         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13266                                          SourceLocation(),
13267                                          MemberInit.getAs<Expr>(),
13268                                          SourceLocation());
13269       AllToInit.push_back(Member);
13270 
13271       // Be sure that the destructor is accessible and is marked as referenced.
13272       if (const RecordType *RecordTy =
13273               Context.getBaseElementType(Field->getType())
13274                   ->getAs<RecordType>()) {
13275         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
13276         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
13277           MarkFunctionReferenced(Field->getLocation(), Destructor);
13278           CheckDestructorAccess(Field->getLocation(), Destructor,
13279                             PDiag(diag::err_access_dtor_ivar)
13280                               << Context.getBaseElementType(Field->getType()));
13281         }
13282       }
13283     }
13284     ObjCImplementation->setIvarInitializers(Context,
13285                                             AllToInit.data(), AllToInit.size());
13286   }
13287 }
13288 
13289 static
13290 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13291                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13292                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13293                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13294                            Sema &S) {
13295   if (Ctor->isInvalidDecl())
13296     return;
13297 
13298   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13299 
13300   // Target may not be determinable yet, for instance if this is a dependent
13301   // call in an uninstantiated template.
13302   if (Target) {
13303     const FunctionDecl *FNTarget = nullptr;
13304     (void)Target->hasBody(FNTarget);
13305     Target = const_cast<CXXConstructorDecl*>(
13306       cast_or_null<CXXConstructorDecl>(FNTarget));
13307   }
13308 
13309   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13310                      // Avoid dereferencing a null pointer here.
13311                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
13312 
13313   if (!Current.insert(Canonical).second)
13314     return;
13315 
13316   // We know that beyond here, we aren't chaining into a cycle.
13317   if (!Target || !Target->isDelegatingConstructor() ||
13318       Target->isInvalidDecl() || Valid.count(TCanonical)) {
13319     Valid.insert(Current.begin(), Current.end());
13320     Current.clear();
13321   // We've hit a cycle.
13322   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13323              Current.count(TCanonical)) {
13324     // If we haven't diagnosed this cycle yet, do so now.
13325     if (!Invalid.count(TCanonical)) {
13326       S.Diag((*Ctor->init_begin())->getSourceLocation(),
13327              diag::warn_delegating_ctor_cycle)
13328         << Ctor;
13329 
13330       // Don't add a note for a function delegating directly to itself.
13331       if (TCanonical != Canonical)
13332         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13333 
13334       CXXConstructorDecl *C = Target;
13335       while (C->getCanonicalDecl() != Canonical) {
13336         const FunctionDecl *FNTarget = nullptr;
13337         (void)C->getTargetConstructor()->hasBody(FNTarget);
13338         assert(FNTarget && "Ctor cycle through bodiless function");
13339 
13340         C = const_cast<CXXConstructorDecl*>(
13341           cast<CXXConstructorDecl>(FNTarget));
13342         S.Diag(C->getLocation(), diag::note_which_delegates_to);
13343       }
13344     }
13345 
13346     Invalid.insert(Current.begin(), Current.end());
13347     Current.clear();
13348   } else {
13349     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13350   }
13351 }
13352 
13353 
13354 void Sema::CheckDelegatingCtorCycles() {
13355   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13356 
13357   for (DelegatingCtorDeclsType::iterator
13358          I = DelegatingCtorDecls.begin(ExternalSource),
13359          E = DelegatingCtorDecls.end();
13360        I != E; ++I)
13361     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
13362 
13363   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13364                                                          CE = Invalid.end();
13365        CI != CE; ++CI)
13366     (*CI)->setInvalidDecl();
13367 }
13368 
13369 namespace {
13370   /// \brief AST visitor that finds references to the 'this' expression.
13371   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13372     Sema &S;
13373 
13374   public:
13375     explicit FindCXXThisExpr(Sema &S) : S(S) { }
13376 
13377     bool VisitCXXThisExpr(CXXThisExpr *E) {
13378       S.Diag(E->getLocation(), diag::err_this_static_member_func)
13379         << E->isImplicit();
13380       return false;
13381     }
13382   };
13383 }
13384 
13385 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13386   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13387   if (!TSInfo)
13388     return false;
13389 
13390   TypeLoc TL = TSInfo->getTypeLoc();
13391   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13392   if (!ProtoTL)
13393     return false;
13394 
13395   // C++11 [expr.prim.general]p3:
13396   //   [The expression this] shall not appear before the optional
13397   //   cv-qualifier-seq and it shall not appear within the declaration of a
13398   //   static member function (although its type and value category are defined
13399   //   within a static member function as they are within a non-static member
13400   //   function). [ Note: this is because declaration matching does not occur
13401   //  until the complete declarator is known. - end note ]
13402   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13403   FindCXXThisExpr Finder(*this);
13404 
13405   // If the return type came after the cv-qualifier-seq, check it now.
13406   if (Proto->hasTrailingReturn() &&
13407       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
13408     return true;
13409 
13410   // Check the exception specification.
13411   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13412     return true;
13413 
13414   return checkThisInStaticMemberFunctionAttributes(Method);
13415 }
13416 
13417 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13418   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13419   if (!TSInfo)
13420     return false;
13421 
13422   TypeLoc TL = TSInfo->getTypeLoc();
13423   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13424   if (!ProtoTL)
13425     return false;
13426 
13427   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13428   FindCXXThisExpr Finder(*this);
13429 
13430   switch (Proto->getExceptionSpecType()) {
13431   case EST_Unparsed:
13432   case EST_Uninstantiated:
13433   case EST_Unevaluated:
13434   case EST_BasicNoexcept:
13435   case EST_DynamicNone:
13436   case EST_MSAny:
13437   case EST_None:
13438     break;
13439 
13440   case EST_ComputedNoexcept:
13441     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13442       return true;
13443 
13444   case EST_Dynamic:
13445     for (const auto &E : Proto->exceptions()) {
13446       if (!Finder.TraverseType(E))
13447         return true;
13448     }
13449     break;
13450   }
13451 
13452   return false;
13453 }
13454 
13455 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13456   FindCXXThisExpr Finder(*this);
13457 
13458   // Check attributes.
13459   for (const auto *A : Method->attrs()) {
13460     // FIXME: This should be emitted by tblgen.
13461     Expr *Arg = nullptr;
13462     ArrayRef<Expr *> Args;
13463     if (const auto *G = dyn_cast<GuardedByAttr>(A))
13464       Arg = G->getArg();
13465     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13466       Arg = G->getArg();
13467     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13468       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13469     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13470       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13471     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13472       Arg = ETLF->getSuccessValue();
13473       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13474     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13475       Arg = STLF->getSuccessValue();
13476       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13477     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13478       Arg = LR->getArg();
13479     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13480       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13481     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13482       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13483     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13484       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13485     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13486       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13487     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13488       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13489 
13490     if (Arg && !Finder.TraverseStmt(Arg))
13491       return true;
13492 
13493     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13494       if (!Finder.TraverseStmt(Args[I]))
13495         return true;
13496     }
13497   }
13498 
13499   return false;
13500 }
13501 
13502 void Sema::checkExceptionSpecification(
13503     bool IsTopLevel, ExceptionSpecificationType EST,
13504     ArrayRef<ParsedType> DynamicExceptions,
13505     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13506     SmallVectorImpl<QualType> &Exceptions,
13507     FunctionProtoType::ExceptionSpecInfo &ESI) {
13508   Exceptions.clear();
13509   ESI.Type = EST;
13510   if (EST == EST_Dynamic) {
13511     Exceptions.reserve(DynamicExceptions.size());
13512     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13513       // FIXME: Preserve type source info.
13514       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13515 
13516       if (IsTopLevel) {
13517         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13518         collectUnexpandedParameterPacks(ET, Unexpanded);
13519         if (!Unexpanded.empty()) {
13520           DiagnoseUnexpandedParameterPacks(
13521               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13522               Unexpanded);
13523           continue;
13524         }
13525       }
13526 
13527       // Check that the type is valid for an exception spec, and
13528       // drop it if not.
13529       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13530         Exceptions.push_back(ET);
13531     }
13532     ESI.Exceptions = Exceptions;
13533     return;
13534   }
13535 
13536   if (EST == EST_ComputedNoexcept) {
13537     // If an error occurred, there's no expression here.
13538     if (NoexceptExpr) {
13539       assert((NoexceptExpr->isTypeDependent() ||
13540               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13541               Context.BoolTy) &&
13542              "Parser should have made sure that the expression is boolean");
13543       if (IsTopLevel && NoexceptExpr &&
13544           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13545         ESI.Type = EST_BasicNoexcept;
13546         return;
13547       }
13548 
13549       if (!NoexceptExpr->isValueDependent())
13550         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13551                          diag::err_noexcept_needs_constant_expression,
13552                          /*AllowFold*/ false).get();
13553       ESI.NoexceptExpr = NoexceptExpr;
13554     }
13555     return;
13556   }
13557 }
13558 
13559 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13560              ExceptionSpecificationType EST,
13561              SourceRange SpecificationRange,
13562              ArrayRef<ParsedType> DynamicExceptions,
13563              ArrayRef<SourceRange> DynamicExceptionRanges,
13564              Expr *NoexceptExpr) {
13565   if (!MethodD)
13566     return;
13567 
13568   // Dig out the method we're referring to.
13569   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13570     MethodD = FunTmpl->getTemplatedDecl();
13571 
13572   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13573   if (!Method)
13574     return;
13575 
13576   // Check the exception specification.
13577   llvm::SmallVector<QualType, 4> Exceptions;
13578   FunctionProtoType::ExceptionSpecInfo ESI;
13579   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13580                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
13581                               ESI);
13582 
13583   // Update the exception specification on the function type.
13584   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13585 
13586   if (Method->isStatic())
13587     checkThisInStaticMemberFunctionExceptionSpec(Method);
13588 
13589   if (Method->isVirtual()) {
13590     // Check overrides, which we previously had to delay.
13591     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13592                                      OEnd = Method->end_overridden_methods();
13593          O != OEnd; ++O)
13594       CheckOverridingFunctionExceptionSpec(Method, *O);
13595   }
13596 }
13597 
13598 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13599 ///
13600 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13601                                        SourceLocation DeclStart,
13602                                        Declarator &D, Expr *BitWidth,
13603                                        InClassInitStyle InitStyle,
13604                                        AccessSpecifier AS,
13605                                        AttributeList *MSPropertyAttr) {
13606   IdentifierInfo *II = D.getIdentifier();
13607   if (!II) {
13608     Diag(DeclStart, diag::err_anonymous_property);
13609     return nullptr;
13610   }
13611   SourceLocation Loc = D.getIdentifierLoc();
13612 
13613   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13614   QualType T = TInfo->getType();
13615   if (getLangOpts().CPlusPlus) {
13616     CheckExtraCXXDefaultArguments(D);
13617 
13618     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13619                                         UPPC_DataMemberType)) {
13620       D.setInvalidType();
13621       T = Context.IntTy;
13622       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13623     }
13624   }
13625 
13626   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13627 
13628   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13629     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13630          diag::err_invalid_thread)
13631       << DeclSpec::getSpecifierName(TSCS);
13632 
13633   // Check to see if this name was declared as a member previously
13634   NamedDecl *PrevDecl = nullptr;
13635   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13636   LookupName(Previous, S);
13637   switch (Previous.getResultKind()) {
13638   case LookupResult::Found:
13639   case LookupResult::FoundUnresolvedValue:
13640     PrevDecl = Previous.getAsSingle<NamedDecl>();
13641     break;
13642 
13643   case LookupResult::FoundOverloaded:
13644     PrevDecl = Previous.getRepresentativeDecl();
13645     break;
13646 
13647   case LookupResult::NotFound:
13648   case LookupResult::NotFoundInCurrentInstantiation:
13649   case LookupResult::Ambiguous:
13650     break;
13651   }
13652 
13653   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13654     // Maybe we will complain about the shadowed template parameter.
13655     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13656     // Just pretend that we didn't see the previous declaration.
13657     PrevDecl = nullptr;
13658   }
13659 
13660   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13661     PrevDecl = nullptr;
13662 
13663   SourceLocation TSSL = D.getLocStart();
13664   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13665   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13666       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13667   ProcessDeclAttributes(TUScope, NewPD, D);
13668   NewPD->setAccess(AS);
13669 
13670   if (NewPD->isInvalidDecl())
13671     Record->setInvalidDecl();
13672 
13673   if (D.getDeclSpec().isModulePrivateSpecified())
13674     NewPD->setModulePrivate();
13675 
13676   if (NewPD->isInvalidDecl() && PrevDecl) {
13677     // Don't introduce NewFD into scope; there's already something
13678     // with the same name in the same scope.
13679   } else if (II) {
13680     PushOnScopeChains(NewPD, S);
13681   } else
13682     Record->addDecl(NewPD);
13683 
13684   return NewPD;
13685 }
13686