1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for C++ declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ComparisonCategories.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/LiteralSupport.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/CXXFieldCollector.h"
32 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/Initialization.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/ParsedTemplate.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaInternal.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include <map>
44 #include <set>
45 
46 using namespace clang;
47 
48 //===----------------------------------------------------------------------===//
49 // CheckDefaultArgumentVisitor
50 //===----------------------------------------------------------------------===//
51 
52 namespace {
53   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54   /// the default argument of a parameter to determine whether it
55   /// contains any ill-formed subexpressions. For example, this will
56   /// diagnose the use of local variables or parameters within the
57   /// default argument expression.
58   class CheckDefaultArgumentVisitor
59     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
60     Expr *DefaultArg;
61     Sema *S;
62 
63   public:
64     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
65         : DefaultArg(defarg), S(s) {}
66 
67     bool VisitExpr(Expr *Node);
68     bool VisitDeclRefExpr(DeclRefExpr *DRE);
69     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
70     bool VisitLambdaExpr(LambdaExpr *Lambda);
71     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
72   };
73 
74   /// VisitExpr - Visit all of the children of this expression.
75   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76     bool IsInvalid = false;
77     for (Stmt *SubStmt : Node->children())
78       IsInvalid |= Visit(SubStmt);
79     return IsInvalid;
80   }
81 
82   /// VisitDeclRefExpr - Visit a reference to a declaration, to
83   /// determine whether this declaration can be used in the default
84   /// argument expression.
85   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
86     NamedDecl *Decl = DRE->getDecl();
87     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88       // C++ [dcl.fct.default]p9
89       //   Default arguments are evaluated each time the function is
90       //   called. The order of evaluation of function arguments is
91       //   unspecified. Consequently, parameters of a function shall not
92       //   be used in default argument expressions, even if they are not
93       //   evaluated. Parameters of a function declared before a default
94       //   argument expression are in scope and can hide namespace and
95       //   class member names.
96       return S->Diag(DRE->getBeginLoc(),
97                      diag::err_param_default_argument_references_param)
98              << Param->getDeclName() << DefaultArg->getSourceRange();
99     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
100       // C++ [dcl.fct.default]p7
101       //   Local variables shall not be used in default argument
102       //   expressions.
103       if (VDecl->isLocalVarDecl())
104         return S->Diag(DRE->getBeginLoc(),
105                        diag::err_param_default_argument_references_local)
106                << VDecl->getDeclName() << DefaultArg->getSourceRange();
107     }
108 
109     return false;
110   }
111 
112   /// VisitCXXThisExpr - Visit a C++ "this" expression.
113   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114     // C++ [dcl.fct.default]p8:
115     //   The keyword this shall not be used in a default argument of a
116     //   member function.
117     return S->Diag(ThisE->getBeginLoc(),
118                    diag::err_param_default_argument_references_this)
119            << ThisE->getSourceRange();
120   }
121 
122   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123     bool Invalid = false;
124     for (PseudoObjectExpr::semantics_iterator
125            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126       Expr *E = *i;
127 
128       // Look through bindings.
129       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130         E = OVE->getSourceExpr();
131         assert(E && "pseudo-object binding without source expression?");
132       }
133 
134       Invalid |= Visit(E);
135     }
136     return Invalid;
137   }
138 
139   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140     // C++11 [expr.lambda.prim]p13:
141     //   A lambda-expression appearing in a default argument shall not
142     //   implicitly or explicitly capture any entity.
143     if (Lambda->capture_begin() == Lambda->capture_end())
144       return false;
145 
146     return S->Diag(Lambda->getBeginLoc(), 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 we have a throw-all spec at this point, ignore the function.
166   if (ComputedEST == EST_None)
167     return;
168 
169   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
170     EST = EST_BasicNoexcept;
171 
172   switch (EST) {
173   case EST_Unparsed:
174   case EST_Uninstantiated:
175   case EST_Unevaluated:
176     llvm_unreachable("should not see unresolved exception specs here");
177 
178   // If this function can throw any exceptions, make a note of that.
179   case EST_MSAny:
180   case EST_None:
181     // FIXME: Whichever we see last of MSAny and None determines our result.
182     // We should make a consistent, order-independent choice here.
183     ClearExceptions();
184     ComputedEST = EST;
185     return;
186   case EST_NoexceptFalse:
187     ClearExceptions();
188     ComputedEST = EST_None;
189     return;
190   // FIXME: If the call to this decl is using any of its default arguments, we
191   // need to search them for potentially-throwing calls.
192   // If this function has a basic noexcept, it doesn't affect the outcome.
193   case EST_BasicNoexcept:
194   case EST_NoexceptTrue:
195     return;
196   // If we're still at noexcept(true) and there's a throw() callee,
197   // change to that specification.
198   case EST_DynamicNone:
199     if (ComputedEST == EST_BasicNoexcept)
200       ComputedEST = EST_DynamicNone;
201     return;
202   case EST_DependentNoexcept:
203     llvm_unreachable(
204         "should not generate implicit declarations for dependent cases");
205   case EST_Dynamic:
206     break;
207   }
208   assert(EST == EST_Dynamic && "EST case not considered earlier.");
209   assert(ComputedEST != EST_None &&
210          "Shouldn't collect exceptions when throw-all is guaranteed.");
211   ComputedEST = EST_Dynamic;
212   // Record the exceptions in this function's exception specification.
213   for (const auto &E : Proto->exceptions())
214     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
215       Exceptions.push_back(E);
216 }
217 
218 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
219   if (!E || ComputedEST == EST_MSAny)
220     return;
221 
222   // FIXME:
223   //
224   // C++0x [except.spec]p14:
225   //   [An] implicit exception-specification specifies the type-id T if and
226   // only if T is allowed by the exception-specification of a function directly
227   // invoked by f's implicit definition; f shall allow all exceptions if any
228   // function it directly invokes allows all exceptions, and f shall allow no
229   // exceptions if every function it directly invokes allows no exceptions.
230   //
231   // Note in particular that if an implicit exception-specification is generated
232   // for a function containing a throw-expression, that specification can still
233   // be noexcept(true).
234   //
235   // Note also that 'directly invoked' is not defined in the standard, and there
236   // is no indication that we should only consider potentially-evaluated calls.
237   //
238   // Ultimately we should implement the intent of the standard: the exception
239   // specification should be the set of exceptions which can be thrown by the
240   // implicit definition. For now, we assume that any non-nothrow expression can
241   // throw any exception.
242 
243   if (Self->canThrow(E))
244     ComputedEST = EST_None;
245 }
246 
247 bool
248 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
249                               SourceLocation EqualLoc) {
250   if (RequireCompleteType(Param->getLocation(), Param->getType(),
251                           diag::err_typecheck_decl_incomplete_type)) {
252     Param->setInvalidDecl();
253     return true;
254   }
255 
256   // C++ [dcl.fct.default]p5
257   //   A default argument expression is implicitly converted (clause
258   //   4) to the parameter type. The default argument expression has
259   //   the same semantic constraints as the initializer expression in
260   //   a declaration of a variable of the parameter type, using the
261   //   copy-initialization semantics (8.5).
262   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
263                                                                     Param);
264   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
265                                                            EqualLoc);
266   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
267   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
268   if (Result.isInvalid())
269     return true;
270   Arg = Result.getAs<Expr>();
271 
272   CheckCompletedExpr(Arg, EqualLoc);
273   Arg = MaybeCreateExprWithCleanups(Arg);
274 
275   // Okay: add the default argument to the parameter
276   Param->setDefaultArg(Arg);
277 
278   // We have already instantiated this parameter; provide each of the
279   // instantiations with the uninstantiated default argument.
280   UnparsedDefaultArgInstantiationsMap::iterator InstPos
281     = UnparsedDefaultArgInstantiations.find(Param);
282   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
283     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
284       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
285 
286     // We're done tracking this parameter's instantiations.
287     UnparsedDefaultArgInstantiations.erase(InstPos);
288   }
289 
290   return false;
291 }
292 
293 /// ActOnParamDefaultArgument - Check whether the default argument
294 /// provided for a function parameter is well-formed. If so, attach it
295 /// to the parameter declaration.
296 void
297 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
298                                 Expr *DefaultArg) {
299   if (!param || !DefaultArg)
300     return;
301 
302   ParmVarDecl *Param = cast<ParmVarDecl>(param);
303   UnparsedDefaultArgLocs.erase(Param);
304 
305   // Default arguments are only permitted in C++
306   if (!getLangOpts().CPlusPlus) {
307     Diag(EqualLoc, diag::err_param_default_argument)
308       << DefaultArg->getSourceRange();
309     Param->setInvalidDecl();
310     return;
311   }
312 
313   // Check for unexpanded parameter packs.
314   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
315     Param->setInvalidDecl();
316     return;
317   }
318 
319   // C++11 [dcl.fct.default]p3
320   //   A default argument expression [...] shall not be specified for a
321   //   parameter pack.
322   if (Param->isParameterPack()) {
323     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
324         << DefaultArg->getSourceRange();
325     return;
326   }
327 
328   // Check that the default argument is well-formed
329   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
330   if (DefaultArgChecker.Visit(DefaultArg)) {
331     Param->setInvalidDecl();
332     return;
333   }
334 
335   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
336 }
337 
338 /// ActOnParamUnparsedDefaultArgument - We've seen a default
339 /// argument for a function parameter, but we can't parse it yet
340 /// because we're inside a class definition. Note that this default
341 /// argument will be parsed later.
342 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
343                                              SourceLocation EqualLoc,
344                                              SourceLocation ArgLoc) {
345   if (!param)
346     return;
347 
348   ParmVarDecl *Param = cast<ParmVarDecl>(param);
349   Param->setUnparsedDefaultArg();
350   UnparsedDefaultArgLocs[Param] = ArgLoc;
351 }
352 
353 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
354 /// the default argument for the parameter param failed.
355 void Sema::ActOnParamDefaultArgumentError(Decl *param,
356                                           SourceLocation EqualLoc) {
357   if (!param)
358     return;
359 
360   ParmVarDecl *Param = cast<ParmVarDecl>(param);
361   Param->setInvalidDecl();
362   UnparsedDefaultArgLocs.erase(Param);
363   Param->setDefaultArg(new(Context)
364                        OpaqueValueExpr(EqualLoc,
365                                        Param->getType().getNonReferenceType(),
366                                        VK_RValue));
367 }
368 
369 /// CheckExtraCXXDefaultArguments - Check for any extra default
370 /// arguments in the declarator, which is not a function declaration
371 /// or definition and therefore is not permitted to have default
372 /// arguments. This routine should be invoked for every declarator
373 /// that is not a function declaration or definition.
374 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
375   // C++ [dcl.fct.default]p3
376   //   A default argument expression shall be specified only in the
377   //   parameter-declaration-clause of a function declaration or in a
378   //   template-parameter (14.1). It shall not be specified for a
379   //   parameter pack. If it is specified in a
380   //   parameter-declaration-clause, it shall not occur within a
381   //   declarator or abstract-declarator of a parameter-declaration.
382   bool MightBeFunction = D.isFunctionDeclarationContext();
383   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
384     DeclaratorChunk &chunk = D.getTypeObject(i);
385     if (chunk.Kind == DeclaratorChunk::Function) {
386       if (MightBeFunction) {
387         // This is a function declaration. It can have default arguments, but
388         // keep looking in case its return type is a function type with default
389         // arguments.
390         MightBeFunction = false;
391         continue;
392       }
393       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
394            ++argIdx) {
395         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
396         if (Param->hasUnparsedDefaultArg()) {
397           std::unique_ptr<CachedTokens> Toks =
398               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
399           SourceRange SR;
400           if (Toks->size() > 1)
401             SR = SourceRange((*Toks)[1].getLocation(),
402                              Toks->back().getLocation());
403           else
404             SR = UnparsedDefaultArgLocs[Param];
405           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
406             << SR;
407         } else if (Param->getDefaultArg()) {
408           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
409             << Param->getDefaultArg()->getSourceRange();
410           Param->setDefaultArg(nullptr);
411         }
412       }
413     } else if (chunk.Kind != DeclaratorChunk::Paren) {
414       MightBeFunction = false;
415     }
416   }
417 }
418 
419 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
420   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
421     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
422     if (!PVD->hasDefaultArg())
423       return false;
424     if (!PVD->hasInheritedDefaultArg())
425       return true;
426   }
427   return false;
428 }
429 
430 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
431 /// function, once we already know that they have the same
432 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
433 /// error, false otherwise.
434 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
435                                 Scope *S) {
436   bool Invalid = false;
437 
438   // The declaration context corresponding to the scope is the semantic
439   // parent, unless this is a local function declaration, in which case
440   // it is that surrounding function.
441   DeclContext *ScopeDC = New->isLocalExternDecl()
442                              ? New->getLexicalDeclContext()
443                              : New->getDeclContext();
444 
445   // Find the previous declaration for the purpose of default arguments.
446   FunctionDecl *PrevForDefaultArgs = Old;
447   for (/**/; PrevForDefaultArgs;
448        // Don't bother looking back past the latest decl if this is a local
449        // extern declaration; nothing else could work.
450        PrevForDefaultArgs = New->isLocalExternDecl()
451                                 ? nullptr
452                                 : PrevForDefaultArgs->getPreviousDecl()) {
453     // Ignore hidden declarations.
454     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
455       continue;
456 
457     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
458         !New->isCXXClassMember()) {
459       // Ignore default arguments of old decl if they are not in
460       // the same scope and this is not an out-of-line definition of
461       // a member function.
462       continue;
463     }
464 
465     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
466       // If only one of these is a local function declaration, then they are
467       // declared in different scopes, even though isDeclInScope may think
468       // they're in the same scope. (If both are local, the scope check is
469       // sufficient, and if neither is local, then they are in the same scope.)
470       continue;
471     }
472 
473     // We found the right previous declaration.
474     break;
475   }
476 
477   // C++ [dcl.fct.default]p4:
478   //   For non-template functions, default arguments can be added in
479   //   later declarations of a function in the same
480   //   scope. Declarations in different scopes have completely
481   //   distinct sets of default arguments. That is, declarations in
482   //   inner scopes do not acquire default arguments from
483   //   declarations in outer scopes, and vice versa. In a given
484   //   function declaration, all parameters subsequent to a
485   //   parameter with a default argument shall have default
486   //   arguments supplied in this or previous declarations. A
487   //   default argument shall not be redefined by a later
488   //   declaration (not even to the same value).
489   //
490   // C++ [dcl.fct.default]p6:
491   //   Except for member functions of class templates, the default arguments
492   //   in a member function definition that appears outside of the class
493   //   definition are added to the set of default arguments provided by the
494   //   member function declaration in the class definition.
495   for (unsigned p = 0, NumParams = PrevForDefaultArgs
496                                        ? PrevForDefaultArgs->getNumParams()
497                                        : 0;
498        p < NumParams; ++p) {
499     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
500     ParmVarDecl *NewParam = New->getParamDecl(p);
501 
502     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
503     bool NewParamHasDfl = NewParam->hasDefaultArg();
504 
505     if (OldParamHasDfl && NewParamHasDfl) {
506       unsigned DiagDefaultParamID =
507         diag::err_param_default_argument_redefinition;
508 
509       // MSVC accepts that default parameters be redefined for member functions
510       // of template class. The new default parameter's value is ignored.
511       Invalid = true;
512       if (getLangOpts().MicrosoftExt) {
513         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
514         if (MD && MD->getParent()->getDescribedClassTemplate()) {
515           // Merge the old default argument into the new parameter.
516           NewParam->setHasInheritedDefaultArg();
517           if (OldParam->hasUninstantiatedDefaultArg())
518             NewParam->setUninstantiatedDefaultArg(
519                                       OldParam->getUninstantiatedDefaultArg());
520           else
521             NewParam->setDefaultArg(OldParam->getInit());
522           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
523           Invalid = false;
524         }
525       }
526 
527       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
528       // hint here. Alternatively, we could walk the type-source information
529       // for NewParam to find the last source location in the type... but it
530       // isn't worth the effort right now. This is the kind of test case that
531       // is hard to get right:
532       //   int f(int);
533       //   void g(int (*fp)(int) = f);
534       //   void g(int (*fp)(int) = &f);
535       Diag(NewParam->getLocation(), DiagDefaultParamID)
536         << NewParam->getDefaultArgRange();
537 
538       // Look for the function declaration where the default argument was
539       // actually written, which may be a declaration prior to Old.
540       for (auto Older = PrevForDefaultArgs;
541            OldParam->hasInheritedDefaultArg(); /**/) {
542         Older = Older->getPreviousDecl();
543         OldParam = Older->getParamDecl(p);
544       }
545 
546       Diag(OldParam->getLocation(), diag::note_previous_definition)
547         << OldParam->getDefaultArgRange();
548     } else if (OldParamHasDfl) {
549       // Merge the old default argument into the new parameter unless the new
550       // function is a friend declaration in a template class. In the latter
551       // case the default arguments will be inherited when the friend
552       // declaration will be instantiated.
553       if (New->getFriendObjectKind() == Decl::FOK_None ||
554           !New->getLexicalDeclContext()->isDependentContext()) {
555         // It's important to use getInit() here;  getDefaultArg()
556         // strips off any top-level ExprWithCleanups.
557         NewParam->setHasInheritedDefaultArg();
558         if (OldParam->hasUnparsedDefaultArg())
559           NewParam->setUnparsedDefaultArg();
560         else if (OldParam->hasUninstantiatedDefaultArg())
561           NewParam->setUninstantiatedDefaultArg(
562                                        OldParam->getUninstantiatedDefaultArg());
563         else
564           NewParam->setDefaultArg(OldParam->getInit());
565       }
566     } else if (NewParamHasDfl) {
567       if (New->getDescribedFunctionTemplate()) {
568         // Paragraph 4, quoted above, only applies to non-template functions.
569         Diag(NewParam->getLocation(),
570              diag::err_param_default_argument_template_redecl)
571           << NewParam->getDefaultArgRange();
572         Diag(PrevForDefaultArgs->getLocation(),
573              diag::note_template_prev_declaration)
574             << false;
575       } else if (New->getTemplateSpecializationKind()
576                    != TSK_ImplicitInstantiation &&
577                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
578         // C++ [temp.expr.spec]p21:
579         //   Default function arguments shall not be specified in a declaration
580         //   or a definition for one of the following explicit specializations:
581         //     - the explicit specialization of a function template;
582         //     - the explicit specialization of a member function template;
583         //     - the explicit specialization of a member function of a class
584         //       template where the class template specialization to which the
585         //       member function specialization belongs is implicitly
586         //       instantiated.
587         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
588           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
589           << New->getDeclName()
590           << NewParam->getDefaultArgRange();
591       } else if (New->getDeclContext()->isDependentContext()) {
592         // C++ [dcl.fct.default]p6 (DR217):
593         //   Default arguments for a member function of a class template shall
594         //   be specified on the initial declaration of the member function
595         //   within the class template.
596         //
597         // Reading the tea leaves a bit in DR217 and its reference to DR205
598         // leads me to the conclusion that one cannot add default function
599         // arguments for an out-of-line definition of a member function of a
600         // dependent type.
601         int WhichKind = 2;
602         if (CXXRecordDecl *Record
603               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
604           if (Record->getDescribedClassTemplate())
605             WhichKind = 0;
606           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
607             WhichKind = 1;
608           else
609             WhichKind = 2;
610         }
611 
612         Diag(NewParam->getLocation(),
613              diag::err_param_default_argument_member_template_redecl)
614           << WhichKind
615           << NewParam->getDefaultArgRange();
616       }
617     }
618   }
619 
620   // DR1344: If a default argument is added outside a class definition and that
621   // default argument makes the function a special member function, the program
622   // is ill-formed. This can only happen for constructors.
623   if (isa<CXXConstructorDecl>(New) &&
624       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
625     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
626                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
627     if (NewSM != OldSM) {
628       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
629       assert(NewParam->hasDefaultArg());
630       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
631         << NewParam->getDefaultArgRange() << NewSM;
632       Diag(Old->getLocation(), diag::note_previous_declaration);
633     }
634   }
635 
636   const FunctionDecl *Def;
637   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
638   // template has a constexpr specifier then all its declarations shall
639   // contain the constexpr specifier.
640   if (New->isConstexpr() != Old->isConstexpr()) {
641     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
642       << New << New->isConstexpr();
643     Diag(Old->getLocation(), diag::note_previous_declaration);
644     Invalid = true;
645   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
646              Old->isDefined(Def) &&
647              // If a friend function is inlined but does not have 'inline'
648              // specifier, it is a definition. Do not report attribute conflict
649              // in this case, redefinition will be diagnosed later.
650              (New->isInlineSpecified() ||
651               New->getFriendObjectKind() == Decl::FOK_None)) {
652     // C++11 [dcl.fcn.spec]p4:
653     //   If the definition of a function appears in a translation unit before its
654     //   first declaration as inline, the program is ill-formed.
655     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
656     Diag(Def->getLocation(), diag::note_previous_definition);
657     Invalid = true;
658   }
659 
660   // C++17 [temp.deduct.guide]p3:
661   //   Two deduction guide declarations in the same translation unit
662   //   for the same class template shall not have equivalent
663   //   parameter-declaration-clauses.
664   if (isa<CXXDeductionGuideDecl>(New) &&
665       !New->isFunctionTemplateSpecialization()) {
666     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
667     Diag(Old->getLocation(), diag::note_previous_declaration);
668   }
669 
670   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
671   // argument expression, that declaration shall be a definition and shall be
672   // the only declaration of the function or function template in the
673   // translation unit.
674   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
675       functionDeclHasDefaultArgument(Old)) {
676     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
677     Diag(Old->getLocation(), diag::note_previous_declaration);
678     Invalid = true;
679   }
680 
681   return Invalid;
682 }
683 
684 NamedDecl *
685 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
686                                    MultiTemplateParamsArg TemplateParamLists) {
687   assert(D.isDecompositionDeclarator());
688   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
689 
690   // The syntax only allows a decomposition declarator as a simple-declaration,
691   // a for-range-declaration, or a condition in Clang, but we parse it in more
692   // cases than that.
693   if (!D.mayHaveDecompositionDeclarator()) {
694     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
695       << Decomp.getSourceRange();
696     return nullptr;
697   }
698 
699   if (!TemplateParamLists.empty()) {
700     // FIXME: There's no rule against this, but there are also no rules that
701     // would actually make it usable, so we reject it for now.
702     Diag(TemplateParamLists.front()->getTemplateLoc(),
703          diag::err_decomp_decl_template);
704     return nullptr;
705   }
706 
707   Diag(Decomp.getLSquareLoc(),
708        !getLangOpts().CPlusPlus17
709            ? diag::ext_decomp_decl
710            : D.getContext() == DeclaratorContext::ConditionContext
711                  ? diag::ext_decomp_decl_cond
712                  : diag::warn_cxx14_compat_decomp_decl)
713       << Decomp.getSourceRange();
714 
715   // The semantic context is always just the current context.
716   DeclContext *const DC = CurContext;
717 
718   // C++1z [dcl.dcl]/8:
719   //   The decl-specifier-seq shall contain only the type-specifier auto
720   //   and cv-qualifiers.
721   auto &DS = D.getDeclSpec();
722   {
723     SmallVector<StringRef, 8> BadSpecifiers;
724     SmallVector<SourceLocation, 8> BadSpecifierLocs;
725     if (auto SCS = DS.getStorageClassSpec()) {
726       BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
727       BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
728     }
729     if (auto TSCS = DS.getThreadStorageClassSpec()) {
730       BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
731       BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
732     }
733     if (DS.isConstexprSpecified()) {
734       BadSpecifiers.push_back("constexpr");
735       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
736     }
737     if (DS.isInlineSpecified()) {
738       BadSpecifiers.push_back("inline");
739       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
740     }
741     if (!BadSpecifiers.empty()) {
742       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
743       Err << (int)BadSpecifiers.size()
744           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
745       // Don't add FixItHints to remove the specifiers; we do still respect
746       // them when building the underlying variable.
747       for (auto Loc : BadSpecifierLocs)
748         Err << SourceRange(Loc, Loc);
749     }
750     // We can't recover from it being declared as a typedef.
751     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
752       return nullptr;
753   }
754 
755   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
756   QualType R = TInfo->getType();
757 
758   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
759                                       UPPC_DeclarationType))
760     D.setInvalidType();
761 
762   // The syntax only allows a single ref-qualifier prior to the decomposition
763   // declarator. No other declarator chunks are permitted. Also check the type
764   // specifier here.
765   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
766       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
767       (D.getNumTypeObjects() == 1 &&
768        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
769     Diag(Decomp.getLSquareLoc(),
770          (D.hasGroupingParens() ||
771           (D.getNumTypeObjects() &&
772            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
773              ? diag::err_decomp_decl_parens
774              : diag::err_decomp_decl_type)
775         << R;
776 
777     // In most cases, there's no actual problem with an explicitly-specified
778     // type, but a function type won't work here, and ActOnVariableDeclarator
779     // shouldn't be called for such a type.
780     if (R->isFunctionType())
781       D.setInvalidType();
782   }
783 
784   // Build the BindingDecls.
785   SmallVector<BindingDecl*, 8> Bindings;
786 
787   // Build the BindingDecls.
788   for (auto &B : D.getDecompositionDeclarator().bindings()) {
789     // Check for name conflicts.
790     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
791     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
792                           ForVisibleRedeclaration);
793     LookupName(Previous, S,
794                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
795 
796     // It's not permitted to shadow a template parameter name.
797     if (Previous.isSingleResult() &&
798         Previous.getFoundDecl()->isTemplateParameter()) {
799       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
800                                       Previous.getFoundDecl());
801       Previous.clear();
802     }
803 
804     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
805                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
806     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
807                          /*AllowInlineNamespace*/false);
808     if (!Previous.empty()) {
809       auto *Old = Previous.getRepresentativeDecl();
810       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
811       Diag(Old->getLocation(), diag::note_previous_definition);
812     }
813 
814     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
815     PushOnScopeChains(BD, S, true);
816     Bindings.push_back(BD);
817     ParsingInitForAutoVars.insert(BD);
818   }
819 
820   // There are no prior lookup results for the variable itself, because it
821   // is unnamed.
822   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
823                                Decomp.getLSquareLoc());
824   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
825                         ForVisibleRedeclaration);
826 
827   // Build the variable that holds the non-decomposed object.
828   bool AddToScope = true;
829   NamedDecl *New =
830       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
831                               MultiTemplateParamsArg(), AddToScope, Bindings);
832   if (AddToScope) {
833     S->AddDecl(New);
834     CurContext->addHiddenDecl(New);
835   }
836 
837   if (isInOpenMPDeclareTargetContext())
838     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
839 
840   return New;
841 }
842 
843 static bool checkSimpleDecomposition(
844     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
845     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
846     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
847   if ((int64_t)Bindings.size() != NumElems) {
848     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
849         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
850         << (NumElems < Bindings.size());
851     return true;
852   }
853 
854   unsigned I = 0;
855   for (auto *B : Bindings) {
856     SourceLocation Loc = B->getLocation();
857     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
858     if (E.isInvalid())
859       return true;
860     E = GetInit(Loc, E.get(), I++);
861     if (E.isInvalid())
862       return true;
863     B->setBinding(ElemType, E.get());
864   }
865 
866   return false;
867 }
868 
869 static bool checkArrayLikeDecomposition(Sema &S,
870                                         ArrayRef<BindingDecl *> Bindings,
871                                         ValueDecl *Src, QualType DecompType,
872                                         const llvm::APSInt &NumElems,
873                                         QualType ElemType) {
874   return checkSimpleDecomposition(
875       S, Bindings, Src, DecompType, NumElems, ElemType,
876       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
877         ExprResult E = S.ActOnIntegerConstant(Loc, I);
878         if (E.isInvalid())
879           return ExprError();
880         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
881       });
882 }
883 
884 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
885                                     ValueDecl *Src, QualType DecompType,
886                                     const ConstantArrayType *CAT) {
887   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
888                                      llvm::APSInt(CAT->getSize()),
889                                      CAT->getElementType());
890 }
891 
892 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
893                                      ValueDecl *Src, QualType DecompType,
894                                      const VectorType *VT) {
895   return checkArrayLikeDecomposition(
896       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
897       S.Context.getQualifiedType(VT->getElementType(),
898                                  DecompType.getQualifiers()));
899 }
900 
901 static bool checkComplexDecomposition(Sema &S,
902                                       ArrayRef<BindingDecl *> Bindings,
903                                       ValueDecl *Src, QualType DecompType,
904                                       const ComplexType *CT) {
905   return checkSimpleDecomposition(
906       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
907       S.Context.getQualifiedType(CT->getElementType(),
908                                  DecompType.getQualifiers()),
909       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
910         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
911       });
912 }
913 
914 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
915                                      TemplateArgumentListInfo &Args) {
916   SmallString<128> SS;
917   llvm::raw_svector_ostream OS(SS);
918   bool First = true;
919   for (auto &Arg : Args.arguments()) {
920     if (!First)
921       OS << ", ";
922     Arg.getArgument().print(PrintingPolicy, OS);
923     First = false;
924   }
925   return OS.str();
926 }
927 
928 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
929                                      SourceLocation Loc, StringRef Trait,
930                                      TemplateArgumentListInfo &Args,
931                                      unsigned DiagID) {
932   auto DiagnoseMissing = [&] {
933     if (DiagID)
934       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
935                                                Args);
936     return true;
937   };
938 
939   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
940   NamespaceDecl *Std = S.getStdNamespace();
941   if (!Std)
942     return DiagnoseMissing();
943 
944   // Look up the trait itself, within namespace std. We can diagnose various
945   // problems with this lookup even if we've been asked to not diagnose a
946   // missing specialization, because this can only fail if the user has been
947   // declaring their own names in namespace std or we don't support the
948   // standard library implementation in use.
949   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
950                       Loc, Sema::LookupOrdinaryName);
951   if (!S.LookupQualifiedName(Result, Std))
952     return DiagnoseMissing();
953   if (Result.isAmbiguous())
954     return true;
955 
956   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
957   if (!TraitTD) {
958     Result.suppressDiagnostics();
959     NamedDecl *Found = *Result.begin();
960     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
961     S.Diag(Found->getLocation(), diag::note_declared_at);
962     return true;
963   }
964 
965   // Build the template-id.
966   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
967   if (TraitTy.isNull())
968     return true;
969   if (!S.isCompleteType(Loc, TraitTy)) {
970     if (DiagID)
971       S.RequireCompleteType(
972           Loc, TraitTy, DiagID,
973           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
974     return true;
975   }
976 
977   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
978   assert(RD && "specialization of class template is not a class?");
979 
980   // Look up the member of the trait type.
981   S.LookupQualifiedName(TraitMemberLookup, RD);
982   return TraitMemberLookup.isAmbiguous();
983 }
984 
985 static TemplateArgumentLoc
986 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
987                                    uint64_t I) {
988   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
989   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
990 }
991 
992 static TemplateArgumentLoc
993 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
994   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
995 }
996 
997 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
998 
999 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1000                                llvm::APSInt &Size) {
1001   EnterExpressionEvaluationContext ContextRAII(
1002       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1003 
1004   DeclarationName Value = S.PP.getIdentifierInfo("value");
1005   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1006 
1007   // Form template argument list for tuple_size<T>.
1008   TemplateArgumentListInfo Args(Loc, Loc);
1009   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1010 
1011   // If there's no tuple_size specialization, it's not tuple-like.
1012   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1013     return IsTupleLike::NotTupleLike;
1014 
1015   // If we get this far, we've committed to the tuple interpretation, but
1016   // we can still fail if there actually isn't a usable ::value.
1017 
1018   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1019     LookupResult &R;
1020     TemplateArgumentListInfo &Args;
1021     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1022         : R(R), Args(Args) {}
1023     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1024       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1025           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1026     }
1027   } Diagnoser(R, Args);
1028 
1029   if (R.empty()) {
1030     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1031     return IsTupleLike::Error;
1032   }
1033 
1034   ExprResult E =
1035       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1036   if (E.isInvalid())
1037     return IsTupleLike::Error;
1038 
1039   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1040   if (E.isInvalid())
1041     return IsTupleLike::Error;
1042 
1043   return IsTupleLike::TupleLike;
1044 }
1045 
1046 /// \return std::tuple_element<I, T>::type.
1047 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1048                                         unsigned I, QualType T) {
1049   // Form template argument list for tuple_element<I, T>.
1050   TemplateArgumentListInfo Args(Loc, Loc);
1051   Args.addArgument(
1052       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1053   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1054 
1055   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1056   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1057   if (lookupStdTypeTraitMember(
1058           S, R, Loc, "tuple_element", Args,
1059           diag::err_decomp_decl_std_tuple_element_not_specialized))
1060     return QualType();
1061 
1062   auto *TD = R.getAsSingle<TypeDecl>();
1063   if (!TD) {
1064     R.suppressDiagnostics();
1065     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1066       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1067     if (!R.empty())
1068       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1069     return QualType();
1070   }
1071 
1072   return S.Context.getTypeDeclType(TD);
1073 }
1074 
1075 namespace {
1076 struct BindingDiagnosticTrap {
1077   Sema &S;
1078   DiagnosticErrorTrap Trap;
1079   BindingDecl *BD;
1080 
1081   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1082       : S(S), Trap(S.Diags), BD(BD) {}
1083   ~BindingDiagnosticTrap() {
1084     if (Trap.hasErrorOccurred())
1085       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1086   }
1087 };
1088 }
1089 
1090 static bool checkTupleLikeDecomposition(Sema &S,
1091                                         ArrayRef<BindingDecl *> Bindings,
1092                                         VarDecl *Src, QualType DecompType,
1093                                         const llvm::APSInt &TupleSize) {
1094   if ((int64_t)Bindings.size() != TupleSize) {
1095     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1096         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1097         << (TupleSize < Bindings.size());
1098     return true;
1099   }
1100 
1101   if (Bindings.empty())
1102     return false;
1103 
1104   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1105 
1106   // [dcl.decomp]p3:
1107   //   The unqualified-id get is looked up in the scope of E by class member
1108   //   access lookup ...
1109   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1110   bool UseMemberGet = false;
1111   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1112     if (auto *RD = DecompType->getAsCXXRecordDecl())
1113       S.LookupQualifiedName(MemberGet, RD);
1114     if (MemberGet.isAmbiguous())
1115       return true;
1116     //   ... and if that finds at least one declaration that is a function
1117     //   template whose first template parameter is a non-type parameter ...
1118     for (NamedDecl *D : MemberGet) {
1119       if (FunctionTemplateDecl *FTD =
1120               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1121         TemplateParameterList *TPL = FTD->getTemplateParameters();
1122         if (TPL->size() != 0 &&
1123             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1124           //   ... the initializer is e.get<i>().
1125           UseMemberGet = true;
1126           break;
1127         }
1128       }
1129     }
1130   }
1131 
1132   unsigned I = 0;
1133   for (auto *B : Bindings) {
1134     BindingDiagnosticTrap Trap(S, B);
1135     SourceLocation Loc = B->getLocation();
1136 
1137     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1138     if (E.isInvalid())
1139       return true;
1140 
1141     //   e is an lvalue if the type of the entity is an lvalue reference and
1142     //   an xvalue otherwise
1143     if (!Src->getType()->isLValueReferenceType())
1144       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1145                                    E.get(), nullptr, VK_XValue);
1146 
1147     TemplateArgumentListInfo Args(Loc, Loc);
1148     Args.addArgument(
1149         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1150 
1151     if (UseMemberGet) {
1152       //   if [lookup of member get] finds at least one declaration, the
1153       //   initializer is e.get<i-1>().
1154       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1155                                      CXXScopeSpec(), SourceLocation(), nullptr,
1156                                      MemberGet, &Args, nullptr);
1157       if (E.isInvalid())
1158         return true;
1159 
1160       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1161     } else {
1162       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1163       //   in the associated namespaces.
1164       Expr *Get = UnresolvedLookupExpr::Create(
1165           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1166           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1167           UnresolvedSetIterator(), UnresolvedSetIterator());
1168 
1169       Expr *Arg = E.get();
1170       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1171     }
1172     if (E.isInvalid())
1173       return true;
1174     Expr *Init = E.get();
1175 
1176     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1177     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1178     if (T.isNull())
1179       return true;
1180 
1181     //   each vi is a variable of type "reference to T" initialized with the
1182     //   initializer, where the reference is an lvalue reference if the
1183     //   initializer is an lvalue and an rvalue reference otherwise
1184     QualType RefType =
1185         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1186     if (RefType.isNull())
1187       return true;
1188     auto *RefVD = VarDecl::Create(
1189         S.Context, Src->getDeclContext(), Loc, Loc,
1190         B->getDeclName().getAsIdentifierInfo(), RefType,
1191         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1192     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1193     RefVD->setTSCSpec(Src->getTSCSpec());
1194     RefVD->setImplicit();
1195     if (Src->isInlineSpecified())
1196       RefVD->setInlineSpecified();
1197     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1198 
1199     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1200     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1201     InitializationSequence Seq(S, Entity, Kind, Init);
1202     E = Seq.Perform(S, Entity, Kind, Init);
1203     if (E.isInvalid())
1204       return true;
1205     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1206     if (E.isInvalid())
1207       return true;
1208     RefVD->setInit(E.get());
1209     RefVD->checkInitIsICE();
1210 
1211     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1212                                    DeclarationNameInfo(B->getDeclName(), Loc),
1213                                    RefVD);
1214     if (E.isInvalid())
1215       return true;
1216 
1217     B->setBinding(T, E.get());
1218     I++;
1219   }
1220 
1221   return false;
1222 }
1223 
1224 /// Find the base class to decompose in a built-in decomposition of a class type.
1225 /// This base class search is, unfortunately, not quite like any other that we
1226 /// perform anywhere else in C++.
1227 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1228                                                 const CXXRecordDecl *RD,
1229                                                 CXXCastPath &BasePath) {
1230   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1231                           CXXBasePath &Path) {
1232     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1233   };
1234 
1235   const CXXRecordDecl *ClassWithFields = nullptr;
1236   AccessSpecifier AS = AS_public;
1237   if (RD->hasDirectFields())
1238     // [dcl.decomp]p4:
1239     //   Otherwise, all of E's non-static data members shall be public direct
1240     //   members of E ...
1241     ClassWithFields = RD;
1242   else {
1243     //   ... or of ...
1244     CXXBasePaths Paths;
1245     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1246     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1247       // If no classes have fields, just decompose RD itself. (This will work
1248       // if and only if zero bindings were provided.)
1249       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1250     }
1251 
1252     CXXBasePath *BestPath = nullptr;
1253     for (auto &P : Paths) {
1254       if (!BestPath)
1255         BestPath = &P;
1256       else if (!S.Context.hasSameType(P.back().Base->getType(),
1257                                       BestPath->back().Base->getType())) {
1258         //   ... the same ...
1259         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1260           << false << RD << BestPath->back().Base->getType()
1261           << P.back().Base->getType();
1262         return DeclAccessPair();
1263       } else if (P.Access < BestPath->Access) {
1264         BestPath = &P;
1265       }
1266     }
1267 
1268     //   ... unambiguous ...
1269     QualType BaseType = BestPath->back().Base->getType();
1270     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1271       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1272         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1273       return DeclAccessPair();
1274     }
1275 
1276     //   ... [accessible, implied by other rules] base class of E.
1277     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1278                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1279     AS = BestPath->Access;
1280 
1281     ClassWithFields = BaseType->getAsCXXRecordDecl();
1282     S.BuildBasePathArray(Paths, BasePath);
1283   }
1284 
1285   // The above search did not check whether the selected class itself has base
1286   // classes with fields, so check that now.
1287   CXXBasePaths Paths;
1288   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1289     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1290       << (ClassWithFields == RD) << RD << ClassWithFields
1291       << Paths.front().back().Base->getType();
1292     return DeclAccessPair();
1293   }
1294 
1295   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1296 }
1297 
1298 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1299                                      ValueDecl *Src, QualType DecompType,
1300                                      const CXXRecordDecl *OrigRD) {
1301   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1302                             diag::err_incomplete_type))
1303     return true;
1304 
1305   CXXCastPath BasePath;
1306   DeclAccessPair BasePair =
1307       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1308   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1309   if (!RD)
1310     return true;
1311   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1312                                                  DecompType.getQualifiers());
1313 
1314   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1315     unsigned NumFields =
1316         std::count_if(RD->field_begin(), RD->field_end(),
1317                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1318     assert(Bindings.size() != NumFields);
1319     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1320         << DecompType << (unsigned)Bindings.size() << NumFields
1321         << (NumFields < Bindings.size());
1322     return true;
1323   };
1324 
1325   //   all of E's non-static data members shall be [...] well-formed
1326   //   when named as e.name in the context of the structured binding,
1327   //   E shall not have an anonymous union member, ...
1328   unsigned I = 0;
1329   for (auto *FD : RD->fields()) {
1330     if (FD->isUnnamedBitfield())
1331       continue;
1332 
1333     if (FD->isAnonymousStructOrUnion()) {
1334       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1335         << DecompType << FD->getType()->isUnionType();
1336       S.Diag(FD->getLocation(), diag::note_declared_at);
1337       return true;
1338     }
1339 
1340     // We have a real field to bind.
1341     if (I >= Bindings.size())
1342       return DiagnoseBadNumberOfBindings();
1343     auto *B = Bindings[I++];
1344     SourceLocation Loc = B->getLocation();
1345 
1346     // The field must be accessible in the context of the structured binding.
1347     // We already checked that the base class is accessible.
1348     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1349     // const_cast here.
1350     S.CheckStructuredBindingMemberAccess(
1351         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1352         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1353                                      BasePair.getAccess(), FD->getAccess())));
1354 
1355     // Initialize the binding to Src.FD.
1356     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1357     if (E.isInvalid())
1358       return true;
1359     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1360                             VK_LValue, &BasePath);
1361     if (E.isInvalid())
1362       return true;
1363     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1364                                   CXXScopeSpec(), FD,
1365                                   DeclAccessPair::make(FD, FD->getAccess()),
1366                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1367     if (E.isInvalid())
1368       return true;
1369 
1370     // If the type of the member is T, the referenced type is cv T, where cv is
1371     // the cv-qualification of the decomposition expression.
1372     //
1373     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1374     // 'const' to the type of the field.
1375     Qualifiers Q = DecompType.getQualifiers();
1376     if (FD->isMutable())
1377       Q.removeConst();
1378     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1379   }
1380 
1381   if (I != Bindings.size())
1382     return DiagnoseBadNumberOfBindings();
1383 
1384   return false;
1385 }
1386 
1387 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1388   QualType DecompType = DD->getType();
1389 
1390   // If the type of the decomposition is dependent, then so is the type of
1391   // each binding.
1392   if (DecompType->isDependentType()) {
1393     for (auto *B : DD->bindings())
1394       B->setType(Context.DependentTy);
1395     return;
1396   }
1397 
1398   DecompType = DecompType.getNonReferenceType();
1399   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1400 
1401   // C++1z [dcl.decomp]/2:
1402   //   If E is an array type [...]
1403   // As an extension, we also support decomposition of built-in complex and
1404   // vector types.
1405   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1406     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1407       DD->setInvalidDecl();
1408     return;
1409   }
1410   if (auto *VT = DecompType->getAs<VectorType>()) {
1411     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1412       DD->setInvalidDecl();
1413     return;
1414   }
1415   if (auto *CT = DecompType->getAs<ComplexType>()) {
1416     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1417       DD->setInvalidDecl();
1418     return;
1419   }
1420 
1421   // C++1z [dcl.decomp]/3:
1422   //   if the expression std::tuple_size<E>::value is a well-formed integral
1423   //   constant expression, [...]
1424   llvm::APSInt TupleSize(32);
1425   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1426   case IsTupleLike::Error:
1427     DD->setInvalidDecl();
1428     return;
1429 
1430   case IsTupleLike::TupleLike:
1431     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1432       DD->setInvalidDecl();
1433     return;
1434 
1435   case IsTupleLike::NotTupleLike:
1436     break;
1437   }
1438 
1439   // C++1z [dcl.dcl]/8:
1440   //   [E shall be of array or non-union class type]
1441   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1442   if (!RD || RD->isUnion()) {
1443     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1444         << DD << !RD << DecompType;
1445     DD->setInvalidDecl();
1446     return;
1447   }
1448 
1449   // C++1z [dcl.decomp]/4:
1450   //   all of E's non-static data members shall be [...] direct members of
1451   //   E or of the same unambiguous public base class of E, ...
1452   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1453     DD->setInvalidDecl();
1454 }
1455 
1456 /// Merge the exception specifications of two variable declarations.
1457 ///
1458 /// This is called when there's a redeclaration of a VarDecl. The function
1459 /// checks if the redeclaration might have an exception specification and
1460 /// validates compatibility and merges the specs if necessary.
1461 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1462   // Shortcut if exceptions are disabled.
1463   if (!getLangOpts().CXXExceptions)
1464     return;
1465 
1466   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1467          "Should only be called if types are otherwise the same.");
1468 
1469   QualType NewType = New->getType();
1470   QualType OldType = Old->getType();
1471 
1472   // We're only interested in pointers and references to functions, as well
1473   // as pointers to member functions.
1474   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1475     NewType = R->getPointeeType();
1476     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1477   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1478     NewType = P->getPointeeType();
1479     OldType = OldType->getAs<PointerType>()->getPointeeType();
1480   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1481     NewType = M->getPointeeType();
1482     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1483   }
1484 
1485   if (!NewType->isFunctionProtoType())
1486     return;
1487 
1488   // There's lots of special cases for functions. For function pointers, system
1489   // libraries are hopefully not as broken so that we don't need these
1490   // workarounds.
1491   if (CheckEquivalentExceptionSpec(
1492         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1493         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1494     New->setInvalidDecl();
1495   }
1496 }
1497 
1498 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1499 /// function declaration are well-formed according to C++
1500 /// [dcl.fct.default].
1501 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1502   unsigned NumParams = FD->getNumParams();
1503   unsigned p;
1504 
1505   // Find first parameter with a default argument
1506   for (p = 0; p < NumParams; ++p) {
1507     ParmVarDecl *Param = FD->getParamDecl(p);
1508     if (Param->hasDefaultArg())
1509       break;
1510   }
1511 
1512   // C++11 [dcl.fct.default]p4:
1513   //   In a given function declaration, each parameter subsequent to a parameter
1514   //   with a default argument shall have a default argument supplied in this or
1515   //   a previous declaration or shall be a function parameter pack. A default
1516   //   argument shall not be redefined by a later declaration (not even to the
1517   //   same value).
1518   unsigned LastMissingDefaultArg = 0;
1519   for (; p < NumParams; ++p) {
1520     ParmVarDecl *Param = FD->getParamDecl(p);
1521     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1522       if (Param->isInvalidDecl())
1523         /* We already complained about this parameter. */;
1524       else if (Param->getIdentifier())
1525         Diag(Param->getLocation(),
1526              diag::err_param_default_argument_missing_name)
1527           << Param->getIdentifier();
1528       else
1529         Diag(Param->getLocation(),
1530              diag::err_param_default_argument_missing);
1531 
1532       LastMissingDefaultArg = p;
1533     }
1534   }
1535 
1536   if (LastMissingDefaultArg > 0) {
1537     // Some default arguments were missing. Clear out all of the
1538     // default arguments up to (and including) the last missing
1539     // default argument, so that we leave the function parameters
1540     // in a semantically valid state.
1541     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1542       ParmVarDecl *Param = FD->getParamDecl(p);
1543       if (Param->hasDefaultArg()) {
1544         Param->setDefaultArg(nullptr);
1545       }
1546     }
1547   }
1548 }
1549 
1550 // CheckConstexprParameterTypes - Check whether a function's parameter types
1551 // are all literal types. If so, return true. If not, produce a suitable
1552 // diagnostic and return false.
1553 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1554                                          const FunctionDecl *FD) {
1555   unsigned ArgIndex = 0;
1556   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1557   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1558                                               e = FT->param_type_end();
1559        i != e; ++i, ++ArgIndex) {
1560     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1561     SourceLocation ParamLoc = PD->getLocation();
1562     if (!(*i)->isDependentType() &&
1563         SemaRef.RequireLiteralType(ParamLoc, *i,
1564                                    diag::err_constexpr_non_literal_param,
1565                                    ArgIndex+1, PD->getSourceRange(),
1566                                    isa<CXXConstructorDecl>(FD)))
1567       return false;
1568   }
1569   return true;
1570 }
1571 
1572 /// Get diagnostic %select index for tag kind for
1573 /// record diagnostic message.
1574 /// WARNING: Indexes apply to particular diagnostics only!
1575 ///
1576 /// \returns diagnostic %select index.
1577 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1578   switch (Tag) {
1579   case TTK_Struct: return 0;
1580   case TTK_Interface: return 1;
1581   case TTK_Class:  return 2;
1582   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1583   }
1584 }
1585 
1586 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1587 // the requirements of a constexpr function definition or a constexpr
1588 // constructor definition. If so, return true. If not, produce appropriate
1589 // diagnostics and return false.
1590 //
1591 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1592 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1593   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1594   if (MD && MD->isInstance()) {
1595     // C++11 [dcl.constexpr]p4:
1596     //  The definition of a constexpr constructor shall satisfy the following
1597     //  constraints:
1598     //  - the class shall not have any virtual base classes;
1599     //
1600     // FIXME: This only applies to constructors, not arbitrary member
1601     // functions.
1602     const CXXRecordDecl *RD = MD->getParent();
1603     if (RD->getNumVBases()) {
1604       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1605         << isa<CXXConstructorDecl>(NewFD)
1606         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1607       for (const auto &I : RD->vbases())
1608         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1609             << I.getSourceRange();
1610       return false;
1611     }
1612   }
1613 
1614   if (!isa<CXXConstructorDecl>(NewFD)) {
1615     // C++11 [dcl.constexpr]p3:
1616     //  The definition of a constexpr function shall satisfy the following
1617     //  constraints:
1618     // - it shall not be virtual; (removed in C++20)
1619     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1620     if (Method && Method->isVirtual()) {
1621       if (getLangOpts().CPlusPlus2a) {
1622         Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1623       } else {
1624         Method = Method->getCanonicalDecl();
1625         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1626 
1627         // If it's not obvious why this function is virtual, find an overridden
1628         // function which uses the 'virtual' keyword.
1629         const CXXMethodDecl *WrittenVirtual = Method;
1630         while (!WrittenVirtual->isVirtualAsWritten())
1631           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1632         if (WrittenVirtual != Method)
1633           Diag(WrittenVirtual->getLocation(),
1634                diag::note_overridden_virtual_function);
1635         return false;
1636       }
1637     }
1638 
1639     // - its return type shall be a literal type;
1640     QualType RT = NewFD->getReturnType();
1641     if (!RT->isDependentType() &&
1642         RequireLiteralType(NewFD->getLocation(), RT,
1643                            diag::err_constexpr_non_literal_return))
1644       return false;
1645   }
1646 
1647   // - each of its parameter types shall be a literal type;
1648   if (!CheckConstexprParameterTypes(*this, NewFD))
1649     return false;
1650 
1651   return true;
1652 }
1653 
1654 /// Check the given declaration statement is legal within a constexpr function
1655 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1656 ///
1657 /// \return true if the body is OK (maybe only as an extension), false if we
1658 ///         have diagnosed a problem.
1659 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1660                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1661   // C++11 [dcl.constexpr]p3 and p4:
1662   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1663   //  contain only
1664   for (const auto *DclIt : DS->decls()) {
1665     switch (DclIt->getKind()) {
1666     case Decl::StaticAssert:
1667     case Decl::Using:
1668     case Decl::UsingShadow:
1669     case Decl::UsingDirective:
1670     case Decl::UnresolvedUsingTypename:
1671     case Decl::UnresolvedUsingValue:
1672       //   - static_assert-declarations
1673       //   - using-declarations,
1674       //   - using-directives,
1675       continue;
1676 
1677     case Decl::Typedef:
1678     case Decl::TypeAlias: {
1679       //   - typedef declarations and alias-declarations that do not define
1680       //     classes or enumerations,
1681       const auto *TN = cast<TypedefNameDecl>(DclIt);
1682       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1683         // Don't allow variably-modified types in constexpr functions.
1684         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1685         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1686           << TL.getSourceRange() << TL.getType()
1687           << isa<CXXConstructorDecl>(Dcl);
1688         return false;
1689       }
1690       continue;
1691     }
1692 
1693     case Decl::Enum:
1694     case Decl::CXXRecord:
1695       // C++1y allows types to be defined, not just declared.
1696       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1697         SemaRef.Diag(DS->getBeginLoc(),
1698                      SemaRef.getLangOpts().CPlusPlus14
1699                          ? diag::warn_cxx11_compat_constexpr_type_definition
1700                          : diag::ext_constexpr_type_definition)
1701             << isa<CXXConstructorDecl>(Dcl);
1702       continue;
1703 
1704     case Decl::EnumConstant:
1705     case Decl::IndirectField:
1706     case Decl::ParmVar:
1707       // These can only appear with other declarations which are banned in
1708       // C++11 and permitted in C++1y, so ignore them.
1709       continue;
1710 
1711     case Decl::Var:
1712     case Decl::Decomposition: {
1713       // C++1y [dcl.constexpr]p3 allows anything except:
1714       //   a definition of a variable of non-literal type or of static or
1715       //   thread storage duration or for which no initialization is performed.
1716       const auto *VD = cast<VarDecl>(DclIt);
1717       if (VD->isThisDeclarationADefinition()) {
1718         if (VD->isStaticLocal()) {
1719           SemaRef.Diag(VD->getLocation(),
1720                        diag::err_constexpr_local_var_static)
1721             << isa<CXXConstructorDecl>(Dcl)
1722             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1723           return false;
1724         }
1725         if (!VD->getType()->isDependentType() &&
1726             SemaRef.RequireLiteralType(
1727               VD->getLocation(), VD->getType(),
1728               diag::err_constexpr_local_var_non_literal_type,
1729               isa<CXXConstructorDecl>(Dcl)))
1730           return false;
1731         if (!VD->getType()->isDependentType() &&
1732             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1733           SemaRef.Diag(VD->getLocation(),
1734                        diag::err_constexpr_local_var_no_init)
1735             << isa<CXXConstructorDecl>(Dcl);
1736           return false;
1737         }
1738       }
1739       SemaRef.Diag(VD->getLocation(),
1740                    SemaRef.getLangOpts().CPlusPlus14
1741                     ? diag::warn_cxx11_compat_constexpr_local_var
1742                     : diag::ext_constexpr_local_var)
1743         << isa<CXXConstructorDecl>(Dcl);
1744       continue;
1745     }
1746 
1747     case Decl::NamespaceAlias:
1748     case Decl::Function:
1749       // These are disallowed in C++11 and permitted in C++1y. Allow them
1750       // everywhere as an extension.
1751       if (!Cxx1yLoc.isValid())
1752         Cxx1yLoc = DS->getBeginLoc();
1753       continue;
1754 
1755     default:
1756       SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1757           << isa<CXXConstructorDecl>(Dcl);
1758       return false;
1759     }
1760   }
1761 
1762   return true;
1763 }
1764 
1765 /// Check that the given field is initialized within a constexpr constructor.
1766 ///
1767 /// \param Dcl The constexpr constructor being checked.
1768 /// \param Field The field being checked. This may be a member of an anonymous
1769 ///        struct or union nested within the class being checked.
1770 /// \param Inits All declarations, including anonymous struct/union members and
1771 ///        indirect members, for which any initialization was provided.
1772 /// \param Diagnosed Set to true if an error is produced.
1773 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1774                                           const FunctionDecl *Dcl,
1775                                           FieldDecl *Field,
1776                                           llvm::SmallSet<Decl*, 16> &Inits,
1777                                           bool &Diagnosed) {
1778   if (Field->isInvalidDecl())
1779     return;
1780 
1781   if (Field->isUnnamedBitfield())
1782     return;
1783 
1784   // Anonymous unions with no variant members and empty anonymous structs do not
1785   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1786   // indirect fields don't need initializing.
1787   if (Field->isAnonymousStructOrUnion() &&
1788       (Field->getType()->isUnionType()
1789            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1790            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1791     return;
1792 
1793   if (!Inits.count(Field)) {
1794     if (!Diagnosed) {
1795       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1796       Diagnosed = true;
1797     }
1798     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1799   } else if (Field->isAnonymousStructOrUnion()) {
1800     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1801     for (auto *I : RD->fields())
1802       // If an anonymous union contains an anonymous struct of which any member
1803       // is initialized, all members must be initialized.
1804       if (!RD->isUnion() || Inits.count(I))
1805         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1806   }
1807 }
1808 
1809 /// Check the provided statement is allowed in a constexpr function
1810 /// definition.
1811 static bool
1812 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1813                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1814                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc) {
1815   // - its function-body shall be [...] a compound-statement that contains only
1816   switch (S->getStmtClass()) {
1817   case Stmt::NullStmtClass:
1818     //   - null statements,
1819     return true;
1820 
1821   case Stmt::DeclStmtClass:
1822     //   - static_assert-declarations
1823     //   - using-declarations,
1824     //   - using-directives,
1825     //   - typedef declarations and alias-declarations that do not define
1826     //     classes or enumerations,
1827     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1828       return false;
1829     return true;
1830 
1831   case Stmt::ReturnStmtClass:
1832     //   - and exactly one return statement;
1833     if (isa<CXXConstructorDecl>(Dcl)) {
1834       // C++1y allows return statements in constexpr constructors.
1835       if (!Cxx1yLoc.isValid())
1836         Cxx1yLoc = S->getBeginLoc();
1837       return true;
1838     }
1839 
1840     ReturnStmts.push_back(S->getBeginLoc());
1841     return true;
1842 
1843   case Stmt::CompoundStmtClass: {
1844     // C++1y allows compound-statements.
1845     if (!Cxx1yLoc.isValid())
1846       Cxx1yLoc = S->getBeginLoc();
1847 
1848     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1849     for (auto *BodyIt : CompStmt->body()) {
1850       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1851                                       Cxx1yLoc, Cxx2aLoc))
1852         return false;
1853     }
1854     return true;
1855   }
1856 
1857   case Stmt::AttributedStmtClass:
1858     if (!Cxx1yLoc.isValid())
1859       Cxx1yLoc = S->getBeginLoc();
1860     return true;
1861 
1862   case Stmt::IfStmtClass: {
1863     // C++1y allows if-statements.
1864     if (!Cxx1yLoc.isValid())
1865       Cxx1yLoc = S->getBeginLoc();
1866 
1867     IfStmt *If = cast<IfStmt>(S);
1868     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1869                                     Cxx1yLoc, Cxx2aLoc))
1870       return false;
1871     if (If->getElse() &&
1872         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1873                                     Cxx1yLoc, Cxx2aLoc))
1874       return false;
1875     return true;
1876   }
1877 
1878   case Stmt::WhileStmtClass:
1879   case Stmt::DoStmtClass:
1880   case Stmt::ForStmtClass:
1881   case Stmt::CXXForRangeStmtClass:
1882   case Stmt::ContinueStmtClass:
1883     // C++1y allows all of these. We don't allow them as extensions in C++11,
1884     // because they don't make sense without variable mutation.
1885     if (!SemaRef.getLangOpts().CPlusPlus14)
1886       break;
1887     if (!Cxx1yLoc.isValid())
1888       Cxx1yLoc = S->getBeginLoc();
1889     for (Stmt *SubStmt : S->children())
1890       if (SubStmt &&
1891           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1892                                       Cxx1yLoc, Cxx2aLoc))
1893         return false;
1894     return true;
1895 
1896   case Stmt::SwitchStmtClass:
1897   case Stmt::CaseStmtClass:
1898   case Stmt::DefaultStmtClass:
1899   case Stmt::BreakStmtClass:
1900     // C++1y allows switch-statements, and since they don't need variable
1901     // mutation, we can reasonably allow them in C++11 as an extension.
1902     if (!Cxx1yLoc.isValid())
1903       Cxx1yLoc = S->getBeginLoc();
1904     for (Stmt *SubStmt : S->children())
1905       if (SubStmt &&
1906           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1907                                       Cxx1yLoc, Cxx2aLoc))
1908         return false;
1909     return true;
1910 
1911   case Stmt::CXXTryStmtClass:
1912     if (Cxx2aLoc.isInvalid())
1913       Cxx2aLoc = S->getBeginLoc();
1914     for (Stmt *SubStmt : S->children()) {
1915       if (SubStmt &&
1916           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1917                                       Cxx1yLoc, Cxx2aLoc))
1918         return false;
1919     }
1920     return true;
1921 
1922   case Stmt::CXXCatchStmtClass:
1923     // Do not bother checking the language mode (already covered by the
1924     // try block check).
1925     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
1926                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
1927                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc))
1928       return false;
1929     return true;
1930 
1931   default:
1932     if (!isa<Expr>(S))
1933       break;
1934 
1935     // C++1y allows expression-statements.
1936     if (!Cxx1yLoc.isValid())
1937       Cxx1yLoc = S->getBeginLoc();
1938     return true;
1939   }
1940 
1941   SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1942       << isa<CXXConstructorDecl>(Dcl);
1943   return false;
1944 }
1945 
1946 /// Check the body for the given constexpr function declaration only contains
1947 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1948 ///
1949 /// \return true if the body is OK, false if we have diagnosed a problem.
1950 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1951   SmallVector<SourceLocation, 4> ReturnStmts;
1952 
1953   if (isa<CXXTryStmt>(Body)) {
1954     // C++11 [dcl.constexpr]p3:
1955     //  The definition of a constexpr function shall satisfy the following
1956     //  constraints: [...]
1957     // - its function-body shall be = delete, = default, or a
1958     //   compound-statement
1959     //
1960     // C++11 [dcl.constexpr]p4:
1961     //  In the definition of a constexpr constructor, [...]
1962     // - its function-body shall not be a function-try-block;
1963     //
1964     // This restriction is lifted in C++2a, as long as inner statements also
1965     // apply the general constexpr rules.
1966     Diag(Body->getBeginLoc(),
1967          !getLangOpts().CPlusPlus2a
1968              ? diag::ext_constexpr_function_try_block_cxx2a
1969              : diag::warn_cxx17_compat_constexpr_function_try_block)
1970         << isa<CXXConstructorDecl>(Dcl);
1971   }
1972 
1973   // - its function-body shall be [...] a compound-statement that contains only
1974   //   [... list of cases ...]
1975   //
1976   // Note that walking the children here is enough to properly check for
1977   // CompoundStmt and CXXTryStmt body.
1978   SourceLocation Cxx1yLoc, Cxx2aLoc;
1979   for (Stmt *SubStmt : Body->children()) {
1980     if (SubStmt &&
1981         !CheckConstexprFunctionStmt(*this, Dcl, SubStmt, ReturnStmts,
1982                                     Cxx1yLoc, Cxx2aLoc))
1983       return false;
1984   }
1985 
1986   if (Cxx2aLoc.isValid())
1987     Diag(Cxx2aLoc,
1988          getLangOpts().CPlusPlus2a
1989            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
1990            : diag::ext_constexpr_body_invalid_stmt_cxx2a)
1991       << isa<CXXConstructorDecl>(Dcl);
1992   if (Cxx1yLoc.isValid())
1993     Diag(Cxx1yLoc,
1994          getLangOpts().CPlusPlus14
1995            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1996            : diag::ext_constexpr_body_invalid_stmt)
1997       << isa<CXXConstructorDecl>(Dcl);
1998 
1999   if (const CXXConstructorDecl *Constructor
2000         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2001     const CXXRecordDecl *RD = Constructor->getParent();
2002     // DR1359:
2003     // - every non-variant non-static data member and base class sub-object
2004     //   shall be initialized;
2005     // DR1460:
2006     // - if the class is a union having variant members, exactly one of them
2007     //   shall be initialized;
2008     if (RD->isUnion()) {
2009       if (Constructor->getNumCtorInitializers() == 0 &&
2010           RD->hasVariantMembers()) {
2011         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
2012         return false;
2013       }
2014     } else if (!Constructor->isDependentContext() &&
2015                !Constructor->isDelegatingConstructor()) {
2016       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2017 
2018       // Skip detailed checking if we have enough initializers, and we would
2019       // allow at most one initializer per member.
2020       bool AnyAnonStructUnionMembers = false;
2021       unsigned Fields = 0;
2022       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2023            E = RD->field_end(); I != E; ++I, ++Fields) {
2024         if (I->isAnonymousStructOrUnion()) {
2025           AnyAnonStructUnionMembers = true;
2026           break;
2027         }
2028       }
2029       // DR1460:
2030       // - if the class is a union-like class, but is not a union, for each of
2031       //   its anonymous union members having variant members, exactly one of
2032       //   them shall be initialized;
2033       if (AnyAnonStructUnionMembers ||
2034           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2035         // Check initialization of non-static data members. Base classes are
2036         // always initialized so do not need to be checked. Dependent bases
2037         // might not have initializers in the member initializer list.
2038         llvm::SmallSet<Decl*, 16> Inits;
2039         for (const auto *I: Constructor->inits()) {
2040           if (FieldDecl *FD = I->getMember())
2041             Inits.insert(FD);
2042           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2043             Inits.insert(ID->chain_begin(), ID->chain_end());
2044         }
2045 
2046         bool Diagnosed = false;
2047         for (auto *I : RD->fields())
2048           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2049         if (Diagnosed)
2050           return false;
2051       }
2052     }
2053   } else {
2054     if (ReturnStmts.empty()) {
2055       // C++1y doesn't require constexpr functions to contain a 'return'
2056       // statement. We still do, unless the return type might be void, because
2057       // otherwise if there's no return statement, the function cannot
2058       // be used in a core constant expression.
2059       bool OK = getLangOpts().CPlusPlus14 &&
2060                 (Dcl->getReturnType()->isVoidType() ||
2061                  Dcl->getReturnType()->isDependentType());
2062       Diag(Dcl->getLocation(),
2063            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2064               : diag::err_constexpr_body_no_return);
2065       if (!OK)
2066         return false;
2067     } else if (ReturnStmts.size() > 1) {
2068       Diag(ReturnStmts.back(),
2069            getLangOpts().CPlusPlus14
2070              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2071              : diag::ext_constexpr_body_multiple_return);
2072       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2073         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2074     }
2075   }
2076 
2077   // C++11 [dcl.constexpr]p5:
2078   //   if no function argument values exist such that the function invocation
2079   //   substitution would produce a constant expression, the program is
2080   //   ill-formed; no diagnostic required.
2081   // C++11 [dcl.constexpr]p3:
2082   //   - every constructor call and implicit conversion used in initializing the
2083   //     return value shall be one of those allowed in a constant expression.
2084   // C++11 [dcl.constexpr]p4:
2085   //   - every constructor involved in initializing non-static data members and
2086   //     base class sub-objects shall be a constexpr constructor.
2087   SmallVector<PartialDiagnosticAt, 8> Diags;
2088   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2089     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2090       << isa<CXXConstructorDecl>(Dcl);
2091     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2092       Diag(Diags[I].first, Diags[I].second);
2093     // Don't return false here: we allow this for compatibility in
2094     // system headers.
2095   }
2096 
2097   return true;
2098 }
2099 
2100 /// Get the class that is directly named by the current context. This is the
2101 /// class for which an unqualified-id in this scope could name a constructor
2102 /// or destructor.
2103 ///
2104 /// If the scope specifier denotes a class, this will be that class.
2105 /// If the scope specifier is empty, this will be the class whose
2106 /// member-specification we are currently within. Otherwise, there
2107 /// is no such class.
2108 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2109   assert(getLangOpts().CPlusPlus && "No class names in C!");
2110 
2111   if (SS && SS->isInvalid())
2112     return nullptr;
2113 
2114   if (SS && SS->isNotEmpty()) {
2115     DeclContext *DC = computeDeclContext(*SS, true);
2116     return dyn_cast_or_null<CXXRecordDecl>(DC);
2117   }
2118 
2119   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2120 }
2121 
2122 /// isCurrentClassName - Determine whether the identifier II is the
2123 /// name of the class type currently being defined. In the case of
2124 /// nested classes, this will only return true if II is the name of
2125 /// the innermost class.
2126 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2127                               const CXXScopeSpec *SS) {
2128   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2129   return CurDecl && &II == CurDecl->getIdentifier();
2130 }
2131 
2132 /// Determine whether the identifier II is a typo for the name of
2133 /// the class type currently being defined. If so, update it to the identifier
2134 /// that should have been used.
2135 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2136   assert(getLangOpts().CPlusPlus && "No class names in C!");
2137 
2138   if (!getLangOpts().SpellChecking)
2139     return false;
2140 
2141   CXXRecordDecl *CurDecl;
2142   if (SS && SS->isSet() && !SS->isInvalid()) {
2143     DeclContext *DC = computeDeclContext(*SS, true);
2144     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2145   } else
2146     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2147 
2148   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2149       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2150           < II->getLength()) {
2151     II = CurDecl->getIdentifier();
2152     return true;
2153   }
2154 
2155   return false;
2156 }
2157 
2158 /// Determine whether the given class is a base class of the given
2159 /// class, including looking at dependent bases.
2160 static bool findCircularInheritance(const CXXRecordDecl *Class,
2161                                     const CXXRecordDecl *Current) {
2162   SmallVector<const CXXRecordDecl*, 8> Queue;
2163 
2164   Class = Class->getCanonicalDecl();
2165   while (true) {
2166     for (const auto &I : Current->bases()) {
2167       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2168       if (!Base)
2169         continue;
2170 
2171       Base = Base->getDefinition();
2172       if (!Base)
2173         continue;
2174 
2175       if (Base->getCanonicalDecl() == Class)
2176         return true;
2177 
2178       Queue.push_back(Base);
2179     }
2180 
2181     if (Queue.empty())
2182       return false;
2183 
2184     Current = Queue.pop_back_val();
2185   }
2186 
2187   return false;
2188 }
2189 
2190 /// Check the validity of a C++ base class specifier.
2191 ///
2192 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2193 /// and returns NULL otherwise.
2194 CXXBaseSpecifier *
2195 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2196                          SourceRange SpecifierRange,
2197                          bool Virtual, AccessSpecifier Access,
2198                          TypeSourceInfo *TInfo,
2199                          SourceLocation EllipsisLoc) {
2200   QualType BaseType = TInfo->getType();
2201 
2202   // C++ [class.union]p1:
2203   //   A union shall not have base classes.
2204   if (Class->isUnion()) {
2205     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2206       << SpecifierRange;
2207     return nullptr;
2208   }
2209 
2210   if (EllipsisLoc.isValid() &&
2211       !TInfo->getType()->containsUnexpandedParameterPack()) {
2212     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2213       << TInfo->getTypeLoc().getSourceRange();
2214     EllipsisLoc = SourceLocation();
2215   }
2216 
2217   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2218 
2219   if (BaseType->isDependentType()) {
2220     // Make sure that we don't have circular inheritance among our dependent
2221     // bases. For non-dependent bases, the check for completeness below handles
2222     // this.
2223     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2224       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2225           ((BaseDecl = BaseDecl->getDefinition()) &&
2226            findCircularInheritance(Class, BaseDecl))) {
2227         Diag(BaseLoc, diag::err_circular_inheritance)
2228           << BaseType << Context.getTypeDeclType(Class);
2229 
2230         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2231           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2232             << BaseType;
2233 
2234         return nullptr;
2235       }
2236     }
2237 
2238     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2239                                           Class->getTagKind() == TTK_Class,
2240                                           Access, TInfo, EllipsisLoc);
2241   }
2242 
2243   // Base specifiers must be record types.
2244   if (!BaseType->isRecordType()) {
2245     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2246     return nullptr;
2247   }
2248 
2249   // C++ [class.union]p1:
2250   //   A union shall not be used as a base class.
2251   if (BaseType->isUnionType()) {
2252     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2253     return nullptr;
2254   }
2255 
2256   // For the MS ABI, propagate DLL attributes to base class templates.
2257   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2258     if (Attr *ClassAttr = getDLLAttr(Class)) {
2259       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2260               BaseType->getAsCXXRecordDecl())) {
2261         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2262                                             BaseLoc);
2263       }
2264     }
2265   }
2266 
2267   // C++ [class.derived]p2:
2268   //   The class-name in a base-specifier shall not be an incompletely
2269   //   defined class.
2270   if (RequireCompleteType(BaseLoc, BaseType,
2271                           diag::err_incomplete_base_class, SpecifierRange)) {
2272     Class->setInvalidDecl();
2273     return nullptr;
2274   }
2275 
2276   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2277   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2278   assert(BaseDecl && "Record type has no declaration");
2279   BaseDecl = BaseDecl->getDefinition();
2280   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2281   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2282   assert(CXXBaseDecl && "Base type is not a C++ type");
2283 
2284   // Microsoft docs say:
2285   // "If a base-class has a code_seg attribute, derived classes must have the
2286   // same attribute."
2287   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2288   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2289   if ((DerivedCSA || BaseCSA) &&
2290       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2291     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2292     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2293       << CXXBaseDecl;
2294     return nullptr;
2295   }
2296 
2297   // A class which contains a flexible array member is not suitable for use as a
2298   // base class:
2299   //   - If the layout determines that a base comes before another base,
2300   //     the flexible array member would index into the subsequent base.
2301   //   - If the layout determines that base comes before the derived class,
2302   //     the flexible array member would index into the derived class.
2303   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2304     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2305       << CXXBaseDecl->getDeclName();
2306     return nullptr;
2307   }
2308 
2309   // C++ [class]p3:
2310   //   If a class is marked final and it appears as a base-type-specifier in
2311   //   base-clause, the program is ill-formed.
2312   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2313     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2314       << CXXBaseDecl->getDeclName()
2315       << FA->isSpelledAsSealed();
2316     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2317         << CXXBaseDecl->getDeclName() << FA->getRange();
2318     return nullptr;
2319   }
2320 
2321   if (BaseDecl->isInvalidDecl())
2322     Class->setInvalidDecl();
2323 
2324   // Create the base specifier.
2325   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2326                                         Class->getTagKind() == TTK_Class,
2327                                         Access, TInfo, EllipsisLoc);
2328 }
2329 
2330 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2331 /// one entry in the base class list of a class specifier, for
2332 /// example:
2333 ///    class foo : public bar, virtual private baz {
2334 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2335 BaseResult
2336 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2337                          ParsedAttributes &Attributes,
2338                          bool Virtual, AccessSpecifier Access,
2339                          ParsedType basetype, SourceLocation BaseLoc,
2340                          SourceLocation EllipsisLoc) {
2341   if (!classdecl)
2342     return true;
2343 
2344   AdjustDeclIfTemplate(classdecl);
2345   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2346   if (!Class)
2347     return true;
2348 
2349   // We haven't yet attached the base specifiers.
2350   Class->setIsParsingBaseSpecifiers();
2351 
2352   // We do not support any C++11 attributes on base-specifiers yet.
2353   // Diagnose any attributes we see.
2354   for (const ParsedAttr &AL : Attributes) {
2355     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2356       continue;
2357     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2358                           ? (unsigned)diag::warn_unknown_attribute_ignored
2359                           : (unsigned)diag::err_base_specifier_attribute)
2360         << AL.getName();
2361   }
2362 
2363   TypeSourceInfo *TInfo = nullptr;
2364   GetTypeFromParser(basetype, &TInfo);
2365 
2366   if (EllipsisLoc.isInvalid() &&
2367       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2368                                       UPPC_BaseType))
2369     return true;
2370 
2371   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2372                                                       Virtual, Access, TInfo,
2373                                                       EllipsisLoc))
2374     return BaseSpec;
2375   else
2376     Class->setInvalidDecl();
2377 
2378   return true;
2379 }
2380 
2381 /// Use small set to collect indirect bases.  As this is only used
2382 /// locally, there's no need to abstract the small size parameter.
2383 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2384 
2385 /// Recursively add the bases of Type.  Don't add Type itself.
2386 static void
2387 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2388                   const QualType &Type)
2389 {
2390   // Even though the incoming type is a base, it might not be
2391   // a class -- it could be a template parm, for instance.
2392   if (auto Rec = Type->getAs<RecordType>()) {
2393     auto Decl = Rec->getAsCXXRecordDecl();
2394 
2395     // Iterate over its bases.
2396     for (const auto &BaseSpec : Decl->bases()) {
2397       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2398         .getUnqualifiedType();
2399       if (Set.insert(Base).second)
2400         // If we've not already seen it, recurse.
2401         NoteIndirectBases(Context, Set, Base);
2402     }
2403   }
2404 }
2405 
2406 /// Performs the actual work of attaching the given base class
2407 /// specifiers to a C++ class.
2408 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2409                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2410  if (Bases.empty())
2411     return false;
2412 
2413   // Used to keep track of which base types we have already seen, so
2414   // that we can properly diagnose redundant direct base types. Note
2415   // that the key is always the unqualified canonical type of the base
2416   // class.
2417   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2418 
2419   // Used to track indirect bases so we can see if a direct base is
2420   // ambiguous.
2421   IndirectBaseSet IndirectBaseTypes;
2422 
2423   // Copy non-redundant base specifiers into permanent storage.
2424   unsigned NumGoodBases = 0;
2425   bool Invalid = false;
2426   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2427     QualType NewBaseType
2428       = Context.getCanonicalType(Bases[idx]->getType());
2429     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2430 
2431     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2432     if (KnownBase) {
2433       // C++ [class.mi]p3:
2434       //   A class shall not be specified as a direct base class of a
2435       //   derived class more than once.
2436       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2437           << KnownBase->getType() << Bases[idx]->getSourceRange();
2438 
2439       // Delete the duplicate base class specifier; we're going to
2440       // overwrite its pointer later.
2441       Context.Deallocate(Bases[idx]);
2442 
2443       Invalid = true;
2444     } else {
2445       // Okay, add this new base class.
2446       KnownBase = Bases[idx];
2447       Bases[NumGoodBases++] = Bases[idx];
2448 
2449       // Note this base's direct & indirect bases, if there could be ambiguity.
2450       if (Bases.size() > 1)
2451         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2452 
2453       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2454         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2455         if (Class->isInterface() &&
2456               (!RD->isInterfaceLike() ||
2457                KnownBase->getAccessSpecifier() != AS_public)) {
2458           // The Microsoft extension __interface does not permit bases that
2459           // are not themselves public interfaces.
2460           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2461               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2462               << RD->getSourceRange();
2463           Invalid = true;
2464         }
2465         if (RD->hasAttr<WeakAttr>())
2466           Class->addAttr(WeakAttr::CreateImplicit(Context));
2467       }
2468     }
2469   }
2470 
2471   // Attach the remaining base class specifiers to the derived class.
2472   Class->setBases(Bases.data(), NumGoodBases);
2473 
2474   // Check that the only base classes that are duplicate are virtual.
2475   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2476     // Check whether this direct base is inaccessible due to ambiguity.
2477     QualType BaseType = Bases[idx]->getType();
2478 
2479     // Skip all dependent types in templates being used as base specifiers.
2480     // Checks below assume that the base specifier is a CXXRecord.
2481     if (BaseType->isDependentType())
2482       continue;
2483 
2484     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2485       .getUnqualifiedType();
2486 
2487     if (IndirectBaseTypes.count(CanonicalBase)) {
2488       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2489                          /*DetectVirtual=*/true);
2490       bool found
2491         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2492       assert(found);
2493       (void)found;
2494 
2495       if (Paths.isAmbiguous(CanonicalBase))
2496         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2497             << BaseType << getAmbiguousPathsDisplayString(Paths)
2498             << Bases[idx]->getSourceRange();
2499       else
2500         assert(Bases[idx]->isVirtual());
2501     }
2502 
2503     // Delete the base class specifier, since its data has been copied
2504     // into the CXXRecordDecl.
2505     Context.Deallocate(Bases[idx]);
2506   }
2507 
2508   return Invalid;
2509 }
2510 
2511 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2512 /// class, after checking whether there are any duplicate base
2513 /// classes.
2514 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2515                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2516   if (!ClassDecl || Bases.empty())
2517     return;
2518 
2519   AdjustDeclIfTemplate(ClassDecl);
2520   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2521 }
2522 
2523 /// Determine whether the type \p Derived is a C++ class that is
2524 /// derived from the type \p Base.
2525 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2526   if (!getLangOpts().CPlusPlus)
2527     return false;
2528 
2529   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2530   if (!DerivedRD)
2531     return false;
2532 
2533   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2534   if (!BaseRD)
2535     return false;
2536 
2537   // If either the base or the derived type is invalid, don't try to
2538   // check whether one is derived from the other.
2539   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2540     return false;
2541 
2542   // FIXME: In a modules build, do we need the entire path to be visible for us
2543   // to be able to use the inheritance relationship?
2544   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2545     return false;
2546 
2547   return DerivedRD->isDerivedFrom(BaseRD);
2548 }
2549 
2550 /// Determine whether the type \p Derived is a C++ class that is
2551 /// derived from the type \p Base.
2552 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2553                          CXXBasePaths &Paths) {
2554   if (!getLangOpts().CPlusPlus)
2555     return false;
2556 
2557   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2558   if (!DerivedRD)
2559     return false;
2560 
2561   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2562   if (!BaseRD)
2563     return false;
2564 
2565   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2566     return false;
2567 
2568   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2569 }
2570 
2571 static void BuildBasePathArray(const CXXBasePath &Path,
2572                                CXXCastPath &BasePathArray) {
2573   // We first go backward and check if we have a virtual base.
2574   // FIXME: It would be better if CXXBasePath had the base specifier for
2575   // the nearest virtual base.
2576   unsigned Start = 0;
2577   for (unsigned I = Path.size(); I != 0; --I) {
2578     if (Path[I - 1].Base->isVirtual()) {
2579       Start = I - 1;
2580       break;
2581     }
2582   }
2583 
2584   // Now add all bases.
2585   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2586     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2587 }
2588 
2589 
2590 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2591                               CXXCastPath &BasePathArray) {
2592   assert(BasePathArray.empty() && "Base path array must be empty!");
2593   assert(Paths.isRecordingPaths() && "Must record paths!");
2594   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2595 }
2596 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2597 /// conversion (where Derived and Base are class types) is
2598 /// well-formed, meaning that the conversion is unambiguous (and
2599 /// that all of the base classes are accessible). Returns true
2600 /// and emits a diagnostic if the code is ill-formed, returns false
2601 /// otherwise. Loc is the location where this routine should point to
2602 /// if there is an error, and Range is the source range to highlight
2603 /// if there is an error.
2604 ///
2605 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2606 /// diagnostic for the respective type of error will be suppressed, but the
2607 /// check for ill-formed code will still be performed.
2608 bool
2609 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2610                                    unsigned InaccessibleBaseID,
2611                                    unsigned AmbigiousBaseConvID,
2612                                    SourceLocation Loc, SourceRange Range,
2613                                    DeclarationName Name,
2614                                    CXXCastPath *BasePath,
2615                                    bool IgnoreAccess) {
2616   // First, determine whether the path from Derived to Base is
2617   // ambiguous. This is slightly more expensive than checking whether
2618   // the Derived to Base conversion exists, because here we need to
2619   // explore multiple paths to determine if there is an ambiguity.
2620   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2621                      /*DetectVirtual=*/false);
2622   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2623   if (!DerivationOkay)
2624     return true;
2625 
2626   const CXXBasePath *Path = nullptr;
2627   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2628     Path = &Paths.front();
2629 
2630   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2631   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2632   // user to access such bases.
2633   if (!Path && getLangOpts().MSVCCompat) {
2634     for (const CXXBasePath &PossiblePath : Paths) {
2635       if (PossiblePath.size() == 1) {
2636         Path = &PossiblePath;
2637         if (AmbigiousBaseConvID)
2638           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2639               << Base << Derived << Range;
2640         break;
2641       }
2642     }
2643   }
2644 
2645   if (Path) {
2646     if (!IgnoreAccess) {
2647       // Check that the base class can be accessed.
2648       switch (
2649           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2650       case AR_inaccessible:
2651         return true;
2652       case AR_accessible:
2653       case AR_dependent:
2654       case AR_delayed:
2655         break;
2656       }
2657     }
2658 
2659     // Build a base path if necessary.
2660     if (BasePath)
2661       ::BuildBasePathArray(*Path, *BasePath);
2662     return false;
2663   }
2664 
2665   if (AmbigiousBaseConvID) {
2666     // We know that the derived-to-base conversion is ambiguous, and
2667     // we're going to produce a diagnostic. Perform the derived-to-base
2668     // search just one more time to compute all of the possible paths so
2669     // that we can print them out. This is more expensive than any of
2670     // the previous derived-to-base checks we've done, but at this point
2671     // performance isn't as much of an issue.
2672     Paths.clear();
2673     Paths.setRecordingPaths(true);
2674     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2675     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2676     (void)StillOkay;
2677 
2678     // Build up a textual representation of the ambiguous paths, e.g.,
2679     // D -> B -> A, that will be used to illustrate the ambiguous
2680     // conversions in the diagnostic. We only print one of the paths
2681     // to each base class subobject.
2682     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2683 
2684     Diag(Loc, AmbigiousBaseConvID)
2685     << Derived << Base << PathDisplayStr << Range << Name;
2686   }
2687   return true;
2688 }
2689 
2690 bool
2691 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2692                                    SourceLocation Loc, SourceRange Range,
2693                                    CXXCastPath *BasePath,
2694                                    bool IgnoreAccess) {
2695   return CheckDerivedToBaseConversion(
2696       Derived, Base, diag::err_upcast_to_inaccessible_base,
2697       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2698       BasePath, IgnoreAccess);
2699 }
2700 
2701 
2702 /// Builds a string representing ambiguous paths from a
2703 /// specific derived class to different subobjects of the same base
2704 /// class.
2705 ///
2706 /// This function builds a string that can be used in error messages
2707 /// to show the different paths that one can take through the
2708 /// inheritance hierarchy to go from the derived class to different
2709 /// subobjects of a base class. The result looks something like this:
2710 /// @code
2711 /// struct D -> struct B -> struct A
2712 /// struct D -> struct C -> struct A
2713 /// @endcode
2714 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2715   std::string PathDisplayStr;
2716   std::set<unsigned> DisplayedPaths;
2717   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2718        Path != Paths.end(); ++Path) {
2719     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2720       // We haven't displayed a path to this particular base
2721       // class subobject yet.
2722       PathDisplayStr += "\n    ";
2723       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2724       for (CXXBasePath::const_iterator Element = Path->begin();
2725            Element != Path->end(); ++Element)
2726         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2727     }
2728   }
2729 
2730   return PathDisplayStr;
2731 }
2732 
2733 //===----------------------------------------------------------------------===//
2734 // C++ class member Handling
2735 //===----------------------------------------------------------------------===//
2736 
2737 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2738 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2739                                 SourceLocation ColonLoc,
2740                                 const ParsedAttributesView &Attrs) {
2741   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2742   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2743                                                   ASLoc, ColonLoc);
2744   CurContext->addHiddenDecl(ASDecl);
2745   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2746 }
2747 
2748 /// CheckOverrideControl - Check C++11 override control semantics.
2749 void Sema::CheckOverrideControl(NamedDecl *D) {
2750   if (D->isInvalidDecl())
2751     return;
2752 
2753   // We only care about "override" and "final" declarations.
2754   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2755     return;
2756 
2757   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2758 
2759   // We can't check dependent instance methods.
2760   if (MD && MD->isInstance() &&
2761       (MD->getParent()->hasAnyDependentBases() ||
2762        MD->getType()->isDependentType()))
2763     return;
2764 
2765   if (MD && !MD->isVirtual()) {
2766     // If we have a non-virtual method, check if if hides a virtual method.
2767     // (In that case, it's most likely the method has the wrong type.)
2768     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2769     FindHiddenVirtualMethods(MD, OverloadedMethods);
2770 
2771     if (!OverloadedMethods.empty()) {
2772       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2773         Diag(OA->getLocation(),
2774              diag::override_keyword_hides_virtual_member_function)
2775           << "override" << (OverloadedMethods.size() > 1);
2776       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2777         Diag(FA->getLocation(),
2778              diag::override_keyword_hides_virtual_member_function)
2779           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2780           << (OverloadedMethods.size() > 1);
2781       }
2782       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2783       MD->setInvalidDecl();
2784       return;
2785     }
2786     // Fall through into the general case diagnostic.
2787     // FIXME: We might want to attempt typo correction here.
2788   }
2789 
2790   if (!MD || !MD->isVirtual()) {
2791     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2792       Diag(OA->getLocation(),
2793            diag::override_keyword_only_allowed_on_virtual_member_functions)
2794         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2795       D->dropAttr<OverrideAttr>();
2796     }
2797     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2798       Diag(FA->getLocation(),
2799            diag::override_keyword_only_allowed_on_virtual_member_functions)
2800         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2801         << FixItHint::CreateRemoval(FA->getLocation());
2802       D->dropAttr<FinalAttr>();
2803     }
2804     return;
2805   }
2806 
2807   // C++11 [class.virtual]p5:
2808   //   If a function is marked with the virt-specifier override and
2809   //   does not override a member function of a base class, the program is
2810   //   ill-formed.
2811   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2812   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2813     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2814       << MD->getDeclName();
2815 }
2816 
2817 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2818   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2819     return;
2820   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2821   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2822     return;
2823 
2824   SourceLocation Loc = MD->getLocation();
2825   SourceLocation SpellingLoc = Loc;
2826   if (getSourceManager().isMacroArgExpansion(Loc))
2827     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2828   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2829   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2830       return;
2831 
2832   if (MD->size_overridden_methods() > 0) {
2833     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2834                           ? diag::warn_destructor_marked_not_override_overriding
2835                           : diag::warn_function_marked_not_override_overriding;
2836     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2837     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2838     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2839   }
2840 }
2841 
2842 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2843 /// function overrides a virtual member function marked 'final', according to
2844 /// C++11 [class.virtual]p4.
2845 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2846                                                   const CXXMethodDecl *Old) {
2847   FinalAttr *FA = Old->getAttr<FinalAttr>();
2848   if (!FA)
2849     return false;
2850 
2851   Diag(New->getLocation(), diag::err_final_function_overridden)
2852     << New->getDeclName()
2853     << FA->isSpelledAsSealed();
2854   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2855   return true;
2856 }
2857 
2858 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2859   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2860   // FIXME: Destruction of ObjC lifetime types has side-effects.
2861   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2862     return !RD->isCompleteDefinition() ||
2863            !RD->hasTrivialDefaultConstructor() ||
2864            !RD->hasTrivialDestructor();
2865   return false;
2866 }
2867 
2868 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
2869   ParsedAttributesView::const_iterator Itr =
2870       llvm::find_if(list, [](const ParsedAttr &AL) {
2871         return AL.isDeclspecPropertyAttribute();
2872       });
2873   if (Itr != list.end())
2874     return &*Itr;
2875   return nullptr;
2876 }
2877 
2878 // Check if there is a field shadowing.
2879 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2880                                       DeclarationName FieldName,
2881                                       const CXXRecordDecl *RD,
2882                                       bool DeclIsField) {
2883   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2884     return;
2885 
2886   // To record a shadowed field in a base
2887   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2888   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2889                            CXXBasePath &Path) {
2890     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2891     // Record an ambiguous path directly
2892     if (Bases.find(Base) != Bases.end())
2893       return true;
2894     for (const auto Field : Base->lookup(FieldName)) {
2895       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2896           Field->getAccess() != AS_private) {
2897         assert(Field->getAccess() != AS_none);
2898         assert(Bases.find(Base) == Bases.end());
2899         Bases[Base] = Field;
2900         return true;
2901       }
2902     }
2903     return false;
2904   };
2905 
2906   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2907                      /*DetectVirtual=*/true);
2908   if (!RD->lookupInBases(FieldShadowed, Paths))
2909     return;
2910 
2911   for (const auto &P : Paths) {
2912     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2913     auto It = Bases.find(Base);
2914     // Skip duplicated bases
2915     if (It == Bases.end())
2916       continue;
2917     auto BaseField = It->second;
2918     assert(BaseField->getAccess() != AS_private);
2919     if (AS_none !=
2920         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2921       Diag(Loc, diag::warn_shadow_field)
2922         << FieldName << RD << Base << DeclIsField;
2923       Diag(BaseField->getLocation(), diag::note_shadow_field);
2924       Bases.erase(It);
2925     }
2926   }
2927 }
2928 
2929 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2930 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2931 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2932 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2933 /// present (but parsing it has been deferred).
2934 NamedDecl *
2935 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2936                                MultiTemplateParamsArg TemplateParameterLists,
2937                                Expr *BW, const VirtSpecifiers &VS,
2938                                InClassInitStyle InitStyle) {
2939   const DeclSpec &DS = D.getDeclSpec();
2940   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2941   DeclarationName Name = NameInfo.getName();
2942   SourceLocation Loc = NameInfo.getLoc();
2943 
2944   // For anonymous bitfields, the location should point to the type.
2945   if (Loc.isInvalid())
2946     Loc = D.getBeginLoc();
2947 
2948   Expr *BitWidth = static_cast<Expr*>(BW);
2949 
2950   assert(isa<CXXRecordDecl>(CurContext));
2951   assert(!DS.isFriendSpecified());
2952 
2953   bool isFunc = D.isDeclarationOfFunction();
2954   const ParsedAttr *MSPropertyAttr =
2955       getMSPropertyAttr(D.getDeclSpec().getAttributes());
2956 
2957   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2958     // The Microsoft extension __interface only permits public member functions
2959     // and prohibits constructors, destructors, operators, non-public member
2960     // functions, static methods and data members.
2961     unsigned InvalidDecl;
2962     bool ShowDeclName = true;
2963     if (!isFunc &&
2964         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2965       InvalidDecl = 0;
2966     else if (!isFunc)
2967       InvalidDecl = 1;
2968     else if (AS != AS_public)
2969       InvalidDecl = 2;
2970     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2971       InvalidDecl = 3;
2972     else switch (Name.getNameKind()) {
2973       case DeclarationName::CXXConstructorName:
2974         InvalidDecl = 4;
2975         ShowDeclName = false;
2976         break;
2977 
2978       case DeclarationName::CXXDestructorName:
2979         InvalidDecl = 5;
2980         ShowDeclName = false;
2981         break;
2982 
2983       case DeclarationName::CXXOperatorName:
2984       case DeclarationName::CXXConversionFunctionName:
2985         InvalidDecl = 6;
2986         break;
2987 
2988       default:
2989         InvalidDecl = 0;
2990         break;
2991     }
2992 
2993     if (InvalidDecl) {
2994       if (ShowDeclName)
2995         Diag(Loc, diag::err_invalid_member_in_interface)
2996           << (InvalidDecl-1) << Name;
2997       else
2998         Diag(Loc, diag::err_invalid_member_in_interface)
2999           << (InvalidDecl-1) << "";
3000       return nullptr;
3001     }
3002   }
3003 
3004   // C++ 9.2p6: A member shall not be declared to have automatic storage
3005   // duration (auto, register) or with the extern storage-class-specifier.
3006   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3007   // data members and cannot be applied to names declared const or static,
3008   // and cannot be applied to reference members.
3009   switch (DS.getStorageClassSpec()) {
3010   case DeclSpec::SCS_unspecified:
3011   case DeclSpec::SCS_typedef:
3012   case DeclSpec::SCS_static:
3013     break;
3014   case DeclSpec::SCS_mutable:
3015     if (isFunc) {
3016       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3017 
3018       // FIXME: It would be nicer if the keyword was ignored only for this
3019       // declarator. Otherwise we could get follow-up errors.
3020       D.getMutableDeclSpec().ClearStorageClassSpecs();
3021     }
3022     break;
3023   default:
3024     Diag(DS.getStorageClassSpecLoc(),
3025          diag::err_storageclass_invalid_for_member);
3026     D.getMutableDeclSpec().ClearStorageClassSpecs();
3027     break;
3028   }
3029 
3030   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3031                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3032                       !isFunc);
3033 
3034   if (DS.isConstexprSpecified() && isInstField) {
3035     SemaDiagnosticBuilder B =
3036         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3037     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3038     if (InitStyle == ICIS_NoInit) {
3039       B << 0 << 0;
3040       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3041         B << FixItHint::CreateRemoval(ConstexprLoc);
3042       else {
3043         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3044         D.getMutableDeclSpec().ClearConstexprSpec();
3045         const char *PrevSpec;
3046         unsigned DiagID;
3047         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3048             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3049         (void)Failed;
3050         assert(!Failed && "Making a constexpr member const shouldn't fail");
3051       }
3052     } else {
3053       B << 1;
3054       const char *PrevSpec;
3055       unsigned DiagID;
3056       if (D.getMutableDeclSpec().SetStorageClassSpec(
3057           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3058           Context.getPrintingPolicy())) {
3059         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3060                "This is the only DeclSpec that should fail to be applied");
3061         B << 1;
3062       } else {
3063         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3064         isInstField = false;
3065       }
3066     }
3067   }
3068 
3069   NamedDecl *Member;
3070   if (isInstField) {
3071     CXXScopeSpec &SS = D.getCXXScopeSpec();
3072 
3073     // Data members must have identifiers for names.
3074     if (!Name.isIdentifier()) {
3075       Diag(Loc, diag::err_bad_variable_name)
3076         << Name;
3077       return nullptr;
3078     }
3079 
3080     IdentifierInfo *II = Name.getAsIdentifierInfo();
3081 
3082     // Member field could not be with "template" keyword.
3083     // So TemplateParameterLists should be empty in this case.
3084     if (TemplateParameterLists.size()) {
3085       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3086       if (TemplateParams->size()) {
3087         // There is no such thing as a member field template.
3088         Diag(D.getIdentifierLoc(), diag::err_template_member)
3089             << II
3090             << SourceRange(TemplateParams->getTemplateLoc(),
3091                 TemplateParams->getRAngleLoc());
3092       } else {
3093         // There is an extraneous 'template<>' for this member.
3094         Diag(TemplateParams->getTemplateLoc(),
3095             diag::err_template_member_noparams)
3096             << II
3097             << SourceRange(TemplateParams->getTemplateLoc(),
3098                 TemplateParams->getRAngleLoc());
3099       }
3100       return nullptr;
3101     }
3102 
3103     if (SS.isSet() && !SS.isInvalid()) {
3104       // The user provided a superfluous scope specifier inside a class
3105       // definition:
3106       //
3107       // class X {
3108       //   int X::member;
3109       // };
3110       if (DeclContext *DC = computeDeclContext(SS, false))
3111         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3112                                      D.getName().getKind() ==
3113                                          UnqualifiedIdKind::IK_TemplateId);
3114       else
3115         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3116           << Name << SS.getRange();
3117 
3118       SS.clear();
3119     }
3120 
3121     if (MSPropertyAttr) {
3122       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3123                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3124       if (!Member)
3125         return nullptr;
3126       isInstField = false;
3127     } else {
3128       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3129                                 BitWidth, InitStyle, AS);
3130       if (!Member)
3131         return nullptr;
3132     }
3133 
3134     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3135   } else {
3136     Member = HandleDeclarator(S, D, TemplateParameterLists);
3137     if (!Member)
3138       return nullptr;
3139 
3140     // Non-instance-fields can't have a bitfield.
3141     if (BitWidth) {
3142       if (Member->isInvalidDecl()) {
3143         // don't emit another diagnostic.
3144       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3145         // C++ 9.6p3: A bit-field shall not be a static member.
3146         // "static member 'A' cannot be a bit-field"
3147         Diag(Loc, diag::err_static_not_bitfield)
3148           << Name << BitWidth->getSourceRange();
3149       } else if (isa<TypedefDecl>(Member)) {
3150         // "typedef member 'x' cannot be a bit-field"
3151         Diag(Loc, diag::err_typedef_not_bitfield)
3152           << Name << BitWidth->getSourceRange();
3153       } else {
3154         // A function typedef ("typedef int f(); f a;").
3155         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3156         Diag(Loc, diag::err_not_integral_type_bitfield)
3157           << Name << cast<ValueDecl>(Member)->getType()
3158           << BitWidth->getSourceRange();
3159       }
3160 
3161       BitWidth = nullptr;
3162       Member->setInvalidDecl();
3163     }
3164 
3165     NamedDecl *NonTemplateMember = Member;
3166     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3167       NonTemplateMember = FunTmpl->getTemplatedDecl();
3168     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3169       NonTemplateMember = VarTmpl->getTemplatedDecl();
3170 
3171     Member->setAccess(AS);
3172 
3173     // If we have declared a member function template or static data member
3174     // template, set the access of the templated declaration as well.
3175     if (NonTemplateMember != Member)
3176       NonTemplateMember->setAccess(AS);
3177 
3178     // C++ [temp.deduct.guide]p3:
3179     //   A deduction guide [...] for a member class template [shall be
3180     //   declared] with the same access [as the template].
3181     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3182       auto *TD = DG->getDeducedTemplate();
3183       // Access specifiers are only meaningful if both the template and the
3184       // deduction guide are from the same scope.
3185       if (AS != TD->getAccess() &&
3186           TD->getDeclContext()->getRedeclContext()->Equals(
3187               DG->getDeclContext()->getRedeclContext())) {
3188         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3189         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3190             << TD->getAccess();
3191         const AccessSpecDecl *LastAccessSpec = nullptr;
3192         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3193           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3194             LastAccessSpec = AccessSpec;
3195         }
3196         assert(LastAccessSpec && "differing access with no access specifier");
3197         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3198             << AS;
3199       }
3200     }
3201   }
3202 
3203   if (VS.isOverrideSpecified())
3204     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3205   if (VS.isFinalSpecified())
3206     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3207                                             VS.isFinalSpelledSealed()));
3208 
3209   if (VS.getLastLocation().isValid()) {
3210     // Update the end location of a method that has a virt-specifiers.
3211     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3212       MD->setRangeEnd(VS.getLastLocation());
3213   }
3214 
3215   CheckOverrideControl(Member);
3216 
3217   assert((Name || isInstField) && "No identifier for non-field ?");
3218 
3219   if (isInstField) {
3220     FieldDecl *FD = cast<FieldDecl>(Member);
3221     FieldCollector->Add(FD);
3222 
3223     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3224       // Remember all explicit private FieldDecls that have a name, no side
3225       // effects and are not part of a dependent type declaration.
3226       if (!FD->isImplicit() && FD->getDeclName() &&
3227           FD->getAccess() == AS_private &&
3228           !FD->hasAttr<UnusedAttr>() &&
3229           !FD->getParent()->isDependentContext() &&
3230           !InitializationHasSideEffects(*FD))
3231         UnusedPrivateFields.insert(FD);
3232     }
3233   }
3234 
3235   return Member;
3236 }
3237 
3238 namespace {
3239   class UninitializedFieldVisitor
3240       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3241     Sema &S;
3242     // List of Decls to generate a warning on.  Also remove Decls that become
3243     // initialized.
3244     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3245     // List of base classes of the record.  Classes are removed after their
3246     // initializers.
3247     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3248     // Vector of decls to be removed from the Decl set prior to visiting the
3249     // nodes.  These Decls may have been initialized in the prior initializer.
3250     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3251     // If non-null, add a note to the warning pointing back to the constructor.
3252     const CXXConstructorDecl *Constructor;
3253     // Variables to hold state when processing an initializer list.  When
3254     // InitList is true, special case initialization of FieldDecls matching
3255     // InitListFieldDecl.
3256     bool InitList;
3257     FieldDecl *InitListFieldDecl;
3258     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3259 
3260   public:
3261     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3262     UninitializedFieldVisitor(Sema &S,
3263                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3264                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3265       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3266         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3267 
3268     // Returns true if the use of ME is not an uninitialized use.
3269     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3270                                          bool CheckReferenceOnly) {
3271       llvm::SmallVector<FieldDecl*, 4> Fields;
3272       bool ReferenceField = false;
3273       while (ME) {
3274         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3275         if (!FD)
3276           return false;
3277         Fields.push_back(FD);
3278         if (FD->getType()->isReferenceType())
3279           ReferenceField = true;
3280         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3281       }
3282 
3283       // Binding a reference to an uninitialized field is not an
3284       // uninitialized use.
3285       if (CheckReferenceOnly && !ReferenceField)
3286         return true;
3287 
3288       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3289       // Discard the first field since it is the field decl that is being
3290       // initialized.
3291       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3292         UsedFieldIndex.push_back((*I)->getFieldIndex());
3293       }
3294 
3295       for (auto UsedIter = UsedFieldIndex.begin(),
3296                 UsedEnd = UsedFieldIndex.end(),
3297                 OrigIter = InitFieldIndex.begin(),
3298                 OrigEnd = InitFieldIndex.end();
3299            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3300         if (*UsedIter < *OrigIter)
3301           return true;
3302         if (*UsedIter > *OrigIter)
3303           break;
3304       }
3305 
3306       return false;
3307     }
3308 
3309     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3310                           bool AddressOf) {
3311       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3312         return;
3313 
3314       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3315       // or union.
3316       MemberExpr *FieldME = ME;
3317 
3318       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3319 
3320       Expr *Base = ME;
3321       while (MemberExpr *SubME =
3322                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3323 
3324         if (isa<VarDecl>(SubME->getMemberDecl()))
3325           return;
3326 
3327         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3328           if (!FD->isAnonymousStructOrUnion())
3329             FieldME = SubME;
3330 
3331         if (!FieldME->getType().isPODType(S.Context))
3332           AllPODFields = false;
3333 
3334         Base = SubME->getBase();
3335       }
3336 
3337       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3338         return;
3339 
3340       if (AddressOf && AllPODFields)
3341         return;
3342 
3343       ValueDecl* FoundVD = FieldME->getMemberDecl();
3344 
3345       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3346         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3347           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3348         }
3349 
3350         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3351           QualType T = BaseCast->getType();
3352           if (T->isPointerType() &&
3353               BaseClasses.count(T->getPointeeType())) {
3354             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3355                 << T->getPointeeType() << FoundVD;
3356           }
3357         }
3358       }
3359 
3360       if (!Decls.count(FoundVD))
3361         return;
3362 
3363       const bool IsReference = FoundVD->getType()->isReferenceType();
3364 
3365       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3366         // Special checking for initializer lists.
3367         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3368           return;
3369         }
3370       } else {
3371         // Prevent double warnings on use of unbounded references.
3372         if (CheckReferenceOnly && !IsReference)
3373           return;
3374       }
3375 
3376       unsigned diag = IsReference
3377           ? diag::warn_reference_field_is_uninit
3378           : diag::warn_field_is_uninit;
3379       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3380       if (Constructor)
3381         S.Diag(Constructor->getLocation(),
3382                diag::note_uninit_in_this_constructor)
3383           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3384 
3385     }
3386 
3387     void HandleValue(Expr *E, bool AddressOf) {
3388       E = E->IgnoreParens();
3389 
3390       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3391         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3392                          AddressOf /*AddressOf*/);
3393         return;
3394       }
3395 
3396       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3397         Visit(CO->getCond());
3398         HandleValue(CO->getTrueExpr(), AddressOf);
3399         HandleValue(CO->getFalseExpr(), AddressOf);
3400         return;
3401       }
3402 
3403       if (BinaryConditionalOperator *BCO =
3404               dyn_cast<BinaryConditionalOperator>(E)) {
3405         Visit(BCO->getCond());
3406         HandleValue(BCO->getFalseExpr(), AddressOf);
3407         return;
3408       }
3409 
3410       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3411         HandleValue(OVE->getSourceExpr(), AddressOf);
3412         return;
3413       }
3414 
3415       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3416         switch (BO->getOpcode()) {
3417         default:
3418           break;
3419         case(BO_PtrMemD):
3420         case(BO_PtrMemI):
3421           HandleValue(BO->getLHS(), AddressOf);
3422           Visit(BO->getRHS());
3423           return;
3424         case(BO_Comma):
3425           Visit(BO->getLHS());
3426           HandleValue(BO->getRHS(), AddressOf);
3427           return;
3428         }
3429       }
3430 
3431       Visit(E);
3432     }
3433 
3434     void CheckInitListExpr(InitListExpr *ILE) {
3435       InitFieldIndex.push_back(0);
3436       for (auto Child : ILE->children()) {
3437         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3438           CheckInitListExpr(SubList);
3439         } else {
3440           Visit(Child);
3441         }
3442         ++InitFieldIndex.back();
3443       }
3444       InitFieldIndex.pop_back();
3445     }
3446 
3447     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3448                           FieldDecl *Field, const Type *BaseClass) {
3449       // Remove Decls that may have been initialized in the previous
3450       // initializer.
3451       for (ValueDecl* VD : DeclsToRemove)
3452         Decls.erase(VD);
3453       DeclsToRemove.clear();
3454 
3455       Constructor = FieldConstructor;
3456       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3457 
3458       if (ILE && Field) {
3459         InitList = true;
3460         InitListFieldDecl = Field;
3461         InitFieldIndex.clear();
3462         CheckInitListExpr(ILE);
3463       } else {
3464         InitList = false;
3465         Visit(E);
3466       }
3467 
3468       if (Field)
3469         Decls.erase(Field);
3470       if (BaseClass)
3471         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3472     }
3473 
3474     void VisitMemberExpr(MemberExpr *ME) {
3475       // All uses of unbounded reference fields will warn.
3476       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3477     }
3478 
3479     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3480       if (E->getCastKind() == CK_LValueToRValue) {
3481         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3482         return;
3483       }
3484 
3485       Inherited::VisitImplicitCastExpr(E);
3486     }
3487 
3488     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3489       if (E->getConstructor()->isCopyConstructor()) {
3490         Expr *ArgExpr = E->getArg(0);
3491         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3492           if (ILE->getNumInits() == 1)
3493             ArgExpr = ILE->getInit(0);
3494         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3495           if (ICE->getCastKind() == CK_NoOp)
3496             ArgExpr = ICE->getSubExpr();
3497         HandleValue(ArgExpr, false /*AddressOf*/);
3498         return;
3499       }
3500       Inherited::VisitCXXConstructExpr(E);
3501     }
3502 
3503     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3504       Expr *Callee = E->getCallee();
3505       if (isa<MemberExpr>(Callee)) {
3506         HandleValue(Callee, false /*AddressOf*/);
3507         for (auto Arg : E->arguments())
3508           Visit(Arg);
3509         return;
3510       }
3511 
3512       Inherited::VisitCXXMemberCallExpr(E);
3513     }
3514 
3515     void VisitCallExpr(CallExpr *E) {
3516       // Treat std::move as a use.
3517       if (E->isCallToStdMove()) {
3518         HandleValue(E->getArg(0), /*AddressOf=*/false);
3519         return;
3520       }
3521 
3522       Inherited::VisitCallExpr(E);
3523     }
3524 
3525     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3526       Expr *Callee = E->getCallee();
3527 
3528       if (isa<UnresolvedLookupExpr>(Callee))
3529         return Inherited::VisitCXXOperatorCallExpr(E);
3530 
3531       Visit(Callee);
3532       for (auto Arg : E->arguments())
3533         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3534     }
3535 
3536     void VisitBinaryOperator(BinaryOperator *E) {
3537       // If a field assignment is detected, remove the field from the
3538       // uninitiailized field set.
3539       if (E->getOpcode() == BO_Assign)
3540         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3541           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3542             if (!FD->getType()->isReferenceType())
3543               DeclsToRemove.push_back(FD);
3544 
3545       if (E->isCompoundAssignmentOp()) {
3546         HandleValue(E->getLHS(), false /*AddressOf*/);
3547         Visit(E->getRHS());
3548         return;
3549       }
3550 
3551       Inherited::VisitBinaryOperator(E);
3552     }
3553 
3554     void VisitUnaryOperator(UnaryOperator *E) {
3555       if (E->isIncrementDecrementOp()) {
3556         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3557         return;
3558       }
3559       if (E->getOpcode() == UO_AddrOf) {
3560         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3561           HandleValue(ME->getBase(), true /*AddressOf*/);
3562           return;
3563         }
3564       }
3565 
3566       Inherited::VisitUnaryOperator(E);
3567     }
3568   };
3569 
3570   // Diagnose value-uses of fields to initialize themselves, e.g.
3571   //   foo(foo)
3572   // where foo is not also a parameter to the constructor.
3573   // Also diagnose across field uninitialized use such as
3574   //   x(y), y(x)
3575   // TODO: implement -Wuninitialized and fold this into that framework.
3576   static void DiagnoseUninitializedFields(
3577       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3578 
3579     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3580                                            Constructor->getLocation())) {
3581       return;
3582     }
3583 
3584     if (Constructor->isInvalidDecl())
3585       return;
3586 
3587     const CXXRecordDecl *RD = Constructor->getParent();
3588 
3589     if (RD->getDescribedClassTemplate())
3590       return;
3591 
3592     // Holds fields that are uninitialized.
3593     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3594 
3595     // At the beginning, all fields are uninitialized.
3596     for (auto *I : RD->decls()) {
3597       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3598         UninitializedFields.insert(FD);
3599       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3600         UninitializedFields.insert(IFD->getAnonField());
3601       }
3602     }
3603 
3604     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3605     for (auto I : RD->bases())
3606       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3607 
3608     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3609       return;
3610 
3611     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3612                                                    UninitializedFields,
3613                                                    UninitializedBaseClasses);
3614 
3615     for (const auto *FieldInit : Constructor->inits()) {
3616       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3617         break;
3618 
3619       Expr *InitExpr = FieldInit->getInit();
3620       if (!InitExpr)
3621         continue;
3622 
3623       if (CXXDefaultInitExpr *Default =
3624               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3625         InitExpr = Default->getExpr();
3626         if (!InitExpr)
3627           continue;
3628         // In class initializers will point to the constructor.
3629         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3630                                               FieldInit->getAnyMember(),
3631                                               FieldInit->getBaseClass());
3632       } else {
3633         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3634                                               FieldInit->getAnyMember(),
3635                                               FieldInit->getBaseClass());
3636       }
3637     }
3638   }
3639 } // namespace
3640 
3641 /// Enter a new C++ default initializer scope. After calling this, the
3642 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3643 /// parsing or instantiating the initializer failed.
3644 void Sema::ActOnStartCXXInClassMemberInitializer() {
3645   // Create a synthetic function scope to represent the call to the constructor
3646   // that notionally surrounds a use of this initializer.
3647   PushFunctionScope();
3648 }
3649 
3650 /// This is invoked after parsing an in-class initializer for a
3651 /// non-static C++ class member, and after instantiating an in-class initializer
3652 /// in a class template. Such actions are deferred until the class is complete.
3653 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3654                                                   SourceLocation InitLoc,
3655                                                   Expr *InitExpr) {
3656   // Pop the notional constructor scope we created earlier.
3657   PopFunctionScopeInfo(nullptr, D);
3658 
3659   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3660   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3661          "must set init style when field is created");
3662 
3663   if (!InitExpr) {
3664     D->setInvalidDecl();
3665     if (FD)
3666       FD->removeInClassInitializer();
3667     return;
3668   }
3669 
3670   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3671     FD->setInvalidDecl();
3672     FD->removeInClassInitializer();
3673     return;
3674   }
3675 
3676   ExprResult Init = InitExpr;
3677   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3678     InitializedEntity Entity =
3679         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3680     InitializationKind Kind =
3681         FD->getInClassInitStyle() == ICIS_ListInit
3682             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3683                                                    InitExpr->getBeginLoc(),
3684                                                    InitExpr->getEndLoc())
3685             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3686     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3687     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3688     if (Init.isInvalid()) {
3689       FD->setInvalidDecl();
3690       return;
3691     }
3692   }
3693 
3694   // C++11 [class.base.init]p7:
3695   //   The initialization of each base and member constitutes a
3696   //   full-expression.
3697   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3698   if (Init.isInvalid()) {
3699     FD->setInvalidDecl();
3700     return;
3701   }
3702 
3703   InitExpr = Init.get();
3704 
3705   FD->setInClassInitializer(InitExpr);
3706 }
3707 
3708 /// Find the direct and/or virtual base specifiers that
3709 /// correspond to the given base type, for use in base initialization
3710 /// within a constructor.
3711 static bool FindBaseInitializer(Sema &SemaRef,
3712                                 CXXRecordDecl *ClassDecl,
3713                                 QualType BaseType,
3714                                 const CXXBaseSpecifier *&DirectBaseSpec,
3715                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3716   // First, check for a direct base class.
3717   DirectBaseSpec = nullptr;
3718   for (const auto &Base : ClassDecl->bases()) {
3719     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3720       // We found a direct base of this type. That's what we're
3721       // initializing.
3722       DirectBaseSpec = &Base;
3723       break;
3724     }
3725   }
3726 
3727   // Check for a virtual base class.
3728   // FIXME: We might be able to short-circuit this if we know in advance that
3729   // there are no virtual bases.
3730   VirtualBaseSpec = nullptr;
3731   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3732     // We haven't found a base yet; search the class hierarchy for a
3733     // virtual base class.
3734     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3735                        /*DetectVirtual=*/false);
3736     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3737                               SemaRef.Context.getTypeDeclType(ClassDecl),
3738                               BaseType, Paths)) {
3739       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3740            Path != Paths.end(); ++Path) {
3741         if (Path->back().Base->isVirtual()) {
3742           VirtualBaseSpec = Path->back().Base;
3743           break;
3744         }
3745       }
3746     }
3747   }
3748 
3749   return DirectBaseSpec || VirtualBaseSpec;
3750 }
3751 
3752 /// Handle a C++ member initializer using braced-init-list syntax.
3753 MemInitResult
3754 Sema::ActOnMemInitializer(Decl *ConstructorD,
3755                           Scope *S,
3756                           CXXScopeSpec &SS,
3757                           IdentifierInfo *MemberOrBase,
3758                           ParsedType TemplateTypeTy,
3759                           const DeclSpec &DS,
3760                           SourceLocation IdLoc,
3761                           Expr *InitList,
3762                           SourceLocation EllipsisLoc) {
3763   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3764                              DS, IdLoc, InitList,
3765                              EllipsisLoc);
3766 }
3767 
3768 /// Handle a C++ member initializer using parentheses syntax.
3769 MemInitResult
3770 Sema::ActOnMemInitializer(Decl *ConstructorD,
3771                           Scope *S,
3772                           CXXScopeSpec &SS,
3773                           IdentifierInfo *MemberOrBase,
3774                           ParsedType TemplateTypeTy,
3775                           const DeclSpec &DS,
3776                           SourceLocation IdLoc,
3777                           SourceLocation LParenLoc,
3778                           ArrayRef<Expr *> Args,
3779                           SourceLocation RParenLoc,
3780                           SourceLocation EllipsisLoc) {
3781   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3782   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3783                              DS, IdLoc, List, EllipsisLoc);
3784 }
3785 
3786 namespace {
3787 
3788 // Callback to only accept typo corrections that can be a valid C++ member
3789 // intializer: either a non-static field member or a base class.
3790 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
3791 public:
3792   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3793       : ClassDecl(ClassDecl) {}
3794 
3795   bool ValidateCandidate(const TypoCorrection &candidate) override {
3796     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3797       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3798         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3799       return isa<TypeDecl>(ND);
3800     }
3801     return false;
3802   }
3803 
3804   std::unique_ptr<CorrectionCandidateCallback> clone() override {
3805     return llvm::make_unique<MemInitializerValidatorCCC>(*this);
3806   }
3807 
3808 private:
3809   CXXRecordDecl *ClassDecl;
3810 };
3811 
3812 }
3813 
3814 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3815                                              CXXScopeSpec &SS,
3816                                              ParsedType TemplateTypeTy,
3817                                              IdentifierInfo *MemberOrBase) {
3818   if (SS.getScopeRep() || TemplateTypeTy)
3819     return nullptr;
3820   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3821   if (Result.empty())
3822     return nullptr;
3823   ValueDecl *Member;
3824   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3825       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3826     return Member;
3827   return nullptr;
3828 }
3829 
3830 /// Handle a C++ member initializer.
3831 MemInitResult
3832 Sema::BuildMemInitializer(Decl *ConstructorD,
3833                           Scope *S,
3834                           CXXScopeSpec &SS,
3835                           IdentifierInfo *MemberOrBase,
3836                           ParsedType TemplateTypeTy,
3837                           const DeclSpec &DS,
3838                           SourceLocation IdLoc,
3839                           Expr *Init,
3840                           SourceLocation EllipsisLoc) {
3841   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3842   if (!Res.isUsable())
3843     return true;
3844   Init = Res.get();
3845 
3846   if (!ConstructorD)
3847     return true;
3848 
3849   AdjustDeclIfTemplate(ConstructorD);
3850 
3851   CXXConstructorDecl *Constructor
3852     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3853   if (!Constructor) {
3854     // The user wrote a constructor initializer on a function that is
3855     // not a C++ constructor. Ignore the error for now, because we may
3856     // have more member initializers coming; we'll diagnose it just
3857     // once in ActOnMemInitializers.
3858     return true;
3859   }
3860 
3861   CXXRecordDecl *ClassDecl = Constructor->getParent();
3862 
3863   // C++ [class.base.init]p2:
3864   //   Names in a mem-initializer-id are looked up in the scope of the
3865   //   constructor's class and, if not found in that scope, are looked
3866   //   up in the scope containing the constructor's definition.
3867   //   [Note: if the constructor's class contains a member with the
3868   //   same name as a direct or virtual base class of the class, a
3869   //   mem-initializer-id naming the member or base class and composed
3870   //   of a single identifier refers to the class member. A
3871   //   mem-initializer-id for the hidden base class may be specified
3872   //   using a qualified name. ]
3873 
3874   // Look for a member, first.
3875   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
3876           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
3877     if (EllipsisLoc.isValid())
3878       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3879           << MemberOrBase
3880           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3881 
3882     return BuildMemberInitializer(Member, Init, IdLoc);
3883   }
3884   // It didn't name a member, so see if it names a class.
3885   QualType BaseType;
3886   TypeSourceInfo *TInfo = nullptr;
3887 
3888   if (TemplateTypeTy) {
3889     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3890     if (BaseType.isNull())
3891       return true;
3892   } else if (DS.getTypeSpecType() == TST_decltype) {
3893     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3894   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3895     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3896     return true;
3897   } else {
3898     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3899     LookupParsedName(R, S, &SS);
3900 
3901     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3902     if (!TyD) {
3903       if (R.isAmbiguous()) return true;
3904 
3905       // We don't want access-control diagnostics here.
3906       R.suppressDiagnostics();
3907 
3908       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3909         bool NotUnknownSpecialization = false;
3910         DeclContext *DC = computeDeclContext(SS, false);
3911         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3912           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3913 
3914         if (!NotUnknownSpecialization) {
3915           // When the scope specifier can refer to a member of an unknown
3916           // specialization, we take it as a type name.
3917           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3918                                        SS.getWithLocInContext(Context),
3919                                        *MemberOrBase, IdLoc);
3920           if (BaseType.isNull())
3921             return true;
3922 
3923           TInfo = Context.CreateTypeSourceInfo(BaseType);
3924           DependentNameTypeLoc TL =
3925               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3926           if (!TL.isNull()) {
3927             TL.setNameLoc(IdLoc);
3928             TL.setElaboratedKeywordLoc(SourceLocation());
3929             TL.setQualifierLoc(SS.getWithLocInContext(Context));
3930           }
3931 
3932           R.clear();
3933           R.setLookupName(MemberOrBase);
3934         }
3935       }
3936 
3937       // If no results were found, try to correct typos.
3938       TypoCorrection Corr;
3939       MemInitializerValidatorCCC CCC(ClassDecl);
3940       if (R.empty() && BaseType.isNull() &&
3941           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3942                               CCC, CTK_ErrorRecovery, ClassDecl))) {
3943         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3944           // We have found a non-static data member with a similar
3945           // name to what was typed; complain and initialize that
3946           // member.
3947           diagnoseTypo(Corr,
3948                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3949                          << MemberOrBase << true);
3950           return BuildMemberInitializer(Member, Init, IdLoc);
3951         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3952           const CXXBaseSpecifier *DirectBaseSpec;
3953           const CXXBaseSpecifier *VirtualBaseSpec;
3954           if (FindBaseInitializer(*this, ClassDecl,
3955                                   Context.getTypeDeclType(Type),
3956                                   DirectBaseSpec, VirtualBaseSpec)) {
3957             // We have found a direct or virtual base class with a
3958             // similar name to what was typed; complain and initialize
3959             // that base class.
3960             diagnoseTypo(Corr,
3961                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3962                            << MemberOrBase << false,
3963                          PDiag() /*Suppress note, we provide our own.*/);
3964 
3965             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3966                                                               : VirtualBaseSpec;
3967             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
3968                 << BaseSpec->getType() << BaseSpec->getSourceRange();
3969 
3970             TyD = Type;
3971           }
3972         }
3973       }
3974 
3975       if (!TyD && BaseType.isNull()) {
3976         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3977           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3978         return true;
3979       }
3980     }
3981 
3982     if (BaseType.isNull()) {
3983       BaseType = Context.getTypeDeclType(TyD);
3984       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3985       if (SS.isSet()) {
3986         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3987                                              BaseType);
3988         TInfo = Context.CreateTypeSourceInfo(BaseType);
3989         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3990         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3991         TL.setElaboratedKeywordLoc(SourceLocation());
3992         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3993       }
3994     }
3995   }
3996 
3997   if (!TInfo)
3998     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3999 
4000   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4001 }
4002 
4003 MemInitResult
4004 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4005                              SourceLocation IdLoc) {
4006   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4007   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4008   assert((DirectMember || IndirectMember) &&
4009          "Member must be a FieldDecl or IndirectFieldDecl");
4010 
4011   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4012     return true;
4013 
4014   if (Member->isInvalidDecl())
4015     return true;
4016 
4017   MultiExprArg Args;
4018   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4019     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4020   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4021     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4022   } else {
4023     // Template instantiation doesn't reconstruct ParenListExprs for us.
4024     Args = Init;
4025   }
4026 
4027   SourceRange InitRange = Init->getSourceRange();
4028 
4029   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4030     // Can't check initialization for a member of dependent type or when
4031     // any of the arguments are type-dependent expressions.
4032     DiscardCleanupsInEvaluationContext();
4033   } else {
4034     bool InitList = false;
4035     if (isa<InitListExpr>(Init)) {
4036       InitList = true;
4037       Args = Init;
4038     }
4039 
4040     // Initialize the member.
4041     InitializedEntity MemberEntity =
4042       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4043                    : InitializedEntity::InitializeMember(IndirectMember,
4044                                                          nullptr);
4045     InitializationKind Kind =
4046         InitList ? InitializationKind::CreateDirectList(
4047                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4048                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4049                                                     InitRange.getEnd());
4050 
4051     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4052     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4053                                             nullptr);
4054     if (MemberInit.isInvalid())
4055       return true;
4056 
4057     // C++11 [class.base.init]p7:
4058     //   The initialization of each base and member constitutes a
4059     //   full-expression.
4060     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4061                                      /*DiscardedValue*/ false);
4062     if (MemberInit.isInvalid())
4063       return true;
4064 
4065     Init = MemberInit.get();
4066   }
4067 
4068   if (DirectMember) {
4069     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4070                                             InitRange.getBegin(), Init,
4071                                             InitRange.getEnd());
4072   } else {
4073     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4074                                             InitRange.getBegin(), Init,
4075                                             InitRange.getEnd());
4076   }
4077 }
4078 
4079 MemInitResult
4080 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4081                                  CXXRecordDecl *ClassDecl) {
4082   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4083   if (!LangOpts.CPlusPlus11)
4084     return Diag(NameLoc, diag::err_delegating_ctor)
4085       << TInfo->getTypeLoc().getLocalSourceRange();
4086   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4087 
4088   bool InitList = true;
4089   MultiExprArg Args = Init;
4090   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4091     InitList = false;
4092     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4093   }
4094 
4095   SourceRange InitRange = Init->getSourceRange();
4096   // Initialize the object.
4097   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4098                                      QualType(ClassDecl->getTypeForDecl(), 0));
4099   InitializationKind Kind =
4100       InitList ? InitializationKind::CreateDirectList(
4101                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4102                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4103                                                   InitRange.getEnd());
4104   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4105   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4106                                               Args, nullptr);
4107   if (DelegationInit.isInvalid())
4108     return true;
4109 
4110   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4111          "Delegating constructor with no target?");
4112 
4113   // C++11 [class.base.init]p7:
4114   //   The initialization of each base and member constitutes a
4115   //   full-expression.
4116   DelegationInit = ActOnFinishFullExpr(
4117       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4118   if (DelegationInit.isInvalid())
4119     return true;
4120 
4121   // If we are in a dependent context, template instantiation will
4122   // perform this type-checking again. Just save the arguments that we
4123   // received in a ParenListExpr.
4124   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4125   // of the information that we have about the base
4126   // initializer. However, deconstructing the ASTs is a dicey process,
4127   // and this approach is far more likely to get the corner cases right.
4128   if (CurContext->isDependentContext())
4129     DelegationInit = Init;
4130 
4131   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4132                                           DelegationInit.getAs<Expr>(),
4133                                           InitRange.getEnd());
4134 }
4135 
4136 MemInitResult
4137 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4138                            Expr *Init, CXXRecordDecl *ClassDecl,
4139                            SourceLocation EllipsisLoc) {
4140   SourceLocation BaseLoc
4141     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4142 
4143   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4144     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4145              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4146 
4147   // C++ [class.base.init]p2:
4148   //   [...] Unless the mem-initializer-id names a nonstatic data
4149   //   member of the constructor's class or a direct or virtual base
4150   //   of that class, the mem-initializer is ill-formed. A
4151   //   mem-initializer-list can initialize a base class using any
4152   //   name that denotes that base class type.
4153   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4154 
4155   SourceRange InitRange = Init->getSourceRange();
4156   if (EllipsisLoc.isValid()) {
4157     // This is a pack expansion.
4158     if (!BaseType->containsUnexpandedParameterPack())  {
4159       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4160         << SourceRange(BaseLoc, InitRange.getEnd());
4161 
4162       EllipsisLoc = SourceLocation();
4163     }
4164   } else {
4165     // Check for any unexpanded parameter packs.
4166     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4167       return true;
4168 
4169     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4170       return true;
4171   }
4172 
4173   // Check for direct and virtual base classes.
4174   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4175   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4176   if (!Dependent) {
4177     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4178                                        BaseType))
4179       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4180 
4181     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4182                         VirtualBaseSpec);
4183 
4184     // C++ [base.class.init]p2:
4185     // Unless the mem-initializer-id names a nonstatic data member of the
4186     // constructor's class or a direct or virtual base of that class, the
4187     // mem-initializer is ill-formed.
4188     if (!DirectBaseSpec && !VirtualBaseSpec) {
4189       // If the class has any dependent bases, then it's possible that
4190       // one of those types will resolve to the same type as
4191       // BaseType. Therefore, just treat this as a dependent base
4192       // class initialization.  FIXME: Should we try to check the
4193       // initialization anyway? It seems odd.
4194       if (ClassDecl->hasAnyDependentBases())
4195         Dependent = true;
4196       else
4197         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4198           << BaseType << Context.getTypeDeclType(ClassDecl)
4199           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4200     }
4201   }
4202 
4203   if (Dependent) {
4204     DiscardCleanupsInEvaluationContext();
4205 
4206     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4207                                             /*IsVirtual=*/false,
4208                                             InitRange.getBegin(), Init,
4209                                             InitRange.getEnd(), EllipsisLoc);
4210   }
4211 
4212   // C++ [base.class.init]p2:
4213   //   If a mem-initializer-id is ambiguous because it designates both
4214   //   a direct non-virtual base class and an inherited virtual base
4215   //   class, the mem-initializer is ill-formed.
4216   if (DirectBaseSpec && VirtualBaseSpec)
4217     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4218       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4219 
4220   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4221   if (!BaseSpec)
4222     BaseSpec = VirtualBaseSpec;
4223 
4224   // Initialize the base.
4225   bool InitList = true;
4226   MultiExprArg Args = Init;
4227   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4228     InitList = false;
4229     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4230   }
4231 
4232   InitializedEntity BaseEntity =
4233     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4234   InitializationKind Kind =
4235       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4236                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4237                                                   InitRange.getEnd());
4238   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4239   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4240   if (BaseInit.isInvalid())
4241     return true;
4242 
4243   // C++11 [class.base.init]p7:
4244   //   The initialization of each base and member constitutes a
4245   //   full-expression.
4246   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4247                                  /*DiscardedValue*/ false);
4248   if (BaseInit.isInvalid())
4249     return true;
4250 
4251   // If we are in a dependent context, template instantiation will
4252   // perform this type-checking again. Just save the arguments that we
4253   // received in a ParenListExpr.
4254   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4255   // of the information that we have about the base
4256   // initializer. However, deconstructing the ASTs is a dicey process,
4257   // and this approach is far more likely to get the corner cases right.
4258   if (CurContext->isDependentContext())
4259     BaseInit = Init;
4260 
4261   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4262                                           BaseSpec->isVirtual(),
4263                                           InitRange.getBegin(),
4264                                           BaseInit.getAs<Expr>(),
4265                                           InitRange.getEnd(), EllipsisLoc);
4266 }
4267 
4268 // Create a static_cast\<T&&>(expr).
4269 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4270   if (T.isNull()) T = E->getType();
4271   QualType TargetType = SemaRef.BuildReferenceType(
4272       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4273   SourceLocation ExprLoc = E->getBeginLoc();
4274   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4275       TargetType, ExprLoc);
4276 
4277   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4278                                    SourceRange(ExprLoc, ExprLoc),
4279                                    E->getSourceRange()).get();
4280 }
4281 
4282 /// ImplicitInitializerKind - How an implicit base or member initializer should
4283 /// initialize its base or member.
4284 enum ImplicitInitializerKind {
4285   IIK_Default,
4286   IIK_Copy,
4287   IIK_Move,
4288   IIK_Inherit
4289 };
4290 
4291 static bool
4292 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4293                              ImplicitInitializerKind ImplicitInitKind,
4294                              CXXBaseSpecifier *BaseSpec,
4295                              bool IsInheritedVirtualBase,
4296                              CXXCtorInitializer *&CXXBaseInit) {
4297   InitializedEntity InitEntity
4298     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4299                                         IsInheritedVirtualBase);
4300 
4301   ExprResult BaseInit;
4302 
4303   switch (ImplicitInitKind) {
4304   case IIK_Inherit:
4305   case IIK_Default: {
4306     InitializationKind InitKind
4307       = InitializationKind::CreateDefault(Constructor->getLocation());
4308     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4309     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4310     break;
4311   }
4312 
4313   case IIK_Move:
4314   case IIK_Copy: {
4315     bool Moving = ImplicitInitKind == IIK_Move;
4316     ParmVarDecl *Param = Constructor->getParamDecl(0);
4317     QualType ParamType = Param->getType().getNonReferenceType();
4318 
4319     Expr *CopyCtorArg =
4320       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4321                           SourceLocation(), Param, false,
4322                           Constructor->getLocation(), ParamType,
4323                           VK_LValue, nullptr);
4324 
4325     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4326 
4327     // Cast to the base class to avoid ambiguities.
4328     QualType ArgTy =
4329       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4330                                        ParamType.getQualifiers());
4331 
4332     if (Moving) {
4333       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4334     }
4335 
4336     CXXCastPath BasePath;
4337     BasePath.push_back(BaseSpec);
4338     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4339                                             CK_UncheckedDerivedToBase,
4340                                             Moving ? VK_XValue : VK_LValue,
4341                                             &BasePath).get();
4342 
4343     InitializationKind InitKind
4344       = InitializationKind::CreateDirect(Constructor->getLocation(),
4345                                          SourceLocation(), SourceLocation());
4346     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4347     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4348     break;
4349   }
4350   }
4351 
4352   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4353   if (BaseInit.isInvalid())
4354     return true;
4355 
4356   CXXBaseInit =
4357     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4358                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4359                                                         SourceLocation()),
4360                                              BaseSpec->isVirtual(),
4361                                              SourceLocation(),
4362                                              BaseInit.getAs<Expr>(),
4363                                              SourceLocation(),
4364                                              SourceLocation());
4365 
4366   return false;
4367 }
4368 
4369 static bool RefersToRValueRef(Expr *MemRef) {
4370   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4371   return Referenced->getType()->isRValueReferenceType();
4372 }
4373 
4374 static bool
4375 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4376                                ImplicitInitializerKind ImplicitInitKind,
4377                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4378                                CXXCtorInitializer *&CXXMemberInit) {
4379   if (Field->isInvalidDecl())
4380     return true;
4381 
4382   SourceLocation Loc = Constructor->getLocation();
4383 
4384   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4385     bool Moving = ImplicitInitKind == IIK_Move;
4386     ParmVarDecl *Param = Constructor->getParamDecl(0);
4387     QualType ParamType = Param->getType().getNonReferenceType();
4388 
4389     // Suppress copying zero-width bitfields.
4390     if (Field->isZeroLengthBitField(SemaRef.Context))
4391       return false;
4392 
4393     Expr *MemberExprBase =
4394       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4395                           SourceLocation(), Param, false,
4396                           Loc, ParamType, VK_LValue, nullptr);
4397 
4398     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4399 
4400     if (Moving) {
4401       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4402     }
4403 
4404     // Build a reference to this field within the parameter.
4405     CXXScopeSpec SS;
4406     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4407                               Sema::LookupMemberName);
4408     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4409                                   : cast<ValueDecl>(Field), AS_public);
4410     MemberLookup.resolveKind();
4411     ExprResult CtorArg
4412       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4413                                          ParamType, Loc,
4414                                          /*IsArrow=*/false,
4415                                          SS,
4416                                          /*TemplateKWLoc=*/SourceLocation(),
4417                                          /*FirstQualifierInScope=*/nullptr,
4418                                          MemberLookup,
4419                                          /*TemplateArgs=*/nullptr,
4420                                          /*S*/nullptr);
4421     if (CtorArg.isInvalid())
4422       return true;
4423 
4424     // C++11 [class.copy]p15:
4425     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4426     //     with static_cast<T&&>(x.m);
4427     if (RefersToRValueRef(CtorArg.get())) {
4428       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4429     }
4430 
4431     InitializedEntity Entity =
4432         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4433                                                        /*Implicit*/ true)
4434                  : InitializedEntity::InitializeMember(Field, nullptr,
4435                                                        /*Implicit*/ true);
4436 
4437     // Direct-initialize to use the copy constructor.
4438     InitializationKind InitKind =
4439       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4440 
4441     Expr *CtorArgE = CtorArg.getAs<Expr>();
4442     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4443     ExprResult MemberInit =
4444         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4445     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4446     if (MemberInit.isInvalid())
4447       return true;
4448 
4449     if (Indirect)
4450       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4451           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4452     else
4453       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4454           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4455     return false;
4456   }
4457 
4458   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4459          "Unhandled implicit init kind!");
4460 
4461   QualType FieldBaseElementType =
4462     SemaRef.Context.getBaseElementType(Field->getType());
4463 
4464   if (FieldBaseElementType->isRecordType()) {
4465     InitializedEntity InitEntity =
4466         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4467                                                        /*Implicit*/ true)
4468                  : InitializedEntity::InitializeMember(Field, nullptr,
4469                                                        /*Implicit*/ true);
4470     InitializationKind InitKind =
4471       InitializationKind::CreateDefault(Loc);
4472 
4473     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4474     ExprResult MemberInit =
4475       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4476 
4477     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4478     if (MemberInit.isInvalid())
4479       return true;
4480 
4481     if (Indirect)
4482       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4483                                                                Indirect, Loc,
4484                                                                Loc,
4485                                                                MemberInit.get(),
4486                                                                Loc);
4487     else
4488       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4489                                                                Field, Loc, Loc,
4490                                                                MemberInit.get(),
4491                                                                Loc);
4492     return false;
4493   }
4494 
4495   if (!Field->getParent()->isUnion()) {
4496     if (FieldBaseElementType->isReferenceType()) {
4497       SemaRef.Diag(Constructor->getLocation(),
4498                    diag::err_uninitialized_member_in_ctor)
4499       << (int)Constructor->isImplicit()
4500       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4501       << 0 << Field->getDeclName();
4502       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4503       return true;
4504     }
4505 
4506     if (FieldBaseElementType.isConstQualified()) {
4507       SemaRef.Diag(Constructor->getLocation(),
4508                    diag::err_uninitialized_member_in_ctor)
4509       << (int)Constructor->isImplicit()
4510       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4511       << 1 << Field->getDeclName();
4512       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4513       return true;
4514     }
4515   }
4516 
4517   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4518     // ARC and Weak:
4519     //   Default-initialize Objective-C pointers to NULL.
4520     CXXMemberInit
4521       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4522                                                  Loc, Loc,
4523                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4524                                                  Loc);
4525     return false;
4526   }
4527 
4528   // Nothing to initialize.
4529   CXXMemberInit = nullptr;
4530   return false;
4531 }
4532 
4533 namespace {
4534 struct BaseAndFieldInfo {
4535   Sema &S;
4536   CXXConstructorDecl *Ctor;
4537   bool AnyErrorsInInits;
4538   ImplicitInitializerKind IIK;
4539   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4540   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4541   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4542 
4543   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4544     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4545     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4546     if (Ctor->getInheritedConstructor())
4547       IIK = IIK_Inherit;
4548     else if (Generated && Ctor->isCopyConstructor())
4549       IIK = IIK_Copy;
4550     else if (Generated && Ctor->isMoveConstructor())
4551       IIK = IIK_Move;
4552     else
4553       IIK = IIK_Default;
4554   }
4555 
4556   bool isImplicitCopyOrMove() const {
4557     switch (IIK) {
4558     case IIK_Copy:
4559     case IIK_Move:
4560       return true;
4561 
4562     case IIK_Default:
4563     case IIK_Inherit:
4564       return false;
4565     }
4566 
4567     llvm_unreachable("Invalid ImplicitInitializerKind!");
4568   }
4569 
4570   bool addFieldInitializer(CXXCtorInitializer *Init) {
4571     AllToInit.push_back(Init);
4572 
4573     // Check whether this initializer makes the field "used".
4574     if (Init->getInit()->HasSideEffects(S.Context))
4575       S.UnusedPrivateFields.remove(Init->getAnyMember());
4576 
4577     return false;
4578   }
4579 
4580   bool isInactiveUnionMember(FieldDecl *Field) {
4581     RecordDecl *Record = Field->getParent();
4582     if (!Record->isUnion())
4583       return false;
4584 
4585     if (FieldDecl *Active =
4586             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4587       return Active != Field->getCanonicalDecl();
4588 
4589     // In an implicit copy or move constructor, ignore any in-class initializer.
4590     if (isImplicitCopyOrMove())
4591       return true;
4592 
4593     // If there's no explicit initialization, the field is active only if it
4594     // has an in-class initializer...
4595     if (Field->hasInClassInitializer())
4596       return false;
4597     // ... or it's an anonymous struct or union whose class has an in-class
4598     // initializer.
4599     if (!Field->isAnonymousStructOrUnion())
4600       return true;
4601     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4602     return !FieldRD->hasInClassInitializer();
4603   }
4604 
4605   /// Determine whether the given field is, or is within, a union member
4606   /// that is inactive (because there was an initializer given for a different
4607   /// member of the union, or because the union was not initialized at all).
4608   bool isWithinInactiveUnionMember(FieldDecl *Field,
4609                                    IndirectFieldDecl *Indirect) {
4610     if (!Indirect)
4611       return isInactiveUnionMember(Field);
4612 
4613     for (auto *C : Indirect->chain()) {
4614       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4615       if (Field && isInactiveUnionMember(Field))
4616         return true;
4617     }
4618     return false;
4619   }
4620 };
4621 }
4622 
4623 /// Determine whether the given type is an incomplete or zero-lenfgth
4624 /// array type.
4625 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4626   if (T->isIncompleteArrayType())
4627     return true;
4628 
4629   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4630     if (!ArrayT->getSize())
4631       return true;
4632 
4633     T = ArrayT->getElementType();
4634   }
4635 
4636   return false;
4637 }
4638 
4639 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4640                                     FieldDecl *Field,
4641                                     IndirectFieldDecl *Indirect = nullptr) {
4642   if (Field->isInvalidDecl())
4643     return false;
4644 
4645   // Overwhelmingly common case: we have a direct initializer for this field.
4646   if (CXXCtorInitializer *Init =
4647           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4648     return Info.addFieldInitializer(Init);
4649 
4650   // C++11 [class.base.init]p8:
4651   //   if the entity is a non-static data member that has a
4652   //   brace-or-equal-initializer and either
4653   //   -- the constructor's class is a union and no other variant member of that
4654   //      union is designated by a mem-initializer-id or
4655   //   -- the constructor's class is not a union, and, if the entity is a member
4656   //      of an anonymous union, no other member of that union is designated by
4657   //      a mem-initializer-id,
4658   //   the entity is initialized as specified in [dcl.init].
4659   //
4660   // We also apply the same rules to handle anonymous structs within anonymous
4661   // unions.
4662   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4663     return false;
4664 
4665   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4666     ExprResult DIE =
4667         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4668     if (DIE.isInvalid())
4669       return true;
4670 
4671     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4672     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4673 
4674     CXXCtorInitializer *Init;
4675     if (Indirect)
4676       Init = new (SemaRef.Context)
4677           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4678                              SourceLocation(), DIE.get(), SourceLocation());
4679     else
4680       Init = new (SemaRef.Context)
4681           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4682                              SourceLocation(), DIE.get(), SourceLocation());
4683     return Info.addFieldInitializer(Init);
4684   }
4685 
4686   // Don't initialize incomplete or zero-length arrays.
4687   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4688     return false;
4689 
4690   // Don't try to build an implicit initializer if there were semantic
4691   // errors in any of the initializers (and therefore we might be
4692   // missing some that the user actually wrote).
4693   if (Info.AnyErrorsInInits)
4694     return false;
4695 
4696   CXXCtorInitializer *Init = nullptr;
4697   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4698                                      Indirect, Init))
4699     return true;
4700 
4701   if (!Init)
4702     return false;
4703 
4704   return Info.addFieldInitializer(Init);
4705 }
4706 
4707 bool
4708 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4709                                CXXCtorInitializer *Initializer) {
4710   assert(Initializer->isDelegatingInitializer());
4711   Constructor->setNumCtorInitializers(1);
4712   CXXCtorInitializer **initializer =
4713     new (Context) CXXCtorInitializer*[1];
4714   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4715   Constructor->setCtorInitializers(initializer);
4716 
4717   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4718     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4719     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4720   }
4721 
4722   DelegatingCtorDecls.push_back(Constructor);
4723 
4724   DiagnoseUninitializedFields(*this, Constructor);
4725 
4726   return false;
4727 }
4728 
4729 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4730                                ArrayRef<CXXCtorInitializer *> Initializers) {
4731   if (Constructor->isDependentContext()) {
4732     // Just store the initializers as written, they will be checked during
4733     // instantiation.
4734     if (!Initializers.empty()) {
4735       Constructor->setNumCtorInitializers(Initializers.size());
4736       CXXCtorInitializer **baseOrMemberInitializers =
4737         new (Context) CXXCtorInitializer*[Initializers.size()];
4738       memcpy(baseOrMemberInitializers, Initializers.data(),
4739              Initializers.size() * sizeof(CXXCtorInitializer*));
4740       Constructor->setCtorInitializers(baseOrMemberInitializers);
4741     }
4742 
4743     // Let template instantiation know whether we had errors.
4744     if (AnyErrors)
4745       Constructor->setInvalidDecl();
4746 
4747     return false;
4748   }
4749 
4750   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4751 
4752   // We need to build the initializer AST according to order of construction
4753   // and not what user specified in the Initializers list.
4754   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4755   if (!ClassDecl)
4756     return true;
4757 
4758   bool HadError = false;
4759 
4760   for (unsigned i = 0; i < Initializers.size(); i++) {
4761     CXXCtorInitializer *Member = Initializers[i];
4762 
4763     if (Member->isBaseInitializer())
4764       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4765     else {
4766       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4767 
4768       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4769         for (auto *C : F->chain()) {
4770           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4771           if (FD && FD->getParent()->isUnion())
4772             Info.ActiveUnionMember.insert(std::make_pair(
4773                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4774         }
4775       } else if (FieldDecl *FD = Member->getMember()) {
4776         if (FD->getParent()->isUnion())
4777           Info.ActiveUnionMember.insert(std::make_pair(
4778               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4779       }
4780     }
4781   }
4782 
4783   // Keep track of the direct virtual bases.
4784   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4785   for (auto &I : ClassDecl->bases()) {
4786     if (I.isVirtual())
4787       DirectVBases.insert(&I);
4788   }
4789 
4790   // Push virtual bases before others.
4791   for (auto &VBase : ClassDecl->vbases()) {
4792     if (CXXCtorInitializer *Value
4793         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4794       // [class.base.init]p7, per DR257:
4795       //   A mem-initializer where the mem-initializer-id names a virtual base
4796       //   class is ignored during execution of a constructor of any class that
4797       //   is not the most derived class.
4798       if (ClassDecl->isAbstract()) {
4799         // FIXME: Provide a fixit to remove the base specifier. This requires
4800         // tracking the location of the associated comma for a base specifier.
4801         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4802           << VBase.getType() << ClassDecl;
4803         DiagnoseAbstractType(ClassDecl);
4804       }
4805 
4806       Info.AllToInit.push_back(Value);
4807     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4808       // [class.base.init]p8, per DR257:
4809       //   If a given [...] base class is not named by a mem-initializer-id
4810       //   [...] and the entity is not a virtual base class of an abstract
4811       //   class, then [...] the entity is default-initialized.
4812       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4813       CXXCtorInitializer *CXXBaseInit;
4814       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4815                                        &VBase, IsInheritedVirtualBase,
4816                                        CXXBaseInit)) {
4817         HadError = true;
4818         continue;
4819       }
4820 
4821       Info.AllToInit.push_back(CXXBaseInit);
4822     }
4823   }
4824 
4825   // Non-virtual bases.
4826   for (auto &Base : ClassDecl->bases()) {
4827     // Virtuals are in the virtual base list and already constructed.
4828     if (Base.isVirtual())
4829       continue;
4830 
4831     if (CXXCtorInitializer *Value
4832           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4833       Info.AllToInit.push_back(Value);
4834     } else if (!AnyErrors) {
4835       CXXCtorInitializer *CXXBaseInit;
4836       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4837                                        &Base, /*IsInheritedVirtualBase=*/false,
4838                                        CXXBaseInit)) {
4839         HadError = true;
4840         continue;
4841       }
4842 
4843       Info.AllToInit.push_back(CXXBaseInit);
4844     }
4845   }
4846 
4847   // Fields.
4848   for (auto *Mem : ClassDecl->decls()) {
4849     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4850       // C++ [class.bit]p2:
4851       //   A declaration for a bit-field that omits the identifier declares an
4852       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4853       //   initialized.
4854       if (F->isUnnamedBitfield())
4855         continue;
4856 
4857       // If we're not generating the implicit copy/move constructor, then we'll
4858       // handle anonymous struct/union fields based on their individual
4859       // indirect fields.
4860       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4861         continue;
4862 
4863       if (CollectFieldInitializer(*this, Info, F))
4864         HadError = true;
4865       continue;
4866     }
4867 
4868     // Beyond this point, we only consider default initialization.
4869     if (Info.isImplicitCopyOrMove())
4870       continue;
4871 
4872     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4873       if (F->getType()->isIncompleteArrayType()) {
4874         assert(ClassDecl->hasFlexibleArrayMember() &&
4875                "Incomplete array type is not valid");
4876         continue;
4877       }
4878 
4879       // Initialize each field of an anonymous struct individually.
4880       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4881         HadError = true;
4882 
4883       continue;
4884     }
4885   }
4886 
4887   unsigned NumInitializers = Info.AllToInit.size();
4888   if (NumInitializers > 0) {
4889     Constructor->setNumCtorInitializers(NumInitializers);
4890     CXXCtorInitializer **baseOrMemberInitializers =
4891       new (Context) CXXCtorInitializer*[NumInitializers];
4892     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4893            NumInitializers * sizeof(CXXCtorInitializer*));
4894     Constructor->setCtorInitializers(baseOrMemberInitializers);
4895 
4896     // Constructors implicitly reference the base and member
4897     // destructors.
4898     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4899                                            Constructor->getParent());
4900   }
4901 
4902   return HadError;
4903 }
4904 
4905 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4906   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4907     const RecordDecl *RD = RT->getDecl();
4908     if (RD->isAnonymousStructOrUnion()) {
4909       for (auto *Field : RD->fields())
4910         PopulateKeysForFields(Field, IdealInits);
4911       return;
4912     }
4913   }
4914   IdealInits.push_back(Field->getCanonicalDecl());
4915 }
4916 
4917 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4918   return Context.getCanonicalType(BaseType).getTypePtr();
4919 }
4920 
4921 static const void *GetKeyForMember(ASTContext &Context,
4922                                    CXXCtorInitializer *Member) {
4923   if (!Member->isAnyMemberInitializer())
4924     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4925 
4926   return Member->getAnyMember()->getCanonicalDecl();
4927 }
4928 
4929 static void DiagnoseBaseOrMemInitializerOrder(
4930     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4931     ArrayRef<CXXCtorInitializer *> Inits) {
4932   if (Constructor->getDeclContext()->isDependentContext())
4933     return;
4934 
4935   // Don't check initializers order unless the warning is enabled at the
4936   // location of at least one initializer.
4937   bool ShouldCheckOrder = false;
4938   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4939     CXXCtorInitializer *Init = Inits[InitIndex];
4940     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4941                                  Init->getSourceLocation())) {
4942       ShouldCheckOrder = true;
4943       break;
4944     }
4945   }
4946   if (!ShouldCheckOrder)
4947     return;
4948 
4949   // Build the list of bases and members in the order that they'll
4950   // actually be initialized.  The explicit initializers should be in
4951   // this same order but may be missing things.
4952   SmallVector<const void*, 32> IdealInitKeys;
4953 
4954   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4955 
4956   // 1. Virtual bases.
4957   for (const auto &VBase : ClassDecl->vbases())
4958     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4959 
4960   // 2. Non-virtual bases.
4961   for (const auto &Base : ClassDecl->bases()) {
4962     if (Base.isVirtual())
4963       continue;
4964     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4965   }
4966 
4967   // 3. Direct fields.
4968   for (auto *Field : ClassDecl->fields()) {
4969     if (Field->isUnnamedBitfield())
4970       continue;
4971 
4972     PopulateKeysForFields(Field, IdealInitKeys);
4973   }
4974 
4975   unsigned NumIdealInits = IdealInitKeys.size();
4976   unsigned IdealIndex = 0;
4977 
4978   CXXCtorInitializer *PrevInit = nullptr;
4979   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4980     CXXCtorInitializer *Init = Inits[InitIndex];
4981     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4982 
4983     // Scan forward to try to find this initializer in the idealized
4984     // initializers list.
4985     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4986       if (InitKey == IdealInitKeys[IdealIndex])
4987         break;
4988 
4989     // If we didn't find this initializer, it must be because we
4990     // scanned past it on a previous iteration.  That can only
4991     // happen if we're out of order;  emit a warning.
4992     if (IdealIndex == NumIdealInits && PrevInit) {
4993       Sema::SemaDiagnosticBuilder D =
4994         SemaRef.Diag(PrevInit->getSourceLocation(),
4995                      diag::warn_initializer_out_of_order);
4996 
4997       if (PrevInit->isAnyMemberInitializer())
4998         D << 0 << PrevInit->getAnyMember()->getDeclName();
4999       else
5000         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5001 
5002       if (Init->isAnyMemberInitializer())
5003         D << 0 << Init->getAnyMember()->getDeclName();
5004       else
5005         D << 1 << Init->getTypeSourceInfo()->getType();
5006 
5007       // Move back to the initializer's location in the ideal list.
5008       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5009         if (InitKey == IdealInitKeys[IdealIndex])
5010           break;
5011 
5012       assert(IdealIndex < NumIdealInits &&
5013              "initializer not found in initializer list");
5014     }
5015 
5016     PrevInit = Init;
5017   }
5018 }
5019 
5020 namespace {
5021 bool CheckRedundantInit(Sema &S,
5022                         CXXCtorInitializer *Init,
5023                         CXXCtorInitializer *&PrevInit) {
5024   if (!PrevInit) {
5025     PrevInit = Init;
5026     return false;
5027   }
5028 
5029   if (FieldDecl *Field = Init->getAnyMember())
5030     S.Diag(Init->getSourceLocation(),
5031            diag::err_multiple_mem_initialization)
5032       << Field->getDeclName()
5033       << Init->getSourceRange();
5034   else {
5035     const Type *BaseClass = Init->getBaseClass();
5036     assert(BaseClass && "neither field nor base");
5037     S.Diag(Init->getSourceLocation(),
5038            diag::err_multiple_base_initialization)
5039       << QualType(BaseClass, 0)
5040       << Init->getSourceRange();
5041   }
5042   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5043     << 0 << PrevInit->getSourceRange();
5044 
5045   return true;
5046 }
5047 
5048 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5049 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5050 
5051 bool CheckRedundantUnionInit(Sema &S,
5052                              CXXCtorInitializer *Init,
5053                              RedundantUnionMap &Unions) {
5054   FieldDecl *Field = Init->getAnyMember();
5055   RecordDecl *Parent = Field->getParent();
5056   NamedDecl *Child = Field;
5057 
5058   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5059     if (Parent->isUnion()) {
5060       UnionEntry &En = Unions[Parent];
5061       if (En.first && En.first != Child) {
5062         S.Diag(Init->getSourceLocation(),
5063                diag::err_multiple_mem_union_initialization)
5064           << Field->getDeclName()
5065           << Init->getSourceRange();
5066         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5067           << 0 << En.second->getSourceRange();
5068         return true;
5069       }
5070       if (!En.first) {
5071         En.first = Child;
5072         En.second = Init;
5073       }
5074       if (!Parent->isAnonymousStructOrUnion())
5075         return false;
5076     }
5077 
5078     Child = Parent;
5079     Parent = cast<RecordDecl>(Parent->getDeclContext());
5080   }
5081 
5082   return false;
5083 }
5084 }
5085 
5086 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5087 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5088                                 SourceLocation ColonLoc,
5089                                 ArrayRef<CXXCtorInitializer*> MemInits,
5090                                 bool AnyErrors) {
5091   if (!ConstructorDecl)
5092     return;
5093 
5094   AdjustDeclIfTemplate(ConstructorDecl);
5095 
5096   CXXConstructorDecl *Constructor
5097     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5098 
5099   if (!Constructor) {
5100     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5101     return;
5102   }
5103 
5104   // Mapping for the duplicate initializers check.
5105   // For member initializers, this is keyed with a FieldDecl*.
5106   // For base initializers, this is keyed with a Type*.
5107   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5108 
5109   // Mapping for the inconsistent anonymous-union initializers check.
5110   RedundantUnionMap MemberUnions;
5111 
5112   bool HadError = false;
5113   for (unsigned i = 0; i < MemInits.size(); i++) {
5114     CXXCtorInitializer *Init = MemInits[i];
5115 
5116     // Set the source order index.
5117     Init->setSourceOrder(i);
5118 
5119     if (Init->isAnyMemberInitializer()) {
5120       const void *Key = GetKeyForMember(Context, Init);
5121       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5122           CheckRedundantUnionInit(*this, Init, MemberUnions))
5123         HadError = true;
5124     } else if (Init->isBaseInitializer()) {
5125       const void *Key = GetKeyForMember(Context, Init);
5126       if (CheckRedundantInit(*this, Init, Members[Key]))
5127         HadError = true;
5128     } else {
5129       assert(Init->isDelegatingInitializer());
5130       // This must be the only initializer
5131       if (MemInits.size() != 1) {
5132         Diag(Init->getSourceLocation(),
5133              diag::err_delegating_initializer_alone)
5134           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5135         // We will treat this as being the only initializer.
5136       }
5137       SetDelegatingInitializer(Constructor, MemInits[i]);
5138       // Return immediately as the initializer is set.
5139       return;
5140     }
5141   }
5142 
5143   if (HadError)
5144     return;
5145 
5146   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5147 
5148   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5149 
5150   DiagnoseUninitializedFields(*this, Constructor);
5151 }
5152 
5153 void
5154 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5155                                              CXXRecordDecl *ClassDecl) {
5156   // Ignore dependent contexts. Also ignore unions, since their members never
5157   // have destructors implicitly called.
5158   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5159     return;
5160 
5161   // FIXME: all the access-control diagnostics are positioned on the
5162   // field/base declaration.  That's probably good; that said, the
5163   // user might reasonably want to know why the destructor is being
5164   // emitted, and we currently don't say.
5165 
5166   // Non-static data members.
5167   for (auto *Field : ClassDecl->fields()) {
5168     if (Field->isInvalidDecl())
5169       continue;
5170 
5171     // Don't destroy incomplete or zero-length arrays.
5172     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5173       continue;
5174 
5175     QualType FieldType = Context.getBaseElementType(Field->getType());
5176 
5177     const RecordType* RT = FieldType->getAs<RecordType>();
5178     if (!RT)
5179       continue;
5180 
5181     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5182     if (FieldClassDecl->isInvalidDecl())
5183       continue;
5184     if (FieldClassDecl->hasIrrelevantDestructor())
5185       continue;
5186     // The destructor for an implicit anonymous union member is never invoked.
5187     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5188       continue;
5189 
5190     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5191     assert(Dtor && "No dtor found for FieldClassDecl!");
5192     CheckDestructorAccess(Field->getLocation(), Dtor,
5193                           PDiag(diag::err_access_dtor_field)
5194                             << Field->getDeclName()
5195                             << FieldType);
5196 
5197     MarkFunctionReferenced(Location, Dtor);
5198     DiagnoseUseOfDecl(Dtor, Location);
5199   }
5200 
5201   // We only potentially invoke the destructors of potentially constructed
5202   // subobjects.
5203   bool VisitVirtualBases = !ClassDecl->isAbstract();
5204 
5205   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5206 
5207   // Bases.
5208   for (const auto &Base : ClassDecl->bases()) {
5209     // Bases are always records in a well-formed non-dependent class.
5210     const RecordType *RT = Base.getType()->getAs<RecordType>();
5211 
5212     // Remember direct virtual bases.
5213     if (Base.isVirtual()) {
5214       if (!VisitVirtualBases)
5215         continue;
5216       DirectVirtualBases.insert(RT);
5217     }
5218 
5219     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5220     // If our base class is invalid, we probably can't get its dtor anyway.
5221     if (BaseClassDecl->isInvalidDecl())
5222       continue;
5223     if (BaseClassDecl->hasIrrelevantDestructor())
5224       continue;
5225 
5226     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5227     assert(Dtor && "No dtor found for BaseClassDecl!");
5228 
5229     // FIXME: caret should be on the start of the class name
5230     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5231                           PDiag(diag::err_access_dtor_base)
5232                               << Base.getType() << Base.getSourceRange(),
5233                           Context.getTypeDeclType(ClassDecl));
5234 
5235     MarkFunctionReferenced(Location, Dtor);
5236     DiagnoseUseOfDecl(Dtor, Location);
5237   }
5238 
5239   if (!VisitVirtualBases)
5240     return;
5241 
5242   // Virtual bases.
5243   for (const auto &VBase : ClassDecl->vbases()) {
5244     // Bases are always records in a well-formed non-dependent class.
5245     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5246 
5247     // Ignore direct virtual bases.
5248     if (DirectVirtualBases.count(RT))
5249       continue;
5250 
5251     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5252     // If our base class is invalid, we probably can't get its dtor anyway.
5253     if (BaseClassDecl->isInvalidDecl())
5254       continue;
5255     if (BaseClassDecl->hasIrrelevantDestructor())
5256       continue;
5257 
5258     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5259     assert(Dtor && "No dtor found for BaseClassDecl!");
5260     if (CheckDestructorAccess(
5261             ClassDecl->getLocation(), Dtor,
5262             PDiag(diag::err_access_dtor_vbase)
5263                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5264             Context.getTypeDeclType(ClassDecl)) ==
5265         AR_accessible) {
5266       CheckDerivedToBaseConversion(
5267           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5268           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5269           SourceRange(), DeclarationName(), nullptr);
5270     }
5271 
5272     MarkFunctionReferenced(Location, Dtor);
5273     DiagnoseUseOfDecl(Dtor, Location);
5274   }
5275 }
5276 
5277 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5278   if (!CDtorDecl)
5279     return;
5280 
5281   if (CXXConstructorDecl *Constructor
5282       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5283     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5284     DiagnoseUninitializedFields(*this, Constructor);
5285   }
5286 }
5287 
5288 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5289   if (!getLangOpts().CPlusPlus)
5290     return false;
5291 
5292   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5293   if (!RD)
5294     return false;
5295 
5296   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5297   // class template specialization here, but doing so breaks a lot of code.
5298 
5299   // We can't answer whether something is abstract until it has a
5300   // definition. If it's currently being defined, we'll walk back
5301   // over all the declarations when we have a full definition.
5302   const CXXRecordDecl *Def = RD->getDefinition();
5303   if (!Def || Def->isBeingDefined())
5304     return false;
5305 
5306   return RD->isAbstract();
5307 }
5308 
5309 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5310                                   TypeDiagnoser &Diagnoser) {
5311   if (!isAbstractType(Loc, T))
5312     return false;
5313 
5314   T = Context.getBaseElementType(T);
5315   Diagnoser.diagnose(*this, Loc, T);
5316   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5317   return true;
5318 }
5319 
5320 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5321   // Check if we've already emitted the list of pure virtual functions
5322   // for this class.
5323   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5324     return;
5325 
5326   // If the diagnostic is suppressed, don't emit the notes. We're only
5327   // going to emit them once, so try to attach them to a diagnostic we're
5328   // actually going to show.
5329   if (Diags.isLastDiagnosticIgnored())
5330     return;
5331 
5332   CXXFinalOverriderMap FinalOverriders;
5333   RD->getFinalOverriders(FinalOverriders);
5334 
5335   // Keep a set of seen pure methods so we won't diagnose the same method
5336   // more than once.
5337   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5338 
5339   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5340                                    MEnd = FinalOverriders.end();
5341        M != MEnd;
5342        ++M) {
5343     for (OverridingMethods::iterator SO = M->second.begin(),
5344                                   SOEnd = M->second.end();
5345          SO != SOEnd; ++SO) {
5346       // C++ [class.abstract]p4:
5347       //   A class is abstract if it contains or inherits at least one
5348       //   pure virtual function for which the final overrider is pure
5349       //   virtual.
5350 
5351       //
5352       if (SO->second.size() != 1)
5353         continue;
5354 
5355       if (!SO->second.front().Method->isPure())
5356         continue;
5357 
5358       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5359         continue;
5360 
5361       Diag(SO->second.front().Method->getLocation(),
5362            diag::note_pure_virtual_function)
5363         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5364     }
5365   }
5366 
5367   if (!PureVirtualClassDiagSet)
5368     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5369   PureVirtualClassDiagSet->insert(RD);
5370 }
5371 
5372 namespace {
5373 struct AbstractUsageInfo {
5374   Sema &S;
5375   CXXRecordDecl *Record;
5376   CanQualType AbstractType;
5377   bool Invalid;
5378 
5379   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5380     : S(S), Record(Record),
5381       AbstractType(S.Context.getCanonicalType(
5382                    S.Context.getTypeDeclType(Record))),
5383       Invalid(false) {}
5384 
5385   void DiagnoseAbstractType() {
5386     if (Invalid) return;
5387     S.DiagnoseAbstractType(Record);
5388     Invalid = true;
5389   }
5390 
5391   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5392 };
5393 
5394 struct CheckAbstractUsage {
5395   AbstractUsageInfo &Info;
5396   const NamedDecl *Ctx;
5397 
5398   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5399     : Info(Info), Ctx(Ctx) {}
5400 
5401   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5402     switch (TL.getTypeLocClass()) {
5403 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5404 #define TYPELOC(CLASS, PARENT) \
5405     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5406 #include "clang/AST/TypeLocNodes.def"
5407     }
5408   }
5409 
5410   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5411     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5412     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5413       if (!TL.getParam(I))
5414         continue;
5415 
5416       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5417       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5418     }
5419   }
5420 
5421   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5422     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5423   }
5424 
5425   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5426     // Visit the type parameters from a permissive context.
5427     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5428       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5429       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5430         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5431           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5432       // TODO: other template argument types?
5433     }
5434   }
5435 
5436   // Visit pointee types from a permissive context.
5437 #define CheckPolymorphic(Type) \
5438   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5439     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5440   }
5441   CheckPolymorphic(PointerTypeLoc)
5442   CheckPolymorphic(ReferenceTypeLoc)
5443   CheckPolymorphic(MemberPointerTypeLoc)
5444   CheckPolymorphic(BlockPointerTypeLoc)
5445   CheckPolymorphic(AtomicTypeLoc)
5446 
5447   /// Handle all the types we haven't given a more specific
5448   /// implementation for above.
5449   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5450     // Every other kind of type that we haven't called out already
5451     // that has an inner type is either (1) sugar or (2) contains that
5452     // inner type in some way as a subobject.
5453     if (TypeLoc Next = TL.getNextTypeLoc())
5454       return Visit(Next, Sel);
5455 
5456     // If there's no inner type and we're in a permissive context,
5457     // don't diagnose.
5458     if (Sel == Sema::AbstractNone) return;
5459 
5460     // Check whether the type matches the abstract type.
5461     QualType T = TL.getType();
5462     if (T->isArrayType()) {
5463       Sel = Sema::AbstractArrayType;
5464       T = Info.S.Context.getBaseElementType(T);
5465     }
5466     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5467     if (CT != Info.AbstractType) return;
5468 
5469     // It matched; do some magic.
5470     if (Sel == Sema::AbstractArrayType) {
5471       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5472         << T << TL.getSourceRange();
5473     } else {
5474       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5475         << Sel << T << TL.getSourceRange();
5476     }
5477     Info.DiagnoseAbstractType();
5478   }
5479 };
5480 
5481 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5482                                   Sema::AbstractDiagSelID Sel) {
5483   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5484 }
5485 
5486 }
5487 
5488 /// Check for invalid uses of an abstract type in a method declaration.
5489 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5490                                     CXXMethodDecl *MD) {
5491   // No need to do the check on definitions, which require that
5492   // the return/param types be complete.
5493   if (MD->doesThisDeclarationHaveABody())
5494     return;
5495 
5496   // For safety's sake, just ignore it if we don't have type source
5497   // information.  This should never happen for non-implicit methods,
5498   // but...
5499   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5500     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5501 }
5502 
5503 /// Check for invalid uses of an abstract type within a class definition.
5504 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5505                                     CXXRecordDecl *RD) {
5506   for (auto *D : RD->decls()) {
5507     if (D->isImplicit()) continue;
5508 
5509     // Methods and method templates.
5510     if (isa<CXXMethodDecl>(D)) {
5511       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5512     } else if (isa<FunctionTemplateDecl>(D)) {
5513       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5514       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5515 
5516     // Fields and static variables.
5517     } else if (isa<FieldDecl>(D)) {
5518       FieldDecl *FD = cast<FieldDecl>(D);
5519       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5520         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5521     } else if (isa<VarDecl>(D)) {
5522       VarDecl *VD = cast<VarDecl>(D);
5523       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5524         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5525 
5526     // Nested classes and class templates.
5527     } else if (isa<CXXRecordDecl>(D)) {
5528       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5529     } else if (isa<ClassTemplateDecl>(D)) {
5530       CheckAbstractClassUsage(Info,
5531                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5532     }
5533   }
5534 }
5535 
5536 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5537   Attr *ClassAttr = getDLLAttr(Class);
5538   if (!ClassAttr)
5539     return;
5540 
5541   assert(ClassAttr->getKind() == attr::DLLExport);
5542 
5543   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5544 
5545   if (TSK == TSK_ExplicitInstantiationDeclaration)
5546     // Don't go any further if this is just an explicit instantiation
5547     // declaration.
5548     return;
5549 
5550   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5551     S.MarkVTableUsed(Class->getLocation(), Class, true);
5552 
5553   for (Decl *Member : Class->decls()) {
5554     // Defined static variables that are members of an exported base
5555     // class must be marked export too.
5556     auto *VD = dyn_cast<VarDecl>(Member);
5557     if (VD && Member->getAttr<DLLExportAttr>() &&
5558         VD->getStorageClass() == SC_Static &&
5559         TSK == TSK_ImplicitInstantiation)
5560       S.MarkVariableReferenced(VD->getLocation(), VD);
5561 
5562     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5563     if (!MD)
5564       continue;
5565 
5566     if (Member->getAttr<DLLExportAttr>()) {
5567       if (MD->isUserProvided()) {
5568         // Instantiate non-default class member functions ...
5569 
5570         // .. except for certain kinds of template specializations.
5571         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5572           continue;
5573 
5574         S.MarkFunctionReferenced(Class->getLocation(), MD);
5575 
5576         // The function will be passed to the consumer when its definition is
5577         // encountered.
5578       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5579                  MD->isCopyAssignmentOperator() ||
5580                  MD->isMoveAssignmentOperator()) {
5581         // Synthesize and instantiate non-trivial implicit methods, explicitly
5582         // defaulted methods, and the copy and move assignment operators. The
5583         // latter are exported even if they are trivial, because the address of
5584         // an operator can be taken and should compare equal across libraries.
5585         DiagnosticErrorTrap Trap(S.Diags);
5586         S.MarkFunctionReferenced(Class->getLocation(), MD);
5587         if (Trap.hasErrorOccurred()) {
5588           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5589               << Class << !S.getLangOpts().CPlusPlus11;
5590           break;
5591         }
5592 
5593         // There is no later point when we will see the definition of this
5594         // function, so pass it to the consumer now.
5595         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5596       }
5597     }
5598   }
5599 }
5600 
5601 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5602                                                         CXXRecordDecl *Class) {
5603   // Only the MS ABI has default constructor closures, so we don't need to do
5604   // this semantic checking anywhere else.
5605   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5606     return;
5607 
5608   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5609   for (Decl *Member : Class->decls()) {
5610     // Look for exported default constructors.
5611     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5612     if (!CD || !CD->isDefaultConstructor())
5613       continue;
5614     auto *Attr = CD->getAttr<DLLExportAttr>();
5615     if (!Attr)
5616       continue;
5617 
5618     // If the class is non-dependent, mark the default arguments as ODR-used so
5619     // that we can properly codegen the constructor closure.
5620     if (!Class->isDependentContext()) {
5621       for (ParmVarDecl *PD : CD->parameters()) {
5622         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5623         S.DiscardCleanupsInEvaluationContext();
5624       }
5625     }
5626 
5627     if (LastExportedDefaultCtor) {
5628       S.Diag(LastExportedDefaultCtor->getLocation(),
5629              diag::err_attribute_dll_ambiguous_default_ctor)
5630           << Class;
5631       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5632           << CD->getDeclName();
5633       return;
5634     }
5635     LastExportedDefaultCtor = CD;
5636   }
5637 }
5638 
5639 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5640   // Mark any compiler-generated routines with the implicit code_seg attribute.
5641   for (auto *Method : Class->methods()) {
5642     if (Method->isUserProvided())
5643       continue;
5644     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5645       Method->addAttr(A);
5646   }
5647 }
5648 
5649 /// Check class-level dllimport/dllexport attribute.
5650 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5651   Attr *ClassAttr = getDLLAttr(Class);
5652 
5653   // MSVC inherits DLL attributes to partial class template specializations.
5654   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5655     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5656       if (Attr *TemplateAttr =
5657               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5658         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5659         A->setInherited(true);
5660         ClassAttr = A;
5661       }
5662     }
5663   }
5664 
5665   if (!ClassAttr)
5666     return;
5667 
5668   if (!Class->isExternallyVisible()) {
5669     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5670         << Class << ClassAttr;
5671     return;
5672   }
5673 
5674   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5675       !ClassAttr->isInherited()) {
5676     // Diagnose dll attributes on members of class with dll attribute.
5677     for (Decl *Member : Class->decls()) {
5678       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5679         continue;
5680       InheritableAttr *MemberAttr = getDLLAttr(Member);
5681       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5682         continue;
5683 
5684       Diag(MemberAttr->getLocation(),
5685              diag::err_attribute_dll_member_of_dll_class)
5686           << MemberAttr << ClassAttr;
5687       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5688       Member->setInvalidDecl();
5689     }
5690   }
5691 
5692   if (Class->getDescribedClassTemplate())
5693     // Don't inherit dll attribute until the template is instantiated.
5694     return;
5695 
5696   // The class is either imported or exported.
5697   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5698 
5699   // Check if this was a dllimport attribute propagated from a derived class to
5700   // a base class template specialization. We don't apply these attributes to
5701   // static data members.
5702   const bool PropagatedImport =
5703       !ClassExported &&
5704       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5705 
5706   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5707 
5708   // Ignore explicit dllexport on explicit class template instantiation
5709   // declarations, except in MinGW mode.
5710   if (ClassExported && !ClassAttr->isInherited() &&
5711       TSK == TSK_ExplicitInstantiationDeclaration &&
5712       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
5713     Class->dropAttr<DLLExportAttr>();
5714     return;
5715   }
5716 
5717   // Force declaration of implicit members so they can inherit the attribute.
5718   ForceDeclarationOfImplicitMembers(Class);
5719 
5720   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5721   // seem to be true in practice?
5722 
5723   for (Decl *Member : Class->decls()) {
5724     VarDecl *VD = dyn_cast<VarDecl>(Member);
5725     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5726 
5727     // Only methods and static fields inherit the attributes.
5728     if (!VD && !MD)
5729       continue;
5730 
5731     if (MD) {
5732       // Don't process deleted methods.
5733       if (MD->isDeleted())
5734         continue;
5735 
5736       if (MD->isInlined()) {
5737         // MinGW does not import or export inline methods. But do it for
5738         // template instantiations.
5739         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5740             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
5741             TSK != TSK_ExplicitInstantiationDeclaration &&
5742             TSK != TSK_ExplicitInstantiationDefinition)
5743           continue;
5744 
5745         // MSVC versions before 2015 don't export the move assignment operators
5746         // and move constructor, so don't attempt to import/export them if
5747         // we have a definition.
5748         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5749         if ((MD->isMoveAssignmentOperator() ||
5750              (Ctor && Ctor->isMoveConstructor())) &&
5751             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5752           continue;
5753 
5754         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5755         // operator is exported anyway.
5756         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5757             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5758           continue;
5759       }
5760     }
5761 
5762     // Don't apply dllimport attributes to static data members of class template
5763     // instantiations when the attribute is propagated from a derived class.
5764     if (VD && PropagatedImport)
5765       continue;
5766 
5767     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5768       continue;
5769 
5770     if (!getDLLAttr(Member)) {
5771       InheritableAttr *NewAttr = nullptr;
5772 
5773       // Do not export/import inline function when -fno-dllexport-inlines is
5774       // passed. But add attribute for later local static var check.
5775       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5776           TSK != TSK_ExplicitInstantiationDeclaration &&
5777           TSK != TSK_ExplicitInstantiationDefinition) {
5778         if (ClassExported) {
5779           NewAttr = ::new (getASTContext())
5780             DLLExportStaticLocalAttr(ClassAttr->getRange(),
5781                                      getASTContext(),
5782                                      ClassAttr->getSpellingListIndex());
5783         } else {
5784           NewAttr = ::new (getASTContext())
5785             DLLImportStaticLocalAttr(ClassAttr->getRange(),
5786                                      getASTContext(),
5787                                      ClassAttr->getSpellingListIndex());
5788         }
5789       } else {
5790         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5791       }
5792 
5793       NewAttr->setInherited(true);
5794       Member->addAttr(NewAttr);
5795 
5796       if (MD) {
5797         // Propagate DLLAttr to friend re-declarations of MD that have already
5798         // been constructed.
5799         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5800              FD = FD->getPreviousDecl()) {
5801           if (FD->getFriendObjectKind() == Decl::FOK_None)
5802             continue;
5803           assert(!getDLLAttr(FD) &&
5804                  "friend re-decl should not already have a DLLAttr");
5805           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5806           NewAttr->setInherited(true);
5807           FD->addAttr(NewAttr);
5808         }
5809       }
5810     }
5811   }
5812 
5813   if (ClassExported)
5814     DelayedDllExportClasses.push_back(Class);
5815 }
5816 
5817 /// Perform propagation of DLL attributes from a derived class to a
5818 /// templated base class for MS compatibility.
5819 void Sema::propagateDLLAttrToBaseClassTemplate(
5820     CXXRecordDecl *Class, Attr *ClassAttr,
5821     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5822   if (getDLLAttr(
5823           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5824     // If the base class template has a DLL attribute, don't try to change it.
5825     return;
5826   }
5827 
5828   auto TSK = BaseTemplateSpec->getSpecializationKind();
5829   if (!getDLLAttr(BaseTemplateSpec) &&
5830       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5831        TSK == TSK_ImplicitInstantiation)) {
5832     // The template hasn't been instantiated yet (or it has, but only as an
5833     // explicit instantiation declaration or implicit instantiation, which means
5834     // we haven't codegenned any members yet), so propagate the attribute.
5835     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5836     NewAttr->setInherited(true);
5837     BaseTemplateSpec->addAttr(NewAttr);
5838 
5839     // If this was an import, mark that we propagated it from a derived class to
5840     // a base class template specialization.
5841     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5842       ImportAttr->setPropagatedToBaseTemplate();
5843 
5844     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5845     // needs to be run again to work see the new attribute. Otherwise this will
5846     // get run whenever the template is instantiated.
5847     if (TSK != TSK_Undeclared)
5848       checkClassLevelDLLAttribute(BaseTemplateSpec);
5849 
5850     return;
5851   }
5852 
5853   if (getDLLAttr(BaseTemplateSpec)) {
5854     // The template has already been specialized or instantiated with an
5855     // attribute, explicitly or through propagation. We should not try to change
5856     // it.
5857     return;
5858   }
5859 
5860   // The template was previously instantiated or explicitly specialized without
5861   // a dll attribute, It's too late for us to add an attribute, so warn that
5862   // this is unsupported.
5863   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5864       << BaseTemplateSpec->isExplicitSpecialization();
5865   Diag(ClassAttr->getLocation(), diag::note_attribute);
5866   if (BaseTemplateSpec->isExplicitSpecialization()) {
5867     Diag(BaseTemplateSpec->getLocation(),
5868            diag::note_template_class_explicit_specialization_was_here)
5869         << BaseTemplateSpec;
5870   } else {
5871     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5872            diag::note_template_class_instantiation_was_here)
5873         << BaseTemplateSpec;
5874   }
5875 }
5876 
5877 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5878                                         SourceLocation DefaultLoc) {
5879   switch (S.getSpecialMember(MD)) {
5880   case Sema::CXXDefaultConstructor:
5881     S.DefineImplicitDefaultConstructor(DefaultLoc,
5882                                        cast<CXXConstructorDecl>(MD));
5883     break;
5884   case Sema::CXXCopyConstructor:
5885     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5886     break;
5887   case Sema::CXXCopyAssignment:
5888     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5889     break;
5890   case Sema::CXXDestructor:
5891     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5892     break;
5893   case Sema::CXXMoveConstructor:
5894     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5895     break;
5896   case Sema::CXXMoveAssignment:
5897     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5898     break;
5899   case Sema::CXXInvalid:
5900     llvm_unreachable("Invalid special member.");
5901   }
5902 }
5903 
5904 /// Determine whether a type is permitted to be passed or returned in
5905 /// registers, per C++ [class.temporary]p3.
5906 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5907                                TargetInfo::CallingConvKind CCK) {
5908   if (D->isDependentType() || D->isInvalidDecl())
5909     return false;
5910 
5911   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5912   // The PS4 platform ABI follows the behavior of Clang 3.2.
5913   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5914     return !D->hasNonTrivialDestructorForCall() &&
5915            !D->hasNonTrivialCopyConstructorForCall();
5916 
5917   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
5918     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5919     bool DtorIsTrivialForCall = false;
5920 
5921     // If a class has at least one non-deleted, trivial copy constructor, it
5922     // is passed according to the C ABI. Otherwise, it is passed indirectly.
5923     //
5924     // Note: This permits classes with non-trivial copy or move ctors to be
5925     // passed in registers, so long as they *also* have a trivial copy ctor,
5926     // which is non-conforming.
5927     if (D->needsImplicitCopyConstructor()) {
5928       if (!D->defaultedCopyConstructorIsDeleted()) {
5929         if (D->hasTrivialCopyConstructor())
5930           CopyCtorIsTrivial = true;
5931         if (D->hasTrivialCopyConstructorForCall())
5932           CopyCtorIsTrivialForCall = true;
5933       }
5934     } else {
5935       for (const CXXConstructorDecl *CD : D->ctors()) {
5936         if (CD->isCopyConstructor() && !CD->isDeleted()) {
5937           if (CD->isTrivial())
5938             CopyCtorIsTrivial = true;
5939           if (CD->isTrivialForCall())
5940             CopyCtorIsTrivialForCall = true;
5941         }
5942       }
5943     }
5944 
5945     if (D->needsImplicitDestructor()) {
5946       if (!D->defaultedDestructorIsDeleted() &&
5947           D->hasTrivialDestructorForCall())
5948         DtorIsTrivialForCall = true;
5949     } else if (const auto *DD = D->getDestructor()) {
5950       if (!DD->isDeleted() && DD->isTrivialForCall())
5951         DtorIsTrivialForCall = true;
5952     }
5953 
5954     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5955     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5956       return true;
5957 
5958     // If a class has a destructor, we'd really like to pass it indirectly
5959     // because it allows us to elide copies.  Unfortunately, MSVC makes that
5960     // impossible for small types, which it will pass in a single register or
5961     // stack slot. Most objects with dtors are large-ish, so handle that early.
5962     // We can't call out all large objects as being indirect because there are
5963     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5964     // how we pass large POD types.
5965 
5966     // Note: This permits small classes with nontrivial destructors to be
5967     // passed in registers, which is non-conforming.
5968     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5969     uint64_t TypeSize = isAArch64 ? 128 : 64;
5970 
5971     if (CopyCtorIsTrivial &&
5972         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
5973       return true;
5974     return false;
5975   }
5976 
5977   // Per C++ [class.temporary]p3, the relevant condition is:
5978   //   each copy constructor, move constructor, and destructor of X is
5979   //   either trivial or deleted, and X has at least one non-deleted copy
5980   //   or move constructor
5981   bool HasNonDeletedCopyOrMove = false;
5982 
5983   if (D->needsImplicitCopyConstructor() &&
5984       !D->defaultedCopyConstructorIsDeleted()) {
5985     if (!D->hasTrivialCopyConstructorForCall())
5986       return false;
5987     HasNonDeletedCopyOrMove = true;
5988   }
5989 
5990   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5991       !D->defaultedMoveConstructorIsDeleted()) {
5992     if (!D->hasTrivialMoveConstructorForCall())
5993       return false;
5994     HasNonDeletedCopyOrMove = true;
5995   }
5996 
5997   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5998       !D->hasTrivialDestructorForCall())
5999     return false;
6000 
6001   for (const CXXMethodDecl *MD : D->methods()) {
6002     if (MD->isDeleted())
6003       continue;
6004 
6005     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6006     if (CD && CD->isCopyOrMoveConstructor())
6007       HasNonDeletedCopyOrMove = true;
6008     else if (!isa<CXXDestructorDecl>(MD))
6009       continue;
6010 
6011     if (!MD->isTrivialForCall())
6012       return false;
6013   }
6014 
6015   return HasNonDeletedCopyOrMove;
6016 }
6017 
6018 /// Perform semantic checks on a class definition that has been
6019 /// completing, introducing implicitly-declared members, checking for
6020 /// abstract types, etc.
6021 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
6022   if (!Record)
6023     return;
6024 
6025   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6026     AbstractUsageInfo Info(*this, Record);
6027     CheckAbstractClassUsage(Info, Record);
6028   }
6029 
6030   // If this is not an aggregate type and has no user-declared constructor,
6031   // complain about any non-static data members of reference or const scalar
6032   // type, since they will never get initializers.
6033   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6034       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6035       !Record->isLambda()) {
6036     bool Complained = false;
6037     for (const auto *F : Record->fields()) {
6038       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6039         continue;
6040 
6041       if (F->getType()->isReferenceType() ||
6042           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6043         if (!Complained) {
6044           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6045             << Record->getTagKind() << Record;
6046           Complained = true;
6047         }
6048 
6049         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6050           << F->getType()->isReferenceType()
6051           << F->getDeclName();
6052       }
6053     }
6054   }
6055 
6056   if (Record->getIdentifier()) {
6057     // C++ [class.mem]p13:
6058     //   If T is the name of a class, then each of the following shall have a
6059     //   name different from T:
6060     //     - every member of every anonymous union that is a member of class T.
6061     //
6062     // C++ [class.mem]p14:
6063     //   In addition, if class T has a user-declared constructor (12.1), every
6064     //   non-static data member of class T shall have a name different from T.
6065     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6066     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6067          ++I) {
6068       NamedDecl *D = (*I)->getUnderlyingDecl();
6069       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6070            Record->hasUserDeclaredConstructor()) ||
6071           isa<IndirectFieldDecl>(D)) {
6072         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6073           << D->getDeclName();
6074         break;
6075       }
6076     }
6077   }
6078 
6079   // Warn if the class has virtual methods but non-virtual public destructor.
6080   if (Record->isPolymorphic() && !Record->isDependentType()) {
6081     CXXDestructorDecl *dtor = Record->getDestructor();
6082     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6083         !Record->hasAttr<FinalAttr>())
6084       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6085            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6086   }
6087 
6088   if (Record->isAbstract()) {
6089     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6090       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6091         << FA->isSpelledAsSealed();
6092       DiagnoseAbstractType(Record);
6093     }
6094   }
6095 
6096   // See if trivial_abi has to be dropped.
6097   if (Record->hasAttr<TrivialABIAttr>())
6098     checkIllFormedTrivialABIStruct(*Record);
6099 
6100   // Set HasTrivialSpecialMemberForCall if the record has attribute
6101   // "trivial_abi".
6102   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6103 
6104   if (HasTrivialABI)
6105     Record->setHasTrivialSpecialMemberForCall();
6106 
6107   bool HasMethodWithOverrideControl = false,
6108        HasOverridingMethodWithoutOverrideControl = false;
6109   if (!Record->isDependentType()) {
6110     for (auto *M : Record->methods()) {
6111       // See if a method overloads virtual methods in a base
6112       // class without overriding any.
6113       if (!M->isStatic())
6114         DiagnoseHiddenVirtualMethods(M);
6115       if (M->hasAttr<OverrideAttr>())
6116         HasMethodWithOverrideControl = true;
6117       else if (M->size_overridden_methods() > 0)
6118         HasOverridingMethodWithoutOverrideControl = true;
6119       // Check whether the explicitly-defaulted special members are valid.
6120       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6121         CheckExplicitlyDefaultedSpecialMember(M);
6122 
6123       // For an explicitly defaulted or deleted special member, we defer
6124       // determining triviality until the class is complete. That time is now!
6125       CXXSpecialMember CSM = getSpecialMember(M);
6126       if (!M->isImplicit() && !M->isUserProvided()) {
6127         if (CSM != CXXInvalid) {
6128           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6129           // Inform the class that we've finished declaring this member.
6130           Record->finishedDefaultedOrDeletedMember(M);
6131           M->setTrivialForCall(
6132               HasTrivialABI ||
6133               SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6134           Record->setTrivialForCallFlags(M);
6135         }
6136       }
6137 
6138       // Set triviality for the purpose of calls if this is a user-provided
6139       // copy/move constructor or destructor.
6140       if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6141            CSM == CXXDestructor) && M->isUserProvided()) {
6142         M->setTrivialForCall(HasTrivialABI);
6143         Record->setTrivialForCallFlags(M);
6144       }
6145 
6146       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6147           M->hasAttr<DLLExportAttr>()) {
6148         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6149             M->isTrivial() &&
6150             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6151              CSM == CXXDestructor))
6152           M->dropAttr<DLLExportAttr>();
6153 
6154         if (M->hasAttr<DLLExportAttr>()) {
6155           DefineImplicitSpecialMember(*this, M, M->getLocation());
6156           ActOnFinishInlineFunctionDef(M);
6157         }
6158       }
6159     }
6160   }
6161 
6162   if (HasMethodWithOverrideControl &&
6163       HasOverridingMethodWithoutOverrideControl) {
6164     // At least one method has the 'override' control declared.
6165     // Diagnose all other overridden methods which do not have 'override' specified on them.
6166     for (auto *M : Record->methods())
6167       DiagnoseAbsenceOfOverrideControl(M);
6168   }
6169 
6170   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6171   // whether this class uses any C++ features that are implemented
6172   // completely differently in MSVC, and if so, emit a diagnostic.
6173   // That diagnostic defaults to an error, but we allow projects to
6174   // map it down to a warning (or ignore it).  It's a fairly common
6175   // practice among users of the ms_struct pragma to mass-annotate
6176   // headers, sweeping up a bunch of types that the project doesn't
6177   // really rely on MSVC-compatible layout for.  We must therefore
6178   // support "ms_struct except for C++ stuff" as a secondary ABI.
6179   if (Record->isMsStruct(Context) &&
6180       (Record->isPolymorphic() || Record->getNumBases())) {
6181     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6182   }
6183 
6184   checkClassLevelDLLAttribute(Record);
6185   checkClassLevelCodeSegAttribute(Record);
6186 
6187   bool ClangABICompat4 =
6188       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6189   TargetInfo::CallingConvKind CCK =
6190       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6191   bool CanPass = canPassInRegisters(*this, Record, CCK);
6192 
6193   // Do not change ArgPassingRestrictions if it has already been set to
6194   // APK_CanNeverPassInRegs.
6195   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6196     Record->setArgPassingRestrictions(CanPass
6197                                           ? RecordDecl::APK_CanPassInRegs
6198                                           : RecordDecl::APK_CannotPassInRegs);
6199 
6200   // If canPassInRegisters returns true despite the record having a non-trivial
6201   // destructor, the record is destructed in the callee. This happens only when
6202   // the record or one of its subobjects has a field annotated with trivial_abi
6203   // or a field qualified with ObjC __strong/__weak.
6204   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6205     Record->setParamDestroyedInCallee(true);
6206   else if (Record->hasNonTrivialDestructor())
6207     Record->setParamDestroyedInCallee(CanPass);
6208 
6209   if (getLangOpts().ForceEmitVTables) {
6210     // If we want to emit all the vtables, we need to mark it as used.  This
6211     // is especially required for cases like vtable assumption loads.
6212     MarkVTableUsed(Record->getInnerLocStart(), Record);
6213   }
6214 }
6215 
6216 /// Look up the special member function that would be called by a special
6217 /// member function for a subobject of class type.
6218 ///
6219 /// \param Class The class type of the subobject.
6220 /// \param CSM The kind of special member function.
6221 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6222 /// \param ConstRHS True if this is a copy operation with a const object
6223 ///        on its RHS, that is, if the argument to the outer special member
6224 ///        function is 'const' and this is not a field marked 'mutable'.
6225 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6226     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6227     unsigned FieldQuals, bool ConstRHS) {
6228   unsigned LHSQuals = 0;
6229   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6230     LHSQuals = FieldQuals;
6231 
6232   unsigned RHSQuals = FieldQuals;
6233   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6234     RHSQuals = 0;
6235   else if (ConstRHS)
6236     RHSQuals |= Qualifiers::Const;
6237 
6238   return S.LookupSpecialMember(Class, CSM,
6239                                RHSQuals & Qualifiers::Const,
6240                                RHSQuals & Qualifiers::Volatile,
6241                                false,
6242                                LHSQuals & Qualifiers::Const,
6243                                LHSQuals & Qualifiers::Volatile);
6244 }
6245 
6246 class Sema::InheritedConstructorInfo {
6247   Sema &S;
6248   SourceLocation UseLoc;
6249 
6250   /// A mapping from the base classes through which the constructor was
6251   /// inherited to the using shadow declaration in that base class (or a null
6252   /// pointer if the constructor was declared in that base class).
6253   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6254       InheritedFromBases;
6255 
6256 public:
6257   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6258                            ConstructorUsingShadowDecl *Shadow)
6259       : S(S), UseLoc(UseLoc) {
6260     bool DiagnosedMultipleConstructedBases = false;
6261     CXXRecordDecl *ConstructedBase = nullptr;
6262     UsingDecl *ConstructedBaseUsing = nullptr;
6263 
6264     // Find the set of such base class subobjects and check that there's a
6265     // unique constructed subobject.
6266     for (auto *D : Shadow->redecls()) {
6267       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6268       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6269       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6270 
6271       InheritedFromBases.insert(
6272           std::make_pair(DNominatedBase->getCanonicalDecl(),
6273                          DShadow->getNominatedBaseClassShadowDecl()));
6274       if (DShadow->constructsVirtualBase())
6275         InheritedFromBases.insert(
6276             std::make_pair(DConstructedBase->getCanonicalDecl(),
6277                            DShadow->getConstructedBaseClassShadowDecl()));
6278       else
6279         assert(DNominatedBase == DConstructedBase);
6280 
6281       // [class.inhctor.init]p2:
6282       //   If the constructor was inherited from multiple base class subobjects
6283       //   of type B, the program is ill-formed.
6284       if (!ConstructedBase) {
6285         ConstructedBase = DConstructedBase;
6286         ConstructedBaseUsing = D->getUsingDecl();
6287       } else if (ConstructedBase != DConstructedBase &&
6288                  !Shadow->isInvalidDecl()) {
6289         if (!DiagnosedMultipleConstructedBases) {
6290           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6291               << Shadow->getTargetDecl();
6292           S.Diag(ConstructedBaseUsing->getLocation(),
6293                diag::note_ambiguous_inherited_constructor_using)
6294               << ConstructedBase;
6295           DiagnosedMultipleConstructedBases = true;
6296         }
6297         S.Diag(D->getUsingDecl()->getLocation(),
6298                diag::note_ambiguous_inherited_constructor_using)
6299             << DConstructedBase;
6300       }
6301     }
6302 
6303     if (DiagnosedMultipleConstructedBases)
6304       Shadow->setInvalidDecl();
6305   }
6306 
6307   /// Find the constructor to use for inherited construction of a base class,
6308   /// and whether that base class constructor inherits the constructor from a
6309   /// virtual base class (in which case it won't actually invoke it).
6310   std::pair<CXXConstructorDecl *, bool>
6311   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6312     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6313     if (It == InheritedFromBases.end())
6314       return std::make_pair(nullptr, false);
6315 
6316     // This is an intermediary class.
6317     if (It->second)
6318       return std::make_pair(
6319           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6320           It->second->constructsVirtualBase());
6321 
6322     // This is the base class from which the constructor was inherited.
6323     return std::make_pair(Ctor, false);
6324   }
6325 };
6326 
6327 /// Is the special member function which would be selected to perform the
6328 /// specified operation on the specified class type a constexpr constructor?
6329 static bool
6330 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6331                          Sema::CXXSpecialMember CSM, unsigned Quals,
6332                          bool ConstRHS,
6333                          CXXConstructorDecl *InheritedCtor = nullptr,
6334                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6335   // If we're inheriting a constructor, see if we need to call it for this base
6336   // class.
6337   if (InheritedCtor) {
6338     assert(CSM == Sema::CXXDefaultConstructor);
6339     auto BaseCtor =
6340         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6341     if (BaseCtor)
6342       return BaseCtor->isConstexpr();
6343   }
6344 
6345   if (CSM == Sema::CXXDefaultConstructor)
6346     return ClassDecl->hasConstexprDefaultConstructor();
6347 
6348   Sema::SpecialMemberOverloadResult SMOR =
6349       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6350   if (!SMOR.getMethod())
6351     // A constructor we wouldn't select can't be "involved in initializing"
6352     // anything.
6353     return true;
6354   return SMOR.getMethod()->isConstexpr();
6355 }
6356 
6357 /// Determine whether the specified special member function would be constexpr
6358 /// if it were implicitly defined.
6359 static bool defaultedSpecialMemberIsConstexpr(
6360     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6361     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6362     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6363   if (!S.getLangOpts().CPlusPlus11)
6364     return false;
6365 
6366   // C++11 [dcl.constexpr]p4:
6367   // In the definition of a constexpr constructor [...]
6368   bool Ctor = true;
6369   switch (CSM) {
6370   case Sema::CXXDefaultConstructor:
6371     if (Inherited)
6372       break;
6373     // Since default constructor lookup is essentially trivial (and cannot
6374     // involve, for instance, template instantiation), we compute whether a
6375     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6376     //
6377     // This is important for performance; we need to know whether the default
6378     // constructor is constexpr to determine whether the type is a literal type.
6379     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6380 
6381   case Sema::CXXCopyConstructor:
6382   case Sema::CXXMoveConstructor:
6383     // For copy or move constructors, we need to perform overload resolution.
6384     break;
6385 
6386   case Sema::CXXCopyAssignment:
6387   case Sema::CXXMoveAssignment:
6388     if (!S.getLangOpts().CPlusPlus14)
6389       return false;
6390     // In C++1y, we need to perform overload resolution.
6391     Ctor = false;
6392     break;
6393 
6394   case Sema::CXXDestructor:
6395   case Sema::CXXInvalid:
6396     return false;
6397   }
6398 
6399   //   -- if the class is a non-empty union, or for each non-empty anonymous
6400   //      union member of a non-union class, exactly one non-static data member
6401   //      shall be initialized; [DR1359]
6402   //
6403   // If we squint, this is guaranteed, since exactly one non-static data member
6404   // will be initialized (if the constructor isn't deleted), we just don't know
6405   // which one.
6406   if (Ctor && ClassDecl->isUnion())
6407     return CSM == Sema::CXXDefaultConstructor
6408                ? ClassDecl->hasInClassInitializer() ||
6409                      !ClassDecl->hasVariantMembers()
6410                : true;
6411 
6412   //   -- the class shall not have any virtual base classes;
6413   if (Ctor && ClassDecl->getNumVBases())
6414     return false;
6415 
6416   // C++1y [class.copy]p26:
6417   //   -- [the class] is a literal type, and
6418   if (!Ctor && !ClassDecl->isLiteral())
6419     return false;
6420 
6421   //   -- every constructor involved in initializing [...] base class
6422   //      sub-objects shall be a constexpr constructor;
6423   //   -- the assignment operator selected to copy/move each direct base
6424   //      class is a constexpr function, and
6425   for (const auto &B : ClassDecl->bases()) {
6426     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6427     if (!BaseType) continue;
6428 
6429     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6430     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6431                                   InheritedCtor, Inherited))
6432       return false;
6433   }
6434 
6435   //   -- every constructor involved in initializing non-static data members
6436   //      [...] shall be a constexpr constructor;
6437   //   -- every non-static data member and base class sub-object shall be
6438   //      initialized
6439   //   -- for each non-static data member of X that is of class type (or array
6440   //      thereof), the assignment operator selected to copy/move that member is
6441   //      a constexpr function
6442   for (const auto *F : ClassDecl->fields()) {
6443     if (F->isInvalidDecl())
6444       continue;
6445     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6446       continue;
6447     QualType BaseType = S.Context.getBaseElementType(F->getType());
6448     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6449       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6450       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6451                                     BaseType.getCVRQualifiers(),
6452                                     ConstArg && !F->isMutable()))
6453         return false;
6454     } else if (CSM == Sema::CXXDefaultConstructor) {
6455       return false;
6456     }
6457   }
6458 
6459   // All OK, it's constexpr!
6460   return true;
6461 }
6462 
6463 static Sema::ImplicitExceptionSpecification
6464 ComputeDefaultedSpecialMemberExceptionSpec(
6465     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6466     Sema::InheritedConstructorInfo *ICI);
6467 
6468 static Sema::ImplicitExceptionSpecification
6469 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6470   auto CSM = S.getSpecialMember(MD);
6471   if (CSM != Sema::CXXInvalid)
6472     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6473 
6474   auto *CD = cast<CXXConstructorDecl>(MD);
6475   assert(CD->getInheritedConstructor() &&
6476          "only special members have implicit exception specs");
6477   Sema::InheritedConstructorInfo ICI(
6478       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6479   return ComputeDefaultedSpecialMemberExceptionSpec(
6480       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6481 }
6482 
6483 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6484                                                             CXXMethodDecl *MD) {
6485   FunctionProtoType::ExtProtoInfo EPI;
6486 
6487   // Build an exception specification pointing back at this member.
6488   EPI.ExceptionSpec.Type = EST_Unevaluated;
6489   EPI.ExceptionSpec.SourceDecl = MD;
6490 
6491   // Set the calling convention to the default for C++ instance methods.
6492   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6493       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6494                                             /*IsCXXMethod=*/true));
6495   return EPI;
6496 }
6497 
6498 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6499   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6500   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6501     return;
6502 
6503   // Evaluate the exception specification.
6504   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6505   auto ESI = IES.getExceptionSpec();
6506 
6507   // Update the type of the special member to use it.
6508   UpdateExceptionSpec(MD, ESI);
6509 
6510   // A user-provided destructor can be defined outside the class. When that
6511   // happens, be sure to update the exception specification on both
6512   // declarations.
6513   const FunctionProtoType *CanonicalFPT =
6514     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6515   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6516     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6517 }
6518 
6519 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6520   CXXRecordDecl *RD = MD->getParent();
6521   CXXSpecialMember CSM = getSpecialMember(MD);
6522 
6523   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6524          "not an explicitly-defaulted special member");
6525 
6526   // Whether this was the first-declared instance of the constructor.
6527   // This affects whether we implicitly add an exception spec and constexpr.
6528   bool First = MD == MD->getCanonicalDecl();
6529 
6530   bool HadError = false;
6531 
6532   // C++11 [dcl.fct.def.default]p1:
6533   //   A function that is explicitly defaulted shall
6534   //     -- be a special member function (checked elsewhere),
6535   //     -- have the same type (except for ref-qualifiers, and except that a
6536   //        copy operation can take a non-const reference) as an implicit
6537   //        declaration, and
6538   //     -- not have default arguments.
6539   // C++2a changes the second bullet to instead delete the function if it's
6540   // defaulted on its first declaration, unless it's "an assignment operator,
6541   // and its return type differs or its parameter type is not a reference".
6542   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6543   bool ShouldDeleteForTypeMismatch = false;
6544   unsigned ExpectedParams = 1;
6545   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6546     ExpectedParams = 0;
6547   if (MD->getNumParams() != ExpectedParams) {
6548     // This checks for default arguments: a copy or move constructor with a
6549     // default argument is classified as a default constructor, and assignment
6550     // operations and destructors can't have default arguments.
6551     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6552       << CSM << MD->getSourceRange();
6553     HadError = true;
6554   } else if (MD->isVariadic()) {
6555     if (DeleteOnTypeMismatch)
6556       ShouldDeleteForTypeMismatch = true;
6557     else {
6558       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6559         << CSM << MD->getSourceRange();
6560       HadError = true;
6561     }
6562   }
6563 
6564   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6565 
6566   bool CanHaveConstParam = false;
6567   if (CSM == CXXCopyConstructor)
6568     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6569   else if (CSM == CXXCopyAssignment)
6570     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6571 
6572   QualType ReturnType = Context.VoidTy;
6573   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6574     // Check for return type matching.
6575     ReturnType = Type->getReturnType();
6576 
6577     QualType DeclType = Context.getTypeDeclType(RD);
6578     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
6579     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
6580 
6581     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6582       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6583         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6584       HadError = true;
6585     }
6586 
6587     // A defaulted special member cannot have cv-qualifiers.
6588     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
6589       if (DeleteOnTypeMismatch)
6590         ShouldDeleteForTypeMismatch = true;
6591       else {
6592         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6593           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6594         HadError = true;
6595       }
6596     }
6597   }
6598 
6599   // Check for parameter type matching.
6600   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6601   bool HasConstParam = false;
6602   if (ExpectedParams && ArgType->isReferenceType()) {
6603     // Argument must be reference to possibly-const T.
6604     QualType ReferentType = ArgType->getPointeeType();
6605     HasConstParam = ReferentType.isConstQualified();
6606 
6607     if (ReferentType.isVolatileQualified()) {
6608       if (DeleteOnTypeMismatch)
6609         ShouldDeleteForTypeMismatch = true;
6610       else {
6611         Diag(MD->getLocation(),
6612              diag::err_defaulted_special_member_volatile_param) << CSM;
6613         HadError = true;
6614       }
6615     }
6616 
6617     if (HasConstParam && !CanHaveConstParam) {
6618       if (DeleteOnTypeMismatch)
6619         ShouldDeleteForTypeMismatch = true;
6620       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6621         Diag(MD->getLocation(),
6622              diag::err_defaulted_special_member_copy_const_param)
6623           << (CSM == CXXCopyAssignment);
6624         // FIXME: Explain why this special member can't be const.
6625         HadError = true;
6626       } else {
6627         Diag(MD->getLocation(),
6628              diag::err_defaulted_special_member_move_const_param)
6629           << (CSM == CXXMoveAssignment);
6630         HadError = true;
6631       }
6632     }
6633   } else if (ExpectedParams) {
6634     // A copy assignment operator can take its argument by value, but a
6635     // defaulted one cannot.
6636     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6637     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6638     HadError = true;
6639   }
6640 
6641   // C++11 [dcl.fct.def.default]p2:
6642   //   An explicitly-defaulted function may be declared constexpr only if it
6643   //   would have been implicitly declared as constexpr,
6644   // Do not apply this rule to members of class templates, since core issue 1358
6645   // makes such functions always instantiate to constexpr functions. For
6646   // functions which cannot be constexpr (for non-constructors in C++11 and for
6647   // destructors in C++1y), this is checked elsewhere.
6648   //
6649   // FIXME: This should not apply if the member is deleted.
6650   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6651                                                      HasConstParam);
6652   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6653                                  : isa<CXXConstructorDecl>(MD)) &&
6654       MD->isConstexpr() && !Constexpr &&
6655       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6656     Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM;
6657     // FIXME: Explain why the special member can't be constexpr.
6658     HadError = true;
6659   }
6660 
6661   if (First) {
6662     // C++2a [dcl.fct.def.default]p3:
6663     //   If a function is explicitly defaulted on its first declaration, it is
6664     //   implicitly considered to be constexpr if the implicit declaration
6665     //   would be.
6666     MD->setConstexpr(Constexpr);
6667 
6668     if (!Type->hasExceptionSpec()) {
6669       // C++2a [except.spec]p3:
6670       //   If a declaration of a function does not have a noexcept-specifier
6671       //   [and] is defaulted on its first declaration, [...] the exception
6672       //   specification is as specified below
6673       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6674       EPI.ExceptionSpec.Type = EST_Unevaluated;
6675       EPI.ExceptionSpec.SourceDecl = MD;
6676       MD->setType(Context.getFunctionType(ReturnType,
6677                                           llvm::makeArrayRef(&ArgType,
6678                                                              ExpectedParams),
6679                                           EPI));
6680     }
6681   }
6682 
6683   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6684     if (First) {
6685       SetDeclDeleted(MD, MD->getLocation());
6686       if (!inTemplateInstantiation() && !HadError) {
6687         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6688         if (ShouldDeleteForTypeMismatch) {
6689           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6690         } else {
6691           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6692         }
6693       }
6694       if (ShouldDeleteForTypeMismatch && !HadError) {
6695         Diag(MD->getLocation(),
6696              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6697       }
6698     } else {
6699       // C++11 [dcl.fct.def.default]p4:
6700       //   [For a] user-provided explicitly-defaulted function [...] if such a
6701       //   function is implicitly defined as deleted, the program is ill-formed.
6702       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6703       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
6704       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6705       HadError = true;
6706     }
6707   }
6708 
6709   if (HadError)
6710     MD->setInvalidDecl();
6711 }
6712 
6713 void Sema::CheckDelayedMemberExceptionSpecs() {
6714   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6715   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6716 
6717   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6718   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6719 
6720   // Perform any deferred checking of exception specifications for virtual
6721   // destructors.
6722   for (auto &Check : Overriding)
6723     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6724 
6725   // Perform any deferred checking of exception specifications for befriended
6726   // special members.
6727   for (auto &Check : Equivalent)
6728     CheckEquivalentExceptionSpec(Check.second, Check.first);
6729 }
6730 
6731 namespace {
6732 /// CRTP base class for visiting operations performed by a special member
6733 /// function (or inherited constructor).
6734 template<typename Derived>
6735 struct SpecialMemberVisitor {
6736   Sema &S;
6737   CXXMethodDecl *MD;
6738   Sema::CXXSpecialMember CSM;
6739   Sema::InheritedConstructorInfo *ICI;
6740 
6741   // Properties of the special member, computed for convenience.
6742   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6743 
6744   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6745                        Sema::InheritedConstructorInfo *ICI)
6746       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6747     switch (CSM) {
6748     case Sema::CXXDefaultConstructor:
6749     case Sema::CXXCopyConstructor:
6750     case Sema::CXXMoveConstructor:
6751       IsConstructor = true;
6752       break;
6753     case Sema::CXXCopyAssignment:
6754     case Sema::CXXMoveAssignment:
6755       IsAssignment = true;
6756       break;
6757     case Sema::CXXDestructor:
6758       break;
6759     case Sema::CXXInvalid:
6760       llvm_unreachable("invalid special member kind");
6761     }
6762 
6763     if (MD->getNumParams()) {
6764       if (const ReferenceType *RT =
6765               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6766         ConstArg = RT->getPointeeType().isConstQualified();
6767     }
6768   }
6769 
6770   Derived &getDerived() { return static_cast<Derived&>(*this); }
6771 
6772   /// Is this a "move" special member?
6773   bool isMove() const {
6774     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6775   }
6776 
6777   /// Look up the corresponding special member in the given class.
6778   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6779                                              unsigned Quals, bool IsMutable) {
6780     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6781                                        ConstArg && !IsMutable);
6782   }
6783 
6784   /// Look up the constructor for the specified base class to see if it's
6785   /// overridden due to this being an inherited constructor.
6786   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6787     if (!ICI)
6788       return {};
6789     assert(CSM == Sema::CXXDefaultConstructor);
6790     auto *BaseCtor =
6791       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6792     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6793       return MD;
6794     return {};
6795   }
6796 
6797   /// A base or member subobject.
6798   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6799 
6800   /// Get the location to use for a subobject in diagnostics.
6801   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6802     // FIXME: For an indirect virtual base, the direct base leading to
6803     // the indirect virtual base would be a more useful choice.
6804     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6805       return B->getBaseTypeLoc();
6806     else
6807       return Subobj.get<FieldDecl*>()->getLocation();
6808   }
6809 
6810   enum BasesToVisit {
6811     /// Visit all non-virtual (direct) bases.
6812     VisitNonVirtualBases,
6813     /// Visit all direct bases, virtual or not.
6814     VisitDirectBases,
6815     /// Visit all non-virtual bases, and all virtual bases if the class
6816     /// is not abstract.
6817     VisitPotentiallyConstructedBases,
6818     /// Visit all direct or virtual bases.
6819     VisitAllBases
6820   };
6821 
6822   // Visit the bases and members of the class.
6823   bool visit(BasesToVisit Bases) {
6824     CXXRecordDecl *RD = MD->getParent();
6825 
6826     if (Bases == VisitPotentiallyConstructedBases)
6827       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6828 
6829     for (auto &B : RD->bases())
6830       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6831           getDerived().visitBase(&B))
6832         return true;
6833 
6834     if (Bases == VisitAllBases)
6835       for (auto &B : RD->vbases())
6836         if (getDerived().visitBase(&B))
6837           return true;
6838 
6839     for (auto *F : RD->fields())
6840       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6841           getDerived().visitField(F))
6842         return true;
6843 
6844     return false;
6845   }
6846 };
6847 }
6848 
6849 namespace {
6850 struct SpecialMemberDeletionInfo
6851     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6852   bool Diagnose;
6853 
6854   SourceLocation Loc;
6855 
6856   bool AllFieldsAreConst;
6857 
6858   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6859                             Sema::CXXSpecialMember CSM,
6860                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6861       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6862         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6863 
6864   bool inUnion() const { return MD->getParent()->isUnion(); }
6865 
6866   Sema::CXXSpecialMember getEffectiveCSM() {
6867     return ICI ? Sema::CXXInvalid : CSM;
6868   }
6869 
6870   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
6871 
6872   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6873   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6874 
6875   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6876   bool shouldDeleteForField(FieldDecl *FD);
6877   bool shouldDeleteForAllConstMembers();
6878 
6879   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6880                                      unsigned Quals);
6881   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6882                                     Sema::SpecialMemberOverloadResult SMOR,
6883                                     bool IsDtorCallInCtor);
6884 
6885   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6886 };
6887 }
6888 
6889 /// Is the given special member inaccessible when used on the given
6890 /// sub-object.
6891 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6892                                              CXXMethodDecl *target) {
6893   /// If we're operating on a base class, the object type is the
6894   /// type of this special member.
6895   QualType objectTy;
6896   AccessSpecifier access = target->getAccess();
6897   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6898     objectTy = S.Context.getTypeDeclType(MD->getParent());
6899     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6900 
6901   // If we're operating on a field, the object type is the type of the field.
6902   } else {
6903     objectTy = S.Context.getTypeDeclType(target->getParent());
6904   }
6905 
6906   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6907 }
6908 
6909 /// Check whether we should delete a special member due to the implicit
6910 /// definition containing a call to a special member of a subobject.
6911 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6912     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6913     bool IsDtorCallInCtor) {
6914   CXXMethodDecl *Decl = SMOR.getMethod();
6915   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6916 
6917   int DiagKind = -1;
6918 
6919   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6920     DiagKind = !Decl ? 0 : 1;
6921   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6922     DiagKind = 2;
6923   else if (!isAccessible(Subobj, Decl))
6924     DiagKind = 3;
6925   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6926            !Decl->isTrivial()) {
6927     // A member of a union must have a trivial corresponding special member.
6928     // As a weird special case, a destructor call from a union's constructor
6929     // must be accessible and non-deleted, but need not be trivial. Such a
6930     // destructor is never actually called, but is semantically checked as
6931     // if it were.
6932     DiagKind = 4;
6933   }
6934 
6935   if (DiagKind == -1)
6936     return false;
6937 
6938   if (Diagnose) {
6939     if (Field) {
6940       S.Diag(Field->getLocation(),
6941              diag::note_deleted_special_member_class_subobject)
6942         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6943         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
6944     } else {
6945       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6946       S.Diag(Base->getBeginLoc(),
6947              diag::note_deleted_special_member_class_subobject)
6948           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6949           << Base->getType() << DiagKind << IsDtorCallInCtor
6950           << /*IsObjCPtr*/false;
6951     }
6952 
6953     if (DiagKind == 1)
6954       S.NoteDeletedFunction(Decl);
6955     // FIXME: Explain inaccessibility if DiagKind == 3.
6956   }
6957 
6958   return true;
6959 }
6960 
6961 /// Check whether we should delete a special member function due to having a
6962 /// direct or virtual base class or non-static data member of class type M.
6963 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6964     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6965   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6966   bool IsMutable = Field && Field->isMutable();
6967 
6968   // C++11 [class.ctor]p5:
6969   // -- any direct or virtual base class, or non-static data member with no
6970   //    brace-or-equal-initializer, has class type M (or array thereof) and
6971   //    either M has no default constructor or overload resolution as applied
6972   //    to M's default constructor results in an ambiguity or in a function
6973   //    that is deleted or inaccessible
6974   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6975   // -- a direct or virtual base class B that cannot be copied/moved because
6976   //    overload resolution, as applied to B's corresponding special member,
6977   //    results in an ambiguity or a function that is deleted or inaccessible
6978   //    from the defaulted special member
6979   // C++11 [class.dtor]p5:
6980   // -- any direct or virtual base class [...] has a type with a destructor
6981   //    that is deleted or inaccessible
6982   if (!(CSM == Sema::CXXDefaultConstructor &&
6983         Field && Field->hasInClassInitializer()) &&
6984       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6985                                    false))
6986     return true;
6987 
6988   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6989   // -- any direct or virtual base class or non-static data member has a
6990   //    type with a destructor that is deleted or inaccessible
6991   if (IsConstructor) {
6992     Sema::SpecialMemberOverloadResult SMOR =
6993         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6994                               false, false, false, false, false);
6995     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6996       return true;
6997   }
6998 
6999   return false;
7000 }
7001 
7002 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
7003     FieldDecl *FD, QualType FieldType) {
7004   // The defaulted special functions are defined as deleted if this is a variant
7005   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
7006   // type under ARC.
7007   if (!FieldType.hasNonTrivialObjCLifetime())
7008     return false;
7009 
7010   // Don't make the defaulted default constructor defined as deleted if the
7011   // member has an in-class initializer.
7012   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
7013     return false;
7014 
7015   if (Diagnose) {
7016     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
7017     S.Diag(FD->getLocation(),
7018            diag::note_deleted_special_member_class_subobject)
7019         << getEffectiveCSM() << ParentClass << /*IsField*/true
7020         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
7021   }
7022 
7023   return true;
7024 }
7025 
7026 /// Check whether we should delete a special member function due to the class
7027 /// having a particular direct or virtual base class.
7028 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
7029   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
7030   // If program is correct, BaseClass cannot be null, but if it is, the error
7031   // must be reported elsewhere.
7032   if (!BaseClass)
7033     return false;
7034   // If we have an inheriting constructor, check whether we're calling an
7035   // inherited constructor instead of a default constructor.
7036   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
7037   if (auto *BaseCtor = SMOR.getMethod()) {
7038     // Note that we do not check access along this path; other than that,
7039     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
7040     // FIXME: Check that the base has a usable destructor! Sink this into
7041     // shouldDeleteForClassSubobject.
7042     if (BaseCtor->isDeleted() && Diagnose) {
7043       S.Diag(Base->getBeginLoc(),
7044              diag::note_deleted_special_member_class_subobject)
7045           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7046           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
7047           << /*IsObjCPtr*/false;
7048       S.NoteDeletedFunction(BaseCtor);
7049     }
7050     return BaseCtor->isDeleted();
7051   }
7052   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7053 }
7054 
7055 /// Check whether we should delete a special member function due to the class
7056 /// having a particular non-static data member.
7057 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7058   QualType FieldType = S.Context.getBaseElementType(FD->getType());
7059   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7060 
7061   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
7062     return true;
7063 
7064   if (CSM == Sema::CXXDefaultConstructor) {
7065     // For a default constructor, all references must be initialized in-class
7066     // and, if a union, it must have a non-const member.
7067     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7068       if (Diagnose)
7069         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7070           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7071       return true;
7072     }
7073     // C++11 [class.ctor]p5: any non-variant non-static data member of
7074     // const-qualified type (or array thereof) with no
7075     // brace-or-equal-initializer does not have a user-provided default
7076     // constructor.
7077     if (!inUnion() && FieldType.isConstQualified() &&
7078         !FD->hasInClassInitializer() &&
7079         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7080       if (Diagnose)
7081         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7082           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7083       return true;
7084     }
7085 
7086     if (inUnion() && !FieldType.isConstQualified())
7087       AllFieldsAreConst = false;
7088   } else if (CSM == Sema::CXXCopyConstructor) {
7089     // For a copy constructor, data members must not be of rvalue reference
7090     // type.
7091     if (FieldType->isRValueReferenceType()) {
7092       if (Diagnose)
7093         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7094           << MD->getParent() << FD << FieldType;
7095       return true;
7096     }
7097   } else if (IsAssignment) {
7098     // For an assignment operator, data members must not be of reference type.
7099     if (FieldType->isReferenceType()) {
7100       if (Diagnose)
7101         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7102           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7103       return true;
7104     }
7105     if (!FieldRecord && FieldType.isConstQualified()) {
7106       // C++11 [class.copy]p23:
7107       // -- a non-static data member of const non-class type (or array thereof)
7108       if (Diagnose)
7109         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7110           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7111       return true;
7112     }
7113   }
7114 
7115   if (FieldRecord) {
7116     // Some additional restrictions exist on the variant members.
7117     if (!inUnion() && FieldRecord->isUnion() &&
7118         FieldRecord->isAnonymousStructOrUnion()) {
7119       bool AllVariantFieldsAreConst = true;
7120 
7121       // FIXME: Handle anonymous unions declared within anonymous unions.
7122       for (auto *UI : FieldRecord->fields()) {
7123         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7124 
7125         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
7126           return true;
7127 
7128         if (!UnionFieldType.isConstQualified())
7129           AllVariantFieldsAreConst = false;
7130 
7131         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7132         if (UnionFieldRecord &&
7133             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7134                                           UnionFieldType.getCVRQualifiers()))
7135           return true;
7136       }
7137 
7138       // At least one member in each anonymous union must be non-const
7139       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7140           !FieldRecord->field_empty()) {
7141         if (Diagnose)
7142           S.Diag(FieldRecord->getLocation(),
7143                  diag::note_deleted_default_ctor_all_const)
7144             << !!ICI << MD->getParent() << /*anonymous union*/1;
7145         return true;
7146       }
7147 
7148       // Don't check the implicit member of the anonymous union type.
7149       // This is technically non-conformant, but sanity demands it.
7150       return false;
7151     }
7152 
7153     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7154                                       FieldType.getCVRQualifiers()))
7155       return true;
7156   }
7157 
7158   return false;
7159 }
7160 
7161 /// C++11 [class.ctor] p5:
7162 ///   A defaulted default constructor for a class X is defined as deleted if
7163 /// X is a union and all of its variant members are of const-qualified type.
7164 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7165   // This is a silly definition, because it gives an empty union a deleted
7166   // default constructor. Don't do that.
7167   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7168     bool AnyFields = false;
7169     for (auto *F : MD->getParent()->fields())
7170       if ((AnyFields = !F->isUnnamedBitfield()))
7171         break;
7172     if (!AnyFields)
7173       return false;
7174     if (Diagnose)
7175       S.Diag(MD->getParent()->getLocation(),
7176              diag::note_deleted_default_ctor_all_const)
7177         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7178     return true;
7179   }
7180   return false;
7181 }
7182 
7183 /// Determine whether a defaulted special member function should be defined as
7184 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7185 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7186 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7187                                      InheritedConstructorInfo *ICI,
7188                                      bool Diagnose) {
7189   if (MD->isInvalidDecl())
7190     return false;
7191   CXXRecordDecl *RD = MD->getParent();
7192   assert(!RD->isDependentType() && "do deletion after instantiation");
7193   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7194     return false;
7195 
7196   // C++11 [expr.lambda.prim]p19:
7197   //   The closure type associated with a lambda-expression has a
7198   //   deleted (8.4.3) default constructor and a deleted copy
7199   //   assignment operator.
7200   // C++2a adds back these operators if the lambda has no capture-default.
7201   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7202       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7203     if (Diagnose)
7204       Diag(RD->getLocation(), diag::note_lambda_decl);
7205     return true;
7206   }
7207 
7208   // For an anonymous struct or union, the copy and assignment special members
7209   // will never be used, so skip the check. For an anonymous union declared at
7210   // namespace scope, the constructor and destructor are used.
7211   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7212       RD->isAnonymousStructOrUnion())
7213     return false;
7214 
7215   // C++11 [class.copy]p7, p18:
7216   //   If the class definition declares a move constructor or move assignment
7217   //   operator, an implicitly declared copy constructor or copy assignment
7218   //   operator is defined as deleted.
7219   if (MD->isImplicit() &&
7220       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7221     CXXMethodDecl *UserDeclaredMove = nullptr;
7222 
7223     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7224     // deletion of the corresponding copy operation, not both copy operations.
7225     // MSVC 2015 has adopted the standards conforming behavior.
7226     bool DeletesOnlyMatchingCopy =
7227         getLangOpts().MSVCCompat &&
7228         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7229 
7230     if (RD->hasUserDeclaredMoveConstructor() &&
7231         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7232       if (!Diagnose) return true;
7233 
7234       // Find any user-declared move constructor.
7235       for (auto *I : RD->ctors()) {
7236         if (I->isMoveConstructor()) {
7237           UserDeclaredMove = I;
7238           break;
7239         }
7240       }
7241       assert(UserDeclaredMove);
7242     } else if (RD->hasUserDeclaredMoveAssignment() &&
7243                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7244       if (!Diagnose) return true;
7245 
7246       // Find any user-declared move assignment operator.
7247       for (auto *I : RD->methods()) {
7248         if (I->isMoveAssignmentOperator()) {
7249           UserDeclaredMove = I;
7250           break;
7251         }
7252       }
7253       assert(UserDeclaredMove);
7254     }
7255 
7256     if (UserDeclaredMove) {
7257       Diag(UserDeclaredMove->getLocation(),
7258            diag::note_deleted_copy_user_declared_move)
7259         << (CSM == CXXCopyAssignment) << RD
7260         << UserDeclaredMove->isMoveAssignmentOperator();
7261       return true;
7262     }
7263   }
7264 
7265   // Do access control from the special member function
7266   ContextRAII MethodContext(*this, MD);
7267 
7268   // C++11 [class.dtor]p5:
7269   // -- for a virtual destructor, lookup of the non-array deallocation function
7270   //    results in an ambiguity or in a function that is deleted or inaccessible
7271   if (CSM == CXXDestructor && MD->isVirtual()) {
7272     FunctionDecl *OperatorDelete = nullptr;
7273     DeclarationName Name =
7274       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7275     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7276                                  OperatorDelete, /*Diagnose*/false)) {
7277       if (Diagnose)
7278         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7279       return true;
7280     }
7281   }
7282 
7283   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7284 
7285   // Per DR1611, do not consider virtual bases of constructors of abstract
7286   // classes, since we are not going to construct them.
7287   // Per DR1658, do not consider virtual bases of destructors of abstract
7288   // classes either.
7289   // Per DR2180, for assignment operators we only assign (and thus only
7290   // consider) direct bases.
7291   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7292                                  : SMI.VisitPotentiallyConstructedBases))
7293     return true;
7294 
7295   if (SMI.shouldDeleteForAllConstMembers())
7296     return true;
7297 
7298   if (getLangOpts().CUDA) {
7299     // We should delete the special member in CUDA mode if target inference
7300     // failed.
7301     // For inherited constructors (non-null ICI), CSM may be passed so that MD
7302     // is treated as certain special member, which may not reflect what special
7303     // member MD really is. However inferCUDATargetForImplicitSpecialMember
7304     // expects CSM to match MD, therefore recalculate CSM.
7305     assert(ICI || CSM == getSpecialMember(MD));
7306     auto RealCSM = CSM;
7307     if (ICI)
7308       RealCSM = getSpecialMember(MD);
7309 
7310     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7311                                                    SMI.ConstArg, Diagnose);
7312   }
7313 
7314   return false;
7315 }
7316 
7317 /// Perform lookup for a special member of the specified kind, and determine
7318 /// whether it is trivial. If the triviality can be determined without the
7319 /// lookup, skip it. This is intended for use when determining whether a
7320 /// special member of a containing object is trivial, and thus does not ever
7321 /// perform overload resolution for default constructors.
7322 ///
7323 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7324 /// member that was most likely to be intended to be trivial, if any.
7325 ///
7326 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7327 /// determine whether the special member is trivial.
7328 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7329                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7330                                      bool ConstRHS,
7331                                      Sema::TrivialABIHandling TAH,
7332                                      CXXMethodDecl **Selected) {
7333   if (Selected)
7334     *Selected = nullptr;
7335 
7336   switch (CSM) {
7337   case Sema::CXXInvalid:
7338     llvm_unreachable("not a special member");
7339 
7340   case Sema::CXXDefaultConstructor:
7341     // C++11 [class.ctor]p5:
7342     //   A default constructor is trivial if:
7343     //    - all the [direct subobjects] have trivial default constructors
7344     //
7345     // Note, no overload resolution is performed in this case.
7346     if (RD->hasTrivialDefaultConstructor())
7347       return true;
7348 
7349     if (Selected) {
7350       // If there's a default constructor which could have been trivial, dig it
7351       // out. Otherwise, if there's any user-provided default constructor, point
7352       // to that as an example of why there's not a trivial one.
7353       CXXConstructorDecl *DefCtor = nullptr;
7354       if (RD->needsImplicitDefaultConstructor())
7355         S.DeclareImplicitDefaultConstructor(RD);
7356       for (auto *CI : RD->ctors()) {
7357         if (!CI->isDefaultConstructor())
7358           continue;
7359         DefCtor = CI;
7360         if (!DefCtor->isUserProvided())
7361           break;
7362       }
7363 
7364       *Selected = DefCtor;
7365     }
7366 
7367     return false;
7368 
7369   case Sema::CXXDestructor:
7370     // C++11 [class.dtor]p5:
7371     //   A destructor is trivial if:
7372     //    - all the direct [subobjects] have trivial destructors
7373     if (RD->hasTrivialDestructor() ||
7374         (TAH == Sema::TAH_ConsiderTrivialABI &&
7375          RD->hasTrivialDestructorForCall()))
7376       return true;
7377 
7378     if (Selected) {
7379       if (RD->needsImplicitDestructor())
7380         S.DeclareImplicitDestructor(RD);
7381       *Selected = RD->getDestructor();
7382     }
7383 
7384     return false;
7385 
7386   case Sema::CXXCopyConstructor:
7387     // C++11 [class.copy]p12:
7388     //   A copy constructor is trivial if:
7389     //    - the constructor selected to copy each direct [subobject] is trivial
7390     if (RD->hasTrivialCopyConstructor() ||
7391         (TAH == Sema::TAH_ConsiderTrivialABI &&
7392          RD->hasTrivialCopyConstructorForCall())) {
7393       if (Quals == Qualifiers::Const)
7394         // We must either select the trivial copy constructor or reach an
7395         // ambiguity; no need to actually perform overload resolution.
7396         return true;
7397     } else if (!Selected) {
7398       return false;
7399     }
7400     // In C++98, we are not supposed to perform overload resolution here, but we
7401     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7402     // cases like B as having a non-trivial copy constructor:
7403     //   struct A { template<typename T> A(T&); };
7404     //   struct B { mutable A a; };
7405     goto NeedOverloadResolution;
7406 
7407   case Sema::CXXCopyAssignment:
7408     // C++11 [class.copy]p25:
7409     //   A copy assignment operator is trivial if:
7410     //    - the assignment operator selected to copy each direct [subobject] is
7411     //      trivial
7412     if (RD->hasTrivialCopyAssignment()) {
7413       if (Quals == Qualifiers::Const)
7414         return true;
7415     } else if (!Selected) {
7416       return false;
7417     }
7418     // In C++98, we are not supposed to perform overload resolution here, but we
7419     // treat that as a language defect.
7420     goto NeedOverloadResolution;
7421 
7422   case Sema::CXXMoveConstructor:
7423   case Sema::CXXMoveAssignment:
7424   NeedOverloadResolution:
7425     Sema::SpecialMemberOverloadResult SMOR =
7426         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7427 
7428     // The standard doesn't describe how to behave if the lookup is ambiguous.
7429     // We treat it as not making the member non-trivial, just like the standard
7430     // mandates for the default constructor. This should rarely matter, because
7431     // the member will also be deleted.
7432     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7433       return true;
7434 
7435     if (!SMOR.getMethod()) {
7436       assert(SMOR.getKind() ==
7437              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7438       return false;
7439     }
7440 
7441     // We deliberately don't check if we found a deleted special member. We're
7442     // not supposed to!
7443     if (Selected)
7444       *Selected = SMOR.getMethod();
7445 
7446     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7447         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7448       return SMOR.getMethod()->isTrivialForCall();
7449     return SMOR.getMethod()->isTrivial();
7450   }
7451 
7452   llvm_unreachable("unknown special method kind");
7453 }
7454 
7455 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7456   for (auto *CI : RD->ctors())
7457     if (!CI->isImplicit())
7458       return CI;
7459 
7460   // Look for constructor templates.
7461   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7462   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7463     if (CXXConstructorDecl *CD =
7464           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7465       return CD;
7466   }
7467 
7468   return nullptr;
7469 }
7470 
7471 /// The kind of subobject we are checking for triviality. The values of this
7472 /// enumeration are used in diagnostics.
7473 enum TrivialSubobjectKind {
7474   /// The subobject is a base class.
7475   TSK_BaseClass,
7476   /// The subobject is a non-static data member.
7477   TSK_Field,
7478   /// The object is actually the complete object.
7479   TSK_CompleteObject
7480 };
7481 
7482 /// Check whether the special member selected for a given type would be trivial.
7483 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7484                                       QualType SubType, bool ConstRHS,
7485                                       Sema::CXXSpecialMember CSM,
7486                                       TrivialSubobjectKind Kind,
7487                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7488   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7489   if (!SubRD)
7490     return true;
7491 
7492   CXXMethodDecl *Selected;
7493   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7494                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7495     return true;
7496 
7497   if (Diagnose) {
7498     if (ConstRHS)
7499       SubType.addConst();
7500 
7501     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7502       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7503         << Kind << SubType.getUnqualifiedType();
7504       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7505         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7506     } else if (!Selected)
7507       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7508         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7509     else if (Selected->isUserProvided()) {
7510       if (Kind == TSK_CompleteObject)
7511         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7512           << Kind << SubType.getUnqualifiedType() << CSM;
7513       else {
7514         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7515           << Kind << SubType.getUnqualifiedType() << CSM;
7516         S.Diag(Selected->getLocation(), diag::note_declared_at);
7517       }
7518     } else {
7519       if (Kind != TSK_CompleteObject)
7520         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7521           << Kind << SubType.getUnqualifiedType() << CSM;
7522 
7523       // Explain why the defaulted or deleted special member isn't trivial.
7524       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7525                                Diagnose);
7526     }
7527   }
7528 
7529   return false;
7530 }
7531 
7532 /// Check whether the members of a class type allow a special member to be
7533 /// trivial.
7534 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7535                                      Sema::CXXSpecialMember CSM,
7536                                      bool ConstArg,
7537                                      Sema::TrivialABIHandling TAH,
7538                                      bool Diagnose) {
7539   for (const auto *FI : RD->fields()) {
7540     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7541       continue;
7542 
7543     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7544 
7545     // Pretend anonymous struct or union members are members of this class.
7546     if (FI->isAnonymousStructOrUnion()) {
7547       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7548                                     CSM, ConstArg, TAH, Diagnose))
7549         return false;
7550       continue;
7551     }
7552 
7553     // C++11 [class.ctor]p5:
7554     //   A default constructor is trivial if [...]
7555     //    -- no non-static data member of its class has a
7556     //       brace-or-equal-initializer
7557     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7558       if (Diagnose)
7559         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7560       return false;
7561     }
7562 
7563     // Objective C ARC 4.3.5:
7564     //   [...] nontrivally ownership-qualified types are [...] not trivially
7565     //   default constructible, copy constructible, move constructible, copy
7566     //   assignable, move assignable, or destructible [...]
7567     if (FieldType.hasNonTrivialObjCLifetime()) {
7568       if (Diagnose)
7569         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7570           << RD << FieldType.getObjCLifetime();
7571       return false;
7572     }
7573 
7574     bool ConstRHS = ConstArg && !FI->isMutable();
7575     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7576                                    CSM, TSK_Field, TAH, Diagnose))
7577       return false;
7578   }
7579 
7580   return true;
7581 }
7582 
7583 /// Diagnose why the specified class does not have a trivial special member of
7584 /// the given kind.
7585 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7586   QualType Ty = Context.getRecordType(RD);
7587 
7588   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7589   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7590                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7591                             /*Diagnose*/true);
7592 }
7593 
7594 /// Determine whether a defaulted or deleted special member function is trivial,
7595 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7596 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7597 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7598                                   TrivialABIHandling TAH, bool Diagnose) {
7599   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7600 
7601   CXXRecordDecl *RD = MD->getParent();
7602 
7603   bool ConstArg = false;
7604 
7605   // C++11 [class.copy]p12, p25: [DR1593]
7606   //   A [special member] is trivial if [...] its parameter-type-list is
7607   //   equivalent to the parameter-type-list of an implicit declaration [...]
7608   switch (CSM) {
7609   case CXXDefaultConstructor:
7610   case CXXDestructor:
7611     // Trivial default constructors and destructors cannot have parameters.
7612     break;
7613 
7614   case CXXCopyConstructor:
7615   case CXXCopyAssignment: {
7616     // Trivial copy operations always have const, non-volatile parameter types.
7617     ConstArg = true;
7618     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7619     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7620     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7621       if (Diagnose)
7622         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7623           << Param0->getSourceRange() << Param0->getType()
7624           << Context.getLValueReferenceType(
7625                Context.getRecordType(RD).withConst());
7626       return false;
7627     }
7628     break;
7629   }
7630 
7631   case CXXMoveConstructor:
7632   case CXXMoveAssignment: {
7633     // Trivial move operations always have non-cv-qualified parameters.
7634     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7635     const RValueReferenceType *RT =
7636       Param0->getType()->getAs<RValueReferenceType>();
7637     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7638       if (Diagnose)
7639         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7640           << Param0->getSourceRange() << Param0->getType()
7641           << Context.getRValueReferenceType(Context.getRecordType(RD));
7642       return false;
7643     }
7644     break;
7645   }
7646 
7647   case CXXInvalid:
7648     llvm_unreachable("not a special member");
7649   }
7650 
7651   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7652     if (Diagnose)
7653       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7654            diag::note_nontrivial_default_arg)
7655         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7656     return false;
7657   }
7658   if (MD->isVariadic()) {
7659     if (Diagnose)
7660       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7661     return false;
7662   }
7663 
7664   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7665   //   A copy/move [constructor or assignment operator] is trivial if
7666   //    -- the [member] selected to copy/move each direct base class subobject
7667   //       is trivial
7668   //
7669   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7670   //   A [default constructor or destructor] is trivial if
7671   //    -- all the direct base classes have trivial [default constructors or
7672   //       destructors]
7673   for (const auto &BI : RD->bases())
7674     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7675                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7676       return false;
7677 
7678   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7679   //   A copy/move [constructor or assignment operator] for a class X is
7680   //   trivial if
7681   //    -- for each non-static data member of X that is of class type (or array
7682   //       thereof), the constructor selected to copy/move that member is
7683   //       trivial
7684   //
7685   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7686   //   A [default constructor or destructor] is trivial if
7687   //    -- for all of the non-static data members of its class that are of class
7688   //       type (or array thereof), each such class has a trivial [default
7689   //       constructor or destructor]
7690   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7691     return false;
7692 
7693   // C++11 [class.dtor]p5:
7694   //   A destructor is trivial if [...]
7695   //    -- the destructor is not virtual
7696   if (CSM == CXXDestructor && MD->isVirtual()) {
7697     if (Diagnose)
7698       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7699     return false;
7700   }
7701 
7702   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7703   //   A [special member] for class X is trivial if [...]
7704   //    -- class X has no virtual functions and no virtual base classes
7705   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7706     if (!Diagnose)
7707       return false;
7708 
7709     if (RD->getNumVBases()) {
7710       // Check for virtual bases. We already know that the corresponding
7711       // member in all bases is trivial, so vbases must all be direct.
7712       CXXBaseSpecifier &BS = *RD->vbases_begin();
7713       assert(BS.isVirtual());
7714       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7715       return false;
7716     }
7717 
7718     // Must have a virtual method.
7719     for (const auto *MI : RD->methods()) {
7720       if (MI->isVirtual()) {
7721         SourceLocation MLoc = MI->getBeginLoc();
7722         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7723         return false;
7724       }
7725     }
7726 
7727     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7728   }
7729 
7730   // Looks like it's trivial!
7731   return true;
7732 }
7733 
7734 namespace {
7735 struct FindHiddenVirtualMethod {
7736   Sema *S;
7737   CXXMethodDecl *Method;
7738   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7739   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7740 
7741 private:
7742   /// Check whether any most overridden method from MD in Methods
7743   static bool CheckMostOverridenMethods(
7744       const CXXMethodDecl *MD,
7745       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7746     if (MD->size_overridden_methods() == 0)
7747       return Methods.count(MD->getCanonicalDecl());
7748     for (const CXXMethodDecl *O : MD->overridden_methods())
7749       if (CheckMostOverridenMethods(O, Methods))
7750         return true;
7751     return false;
7752   }
7753 
7754 public:
7755   /// Member lookup function that determines whether a given C++
7756   /// method overloads virtual methods in a base class without overriding any,
7757   /// to be used with CXXRecordDecl::lookupInBases().
7758   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7759     RecordDecl *BaseRecord =
7760         Specifier->getType()->getAs<RecordType>()->getDecl();
7761 
7762     DeclarationName Name = Method->getDeclName();
7763     assert(Name.getNameKind() == DeclarationName::Identifier);
7764 
7765     bool foundSameNameMethod = false;
7766     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7767     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7768          Path.Decls = Path.Decls.slice(1)) {
7769       NamedDecl *D = Path.Decls.front();
7770       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7771         MD = MD->getCanonicalDecl();
7772         foundSameNameMethod = true;
7773         // Interested only in hidden virtual methods.
7774         if (!MD->isVirtual())
7775           continue;
7776         // If the method we are checking overrides a method from its base
7777         // don't warn about the other overloaded methods. Clang deviates from
7778         // GCC by only diagnosing overloads of inherited virtual functions that
7779         // do not override any other virtual functions in the base. GCC's
7780         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7781         // function from a base class. These cases may be better served by a
7782         // warning (not specific to virtual functions) on call sites when the
7783         // call would select a different function from the base class, were it
7784         // visible.
7785         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7786         if (!S->IsOverload(Method, MD, false))
7787           return true;
7788         // Collect the overload only if its hidden.
7789         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7790           overloadedMethods.push_back(MD);
7791       }
7792     }
7793 
7794     if (foundSameNameMethod)
7795       OverloadedMethods.append(overloadedMethods.begin(),
7796                                overloadedMethods.end());
7797     return foundSameNameMethod;
7798   }
7799 };
7800 } // end anonymous namespace
7801 
7802 /// Add the most overriden methods from MD to Methods
7803 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7804                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7805   if (MD->size_overridden_methods() == 0)
7806     Methods.insert(MD->getCanonicalDecl());
7807   else
7808     for (const CXXMethodDecl *O : MD->overridden_methods())
7809       AddMostOverridenMethods(O, Methods);
7810 }
7811 
7812 /// Check if a method overloads virtual methods in a base class without
7813 /// overriding any.
7814 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7815                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7816   if (!MD->getDeclName().isIdentifier())
7817     return;
7818 
7819   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7820                      /*bool RecordPaths=*/false,
7821                      /*bool DetectVirtual=*/false);
7822   FindHiddenVirtualMethod FHVM;
7823   FHVM.Method = MD;
7824   FHVM.S = this;
7825 
7826   // Keep the base methods that were overridden or introduced in the subclass
7827   // by 'using' in a set. A base method not in this set is hidden.
7828   CXXRecordDecl *DC = MD->getParent();
7829   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7830   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7831     NamedDecl *ND = *I;
7832     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7833       ND = shad->getTargetDecl();
7834     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7835       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7836   }
7837 
7838   if (DC->lookupInBases(FHVM, Paths))
7839     OverloadedMethods = FHVM.OverloadedMethods;
7840 }
7841 
7842 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7843                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7844   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7845     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7846     PartialDiagnostic PD = PDiag(
7847          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7848     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7849     Diag(overloadedMD->getLocation(), PD);
7850   }
7851 }
7852 
7853 /// Diagnose methods which overload virtual methods in a base class
7854 /// without overriding any.
7855 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7856   if (MD->isInvalidDecl())
7857     return;
7858 
7859   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7860     return;
7861 
7862   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7863   FindHiddenVirtualMethods(MD, OverloadedMethods);
7864   if (!OverloadedMethods.empty()) {
7865     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7866       << MD << (OverloadedMethods.size() > 1);
7867 
7868     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7869   }
7870 }
7871 
7872 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7873   auto PrintDiagAndRemoveAttr = [&]() {
7874     // No diagnostics if this is a template instantiation.
7875     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7876       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7877            diag::ext_cannot_use_trivial_abi) << &RD;
7878     RD.dropAttr<TrivialABIAttr>();
7879   };
7880 
7881   // Ill-formed if the struct has virtual functions.
7882   if (RD.isPolymorphic()) {
7883     PrintDiagAndRemoveAttr();
7884     return;
7885   }
7886 
7887   for (const auto &B : RD.bases()) {
7888     // Ill-formed if the base class is non-trivial for the purpose of calls or a
7889     // virtual base.
7890     if ((!B.getType()->isDependentType() &&
7891          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7892         B.isVirtual()) {
7893       PrintDiagAndRemoveAttr();
7894       return;
7895     }
7896   }
7897 
7898   for (const auto *FD : RD.fields()) {
7899     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7900     // non-trivial for the purpose of calls.
7901     QualType FT = FD->getType();
7902     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7903       PrintDiagAndRemoveAttr();
7904       return;
7905     }
7906 
7907     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7908       if (!RT->isDependentType() &&
7909           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7910         PrintDiagAndRemoveAttr();
7911         return;
7912       }
7913   }
7914 }
7915 
7916 void Sema::ActOnFinishCXXMemberSpecification(
7917     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
7918     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
7919   if (!TagDecl)
7920     return;
7921 
7922   AdjustDeclIfTemplate(TagDecl);
7923 
7924   for (const ParsedAttr &AL : AttrList) {
7925     if (AL.getKind() != ParsedAttr::AT_Visibility)
7926       continue;
7927     AL.setInvalid();
7928     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
7929         << AL.getName();
7930   }
7931 
7932   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7933               // strict aliasing violation!
7934               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7935               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7936 
7937   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7938 }
7939 
7940 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7941 /// special functions, such as the default constructor, copy
7942 /// constructor, or destructor, to the given C++ class (C++
7943 /// [special]p1).  This routine can only be executed just before the
7944 /// definition of the class is complete.
7945 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7946   if (ClassDecl->needsImplicitDefaultConstructor()) {
7947     ++getASTContext().NumImplicitDefaultConstructors;
7948 
7949     if (ClassDecl->hasInheritedConstructor())
7950       DeclareImplicitDefaultConstructor(ClassDecl);
7951   }
7952 
7953   if (ClassDecl->needsImplicitCopyConstructor()) {
7954     ++getASTContext().NumImplicitCopyConstructors;
7955 
7956     // If the properties or semantics of the copy constructor couldn't be
7957     // determined while the class was being declared, force a declaration
7958     // of it now.
7959     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7960         ClassDecl->hasInheritedConstructor())
7961       DeclareImplicitCopyConstructor(ClassDecl);
7962     // For the MS ABI we need to know whether the copy ctor is deleted. A
7963     // prerequisite for deleting the implicit copy ctor is that the class has a
7964     // move ctor or move assignment that is either user-declared or whose
7965     // semantics are inherited from a subobject. FIXME: We should provide a more
7966     // direct way for CodeGen to ask whether the constructor was deleted.
7967     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7968              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7969               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7970               ClassDecl->hasUserDeclaredMoveAssignment() ||
7971               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7972       DeclareImplicitCopyConstructor(ClassDecl);
7973   }
7974 
7975   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7976     ++getASTContext().NumImplicitMoveConstructors;
7977 
7978     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7979         ClassDecl->hasInheritedConstructor())
7980       DeclareImplicitMoveConstructor(ClassDecl);
7981   }
7982 
7983   if (ClassDecl->needsImplicitCopyAssignment()) {
7984     ++getASTContext().NumImplicitCopyAssignmentOperators;
7985 
7986     // If we have a dynamic class, then the copy assignment operator may be
7987     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7988     // it shows up in the right place in the vtable and that we diagnose
7989     // problems with the implicit exception specification.
7990     if (ClassDecl->isDynamicClass() ||
7991         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7992         ClassDecl->hasInheritedAssignment())
7993       DeclareImplicitCopyAssignment(ClassDecl);
7994   }
7995 
7996   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7997     ++getASTContext().NumImplicitMoveAssignmentOperators;
7998 
7999     // Likewise for the move assignment operator.
8000     if (ClassDecl->isDynamicClass() ||
8001         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
8002         ClassDecl->hasInheritedAssignment())
8003       DeclareImplicitMoveAssignment(ClassDecl);
8004   }
8005 
8006   if (ClassDecl->needsImplicitDestructor()) {
8007     ++getASTContext().NumImplicitDestructors;
8008 
8009     // If we have a dynamic class, then the destructor may be virtual, so we
8010     // have to declare the destructor immediately. This ensures that, e.g., it
8011     // shows up in the right place in the vtable and that we diagnose problems
8012     // with the implicit exception specification.
8013     if (ClassDecl->isDynamicClass() ||
8014         ClassDecl->needsOverloadResolutionForDestructor())
8015       DeclareImplicitDestructor(ClassDecl);
8016   }
8017 }
8018 
8019 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
8020   if (!D)
8021     return 0;
8022 
8023   // The order of template parameters is not important here. All names
8024   // get added to the same scope.
8025   SmallVector<TemplateParameterList *, 4> ParameterLists;
8026 
8027   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8028     D = TD->getTemplatedDecl();
8029 
8030   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
8031     ParameterLists.push_back(PSD->getTemplateParameters());
8032 
8033   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
8034     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
8035       ParameterLists.push_back(DD->getTemplateParameterList(i));
8036 
8037     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8038       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
8039         ParameterLists.push_back(FTD->getTemplateParameters());
8040     }
8041   }
8042 
8043   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8044     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
8045       ParameterLists.push_back(TD->getTemplateParameterList(i));
8046 
8047     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
8048       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
8049         ParameterLists.push_back(CTD->getTemplateParameters());
8050     }
8051   }
8052 
8053   unsigned Count = 0;
8054   for (TemplateParameterList *Params : ParameterLists) {
8055     if (Params->size() > 0)
8056       // Ignore explicit specializations; they don't contribute to the template
8057       // depth.
8058       ++Count;
8059     for (NamedDecl *Param : *Params) {
8060       if (Param->getDeclName()) {
8061         S->AddDecl(Param);
8062         IdResolver.AddDecl(Param);
8063       }
8064     }
8065   }
8066 
8067   return Count;
8068 }
8069 
8070 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8071   if (!RecordD) return;
8072   AdjustDeclIfTemplate(RecordD);
8073   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8074   PushDeclContext(S, Record);
8075 }
8076 
8077 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8078   if (!RecordD) return;
8079   PopDeclContext();
8080 }
8081 
8082 /// This is used to implement the constant expression evaluation part of the
8083 /// attribute enable_if extension. There is nothing in standard C++ which would
8084 /// require reentering parameters.
8085 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8086   if (!Param)
8087     return;
8088 
8089   S->AddDecl(Param);
8090   if (Param->getDeclName())
8091     IdResolver.AddDecl(Param);
8092 }
8093 
8094 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
8095 /// parsing a top-level (non-nested) C++ class, and we are now
8096 /// parsing those parts of the given Method declaration that could
8097 /// not be parsed earlier (C++ [class.mem]p2), such as default
8098 /// arguments. This action should enter the scope of the given
8099 /// Method declaration as if we had just parsed the qualified method
8100 /// name. However, it should not bring the parameters into scope;
8101 /// that will be performed by ActOnDelayedCXXMethodParameter.
8102 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8103 }
8104 
8105 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8106 /// C++ method declaration. We're (re-)introducing the given
8107 /// function parameter into scope for use in parsing later parts of
8108 /// the method declaration. For example, we could see an
8109 /// ActOnParamDefaultArgument event for this parameter.
8110 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8111   if (!ParamD)
8112     return;
8113 
8114   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8115 
8116   // If this parameter has an unparsed default argument, clear it out
8117   // to make way for the parsed default argument.
8118   if (Param->hasUnparsedDefaultArg())
8119     Param->setDefaultArg(nullptr);
8120 
8121   S->AddDecl(Param);
8122   if (Param->getDeclName())
8123     IdResolver.AddDecl(Param);
8124 }
8125 
8126 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8127 /// processing the delayed method declaration for Method. The method
8128 /// declaration is now considered finished. There may be a separate
8129 /// ActOnStartOfFunctionDef action later (not necessarily
8130 /// immediately!) for this method, if it was also defined inside the
8131 /// class body.
8132 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8133   if (!MethodD)
8134     return;
8135 
8136   AdjustDeclIfTemplate(MethodD);
8137 
8138   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8139 
8140   // Now that we have our default arguments, check the constructor
8141   // again. It could produce additional diagnostics or affect whether
8142   // the class has implicitly-declared destructors, among other
8143   // things.
8144   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8145     CheckConstructor(Constructor);
8146 
8147   // Check the default arguments, which we may have added.
8148   if (!Method->isInvalidDecl())
8149     CheckCXXDefaultArguments(Method);
8150 }
8151 
8152 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8153 /// the well-formedness of the constructor declarator @p D with type @p
8154 /// R. If there are any errors in the declarator, this routine will
8155 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8156 /// will be updated to reflect a well-formed type for the constructor and
8157 /// returned.
8158 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8159                                           StorageClass &SC) {
8160   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8161 
8162   // C++ [class.ctor]p3:
8163   //   A constructor shall not be virtual (10.3) or static (9.4). A
8164   //   constructor can be invoked for a const, volatile or const
8165   //   volatile object. A constructor shall not be declared const,
8166   //   volatile, or const volatile (9.3.2).
8167   if (isVirtual) {
8168     if (!D.isInvalidType())
8169       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8170         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8171         << SourceRange(D.getIdentifierLoc());
8172     D.setInvalidType();
8173   }
8174   if (SC == SC_Static) {
8175     if (!D.isInvalidType())
8176       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8177         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8178         << SourceRange(D.getIdentifierLoc());
8179     D.setInvalidType();
8180     SC = SC_None;
8181   }
8182 
8183   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8184     diagnoseIgnoredQualifiers(
8185         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8186         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8187         D.getDeclSpec().getRestrictSpecLoc(),
8188         D.getDeclSpec().getAtomicSpecLoc());
8189     D.setInvalidType();
8190   }
8191 
8192   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8193   if (FTI.hasMethodTypeQualifiers()) {
8194     FTI.MethodQualifiers->forEachQualifier(
8195         [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
8196           Diag(SL, diag::err_invalid_qualified_constructor)
8197               << QualName << SourceRange(SL);
8198         });
8199     D.setInvalidType();
8200   }
8201 
8202   // C++0x [class.ctor]p4:
8203   //   A constructor shall not be declared with a ref-qualifier.
8204   if (FTI.hasRefQualifier()) {
8205     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8206       << FTI.RefQualifierIsLValueRef
8207       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8208     D.setInvalidType();
8209   }
8210 
8211   // Rebuild the function type "R" without any type qualifiers (in
8212   // case any of the errors above fired) and with "void" as the
8213   // return type, since constructors don't have return types.
8214   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8215   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8216     return R;
8217 
8218   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8219   EPI.TypeQuals = Qualifiers();
8220   EPI.RefQualifier = RQ_None;
8221 
8222   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8223 }
8224 
8225 /// CheckConstructor - Checks a fully-formed constructor for
8226 /// well-formedness, issuing any diagnostics required. Returns true if
8227 /// the constructor declarator is invalid.
8228 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8229   CXXRecordDecl *ClassDecl
8230     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8231   if (!ClassDecl)
8232     return Constructor->setInvalidDecl();
8233 
8234   // C++ [class.copy]p3:
8235   //   A declaration of a constructor for a class X is ill-formed if
8236   //   its first parameter is of type (optionally cv-qualified) X and
8237   //   either there are no other parameters or else all other
8238   //   parameters have default arguments.
8239   if (!Constructor->isInvalidDecl() &&
8240       ((Constructor->getNumParams() == 1) ||
8241        (Constructor->getNumParams() > 1 &&
8242         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8243       Constructor->getTemplateSpecializationKind()
8244                                               != TSK_ImplicitInstantiation) {
8245     QualType ParamType = Constructor->getParamDecl(0)->getType();
8246     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8247     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8248       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8249       const char *ConstRef
8250         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8251                                                         : " const &";
8252       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8253         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8254 
8255       // FIXME: Rather that making the constructor invalid, we should endeavor
8256       // to fix the type.
8257       Constructor->setInvalidDecl();
8258     }
8259   }
8260 }
8261 
8262 /// CheckDestructor - Checks a fully-formed destructor definition for
8263 /// well-formedness, issuing any diagnostics required.  Returns true
8264 /// on error.
8265 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8266   CXXRecordDecl *RD = Destructor->getParent();
8267 
8268   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8269     SourceLocation Loc;
8270 
8271     if (!Destructor->isImplicit())
8272       Loc = Destructor->getLocation();
8273     else
8274       Loc = RD->getLocation();
8275 
8276     // If we have a virtual destructor, look up the deallocation function
8277     if (FunctionDecl *OperatorDelete =
8278             FindDeallocationFunctionForDestructor(Loc, RD)) {
8279       Expr *ThisArg = nullptr;
8280 
8281       // If the notional 'delete this' expression requires a non-trivial
8282       // conversion from 'this' to the type of a destroying operator delete's
8283       // first parameter, perform that conversion now.
8284       if (OperatorDelete->isDestroyingOperatorDelete()) {
8285         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8286         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8287           // C++ [class.dtor]p13:
8288           //   ... as if for the expression 'delete this' appearing in a
8289           //   non-virtual destructor of the destructor's class.
8290           ContextRAII SwitchContext(*this, Destructor);
8291           ExprResult This =
8292               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8293           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8294           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8295           if (This.isInvalid()) {
8296             // FIXME: Register this as a context note so that it comes out
8297             // in the right order.
8298             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8299             return true;
8300           }
8301           ThisArg = This.get();
8302         }
8303       }
8304 
8305       DiagnoseUseOfDecl(OperatorDelete, Loc);
8306       MarkFunctionReferenced(Loc, OperatorDelete);
8307       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8308     }
8309   }
8310 
8311   return false;
8312 }
8313 
8314 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8315 /// the well-formednes of the destructor declarator @p D with type @p
8316 /// R. If there are any errors in the declarator, this routine will
8317 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8318 /// will be updated to reflect a well-formed type for the destructor and
8319 /// returned.
8320 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8321                                          StorageClass& SC) {
8322   // C++ [class.dtor]p1:
8323   //   [...] A typedef-name that names a class is a class-name
8324   //   (7.1.3); however, a typedef-name that names a class shall not
8325   //   be used as the identifier in the declarator for a destructor
8326   //   declaration.
8327   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8328   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8329     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8330       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8331   else if (const TemplateSpecializationType *TST =
8332              DeclaratorType->getAs<TemplateSpecializationType>())
8333     if (TST->isTypeAlias())
8334       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8335         << DeclaratorType << 1;
8336 
8337   // C++ [class.dtor]p2:
8338   //   A destructor is used to destroy objects of its class type. A
8339   //   destructor takes no parameters, and no return type can be
8340   //   specified for it (not even void). The address of a destructor
8341   //   shall not be taken. A destructor shall not be static. A
8342   //   destructor can be invoked for a const, volatile or const
8343   //   volatile object. A destructor shall not be declared const,
8344   //   volatile or const volatile (9.3.2).
8345   if (SC == SC_Static) {
8346     if (!D.isInvalidType())
8347       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8348         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8349         << SourceRange(D.getIdentifierLoc())
8350         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8351 
8352     SC = SC_None;
8353   }
8354   if (!D.isInvalidType()) {
8355     // Destructors don't have return types, but the parser will
8356     // happily parse something like:
8357     //
8358     //   class X {
8359     //     float ~X();
8360     //   };
8361     //
8362     // The return type will be eliminated later.
8363     if (D.getDeclSpec().hasTypeSpecifier())
8364       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8365         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8366         << SourceRange(D.getIdentifierLoc());
8367     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8368       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8369                                 SourceLocation(),
8370                                 D.getDeclSpec().getConstSpecLoc(),
8371                                 D.getDeclSpec().getVolatileSpecLoc(),
8372                                 D.getDeclSpec().getRestrictSpecLoc(),
8373                                 D.getDeclSpec().getAtomicSpecLoc());
8374       D.setInvalidType();
8375     }
8376   }
8377 
8378   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8379   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
8380     FTI.MethodQualifiers->forEachQualifier(
8381         [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
8382           Diag(SL, diag::err_invalid_qualified_destructor)
8383               << QualName << SourceRange(SL);
8384         });
8385     D.setInvalidType();
8386   }
8387 
8388   // C++0x [class.dtor]p2:
8389   //   A destructor shall not be declared with a ref-qualifier.
8390   if (FTI.hasRefQualifier()) {
8391     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8392       << FTI.RefQualifierIsLValueRef
8393       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8394     D.setInvalidType();
8395   }
8396 
8397   // Make sure we don't have any parameters.
8398   if (FTIHasNonVoidParameters(FTI)) {
8399     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8400 
8401     // Delete the parameters.
8402     FTI.freeParams();
8403     D.setInvalidType();
8404   }
8405 
8406   // Make sure the destructor isn't variadic.
8407   if (FTI.isVariadic) {
8408     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8409     D.setInvalidType();
8410   }
8411 
8412   // Rebuild the function type "R" without any type qualifiers or
8413   // parameters (in case any of the errors above fired) and with
8414   // "void" as the return type, since destructors don't have return
8415   // types.
8416   if (!D.isInvalidType())
8417     return R;
8418 
8419   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8420   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8421   EPI.Variadic = false;
8422   EPI.TypeQuals = Qualifiers();
8423   EPI.RefQualifier = RQ_None;
8424   return Context.getFunctionType(Context.VoidTy, None, EPI);
8425 }
8426 
8427 static void extendLeft(SourceRange &R, SourceRange Before) {
8428   if (Before.isInvalid())
8429     return;
8430   R.setBegin(Before.getBegin());
8431   if (R.getEnd().isInvalid())
8432     R.setEnd(Before.getEnd());
8433 }
8434 
8435 static void extendRight(SourceRange &R, SourceRange After) {
8436   if (After.isInvalid())
8437     return;
8438   if (R.getBegin().isInvalid())
8439     R.setBegin(After.getBegin());
8440   R.setEnd(After.getEnd());
8441 }
8442 
8443 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8444 /// well-formednes of the conversion function declarator @p D with
8445 /// type @p R. If there are any errors in the declarator, this routine
8446 /// will emit diagnostics and return true. Otherwise, it will return
8447 /// false. Either way, the type @p R will be updated to reflect a
8448 /// well-formed type for the conversion operator.
8449 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8450                                      StorageClass& SC) {
8451   // C++ [class.conv.fct]p1:
8452   //   Neither parameter types nor return type can be specified. The
8453   //   type of a conversion function (8.3.5) is "function taking no
8454   //   parameter returning conversion-type-id."
8455   if (SC == SC_Static) {
8456     if (!D.isInvalidType())
8457       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8458         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8459         << D.getName().getSourceRange();
8460     D.setInvalidType();
8461     SC = SC_None;
8462   }
8463 
8464   TypeSourceInfo *ConvTSI = nullptr;
8465   QualType ConvType =
8466       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8467 
8468   const DeclSpec &DS = D.getDeclSpec();
8469   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8470     // Conversion functions don't have return types, but the parser will
8471     // happily parse something like:
8472     //
8473     //   class X {
8474     //     float operator bool();
8475     //   };
8476     //
8477     // The return type will be changed later anyway.
8478     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8479       << SourceRange(DS.getTypeSpecTypeLoc())
8480       << SourceRange(D.getIdentifierLoc());
8481     D.setInvalidType();
8482   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8483     // It's also plausible that the user writes type qualifiers in the wrong
8484     // place, such as:
8485     //   struct S { const operator int(); };
8486     // FIXME: we could provide a fixit to move the qualifiers onto the
8487     // conversion type.
8488     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8489         << SourceRange(D.getIdentifierLoc()) << 0;
8490     D.setInvalidType();
8491   }
8492 
8493   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8494 
8495   // Make sure we don't have any parameters.
8496   if (Proto->getNumParams() > 0) {
8497     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8498 
8499     // Delete the parameters.
8500     D.getFunctionTypeInfo().freeParams();
8501     D.setInvalidType();
8502   } else if (Proto->isVariadic()) {
8503     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8504     D.setInvalidType();
8505   }
8506 
8507   // Diagnose "&operator bool()" and other such nonsense.  This
8508   // is actually a gcc extension which we don't support.
8509   if (Proto->getReturnType() != ConvType) {
8510     bool NeedsTypedef = false;
8511     SourceRange Before, After;
8512 
8513     // Walk the chunks and extract information on them for our diagnostic.
8514     bool PastFunctionChunk = false;
8515     for (auto &Chunk : D.type_objects()) {
8516       switch (Chunk.Kind) {
8517       case DeclaratorChunk::Function:
8518         if (!PastFunctionChunk) {
8519           if (Chunk.Fun.HasTrailingReturnType) {
8520             TypeSourceInfo *TRT = nullptr;
8521             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8522             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8523           }
8524           PastFunctionChunk = true;
8525           break;
8526         }
8527         LLVM_FALLTHROUGH;
8528       case DeclaratorChunk::Array:
8529         NeedsTypedef = true;
8530         extendRight(After, Chunk.getSourceRange());
8531         break;
8532 
8533       case DeclaratorChunk::Pointer:
8534       case DeclaratorChunk::BlockPointer:
8535       case DeclaratorChunk::Reference:
8536       case DeclaratorChunk::MemberPointer:
8537       case DeclaratorChunk::Pipe:
8538         extendLeft(Before, Chunk.getSourceRange());
8539         break;
8540 
8541       case DeclaratorChunk::Paren:
8542         extendLeft(Before, Chunk.Loc);
8543         extendRight(After, Chunk.EndLoc);
8544         break;
8545       }
8546     }
8547 
8548     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8549                          After.isValid()  ? After.getBegin() :
8550                                             D.getIdentifierLoc();
8551     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8552     DB << Before << After;
8553 
8554     if (!NeedsTypedef) {
8555       DB << /*don't need a typedef*/0;
8556 
8557       // If we can provide a correct fix-it hint, do so.
8558       if (After.isInvalid() && ConvTSI) {
8559         SourceLocation InsertLoc =
8560             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8561         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8562            << FixItHint::CreateInsertionFromRange(
8563                   InsertLoc, CharSourceRange::getTokenRange(Before))
8564            << FixItHint::CreateRemoval(Before);
8565       }
8566     } else if (!Proto->getReturnType()->isDependentType()) {
8567       DB << /*typedef*/1 << Proto->getReturnType();
8568     } else if (getLangOpts().CPlusPlus11) {
8569       DB << /*alias template*/2 << Proto->getReturnType();
8570     } else {
8571       DB << /*might not be fixable*/3;
8572     }
8573 
8574     // Recover by incorporating the other type chunks into the result type.
8575     // Note, this does *not* change the name of the function. This is compatible
8576     // with the GCC extension:
8577     //   struct S { &operator int(); } s;
8578     //   int &r = s.operator int(); // ok in GCC
8579     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8580     ConvType = Proto->getReturnType();
8581   }
8582 
8583   // C++ [class.conv.fct]p4:
8584   //   The conversion-type-id shall not represent a function type nor
8585   //   an array type.
8586   if (ConvType->isArrayType()) {
8587     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8588     ConvType = Context.getPointerType(ConvType);
8589     D.setInvalidType();
8590   } else if (ConvType->isFunctionType()) {
8591     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8592     ConvType = Context.getPointerType(ConvType);
8593     D.setInvalidType();
8594   }
8595 
8596   // Rebuild the function type "R" without any parameters (in case any
8597   // of the errors above fired) and with the conversion type as the
8598   // return type.
8599   if (D.isInvalidType())
8600     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8601 
8602   // C++0x explicit conversion operators.
8603   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a)
8604     Diag(DS.getExplicitSpecLoc(),
8605          getLangOpts().CPlusPlus11
8606              ? diag::warn_cxx98_compat_explicit_conversion_functions
8607              : diag::ext_explicit_conversion_functions)
8608         << SourceRange(DS.getExplicitSpecRange());
8609 }
8610 
8611 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8612 /// the declaration of the given C++ conversion function. This routine
8613 /// is responsible for recording the conversion function in the C++
8614 /// class, if possible.
8615 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8616   assert(Conversion && "Expected to receive a conversion function declaration");
8617 
8618   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8619 
8620   // Make sure we aren't redeclaring the conversion function.
8621   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8622 
8623   // C++ [class.conv.fct]p1:
8624   //   [...] A conversion function is never used to convert a
8625   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8626   //   same object type (or a reference to it), to a (possibly
8627   //   cv-qualified) base class of that type (or a reference to it),
8628   //   or to (possibly cv-qualified) void.
8629   // FIXME: Suppress this warning if the conversion function ends up being a
8630   // virtual function that overrides a virtual function in a base class.
8631   QualType ClassType
8632     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8633   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8634     ConvType = ConvTypeRef->getPointeeType();
8635   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8636       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8637     /* Suppress diagnostics for instantiations. */;
8638   else if (ConvType->isRecordType()) {
8639     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8640     if (ConvType == ClassType)
8641       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8642         << ClassType;
8643     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8644       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8645         <<  ClassType << ConvType;
8646   } else if (ConvType->isVoidType()) {
8647     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8648       << ClassType << ConvType;
8649   }
8650 
8651   if (FunctionTemplateDecl *ConversionTemplate
8652                                 = Conversion->getDescribedFunctionTemplate())
8653     return ConversionTemplate;
8654 
8655   return Conversion;
8656 }
8657 
8658 namespace {
8659 /// Utility class to accumulate and print a diagnostic listing the invalid
8660 /// specifier(s) on a declaration.
8661 struct BadSpecifierDiagnoser {
8662   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8663       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8664   ~BadSpecifierDiagnoser() {
8665     Diagnostic << Specifiers;
8666   }
8667 
8668   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8669     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8670   }
8671   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8672     return check(SpecLoc,
8673                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8674   }
8675   void check(SourceLocation SpecLoc, const char *Spec) {
8676     if (SpecLoc.isInvalid()) return;
8677     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8678     if (!Specifiers.empty()) Specifiers += " ";
8679     Specifiers += Spec;
8680   }
8681 
8682   Sema &S;
8683   Sema::SemaDiagnosticBuilder Diagnostic;
8684   std::string Specifiers;
8685 };
8686 }
8687 
8688 /// Check the validity of a declarator that we parsed for a deduction-guide.
8689 /// These aren't actually declarators in the grammar, so we need to check that
8690 /// the user didn't specify any pieces that are not part of the deduction-guide
8691 /// grammar.
8692 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8693                                          StorageClass &SC) {
8694   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8695   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8696   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8697 
8698   // C++ [temp.deduct.guide]p3:
8699   //   A deduction-gide shall be declared in the same scope as the
8700   //   corresponding class template.
8701   if (!CurContext->getRedeclContext()->Equals(
8702           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8703     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8704       << GuidedTemplateDecl;
8705     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8706   }
8707 
8708   auto &DS = D.getMutableDeclSpec();
8709   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8710   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8711       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8712       DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8713     BadSpecifierDiagnoser Diagnoser(
8714         *this, D.getIdentifierLoc(),
8715         diag::err_deduction_guide_invalid_specifier);
8716 
8717     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8718     DS.ClearStorageClassSpecs();
8719     SC = SC_None;
8720 
8721     // 'explicit' is permitted.
8722     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8723     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8724     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8725     DS.ClearConstexprSpec();
8726 
8727     Diagnoser.check(DS.getConstSpecLoc(), "const");
8728     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8729     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8730     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8731     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8732     DS.ClearTypeQualifiers();
8733 
8734     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8735     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8736     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8737     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8738     DS.ClearTypeSpecType();
8739   }
8740 
8741   if (D.isInvalidType())
8742     return;
8743 
8744   // Check the declarator is simple enough.
8745   bool FoundFunction = false;
8746   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8747     if (Chunk.Kind == DeclaratorChunk::Paren)
8748       continue;
8749     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8750       Diag(D.getDeclSpec().getBeginLoc(),
8751            diag::err_deduction_guide_with_complex_decl)
8752           << D.getSourceRange();
8753       break;
8754     }
8755     if (!Chunk.Fun.hasTrailingReturnType()) {
8756       Diag(D.getName().getBeginLoc(),
8757            diag::err_deduction_guide_no_trailing_return_type);
8758       break;
8759     }
8760 
8761     // Check that the return type is written as a specialization of
8762     // the template specified as the deduction-guide's name.
8763     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8764     TypeSourceInfo *TSI = nullptr;
8765     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8766     assert(TSI && "deduction guide has valid type but invalid return type?");
8767     bool AcceptableReturnType = false;
8768     bool MightInstantiateToSpecialization = false;
8769     if (auto RetTST =
8770             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8771       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8772       bool TemplateMatches =
8773           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8774       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8775         AcceptableReturnType = true;
8776       else {
8777         // This could still instantiate to the right type, unless we know it
8778         // names the wrong class template.
8779         auto *TD = SpecifiedName.getAsTemplateDecl();
8780         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8781                                              !TemplateMatches);
8782       }
8783     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8784       MightInstantiateToSpecialization = true;
8785     }
8786 
8787     if (!AcceptableReturnType) {
8788       Diag(TSI->getTypeLoc().getBeginLoc(),
8789            diag::err_deduction_guide_bad_trailing_return_type)
8790           << GuidedTemplate << TSI->getType()
8791           << MightInstantiateToSpecialization
8792           << TSI->getTypeLoc().getSourceRange();
8793     }
8794 
8795     // Keep going to check that we don't have any inner declarator pieces (we
8796     // could still have a function returning a pointer to a function).
8797     FoundFunction = true;
8798   }
8799 
8800   if (D.isFunctionDefinition())
8801     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8802 }
8803 
8804 //===----------------------------------------------------------------------===//
8805 // Namespace Handling
8806 //===----------------------------------------------------------------------===//
8807 
8808 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8809 /// reopened.
8810 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8811                                             SourceLocation Loc,
8812                                             IdentifierInfo *II, bool *IsInline,
8813                                             NamespaceDecl *PrevNS) {
8814   assert(*IsInline != PrevNS->isInline());
8815 
8816   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8817   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8818   // inline namespaces, with the intention of bringing names into namespace std.
8819   //
8820   // We support this just well enough to get that case working; this is not
8821   // sufficient to support reopening namespaces as inline in general.
8822   if (*IsInline && II && II->getName().startswith("__atomic") &&
8823       S.getSourceManager().isInSystemHeader(Loc)) {
8824     // Mark all prior declarations of the namespace as inline.
8825     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8826          NS = NS->getPreviousDecl())
8827       NS->setInline(*IsInline);
8828     // Patch up the lookup table for the containing namespace. This isn't really
8829     // correct, but it's good enough for this particular case.
8830     for (auto *I : PrevNS->decls())
8831       if (auto *ND = dyn_cast<NamedDecl>(I))
8832         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8833     return;
8834   }
8835 
8836   if (PrevNS->isInline())
8837     // The user probably just forgot the 'inline', so suggest that it
8838     // be added back.
8839     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8840       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8841   else
8842     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8843 
8844   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8845   *IsInline = PrevNS->isInline();
8846 }
8847 
8848 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8849 /// definition.
8850 Decl *Sema::ActOnStartNamespaceDef(
8851     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
8852     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
8853     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
8854   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8855   // For anonymous namespace, take the location of the left brace.
8856   SourceLocation Loc = II ? IdentLoc : LBrace;
8857   bool IsInline = InlineLoc.isValid();
8858   bool IsInvalid = false;
8859   bool IsStd = false;
8860   bool AddToKnown = false;
8861   Scope *DeclRegionScope = NamespcScope->getParent();
8862 
8863   NamespaceDecl *PrevNS = nullptr;
8864   if (II) {
8865     // C++ [namespace.def]p2:
8866     //   The identifier in an original-namespace-definition shall not
8867     //   have been previously defined in the declarative region in
8868     //   which the original-namespace-definition appears. The
8869     //   identifier in an original-namespace-definition is the name of
8870     //   the namespace. Subsequently in that declarative region, it is
8871     //   treated as an original-namespace-name.
8872     //
8873     // Since namespace names are unique in their scope, and we don't
8874     // look through using directives, just look for any ordinary names
8875     // as if by qualified name lookup.
8876     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8877                    ForExternalRedeclaration);
8878     LookupQualifiedName(R, CurContext->getRedeclContext());
8879     NamedDecl *PrevDecl =
8880         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8881     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8882 
8883     if (PrevNS) {
8884       // This is an extended namespace definition.
8885       if (IsInline != PrevNS->isInline())
8886         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8887                                         &IsInline, PrevNS);
8888     } else if (PrevDecl) {
8889       // This is an invalid name redefinition.
8890       Diag(Loc, diag::err_redefinition_different_kind)
8891         << II;
8892       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8893       IsInvalid = true;
8894       // Continue on to push Namespc as current DeclContext and return it.
8895     } else if (II->isStr("std") &&
8896                CurContext->getRedeclContext()->isTranslationUnit()) {
8897       // This is the first "real" definition of the namespace "std", so update
8898       // our cache of the "std" namespace to point at this definition.
8899       PrevNS = getStdNamespace();
8900       IsStd = true;
8901       AddToKnown = !IsInline;
8902     } else {
8903       // We've seen this namespace for the first time.
8904       AddToKnown = !IsInline;
8905     }
8906   } else {
8907     // Anonymous namespaces.
8908 
8909     // Determine whether the parent already has an anonymous namespace.
8910     DeclContext *Parent = CurContext->getRedeclContext();
8911     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8912       PrevNS = TU->getAnonymousNamespace();
8913     } else {
8914       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8915       PrevNS = ND->getAnonymousNamespace();
8916     }
8917 
8918     if (PrevNS && IsInline != PrevNS->isInline())
8919       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8920                                       &IsInline, PrevNS);
8921   }
8922 
8923   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8924                                                  StartLoc, Loc, II, PrevNS);
8925   if (IsInvalid)
8926     Namespc->setInvalidDecl();
8927 
8928   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8929   AddPragmaAttributes(DeclRegionScope, Namespc);
8930 
8931   // FIXME: Should we be merging attributes?
8932   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8933     PushNamespaceVisibilityAttr(Attr, Loc);
8934 
8935   if (IsStd)
8936     StdNamespace = Namespc;
8937   if (AddToKnown)
8938     KnownNamespaces[Namespc] = false;
8939 
8940   if (II) {
8941     PushOnScopeChains(Namespc, DeclRegionScope);
8942   } else {
8943     // Link the anonymous namespace into its parent.
8944     DeclContext *Parent = CurContext->getRedeclContext();
8945     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8946       TU->setAnonymousNamespace(Namespc);
8947     } else {
8948       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8949     }
8950 
8951     CurContext->addDecl(Namespc);
8952 
8953     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8954     //   behaves as if it were replaced by
8955     //     namespace unique { /* empty body */ }
8956     //     using namespace unique;
8957     //     namespace unique { namespace-body }
8958     //   where all occurrences of 'unique' in a translation unit are
8959     //   replaced by the same identifier and this identifier differs
8960     //   from all other identifiers in the entire program.
8961 
8962     // We just create the namespace with an empty name and then add an
8963     // implicit using declaration, just like the standard suggests.
8964     //
8965     // CodeGen enforces the "universally unique" aspect by giving all
8966     // declarations semantically contained within an anonymous
8967     // namespace internal linkage.
8968 
8969     if (!PrevNS) {
8970       UD = UsingDirectiveDecl::Create(Context, Parent,
8971                                       /* 'using' */ LBrace,
8972                                       /* 'namespace' */ SourceLocation(),
8973                                       /* qualifier */ NestedNameSpecifierLoc(),
8974                                       /* identifier */ SourceLocation(),
8975                                       Namespc,
8976                                       /* Ancestor */ Parent);
8977       UD->setImplicit();
8978       Parent->addDecl(UD);
8979     }
8980   }
8981 
8982   ActOnDocumentableDecl(Namespc);
8983 
8984   // Although we could have an invalid decl (i.e. the namespace name is a
8985   // redefinition), push it as current DeclContext and try to continue parsing.
8986   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8987   // for the namespace has the declarations that showed up in that particular
8988   // namespace definition.
8989   PushDeclContext(NamespcScope, Namespc);
8990   return Namespc;
8991 }
8992 
8993 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8994 /// is a namespace alias, returns the namespace it points to.
8995 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8996   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8997     return AD->getNamespace();
8998   return dyn_cast_or_null<NamespaceDecl>(D);
8999 }
9000 
9001 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
9002 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
9003 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
9004   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
9005   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
9006   Namespc->setRBraceLoc(RBrace);
9007   PopDeclContext();
9008   if (Namespc->hasAttr<VisibilityAttr>())
9009     PopPragmaVisibility(true, RBrace);
9010   // If this namespace contains an export-declaration, export it now.
9011   if (DeferredExportedNamespaces.erase(Namespc))
9012     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
9013 }
9014 
9015 CXXRecordDecl *Sema::getStdBadAlloc() const {
9016   return cast_or_null<CXXRecordDecl>(
9017                                   StdBadAlloc.get(Context.getExternalSource()));
9018 }
9019 
9020 EnumDecl *Sema::getStdAlignValT() const {
9021   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9022 }
9023 
9024 NamespaceDecl *Sema::getStdNamespace() const {
9025   return cast_or_null<NamespaceDecl>(
9026                                  StdNamespace.get(Context.getExternalSource()));
9027 }
9028 
9029 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
9030   if (!StdExperimentalNamespaceCache) {
9031     if (auto Std = getStdNamespace()) {
9032       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9033                           SourceLocation(), LookupNamespaceName);
9034       if (!LookupQualifiedName(Result, Std) ||
9035           !(StdExperimentalNamespaceCache =
9036                 Result.getAsSingle<NamespaceDecl>()))
9037         Result.suppressDiagnostics();
9038     }
9039   }
9040   return StdExperimentalNamespaceCache;
9041 }
9042 
9043 namespace {
9044 
9045 enum UnsupportedSTLSelect {
9046   USS_InvalidMember,
9047   USS_MissingMember,
9048   USS_NonTrivial,
9049   USS_Other
9050 };
9051 
9052 struct InvalidSTLDiagnoser {
9053   Sema &S;
9054   SourceLocation Loc;
9055   QualType TyForDiags;
9056 
9057   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9058                       const VarDecl *VD = nullptr) {
9059     {
9060       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9061                << TyForDiags << ((int)Sel);
9062       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9063         assert(!Name.empty());
9064         D << Name;
9065       }
9066     }
9067     if (Sel == USS_InvalidMember) {
9068       S.Diag(VD->getLocation(), diag::note_var_declared_here)
9069           << VD << VD->getSourceRange();
9070     }
9071     return QualType();
9072   }
9073 };
9074 } // namespace
9075 
9076 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9077                                            SourceLocation Loc) {
9078   assert(getLangOpts().CPlusPlus &&
9079          "Looking for comparison category type outside of C++.");
9080 
9081   // Check if we've already successfully checked the comparison category type
9082   // before. If so, skip checking it again.
9083   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9084   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9085     return Info->getType();
9086 
9087   // If lookup failed
9088   if (!Info) {
9089     std::string NameForDiags = "std::";
9090     NameForDiags += ComparisonCategories::getCategoryString(Kind);
9091     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9092         << NameForDiags;
9093     return QualType();
9094   }
9095 
9096   assert(Info->Kind == Kind);
9097   assert(Info->Record);
9098 
9099   // Update the Record decl in case we encountered a forward declaration on our
9100   // first pass. FIXME: This is a bit of a hack.
9101   if (Info->Record->hasDefinition())
9102     Info->Record = Info->Record->getDefinition();
9103 
9104   // Use an elaborated type for diagnostics which has a name containing the
9105   // prepended 'std' namespace but not any inline namespace names.
9106   QualType TyForDiags = [&]() {
9107     auto *NNS =
9108         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9109     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9110   }();
9111 
9112   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9113     return QualType();
9114 
9115   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9116 
9117   if (!Info->Record->isTriviallyCopyable())
9118     return UnsupportedSTLError(USS_NonTrivial);
9119 
9120   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9121     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9122     // Tolerate empty base classes.
9123     if (Base->isEmpty())
9124       continue;
9125     // Reject STL implementations which have at least one non-empty base.
9126     return UnsupportedSTLError();
9127   }
9128 
9129   // Check that the STL has implemented the types using a single integer field.
9130   // This expectation allows better codegen for builtin operators. We require:
9131   //   (1) The class has exactly one field.
9132   //   (2) The field is an integral or enumeration type.
9133   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9134   if (std::distance(FIt, FEnd) != 1 ||
9135       !FIt->getType()->isIntegralOrEnumerationType()) {
9136     return UnsupportedSTLError();
9137   }
9138 
9139   // Build each of the require values and store them in Info.
9140   for (ComparisonCategoryResult CCR :
9141        ComparisonCategories::getPossibleResultsForType(Kind)) {
9142     StringRef MemName = ComparisonCategories::getResultString(CCR);
9143     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9144 
9145     if (!ValInfo)
9146       return UnsupportedSTLError(USS_MissingMember, MemName);
9147 
9148     VarDecl *VD = ValInfo->VD;
9149     assert(VD && "should not be null!");
9150 
9151     // Attempt to diagnose reasons why the STL definition of this type
9152     // might be foobar, including it failing to be a constant expression.
9153     // TODO Handle more ways the lookup or result can be invalid.
9154     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9155         !VD->checkInitIsICE())
9156       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9157 
9158     // Attempt to evaluate the var decl as a constant expression and extract
9159     // the value of its first field as a ICE. If this fails, the STL
9160     // implementation is not supported.
9161     if (!ValInfo->hasValidIntValue())
9162       return UnsupportedSTLError();
9163 
9164     MarkVariableReferenced(Loc, VD);
9165   }
9166 
9167   // We've successfully built the required types and expressions. Update
9168   // the cache and return the newly cached value.
9169   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9170   return Info->getType();
9171 }
9172 
9173 /// Retrieve the special "std" namespace, which may require us to
9174 /// implicitly define the namespace.
9175 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9176   if (!StdNamespace) {
9177     // The "std" namespace has not yet been defined, so build one implicitly.
9178     StdNamespace = NamespaceDecl::Create(Context,
9179                                          Context.getTranslationUnitDecl(),
9180                                          /*Inline=*/false,
9181                                          SourceLocation(), SourceLocation(),
9182                                          &PP.getIdentifierTable().get("std"),
9183                                          /*PrevDecl=*/nullptr);
9184     getStdNamespace()->setImplicit(true);
9185   }
9186 
9187   return getStdNamespace();
9188 }
9189 
9190 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9191   assert(getLangOpts().CPlusPlus &&
9192          "Looking for std::initializer_list outside of C++.");
9193 
9194   // We're looking for implicit instantiations of
9195   // template <typename E> class std::initializer_list.
9196 
9197   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9198     return false;
9199 
9200   ClassTemplateDecl *Template = nullptr;
9201   const TemplateArgument *Arguments = nullptr;
9202 
9203   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9204 
9205     ClassTemplateSpecializationDecl *Specialization =
9206         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9207     if (!Specialization)
9208       return false;
9209 
9210     Template = Specialization->getSpecializedTemplate();
9211     Arguments = Specialization->getTemplateArgs().data();
9212   } else if (const TemplateSpecializationType *TST =
9213                  Ty->getAs<TemplateSpecializationType>()) {
9214     Template = dyn_cast_or_null<ClassTemplateDecl>(
9215         TST->getTemplateName().getAsTemplateDecl());
9216     Arguments = TST->getArgs();
9217   }
9218   if (!Template)
9219     return false;
9220 
9221   if (!StdInitializerList) {
9222     // Haven't recognized std::initializer_list yet, maybe this is it.
9223     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9224     if (TemplateClass->getIdentifier() !=
9225             &PP.getIdentifierTable().get("initializer_list") ||
9226         !getStdNamespace()->InEnclosingNamespaceSetOf(
9227             TemplateClass->getDeclContext()))
9228       return false;
9229     // This is a template called std::initializer_list, but is it the right
9230     // template?
9231     TemplateParameterList *Params = Template->getTemplateParameters();
9232     if (Params->getMinRequiredArguments() != 1)
9233       return false;
9234     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9235       return false;
9236 
9237     // It's the right template.
9238     StdInitializerList = Template;
9239   }
9240 
9241   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9242     return false;
9243 
9244   // This is an instance of std::initializer_list. Find the argument type.
9245   if (Element)
9246     *Element = Arguments[0].getAsType();
9247   return true;
9248 }
9249 
9250 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9251   NamespaceDecl *Std = S.getStdNamespace();
9252   if (!Std) {
9253     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9254     return nullptr;
9255   }
9256 
9257   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9258                       Loc, Sema::LookupOrdinaryName);
9259   if (!S.LookupQualifiedName(Result, Std)) {
9260     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9261     return nullptr;
9262   }
9263   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9264   if (!Template) {
9265     Result.suppressDiagnostics();
9266     // We found something weird. Complain about the first thing we found.
9267     NamedDecl *Found = *Result.begin();
9268     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9269     return nullptr;
9270   }
9271 
9272   // We found some template called std::initializer_list. Now verify that it's
9273   // correct.
9274   TemplateParameterList *Params = Template->getTemplateParameters();
9275   if (Params->getMinRequiredArguments() != 1 ||
9276       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9277     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9278     return nullptr;
9279   }
9280 
9281   return Template;
9282 }
9283 
9284 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9285   if (!StdInitializerList) {
9286     StdInitializerList = LookupStdInitializerList(*this, Loc);
9287     if (!StdInitializerList)
9288       return QualType();
9289   }
9290 
9291   TemplateArgumentListInfo Args(Loc, Loc);
9292   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9293                                        Context.getTrivialTypeSourceInfo(Element,
9294                                                                         Loc)));
9295   return Context.getCanonicalType(
9296       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9297 }
9298 
9299 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9300   // C++ [dcl.init.list]p2:
9301   //   A constructor is an initializer-list constructor if its first parameter
9302   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9303   //   std::initializer_list<E> for some type E, and either there are no other
9304   //   parameters or else all other parameters have default arguments.
9305   if (Ctor->getNumParams() < 1 ||
9306       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9307     return false;
9308 
9309   QualType ArgType = Ctor->getParamDecl(0)->getType();
9310   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9311     ArgType = RT->getPointeeType().getUnqualifiedType();
9312 
9313   return isStdInitializerList(ArgType, nullptr);
9314 }
9315 
9316 /// Determine whether a using statement is in a context where it will be
9317 /// apply in all contexts.
9318 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9319   switch (CurContext->getDeclKind()) {
9320     case Decl::TranslationUnit:
9321       return true;
9322     case Decl::LinkageSpec:
9323       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9324     default:
9325       return false;
9326   }
9327 }
9328 
9329 namespace {
9330 
9331 // Callback to only accept typo corrections that are namespaces.
9332 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
9333 public:
9334   bool ValidateCandidate(const TypoCorrection &candidate) override {
9335     if (NamedDecl *ND = candidate.getCorrectionDecl())
9336       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9337     return false;
9338   }
9339 
9340   std::unique_ptr<CorrectionCandidateCallback> clone() override {
9341     return llvm::make_unique<NamespaceValidatorCCC>(*this);
9342   }
9343 };
9344 
9345 }
9346 
9347 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9348                                        CXXScopeSpec &SS,
9349                                        SourceLocation IdentLoc,
9350                                        IdentifierInfo *Ident) {
9351   R.clear();
9352   NamespaceValidatorCCC CCC{};
9353   if (TypoCorrection Corrected =
9354           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
9355                         Sema::CTK_ErrorRecovery)) {
9356     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9357       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9358       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9359                               Ident->getName().equals(CorrectedStr);
9360       S.diagnoseTypo(Corrected,
9361                      S.PDiag(diag::err_using_directive_member_suggest)
9362                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9363                      S.PDiag(diag::note_namespace_defined_here));
9364     } else {
9365       S.diagnoseTypo(Corrected,
9366                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9367                      S.PDiag(diag::note_namespace_defined_here));
9368     }
9369     R.addDecl(Corrected.getFoundDecl());
9370     return true;
9371   }
9372   return false;
9373 }
9374 
9375 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9376                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9377                                 SourceLocation IdentLoc,
9378                                 IdentifierInfo *NamespcName,
9379                                 const ParsedAttributesView &AttrList) {
9380   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9381   assert(NamespcName && "Invalid NamespcName.");
9382   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9383 
9384   // This can only happen along a recovery path.
9385   while (S->isTemplateParamScope())
9386     S = S->getParent();
9387   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9388 
9389   UsingDirectiveDecl *UDir = nullptr;
9390   NestedNameSpecifier *Qualifier = nullptr;
9391   if (SS.isSet())
9392     Qualifier = SS.getScopeRep();
9393 
9394   // Lookup namespace name.
9395   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9396   LookupParsedName(R, S, &SS);
9397   if (R.isAmbiguous())
9398     return nullptr;
9399 
9400   if (R.empty()) {
9401     R.clear();
9402     // Allow "using namespace std;" or "using namespace ::std;" even if
9403     // "std" hasn't been defined yet, for GCC compatibility.
9404     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9405         NamespcName->isStr("std")) {
9406       Diag(IdentLoc, diag::ext_using_undefined_std);
9407       R.addDecl(getOrCreateStdNamespace());
9408       R.resolveKind();
9409     }
9410     // Otherwise, attempt typo correction.
9411     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9412   }
9413 
9414   if (!R.empty()) {
9415     NamedDecl *Named = R.getRepresentativeDecl();
9416     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9417     assert(NS && "expected namespace decl");
9418 
9419     // The use of a nested name specifier may trigger deprecation warnings.
9420     DiagnoseUseOfDecl(Named, IdentLoc);
9421 
9422     // C++ [namespace.udir]p1:
9423     //   A using-directive specifies that the names in the nominated
9424     //   namespace can be used in the scope in which the
9425     //   using-directive appears after the using-directive. During
9426     //   unqualified name lookup (3.4.1), the names appear as if they
9427     //   were declared in the nearest enclosing namespace which
9428     //   contains both the using-directive and the nominated
9429     //   namespace. [Note: in this context, "contains" means "contains
9430     //   directly or indirectly". ]
9431 
9432     // Find enclosing context containing both using-directive and
9433     // nominated namespace.
9434     DeclContext *CommonAncestor = NS;
9435     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9436       CommonAncestor = CommonAncestor->getParent();
9437 
9438     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9439                                       SS.getWithLocInContext(Context),
9440                                       IdentLoc, Named, CommonAncestor);
9441 
9442     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9443         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9444       Diag(IdentLoc, diag::warn_using_directive_in_header);
9445     }
9446 
9447     PushUsingDirective(S, UDir);
9448   } else {
9449     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9450   }
9451 
9452   if (UDir)
9453     ProcessDeclAttributeList(S, UDir, AttrList);
9454 
9455   return UDir;
9456 }
9457 
9458 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9459   // If the scope has an associated entity and the using directive is at
9460   // namespace or translation unit scope, add the UsingDirectiveDecl into
9461   // its lookup structure so qualified name lookup can find it.
9462   DeclContext *Ctx = S->getEntity();
9463   if (Ctx && !Ctx->isFunctionOrMethod())
9464     Ctx->addDecl(UDir);
9465   else
9466     // Otherwise, it is at block scope. The using-directives will affect lookup
9467     // only to the end of the scope.
9468     S->PushUsingDirective(UDir);
9469 }
9470 
9471 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9472                                   SourceLocation UsingLoc,
9473                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
9474                                   UnqualifiedId &Name,
9475                                   SourceLocation EllipsisLoc,
9476                                   const ParsedAttributesView &AttrList) {
9477   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9478 
9479   if (SS.isEmpty()) {
9480     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9481     return nullptr;
9482   }
9483 
9484   switch (Name.getKind()) {
9485   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9486   case UnqualifiedIdKind::IK_Identifier:
9487   case UnqualifiedIdKind::IK_OperatorFunctionId:
9488   case UnqualifiedIdKind::IK_LiteralOperatorId:
9489   case UnqualifiedIdKind::IK_ConversionFunctionId:
9490     break;
9491 
9492   case UnqualifiedIdKind::IK_ConstructorName:
9493   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9494     // C++11 inheriting constructors.
9495     Diag(Name.getBeginLoc(),
9496          getLangOpts().CPlusPlus11
9497              ? diag::warn_cxx98_compat_using_decl_constructor
9498              : diag::err_using_decl_constructor)
9499         << SS.getRange();
9500 
9501     if (getLangOpts().CPlusPlus11) break;
9502 
9503     return nullptr;
9504 
9505   case UnqualifiedIdKind::IK_DestructorName:
9506     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9507     return nullptr;
9508 
9509   case UnqualifiedIdKind::IK_TemplateId:
9510     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9511         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9512     return nullptr;
9513 
9514   case UnqualifiedIdKind::IK_DeductionGuideName:
9515     llvm_unreachable("cannot parse qualified deduction guide name");
9516   }
9517 
9518   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9519   DeclarationName TargetName = TargetNameInfo.getName();
9520   if (!TargetName)
9521     return nullptr;
9522 
9523   // Warn about access declarations.
9524   if (UsingLoc.isInvalid()) {
9525     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9526                                  ? diag::err_access_decl
9527                                  : diag::warn_access_decl_deprecated)
9528         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9529   }
9530 
9531   if (EllipsisLoc.isInvalid()) {
9532     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9533         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9534       return nullptr;
9535   } else {
9536     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9537         !TargetNameInfo.containsUnexpandedParameterPack()) {
9538       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9539         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9540       EllipsisLoc = SourceLocation();
9541     }
9542   }
9543 
9544   NamedDecl *UD =
9545       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9546                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9547                             /*IsInstantiation*/false);
9548   if (UD)
9549     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9550 
9551   return UD;
9552 }
9553 
9554 /// Determine whether a using declaration considers the given
9555 /// declarations as "equivalent", e.g., if they are redeclarations of
9556 /// the same entity or are both typedefs of the same type.
9557 static bool
9558 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9559   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9560     return true;
9561 
9562   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9563     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9564       return Context.hasSameType(TD1->getUnderlyingType(),
9565                                  TD2->getUnderlyingType());
9566 
9567   return false;
9568 }
9569 
9570 
9571 /// Determines whether to create a using shadow decl for a particular
9572 /// decl, given the set of decls existing prior to this using lookup.
9573 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9574                                 const LookupResult &Previous,
9575                                 UsingShadowDecl *&PrevShadow) {
9576   // Diagnose finding a decl which is not from a base class of the
9577   // current class.  We do this now because there are cases where this
9578   // function will silently decide not to build a shadow decl, which
9579   // will pre-empt further diagnostics.
9580   //
9581   // We don't need to do this in C++11 because we do the check once on
9582   // the qualifier.
9583   //
9584   // FIXME: diagnose the following if we care enough:
9585   //   struct A { int foo; };
9586   //   struct B : A { using A::foo; };
9587   //   template <class T> struct C : A {};
9588   //   template <class T> struct D : C<T> { using B::foo; } // <---
9589   // This is invalid (during instantiation) in C++03 because B::foo
9590   // resolves to the using decl in B, which is not a base class of D<T>.
9591   // We can't diagnose it immediately because C<T> is an unknown
9592   // specialization.  The UsingShadowDecl in D<T> then points directly
9593   // to A::foo, which will look well-formed when we instantiate.
9594   // The right solution is to not collapse the shadow-decl chain.
9595   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9596     DeclContext *OrigDC = Orig->getDeclContext();
9597 
9598     // Handle enums and anonymous structs.
9599     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9600     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9601     while (OrigRec->isAnonymousStructOrUnion())
9602       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9603 
9604     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9605       if (OrigDC == CurContext) {
9606         Diag(Using->getLocation(),
9607              diag::err_using_decl_nested_name_specifier_is_current_class)
9608           << Using->getQualifierLoc().getSourceRange();
9609         Diag(Orig->getLocation(), diag::note_using_decl_target);
9610         Using->setInvalidDecl();
9611         return true;
9612       }
9613 
9614       Diag(Using->getQualifierLoc().getBeginLoc(),
9615            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9616         << Using->getQualifier()
9617         << cast<CXXRecordDecl>(CurContext)
9618         << Using->getQualifierLoc().getSourceRange();
9619       Diag(Orig->getLocation(), diag::note_using_decl_target);
9620       Using->setInvalidDecl();
9621       return true;
9622     }
9623   }
9624 
9625   if (Previous.empty()) return false;
9626 
9627   NamedDecl *Target = Orig;
9628   if (isa<UsingShadowDecl>(Target))
9629     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9630 
9631   // If the target happens to be one of the previous declarations, we
9632   // don't have a conflict.
9633   //
9634   // FIXME: but we might be increasing its access, in which case we
9635   // should redeclare it.
9636   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9637   bool FoundEquivalentDecl = false;
9638   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9639          I != E; ++I) {
9640     NamedDecl *D = (*I)->getUnderlyingDecl();
9641     // We can have UsingDecls in our Previous results because we use the same
9642     // LookupResult for checking whether the UsingDecl itself is a valid
9643     // redeclaration.
9644     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9645       continue;
9646 
9647     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9648       // C++ [class.mem]p19:
9649       //   If T is the name of a class, then [every named member other than
9650       //   a non-static data member] shall have a name different from T
9651       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9652           !isa<IndirectFieldDecl>(Target) &&
9653           !isa<UnresolvedUsingValueDecl>(Target) &&
9654           DiagnoseClassNameShadow(
9655               CurContext,
9656               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9657         return true;
9658     }
9659 
9660     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9661       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9662         PrevShadow = Shadow;
9663       FoundEquivalentDecl = true;
9664     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9665       // We don't conflict with an existing using shadow decl of an equivalent
9666       // declaration, but we're not a redeclaration of it.
9667       FoundEquivalentDecl = true;
9668     }
9669 
9670     if (isVisible(D))
9671       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9672   }
9673 
9674   if (FoundEquivalentDecl)
9675     return false;
9676 
9677   if (FunctionDecl *FD = Target->getAsFunction()) {
9678     NamedDecl *OldDecl = nullptr;
9679     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9680                           /*IsForUsingDecl*/ true)) {
9681     case Ovl_Overload:
9682       return false;
9683 
9684     case Ovl_NonFunction:
9685       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9686       break;
9687 
9688     // We found a decl with the exact signature.
9689     case Ovl_Match:
9690       // If we're in a record, we want to hide the target, so we
9691       // return true (without a diagnostic) to tell the caller not to
9692       // build a shadow decl.
9693       if (CurContext->isRecord())
9694         return true;
9695 
9696       // If we're not in a record, this is an error.
9697       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9698       break;
9699     }
9700 
9701     Diag(Target->getLocation(), diag::note_using_decl_target);
9702     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9703     Using->setInvalidDecl();
9704     return true;
9705   }
9706 
9707   // Target is not a function.
9708 
9709   if (isa<TagDecl>(Target)) {
9710     // No conflict between a tag and a non-tag.
9711     if (!Tag) return false;
9712 
9713     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9714     Diag(Target->getLocation(), diag::note_using_decl_target);
9715     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9716     Using->setInvalidDecl();
9717     return true;
9718   }
9719 
9720   // No conflict between a tag and a non-tag.
9721   if (!NonTag) return false;
9722 
9723   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9724   Diag(Target->getLocation(), diag::note_using_decl_target);
9725   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9726   Using->setInvalidDecl();
9727   return true;
9728 }
9729 
9730 /// Determine whether a direct base class is a virtual base class.
9731 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9732   if (!Derived->getNumVBases())
9733     return false;
9734   for (auto &B : Derived->bases())
9735     if (B.getType()->getAsCXXRecordDecl() == Base)
9736       return B.isVirtual();
9737   llvm_unreachable("not a direct base class");
9738 }
9739 
9740 /// Builds a shadow declaration corresponding to a 'using' declaration.
9741 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9742                                             UsingDecl *UD,
9743                                             NamedDecl *Orig,
9744                                             UsingShadowDecl *PrevDecl) {
9745   // If we resolved to another shadow declaration, just coalesce them.
9746   NamedDecl *Target = Orig;
9747   if (isa<UsingShadowDecl>(Target)) {
9748     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9749     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9750   }
9751 
9752   NamedDecl *NonTemplateTarget = Target;
9753   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9754     NonTemplateTarget = TargetTD->getTemplatedDecl();
9755 
9756   UsingShadowDecl *Shadow;
9757   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9758     bool IsVirtualBase =
9759         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9760                             UD->getQualifier()->getAsRecordDecl());
9761     Shadow = ConstructorUsingShadowDecl::Create(
9762         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9763   } else {
9764     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9765                                      Target);
9766   }
9767   UD->addShadowDecl(Shadow);
9768 
9769   Shadow->setAccess(UD->getAccess());
9770   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9771     Shadow->setInvalidDecl();
9772 
9773   Shadow->setPreviousDecl(PrevDecl);
9774 
9775   if (S)
9776     PushOnScopeChains(Shadow, S);
9777   else
9778     CurContext->addDecl(Shadow);
9779 
9780 
9781   return Shadow;
9782 }
9783 
9784 /// Hides a using shadow declaration.  This is required by the current
9785 /// using-decl implementation when a resolvable using declaration in a
9786 /// class is followed by a declaration which would hide or override
9787 /// one or more of the using decl's targets; for example:
9788 ///
9789 ///   struct Base { void foo(int); };
9790 ///   struct Derived : Base {
9791 ///     using Base::foo;
9792 ///     void foo(int);
9793 ///   };
9794 ///
9795 /// The governing language is C++03 [namespace.udecl]p12:
9796 ///
9797 ///   When a using-declaration brings names from a base class into a
9798 ///   derived class scope, member functions in the derived class
9799 ///   override and/or hide member functions with the same name and
9800 ///   parameter types in a base class (rather than conflicting).
9801 ///
9802 /// There are two ways to implement this:
9803 ///   (1) optimistically create shadow decls when they're not hidden
9804 ///       by existing declarations, or
9805 ///   (2) don't create any shadow decls (or at least don't make them
9806 ///       visible) until we've fully parsed/instantiated the class.
9807 /// The problem with (1) is that we might have to retroactively remove
9808 /// a shadow decl, which requires several O(n) operations because the
9809 /// decl structures are (very reasonably) not designed for removal.
9810 /// (2) avoids this but is very fiddly and phase-dependent.
9811 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9812   if (Shadow->getDeclName().getNameKind() ==
9813         DeclarationName::CXXConversionFunctionName)
9814     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9815 
9816   // Remove it from the DeclContext...
9817   Shadow->getDeclContext()->removeDecl(Shadow);
9818 
9819   // ...and the scope, if applicable...
9820   if (S) {
9821     S->RemoveDecl(Shadow);
9822     IdResolver.RemoveDecl(Shadow);
9823   }
9824 
9825   // ...and the using decl.
9826   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9827 
9828   // TODO: complain somehow if Shadow was used.  It shouldn't
9829   // be possible for this to happen, because...?
9830 }
9831 
9832 /// Find the base specifier for a base class with the given type.
9833 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9834                                                 QualType DesiredBase,
9835                                                 bool &AnyDependentBases) {
9836   // Check whether the named type is a direct base class.
9837   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9838   for (auto &Base : Derived->bases()) {
9839     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9840     if (CanonicalDesiredBase == BaseType)
9841       return &Base;
9842     if (BaseType->isDependentType())
9843       AnyDependentBases = true;
9844   }
9845   return nullptr;
9846 }
9847 
9848 namespace {
9849 class UsingValidatorCCC final : public CorrectionCandidateCallback {
9850 public:
9851   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9852                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9853       : HasTypenameKeyword(HasTypenameKeyword),
9854         IsInstantiation(IsInstantiation), OldNNS(NNS),
9855         RequireMemberOf(RequireMemberOf) {}
9856 
9857   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9858     NamedDecl *ND = Candidate.getCorrectionDecl();
9859 
9860     // Keywords are not valid here.
9861     if (!ND || isa<NamespaceDecl>(ND))
9862       return false;
9863 
9864     // Completely unqualified names are invalid for a 'using' declaration.
9865     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9866       return false;
9867 
9868     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9869     // reject.
9870 
9871     if (RequireMemberOf) {
9872       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9873       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9874         // No-one ever wants a using-declaration to name an injected-class-name
9875         // of a base class, unless they're declaring an inheriting constructor.
9876         ASTContext &Ctx = ND->getASTContext();
9877         if (!Ctx.getLangOpts().CPlusPlus11)
9878           return false;
9879         QualType FoundType = Ctx.getRecordType(FoundRecord);
9880 
9881         // Check that the injected-class-name is named as a member of its own
9882         // type; we don't want to suggest 'using Derived::Base;', since that
9883         // means something else.
9884         NestedNameSpecifier *Specifier =
9885             Candidate.WillReplaceSpecifier()
9886                 ? Candidate.getCorrectionSpecifier()
9887                 : OldNNS;
9888         if (!Specifier->getAsType() ||
9889             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9890           return false;
9891 
9892         // Check that this inheriting constructor declaration actually names a
9893         // direct base class of the current class.
9894         bool AnyDependentBases = false;
9895         if (!findDirectBaseWithType(RequireMemberOf,
9896                                     Ctx.getRecordType(FoundRecord),
9897                                     AnyDependentBases) &&
9898             !AnyDependentBases)
9899           return false;
9900       } else {
9901         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9902         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9903           return false;
9904 
9905         // FIXME: Check that the base class member is accessible?
9906       }
9907     } else {
9908       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9909       if (FoundRecord && FoundRecord->isInjectedClassName())
9910         return false;
9911     }
9912 
9913     if (isa<TypeDecl>(ND))
9914       return HasTypenameKeyword || !IsInstantiation;
9915 
9916     return !HasTypenameKeyword;
9917   }
9918 
9919   std::unique_ptr<CorrectionCandidateCallback> clone() override {
9920     return llvm::make_unique<UsingValidatorCCC>(*this);
9921   }
9922 
9923 private:
9924   bool HasTypenameKeyword;
9925   bool IsInstantiation;
9926   NestedNameSpecifier *OldNNS;
9927   CXXRecordDecl *RequireMemberOf;
9928 };
9929 } // end anonymous namespace
9930 
9931 /// Builds a using declaration.
9932 ///
9933 /// \param IsInstantiation - Whether this call arises from an
9934 ///   instantiation of an unresolved using declaration.  We treat
9935 ///   the lookup differently for these declarations.
9936 NamedDecl *Sema::BuildUsingDeclaration(
9937     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9938     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9939     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9940     const ParsedAttributesView &AttrList, bool IsInstantiation) {
9941   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9942   SourceLocation IdentLoc = NameInfo.getLoc();
9943   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9944 
9945   // FIXME: We ignore attributes for now.
9946 
9947   // For an inheriting constructor declaration, the name of the using
9948   // declaration is the name of a constructor in this class, not in the
9949   // base class.
9950   DeclarationNameInfo UsingName = NameInfo;
9951   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9952     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9953       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9954           Context.getCanonicalType(Context.getRecordType(RD))));
9955 
9956   // Do the redeclaration lookup in the current scope.
9957   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9958                         ForVisibleRedeclaration);
9959   Previous.setHideTags(false);
9960   if (S) {
9961     LookupName(Previous, S);
9962 
9963     // It is really dumb that we have to do this.
9964     LookupResult::Filter F = Previous.makeFilter();
9965     while (F.hasNext()) {
9966       NamedDecl *D = F.next();
9967       if (!isDeclInScope(D, CurContext, S))
9968         F.erase();
9969       // If we found a local extern declaration that's not ordinarily visible,
9970       // and this declaration is being added to a non-block scope, ignore it.
9971       // We're only checking for scope conflicts here, not also for violations
9972       // of the linkage rules.
9973       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9974                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9975         F.erase();
9976     }
9977     F.done();
9978   } else {
9979     assert(IsInstantiation && "no scope in non-instantiation");
9980     if (CurContext->isRecord())
9981       LookupQualifiedName(Previous, CurContext);
9982     else {
9983       // No redeclaration check is needed here; in non-member contexts we
9984       // diagnosed all possible conflicts with other using-declarations when
9985       // building the template:
9986       //
9987       // For a dependent non-type using declaration, the only valid case is
9988       // if we instantiate to a single enumerator. We check for conflicts
9989       // between shadow declarations we introduce, and we check in the template
9990       // definition for conflicts between a non-type using declaration and any
9991       // other declaration, which together covers all cases.
9992       //
9993       // A dependent typename using declaration will never successfully
9994       // instantiate, since it will always name a class member, so we reject
9995       // that in the template definition.
9996     }
9997   }
9998 
9999   // Check for invalid redeclarations.
10000   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
10001                                   SS, IdentLoc, Previous))
10002     return nullptr;
10003 
10004   // Check for bad qualifiers.
10005   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
10006                               IdentLoc))
10007     return nullptr;
10008 
10009   DeclContext *LookupContext = computeDeclContext(SS);
10010   NamedDecl *D;
10011   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10012   if (!LookupContext || EllipsisLoc.isValid()) {
10013     if (HasTypenameKeyword) {
10014       // FIXME: not all declaration name kinds are legal here
10015       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
10016                                               UsingLoc, TypenameLoc,
10017                                               QualifierLoc,
10018                                               IdentLoc, NameInfo.getName(),
10019                                               EllipsisLoc);
10020     } else {
10021       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
10022                                            QualifierLoc, NameInfo, EllipsisLoc);
10023     }
10024     D->setAccess(AS);
10025     CurContext->addDecl(D);
10026     return D;
10027   }
10028 
10029   auto Build = [&](bool Invalid) {
10030     UsingDecl *UD =
10031         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10032                           UsingName, HasTypenameKeyword);
10033     UD->setAccess(AS);
10034     CurContext->addDecl(UD);
10035     UD->setInvalidDecl(Invalid);
10036     return UD;
10037   };
10038   auto BuildInvalid = [&]{ return Build(true); };
10039   auto BuildValid = [&]{ return Build(false); };
10040 
10041   if (RequireCompleteDeclContext(SS, LookupContext))
10042     return BuildInvalid();
10043 
10044   // Look up the target name.
10045   LookupResult R(*this, NameInfo, LookupOrdinaryName);
10046 
10047   // Unlike most lookups, we don't always want to hide tag
10048   // declarations: tag names are visible through the using declaration
10049   // even if hidden by ordinary names, *except* in a dependent context
10050   // where it's important for the sanity of two-phase lookup.
10051   if (!IsInstantiation)
10052     R.setHideTags(false);
10053 
10054   // For the purposes of this lookup, we have a base object type
10055   // equal to that of the current context.
10056   if (CurContext->isRecord()) {
10057     R.setBaseObjectType(
10058                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10059   }
10060 
10061   LookupQualifiedName(R, LookupContext);
10062 
10063   // Try to correct typos if possible. If constructor name lookup finds no
10064   // results, that means the named class has no explicit constructors, and we
10065   // suppressed declaring implicit ones (probably because it's dependent or
10066   // invalid).
10067   if (R.empty() &&
10068       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10069     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10070     // it will believe that glibc provides a ::gets in cases where it does not,
10071     // and will try to pull it into namespace std with a using-declaration.
10072     // Just ignore the using-declaration in that case.
10073     auto *II = NameInfo.getName().getAsIdentifierInfo();
10074     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10075         CurContext->isStdNamespace() &&
10076         isa<TranslationUnitDecl>(LookupContext) &&
10077         getSourceManager().isInSystemHeader(UsingLoc))
10078       return nullptr;
10079     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10080                           dyn_cast<CXXRecordDecl>(CurContext));
10081     if (TypoCorrection Corrected =
10082             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
10083                         CTK_ErrorRecovery)) {
10084       // We reject candidates where DroppedSpecifier == true, hence the
10085       // literal '0' below.
10086       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10087                                 << NameInfo.getName() << LookupContext << 0
10088                                 << SS.getRange());
10089 
10090       // If we picked a correction with no attached Decl we can't do anything
10091       // useful with it, bail out.
10092       NamedDecl *ND = Corrected.getCorrectionDecl();
10093       if (!ND)
10094         return BuildInvalid();
10095 
10096       // If we corrected to an inheriting constructor, handle it as one.
10097       auto *RD = dyn_cast<CXXRecordDecl>(ND);
10098       if (RD && RD->isInjectedClassName()) {
10099         // The parent of the injected class name is the class itself.
10100         RD = cast<CXXRecordDecl>(RD->getParent());
10101 
10102         // Fix up the information we'll use to build the using declaration.
10103         if (Corrected.WillReplaceSpecifier()) {
10104           NestedNameSpecifierLocBuilder Builder;
10105           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10106                               QualifierLoc.getSourceRange());
10107           QualifierLoc = Builder.getWithLocInContext(Context);
10108         }
10109 
10110         // In this case, the name we introduce is the name of a derived class
10111         // constructor.
10112         auto *CurClass = cast<CXXRecordDecl>(CurContext);
10113         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10114             Context.getCanonicalType(Context.getRecordType(CurClass))));
10115         UsingName.setNamedTypeInfo(nullptr);
10116         for (auto *Ctor : LookupConstructors(RD))
10117           R.addDecl(Ctor);
10118         R.resolveKind();
10119       } else {
10120         // FIXME: Pick up all the declarations if we found an overloaded
10121         // function.
10122         UsingName.setName(ND->getDeclName());
10123         R.addDecl(ND);
10124       }
10125     } else {
10126       Diag(IdentLoc, diag::err_no_member)
10127         << NameInfo.getName() << LookupContext << SS.getRange();
10128       return BuildInvalid();
10129     }
10130   }
10131 
10132   if (R.isAmbiguous())
10133     return BuildInvalid();
10134 
10135   if (HasTypenameKeyword) {
10136     // If we asked for a typename and got a non-type decl, error out.
10137     if (!R.getAsSingle<TypeDecl>()) {
10138       Diag(IdentLoc, diag::err_using_typename_non_type);
10139       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10140         Diag((*I)->getUnderlyingDecl()->getLocation(),
10141              diag::note_using_decl_target);
10142       return BuildInvalid();
10143     }
10144   } else {
10145     // If we asked for a non-typename and we got a type, error out,
10146     // but only if this is an instantiation of an unresolved using
10147     // decl.  Otherwise just silently find the type name.
10148     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10149       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10150       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10151       return BuildInvalid();
10152     }
10153   }
10154 
10155   // C++14 [namespace.udecl]p6:
10156   // A using-declaration shall not name a namespace.
10157   if (R.getAsSingle<NamespaceDecl>()) {
10158     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10159       << SS.getRange();
10160     return BuildInvalid();
10161   }
10162 
10163   // C++14 [namespace.udecl]p7:
10164   // A using-declaration shall not name a scoped enumerator.
10165   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10166     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10167       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10168         << SS.getRange();
10169       return BuildInvalid();
10170     }
10171   }
10172 
10173   UsingDecl *UD = BuildValid();
10174 
10175   // Some additional rules apply to inheriting constructors.
10176   if (UsingName.getName().getNameKind() ==
10177         DeclarationName::CXXConstructorName) {
10178     // Suppress access diagnostics; the access check is instead performed at the
10179     // point of use for an inheriting constructor.
10180     R.suppressDiagnostics();
10181     if (CheckInheritingConstructorUsingDecl(UD))
10182       return UD;
10183   }
10184 
10185   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10186     UsingShadowDecl *PrevDecl = nullptr;
10187     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10188       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10189   }
10190 
10191   return UD;
10192 }
10193 
10194 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10195                                     ArrayRef<NamedDecl *> Expansions) {
10196   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10197          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10198          isa<UsingPackDecl>(InstantiatedFrom));
10199 
10200   auto *UPD =
10201       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10202   UPD->setAccess(InstantiatedFrom->getAccess());
10203   CurContext->addDecl(UPD);
10204   return UPD;
10205 }
10206 
10207 /// Additional checks for a using declaration referring to a constructor name.
10208 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10209   assert(!UD->hasTypename() && "expecting a constructor name");
10210 
10211   const Type *SourceType = UD->getQualifier()->getAsType();
10212   assert(SourceType &&
10213          "Using decl naming constructor doesn't have type in scope spec.");
10214   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10215 
10216   // Check whether the named type is a direct base class.
10217   bool AnyDependentBases = false;
10218   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10219                                       AnyDependentBases);
10220   if (!Base && !AnyDependentBases) {
10221     Diag(UD->getUsingLoc(),
10222          diag::err_using_decl_constructor_not_in_direct_base)
10223       << UD->getNameInfo().getSourceRange()
10224       << QualType(SourceType, 0) << TargetClass;
10225     UD->setInvalidDecl();
10226     return true;
10227   }
10228 
10229   if (Base)
10230     Base->setInheritConstructors();
10231 
10232   return false;
10233 }
10234 
10235 /// Checks that the given using declaration is not an invalid
10236 /// redeclaration.  Note that this is checking only for the using decl
10237 /// itself, not for any ill-formedness among the UsingShadowDecls.
10238 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10239                                        bool HasTypenameKeyword,
10240                                        const CXXScopeSpec &SS,
10241                                        SourceLocation NameLoc,
10242                                        const LookupResult &Prev) {
10243   NestedNameSpecifier *Qual = SS.getScopeRep();
10244 
10245   // C++03 [namespace.udecl]p8:
10246   // C++0x [namespace.udecl]p10:
10247   //   A using-declaration is a declaration and can therefore be used
10248   //   repeatedly where (and only where) multiple declarations are
10249   //   allowed.
10250   //
10251   // That's in non-member contexts.
10252   if (!CurContext->getRedeclContext()->isRecord()) {
10253     // A dependent qualifier outside a class can only ever resolve to an
10254     // enumeration type. Therefore it conflicts with any other non-type
10255     // declaration in the same scope.
10256     // FIXME: How should we check for dependent type-type conflicts at block
10257     // scope?
10258     if (Qual->isDependent() && !HasTypenameKeyword) {
10259       for (auto *D : Prev) {
10260         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10261           bool OldCouldBeEnumerator =
10262               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10263           Diag(NameLoc,
10264                OldCouldBeEnumerator ? diag::err_redefinition
10265                                     : diag::err_redefinition_different_kind)
10266               << Prev.getLookupName();
10267           Diag(D->getLocation(), diag::note_previous_definition);
10268           return true;
10269         }
10270       }
10271     }
10272     return false;
10273   }
10274 
10275   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10276     NamedDecl *D = *I;
10277 
10278     bool DTypename;
10279     NestedNameSpecifier *DQual;
10280     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10281       DTypename = UD->hasTypename();
10282       DQual = UD->getQualifier();
10283     } else if (UnresolvedUsingValueDecl *UD
10284                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10285       DTypename = false;
10286       DQual = UD->getQualifier();
10287     } else if (UnresolvedUsingTypenameDecl *UD
10288                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10289       DTypename = true;
10290       DQual = UD->getQualifier();
10291     } else continue;
10292 
10293     // using decls differ if one says 'typename' and the other doesn't.
10294     // FIXME: non-dependent using decls?
10295     if (HasTypenameKeyword != DTypename) continue;
10296 
10297     // using decls differ if they name different scopes (but note that
10298     // template instantiation can cause this check to trigger when it
10299     // didn't before instantiation).
10300     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10301         Context.getCanonicalNestedNameSpecifier(DQual))
10302       continue;
10303 
10304     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10305     Diag(D->getLocation(), diag::note_using_decl) << 1;
10306     return true;
10307   }
10308 
10309   return false;
10310 }
10311 
10312 
10313 /// Checks that the given nested-name qualifier used in a using decl
10314 /// in the current context is appropriately related to the current
10315 /// scope.  If an error is found, diagnoses it and returns true.
10316 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10317                                    bool HasTypename,
10318                                    const CXXScopeSpec &SS,
10319                                    const DeclarationNameInfo &NameInfo,
10320                                    SourceLocation NameLoc) {
10321   DeclContext *NamedContext = computeDeclContext(SS);
10322 
10323   if (!CurContext->isRecord()) {
10324     // C++03 [namespace.udecl]p3:
10325     // C++0x [namespace.udecl]p8:
10326     //   A using-declaration for a class member shall be a member-declaration.
10327 
10328     // If we weren't able to compute a valid scope, it might validly be a
10329     // dependent class scope or a dependent enumeration unscoped scope. If
10330     // we have a 'typename' keyword, the scope must resolve to a class type.
10331     if ((HasTypename && !NamedContext) ||
10332         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10333       auto *RD = NamedContext
10334                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10335                      : nullptr;
10336       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10337         RD = nullptr;
10338 
10339       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10340         << SS.getRange();
10341 
10342       // If we have a complete, non-dependent source type, try to suggest a
10343       // way to get the same effect.
10344       if (!RD)
10345         return true;
10346 
10347       // Find what this using-declaration was referring to.
10348       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10349       R.setHideTags(false);
10350       R.suppressDiagnostics();
10351       LookupQualifiedName(R, RD);
10352 
10353       if (R.getAsSingle<TypeDecl>()) {
10354         if (getLangOpts().CPlusPlus11) {
10355           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10356           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10357             << 0 // alias declaration
10358             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10359                                           NameInfo.getName().getAsString() +
10360                                               " = ");
10361         } else {
10362           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10363           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10364           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10365             << 1 // typedef declaration
10366             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10367             << FixItHint::CreateInsertion(
10368                    InsertLoc, " " + NameInfo.getName().getAsString());
10369         }
10370       } else if (R.getAsSingle<VarDecl>()) {
10371         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10372         // repeating the type of the static data member here.
10373         FixItHint FixIt;
10374         if (getLangOpts().CPlusPlus11) {
10375           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10376           FixIt = FixItHint::CreateReplacement(
10377               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10378         }
10379 
10380         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10381           << 2 // reference declaration
10382           << FixIt;
10383       } else if (R.getAsSingle<EnumConstantDecl>()) {
10384         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10385         // repeating the type of the enumeration here, and we can't do so if
10386         // the type is anonymous.
10387         FixItHint FixIt;
10388         if (getLangOpts().CPlusPlus11) {
10389           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10390           FixIt = FixItHint::CreateReplacement(
10391               UsingLoc,
10392               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10393         }
10394 
10395         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10396           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10397           << FixIt;
10398       }
10399       return true;
10400     }
10401 
10402     // Otherwise, this might be valid.
10403     return false;
10404   }
10405 
10406   // The current scope is a record.
10407 
10408   // If the named context is dependent, we can't decide much.
10409   if (!NamedContext) {
10410     // FIXME: in C++0x, we can diagnose if we can prove that the
10411     // nested-name-specifier does not refer to a base class, which is
10412     // still possible in some cases.
10413 
10414     // Otherwise we have to conservatively report that things might be
10415     // okay.
10416     return false;
10417   }
10418 
10419   if (!NamedContext->isRecord()) {
10420     // Ideally this would point at the last name in the specifier,
10421     // but we don't have that level of source info.
10422     Diag(SS.getRange().getBegin(),
10423          diag::err_using_decl_nested_name_specifier_is_not_class)
10424       << SS.getScopeRep() << SS.getRange();
10425     return true;
10426   }
10427 
10428   if (!NamedContext->isDependentContext() &&
10429       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10430     return true;
10431 
10432   if (getLangOpts().CPlusPlus11) {
10433     // C++11 [namespace.udecl]p3:
10434     //   In a using-declaration used as a member-declaration, the
10435     //   nested-name-specifier shall name a base class of the class
10436     //   being defined.
10437 
10438     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10439                                  cast<CXXRecordDecl>(NamedContext))) {
10440       if (CurContext == NamedContext) {
10441         Diag(NameLoc,
10442              diag::err_using_decl_nested_name_specifier_is_current_class)
10443           << SS.getRange();
10444         return true;
10445       }
10446 
10447       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10448         Diag(SS.getRange().getBegin(),
10449              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10450           << SS.getScopeRep()
10451           << cast<CXXRecordDecl>(CurContext)
10452           << SS.getRange();
10453       }
10454       return true;
10455     }
10456 
10457     return false;
10458   }
10459 
10460   // C++03 [namespace.udecl]p4:
10461   //   A using-declaration used as a member-declaration shall refer
10462   //   to a member of a base class of the class being defined [etc.].
10463 
10464   // Salient point: SS doesn't have to name a base class as long as
10465   // lookup only finds members from base classes.  Therefore we can
10466   // diagnose here only if we can prove that that can't happen,
10467   // i.e. if the class hierarchies provably don't intersect.
10468 
10469   // TODO: it would be nice if "definitely valid" results were cached
10470   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10471   // need to be repeated.
10472 
10473   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10474   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10475     Bases.insert(Base);
10476     return true;
10477   };
10478 
10479   // Collect all bases. Return false if we find a dependent base.
10480   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10481     return false;
10482 
10483   // Returns true if the base is dependent or is one of the accumulated base
10484   // classes.
10485   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10486     return !Bases.count(Base);
10487   };
10488 
10489   // Return false if the class has a dependent base or if it or one
10490   // of its bases is present in the base set of the current context.
10491   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10492       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10493     return false;
10494 
10495   Diag(SS.getRange().getBegin(),
10496        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10497     << SS.getScopeRep()
10498     << cast<CXXRecordDecl>(CurContext)
10499     << SS.getRange();
10500 
10501   return true;
10502 }
10503 
10504 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10505                                   MultiTemplateParamsArg TemplateParamLists,
10506                                   SourceLocation UsingLoc, UnqualifiedId &Name,
10507                                   const ParsedAttributesView &AttrList,
10508                                   TypeResult Type, Decl *DeclFromDeclSpec) {
10509   // Skip up to the relevant declaration scope.
10510   while (S->isTemplateParamScope())
10511     S = S->getParent();
10512   assert((S->getFlags() & Scope::DeclScope) &&
10513          "got alias-declaration outside of declaration scope");
10514 
10515   if (Type.isInvalid())
10516     return nullptr;
10517 
10518   bool Invalid = false;
10519   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10520   TypeSourceInfo *TInfo = nullptr;
10521   GetTypeFromParser(Type.get(), &TInfo);
10522 
10523   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10524     return nullptr;
10525 
10526   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10527                                       UPPC_DeclarationType)) {
10528     Invalid = true;
10529     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10530                                              TInfo->getTypeLoc().getBeginLoc());
10531   }
10532 
10533   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10534                         TemplateParamLists.size()
10535                             ? forRedeclarationInCurContext()
10536                             : ForVisibleRedeclaration);
10537   LookupName(Previous, S);
10538 
10539   // Warn about shadowing the name of a template parameter.
10540   if (Previous.isSingleResult() &&
10541       Previous.getFoundDecl()->isTemplateParameter()) {
10542     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10543     Previous.clear();
10544   }
10545 
10546   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10547          "name in alias declaration must be an identifier");
10548   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10549                                                Name.StartLocation,
10550                                                Name.Identifier, TInfo);
10551 
10552   NewTD->setAccess(AS);
10553 
10554   if (Invalid)
10555     NewTD->setInvalidDecl();
10556 
10557   ProcessDeclAttributeList(S, NewTD, AttrList);
10558   AddPragmaAttributes(S, NewTD);
10559 
10560   CheckTypedefForVariablyModifiedType(S, NewTD);
10561   Invalid |= NewTD->isInvalidDecl();
10562 
10563   bool Redeclaration = false;
10564 
10565   NamedDecl *NewND;
10566   if (TemplateParamLists.size()) {
10567     TypeAliasTemplateDecl *OldDecl = nullptr;
10568     TemplateParameterList *OldTemplateParams = nullptr;
10569 
10570     if (TemplateParamLists.size() != 1) {
10571       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10572         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10573          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10574     }
10575     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10576 
10577     // Check that we can declare a template here.
10578     if (CheckTemplateDeclScope(S, TemplateParams))
10579       return nullptr;
10580 
10581     // Only consider previous declarations in the same scope.
10582     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10583                          /*ExplicitInstantiationOrSpecialization*/false);
10584     if (!Previous.empty()) {
10585       Redeclaration = true;
10586 
10587       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10588       if (!OldDecl && !Invalid) {
10589         Diag(UsingLoc, diag::err_redefinition_different_kind)
10590           << Name.Identifier;
10591 
10592         NamedDecl *OldD = Previous.getRepresentativeDecl();
10593         if (OldD->getLocation().isValid())
10594           Diag(OldD->getLocation(), diag::note_previous_definition);
10595 
10596         Invalid = true;
10597       }
10598 
10599       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10600         if (TemplateParameterListsAreEqual(TemplateParams,
10601                                            OldDecl->getTemplateParameters(),
10602                                            /*Complain=*/true,
10603                                            TPL_TemplateMatch))
10604           OldTemplateParams =
10605               OldDecl->getMostRecentDecl()->getTemplateParameters();
10606         else
10607           Invalid = true;
10608 
10609         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10610         if (!Invalid &&
10611             !Context.hasSameType(OldTD->getUnderlyingType(),
10612                                  NewTD->getUnderlyingType())) {
10613           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10614           // but we can't reasonably accept it.
10615           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10616             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10617           if (OldTD->getLocation().isValid())
10618             Diag(OldTD->getLocation(), diag::note_previous_definition);
10619           Invalid = true;
10620         }
10621       }
10622     }
10623 
10624     // Merge any previous default template arguments into our parameters,
10625     // and check the parameter list.
10626     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10627                                    TPC_TypeAliasTemplate))
10628       return nullptr;
10629 
10630     TypeAliasTemplateDecl *NewDecl =
10631       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10632                                     Name.Identifier, TemplateParams,
10633                                     NewTD);
10634     NewTD->setDescribedAliasTemplate(NewDecl);
10635 
10636     NewDecl->setAccess(AS);
10637 
10638     if (Invalid)
10639       NewDecl->setInvalidDecl();
10640     else if (OldDecl) {
10641       NewDecl->setPreviousDecl(OldDecl);
10642       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10643     }
10644 
10645     NewND = NewDecl;
10646   } else {
10647     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10648       setTagNameForLinkagePurposes(TD, NewTD);
10649       handleTagNumbering(TD, S);
10650     }
10651     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10652     NewND = NewTD;
10653   }
10654 
10655   PushOnScopeChains(NewND, S);
10656   ActOnDocumentableDecl(NewND);
10657   return NewND;
10658 }
10659 
10660 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10661                                    SourceLocation AliasLoc,
10662                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10663                                    SourceLocation IdentLoc,
10664                                    IdentifierInfo *Ident) {
10665 
10666   // Lookup the namespace name.
10667   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10668   LookupParsedName(R, S, &SS);
10669 
10670   if (R.isAmbiguous())
10671     return nullptr;
10672 
10673   if (R.empty()) {
10674     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10675       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10676       return nullptr;
10677     }
10678   }
10679   assert(!R.isAmbiguous() && !R.empty());
10680   NamedDecl *ND = R.getRepresentativeDecl();
10681 
10682   // Check if we have a previous declaration with the same name.
10683   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10684                      ForVisibleRedeclaration);
10685   LookupName(PrevR, S);
10686 
10687   // Check we're not shadowing a template parameter.
10688   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10689     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10690     PrevR.clear();
10691   }
10692 
10693   // Filter out any other lookup result from an enclosing scope.
10694   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10695                        /*AllowInlineNamespace*/false);
10696 
10697   // Find the previous declaration and check that we can redeclare it.
10698   NamespaceAliasDecl *Prev = nullptr;
10699   if (PrevR.isSingleResult()) {
10700     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10701     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10702       // We already have an alias with the same name that points to the same
10703       // namespace; check that it matches.
10704       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10705         Prev = AD;
10706       } else if (isVisible(PrevDecl)) {
10707         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10708           << Alias;
10709         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10710           << AD->getNamespace();
10711         return nullptr;
10712       }
10713     } else if (isVisible(PrevDecl)) {
10714       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10715                             ? diag::err_redefinition
10716                             : diag::err_redefinition_different_kind;
10717       Diag(AliasLoc, DiagID) << Alias;
10718       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10719       return nullptr;
10720     }
10721   }
10722 
10723   // The use of a nested name specifier may trigger deprecation warnings.
10724   DiagnoseUseOfDecl(ND, IdentLoc);
10725 
10726   NamespaceAliasDecl *AliasDecl =
10727     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10728                                Alias, SS.getWithLocInContext(Context),
10729                                IdentLoc, ND);
10730   if (Prev)
10731     AliasDecl->setPreviousDecl(Prev);
10732 
10733   PushOnScopeChains(AliasDecl, S);
10734   return AliasDecl;
10735 }
10736 
10737 namespace {
10738 struct SpecialMemberExceptionSpecInfo
10739     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10740   SourceLocation Loc;
10741   Sema::ImplicitExceptionSpecification ExceptSpec;
10742 
10743   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10744                                  Sema::CXXSpecialMember CSM,
10745                                  Sema::InheritedConstructorInfo *ICI,
10746                                  SourceLocation Loc)
10747       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10748 
10749   bool visitBase(CXXBaseSpecifier *Base);
10750   bool visitField(FieldDecl *FD);
10751 
10752   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10753                            unsigned Quals);
10754 
10755   void visitSubobjectCall(Subobject Subobj,
10756                           Sema::SpecialMemberOverloadResult SMOR);
10757 };
10758 }
10759 
10760 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10761   auto *RT = Base->getType()->getAs<RecordType>();
10762   if (!RT)
10763     return false;
10764 
10765   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10766   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10767   if (auto *BaseCtor = SMOR.getMethod()) {
10768     visitSubobjectCall(Base, BaseCtor);
10769     return false;
10770   }
10771 
10772   visitClassSubobject(BaseClass, Base, 0);
10773   return false;
10774 }
10775 
10776 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10777   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10778     Expr *E = FD->getInClassInitializer();
10779     if (!E)
10780       // FIXME: It's a little wasteful to build and throw away a
10781       // CXXDefaultInitExpr here.
10782       // FIXME: We should have a single context note pointing at Loc, and
10783       // this location should be MD->getLocation() instead, since that's
10784       // the location where we actually use the default init expression.
10785       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10786     if (E)
10787       ExceptSpec.CalledExpr(E);
10788   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10789                             ->getAs<RecordType>()) {
10790     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10791                         FD->getType().getCVRQualifiers());
10792   }
10793   return false;
10794 }
10795 
10796 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10797                                                          Subobject Subobj,
10798                                                          unsigned Quals) {
10799   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10800   bool IsMutable = Field && Field->isMutable();
10801   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10802 }
10803 
10804 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10805     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10806   // Note, if lookup fails, it doesn't matter what exception specification we
10807   // choose because the special member will be deleted.
10808   if (CXXMethodDecl *MD = SMOR.getMethod())
10809     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10810 }
10811 
10812 namespace {
10813 /// RAII object to register a special member as being currently declared.
10814 struct ComputingExceptionSpec {
10815   Sema &S;
10816 
10817   ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
10818       : S(S) {
10819     Sema::CodeSynthesisContext Ctx;
10820     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
10821     Ctx.PointOfInstantiation = Loc;
10822     Ctx.Entity = MD;
10823     S.pushCodeSynthesisContext(Ctx);
10824   }
10825   ~ComputingExceptionSpec() {
10826     S.popCodeSynthesisContext();
10827   }
10828 };
10829 }
10830 
10831 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
10832   llvm::APSInt Result;
10833   ExprResult Converted = CheckConvertedConstantExpression(
10834       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
10835   ExplicitSpec.setExpr(Converted.get());
10836   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
10837     ExplicitSpec.setKind(Result.getBoolValue()
10838                              ? ExplicitSpecKind::ResolvedTrue
10839                              : ExplicitSpecKind::ResolvedFalse);
10840     return true;
10841   }
10842   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
10843   return false;
10844 }
10845 
10846 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
10847   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
10848   if (!ExplicitExpr->isTypeDependent())
10849     tryResolveExplicitSpecifier(ES);
10850   return ES;
10851 }
10852 
10853 static Sema::ImplicitExceptionSpecification
10854 ComputeDefaultedSpecialMemberExceptionSpec(
10855     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10856     Sema::InheritedConstructorInfo *ICI) {
10857   ComputingExceptionSpec CES(S, MD, Loc);
10858 
10859   CXXRecordDecl *ClassDecl = MD->getParent();
10860 
10861   // C++ [except.spec]p14:
10862   //   An implicitly declared special member function (Clause 12) shall have an
10863   //   exception-specification. [...]
10864   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
10865   if (ClassDecl->isInvalidDecl())
10866     return Info.ExceptSpec;
10867 
10868   // FIXME: If this diagnostic fires, we're probably missing a check for
10869   // attempting to resolve an exception specification before it's known
10870   // at a higher level.
10871   if (S.RequireCompleteType(MD->getLocation(),
10872                             S.Context.getRecordType(ClassDecl),
10873                             diag::err_exception_spec_incomplete_type))
10874     return Info.ExceptSpec;
10875 
10876   // C++1z [except.spec]p7:
10877   //   [Look for exceptions thrown by] a constructor selected [...] to
10878   //   initialize a potentially constructed subobject,
10879   // C++1z [except.spec]p8:
10880   //   The exception specification for an implicitly-declared destructor, or a
10881   //   destructor without a noexcept-specifier, is potentially-throwing if and
10882   //   only if any of the destructors for any of its potentially constructed
10883   //   subojects is potentially throwing.
10884   // FIXME: We respect the first rule but ignore the "potentially constructed"
10885   // in the second rule to resolve a core issue (no number yet) that would have
10886   // us reject:
10887   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10888   //   struct B : A {};
10889   //   struct C : B { void f(); };
10890   // ... due to giving B::~B() a non-throwing exception specification.
10891   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10892                                 : Info.VisitAllBases);
10893 
10894   return Info.ExceptSpec;
10895 }
10896 
10897 namespace {
10898 /// RAII object to register a special member as being currently declared.
10899 struct DeclaringSpecialMember {
10900   Sema &S;
10901   Sema::SpecialMemberDecl D;
10902   Sema::ContextRAII SavedContext;
10903   bool WasAlreadyBeingDeclared;
10904 
10905   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10906       : S(S), D(RD, CSM), SavedContext(S, RD) {
10907     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10908     if (WasAlreadyBeingDeclared)
10909       // This almost never happens, but if it does, ensure that our cache
10910       // doesn't contain a stale result.
10911       S.SpecialMemberCache.clear();
10912     else {
10913       // Register a note to be produced if we encounter an error while
10914       // declaring the special member.
10915       Sema::CodeSynthesisContext Ctx;
10916       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10917       // FIXME: We don't have a location to use here. Using the class's
10918       // location maintains the fiction that we declare all special members
10919       // with the class, but (1) it's not clear that lying about that helps our
10920       // users understand what's going on, and (2) there may be outer contexts
10921       // on the stack (some of which are relevant) and printing them exposes
10922       // our lies.
10923       Ctx.PointOfInstantiation = RD->getLocation();
10924       Ctx.Entity = RD;
10925       Ctx.SpecialMember = CSM;
10926       S.pushCodeSynthesisContext(Ctx);
10927     }
10928   }
10929   ~DeclaringSpecialMember() {
10930     if (!WasAlreadyBeingDeclared) {
10931       S.SpecialMembersBeingDeclared.erase(D);
10932       S.popCodeSynthesisContext();
10933     }
10934   }
10935 
10936   /// Are we already trying to declare this special member?
10937   bool isAlreadyBeingDeclared() const {
10938     return WasAlreadyBeingDeclared;
10939   }
10940 };
10941 }
10942 
10943 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10944   // Look up any existing declarations, but don't trigger declaration of all
10945   // implicit special members with this name.
10946   DeclarationName Name = FD->getDeclName();
10947   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10948                  ForExternalRedeclaration);
10949   for (auto *D : FD->getParent()->lookup(Name))
10950     if (auto *Acceptable = R.getAcceptableDecl(D))
10951       R.addDecl(Acceptable);
10952   R.resolveKind();
10953   R.suppressDiagnostics();
10954 
10955   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10956 }
10957 
10958 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
10959                                           QualType ResultTy,
10960                                           ArrayRef<QualType> Args) {
10961   // Build an exception specification pointing back at this constructor.
10962   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
10963 
10964   if (getLangOpts().OpenCLCPlusPlus) {
10965     // OpenCL: Implicitly defaulted special member are of the generic address
10966     // space.
10967     EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
10968   }
10969 
10970   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
10971   SpecialMem->setType(QT);
10972 }
10973 
10974 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10975                                                      CXXRecordDecl *ClassDecl) {
10976   // C++ [class.ctor]p5:
10977   //   A default constructor for a class X is a constructor of class X
10978   //   that can be called without an argument. If there is no
10979   //   user-declared constructor for class X, a default constructor is
10980   //   implicitly declared. An implicitly-declared default constructor
10981   //   is an inline public member of its class.
10982   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10983          "Should not build implicit default constructor!");
10984 
10985   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10986   if (DSM.isAlreadyBeingDeclared())
10987     return nullptr;
10988 
10989   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10990                                                      CXXDefaultConstructor,
10991                                                      false);
10992 
10993   // Create the actual constructor declaration.
10994   CanQualType ClassType
10995     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10996   SourceLocation ClassLoc = ClassDecl->getLocation();
10997   DeclarationName Name
10998     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10999   DeclarationNameInfo NameInfo(Name, ClassLoc);
11000   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
11001       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
11002       /*TInfo=*/nullptr, ExplicitSpecifier(),
11003       /*isInline=*/true, /*isImplicitlyDeclared=*/true, Constexpr);
11004   DefaultCon->setAccess(AS_public);
11005   DefaultCon->setDefaulted();
11006 
11007   if (getLangOpts().CUDA) {
11008     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
11009                                             DefaultCon,
11010                                             /* ConstRHS */ false,
11011                                             /* Diagnose */ false);
11012   }
11013 
11014   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
11015 
11016   // We don't need to use SpecialMemberIsTrivial here; triviality for default
11017   // constructors is easy to compute.
11018   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
11019 
11020   // Note that we have declared this constructor.
11021   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
11022 
11023   Scope *S = getScopeForContext(ClassDecl);
11024   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
11025 
11026   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
11027     SetDeclDeleted(DefaultCon, ClassLoc);
11028 
11029   if (S)
11030     PushOnScopeChains(DefaultCon, S, false);
11031   ClassDecl->addDecl(DefaultCon);
11032 
11033   return DefaultCon;
11034 }
11035 
11036 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
11037                                             CXXConstructorDecl *Constructor) {
11038   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
11039           !Constructor->doesThisDeclarationHaveABody() &&
11040           !Constructor->isDeleted()) &&
11041     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
11042   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11043     return;
11044 
11045   CXXRecordDecl *ClassDecl = Constructor->getParent();
11046   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
11047 
11048   SynthesizedFunctionScope Scope(*this, Constructor);
11049 
11050   // The exception specification is needed because we are defining the
11051   // function.
11052   ResolveExceptionSpec(CurrentLocation,
11053                        Constructor->getType()->castAs<FunctionProtoType>());
11054   MarkVTableUsed(CurrentLocation, ClassDecl);
11055 
11056   // Add a context note for diagnostics produced after this point.
11057   Scope.addContextNote(CurrentLocation);
11058 
11059   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11060     Constructor->setInvalidDecl();
11061     return;
11062   }
11063 
11064   SourceLocation Loc = Constructor->getEndLoc().isValid()
11065                            ? Constructor->getEndLoc()
11066                            : Constructor->getLocation();
11067   Constructor->setBody(new (Context) CompoundStmt(Loc));
11068   Constructor->markUsed(Context);
11069 
11070   if (ASTMutationListener *L = getASTMutationListener()) {
11071     L->CompletedImplicitDefinition(Constructor);
11072   }
11073 
11074   DiagnoseUninitializedFields(*this, Constructor);
11075 }
11076 
11077 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
11078   // Perform any delayed checks on exception specifications.
11079   CheckDelayedMemberExceptionSpecs();
11080 }
11081 
11082 /// Find or create the fake constructor we synthesize to model constructing an
11083 /// object of a derived class via a constructor of a base class.
11084 CXXConstructorDecl *
11085 Sema::findInheritingConstructor(SourceLocation Loc,
11086                                 CXXConstructorDecl *BaseCtor,
11087                                 ConstructorUsingShadowDecl *Shadow) {
11088   CXXRecordDecl *Derived = Shadow->getParent();
11089   SourceLocation UsingLoc = Shadow->getLocation();
11090 
11091   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11092   // For now we use the name of the base class constructor as a member of the
11093   // derived class to indicate a (fake) inherited constructor name.
11094   DeclarationName Name = BaseCtor->getDeclName();
11095 
11096   // Check to see if we already have a fake constructor for this inherited
11097   // constructor call.
11098   for (NamedDecl *Ctor : Derived->lookup(Name))
11099     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11100                                ->getInheritedConstructor()
11101                                .getConstructor(),
11102                            BaseCtor))
11103       return cast<CXXConstructorDecl>(Ctor);
11104 
11105   DeclarationNameInfo NameInfo(Name, UsingLoc);
11106   TypeSourceInfo *TInfo =
11107       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11108   FunctionProtoTypeLoc ProtoLoc =
11109       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11110 
11111   // Check the inherited constructor is valid and find the list of base classes
11112   // from which it was inherited.
11113   InheritedConstructorInfo ICI(*this, Loc, Shadow);
11114 
11115   bool Constexpr =
11116       BaseCtor->isConstexpr() &&
11117       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11118                                         false, BaseCtor, &ICI);
11119 
11120   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11121       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11122       BaseCtor->getExplicitSpecifier(), /*Inline=*/true,
11123       /*ImplicitlyDeclared=*/true, Constexpr,
11124       InheritedConstructor(Shadow, BaseCtor));
11125   if (Shadow->isInvalidDecl())
11126     DerivedCtor->setInvalidDecl();
11127 
11128   // Build an unevaluated exception specification for this fake constructor.
11129   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11130   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11131   EPI.ExceptionSpec.Type = EST_Unevaluated;
11132   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11133   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11134                                                FPT->getParamTypes(), EPI));
11135 
11136   // Build the parameter declarations.
11137   SmallVector<ParmVarDecl *, 16> ParamDecls;
11138   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11139     TypeSourceInfo *TInfo =
11140         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11141     ParmVarDecl *PD = ParmVarDecl::Create(
11142         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11143         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
11144     PD->setScopeInfo(0, I);
11145     PD->setImplicit();
11146     // Ensure attributes are propagated onto parameters (this matters for
11147     // format, pass_object_size, ...).
11148     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11149     ParamDecls.push_back(PD);
11150     ProtoLoc.setParam(I, PD);
11151   }
11152 
11153   // Set up the new constructor.
11154   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11155   DerivedCtor->setAccess(BaseCtor->getAccess());
11156   DerivedCtor->setParams(ParamDecls);
11157   Derived->addDecl(DerivedCtor);
11158 
11159   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11160     SetDeclDeleted(DerivedCtor, UsingLoc);
11161 
11162   return DerivedCtor;
11163 }
11164 
11165 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11166   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11167                                Ctor->getInheritedConstructor().getShadowDecl());
11168   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11169                             /*Diagnose*/true);
11170 }
11171 
11172 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11173                                        CXXConstructorDecl *Constructor) {
11174   CXXRecordDecl *ClassDecl = Constructor->getParent();
11175   assert(Constructor->getInheritedConstructor() &&
11176          !Constructor->doesThisDeclarationHaveABody() &&
11177          !Constructor->isDeleted());
11178   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11179     return;
11180 
11181   // Initializations are performed "as if by a defaulted default constructor",
11182   // so enter the appropriate scope.
11183   SynthesizedFunctionScope Scope(*this, Constructor);
11184 
11185   // The exception specification is needed because we are defining the
11186   // function.
11187   ResolveExceptionSpec(CurrentLocation,
11188                        Constructor->getType()->castAs<FunctionProtoType>());
11189   MarkVTableUsed(CurrentLocation, ClassDecl);
11190 
11191   // Add a context note for diagnostics produced after this point.
11192   Scope.addContextNote(CurrentLocation);
11193 
11194   ConstructorUsingShadowDecl *Shadow =
11195       Constructor->getInheritedConstructor().getShadowDecl();
11196   CXXConstructorDecl *InheritedCtor =
11197       Constructor->getInheritedConstructor().getConstructor();
11198 
11199   // [class.inhctor.init]p1:
11200   //   initialization proceeds as if a defaulted default constructor is used to
11201   //   initialize the D object and each base class subobject from which the
11202   //   constructor was inherited
11203 
11204   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11205   CXXRecordDecl *RD = Shadow->getParent();
11206   SourceLocation InitLoc = Shadow->getLocation();
11207 
11208   // Build explicit initializers for all base classes from which the
11209   // constructor was inherited.
11210   SmallVector<CXXCtorInitializer*, 8> Inits;
11211   for (bool VBase : {false, true}) {
11212     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11213       if (B.isVirtual() != VBase)
11214         continue;
11215 
11216       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11217       if (!BaseRD)
11218         continue;
11219 
11220       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11221       if (!BaseCtor.first)
11222         continue;
11223 
11224       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11225       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11226           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11227 
11228       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11229       Inits.push_back(new (Context) CXXCtorInitializer(
11230           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11231           SourceLocation()));
11232     }
11233   }
11234 
11235   // We now proceed as if for a defaulted default constructor, with the relevant
11236   // initializers replaced.
11237 
11238   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11239     Constructor->setInvalidDecl();
11240     return;
11241   }
11242 
11243   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11244   Constructor->markUsed(Context);
11245 
11246   if (ASTMutationListener *L = getASTMutationListener()) {
11247     L->CompletedImplicitDefinition(Constructor);
11248   }
11249 
11250   DiagnoseUninitializedFields(*this, Constructor);
11251 }
11252 
11253 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11254   // C++ [class.dtor]p2:
11255   //   If a class has no user-declared destructor, a destructor is
11256   //   declared implicitly. An implicitly-declared destructor is an
11257   //   inline public member of its class.
11258   assert(ClassDecl->needsImplicitDestructor());
11259 
11260   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11261   if (DSM.isAlreadyBeingDeclared())
11262     return nullptr;
11263 
11264   // Create the actual destructor declaration.
11265   CanQualType ClassType
11266     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11267   SourceLocation ClassLoc = ClassDecl->getLocation();
11268   DeclarationName Name
11269     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11270   DeclarationNameInfo NameInfo(Name, ClassLoc);
11271   CXXDestructorDecl *Destructor
11272       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11273                                   QualType(), nullptr, /*isInline=*/true,
11274                                   /*isImplicitlyDeclared=*/true);
11275   Destructor->setAccess(AS_public);
11276   Destructor->setDefaulted();
11277 
11278   if (getLangOpts().CUDA) {
11279     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11280                                             Destructor,
11281                                             /* ConstRHS */ false,
11282                                             /* Diagnose */ false);
11283   }
11284 
11285   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
11286 
11287   // We don't need to use SpecialMemberIsTrivial here; triviality for
11288   // destructors is easy to compute.
11289   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11290   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11291                                 ClassDecl->hasTrivialDestructorForCall());
11292 
11293   // Note that we have declared this destructor.
11294   ++getASTContext().NumImplicitDestructorsDeclared;
11295 
11296   Scope *S = getScopeForContext(ClassDecl);
11297   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11298 
11299   // We can't check whether an implicit destructor is deleted before we complete
11300   // the definition of the class, because its validity depends on the alignment
11301   // of the class. We'll check this from ActOnFields once the class is complete.
11302   if (ClassDecl->isCompleteDefinition() &&
11303       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11304     SetDeclDeleted(Destructor, ClassLoc);
11305 
11306   // Introduce this destructor into its scope.
11307   if (S)
11308     PushOnScopeChains(Destructor, S, false);
11309   ClassDecl->addDecl(Destructor);
11310 
11311   return Destructor;
11312 }
11313 
11314 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11315                                     CXXDestructorDecl *Destructor) {
11316   assert((Destructor->isDefaulted() &&
11317           !Destructor->doesThisDeclarationHaveABody() &&
11318           !Destructor->isDeleted()) &&
11319          "DefineImplicitDestructor - call it for implicit default dtor");
11320   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11321     return;
11322 
11323   CXXRecordDecl *ClassDecl = Destructor->getParent();
11324   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11325 
11326   SynthesizedFunctionScope Scope(*this, Destructor);
11327 
11328   // The exception specification is needed because we are defining the
11329   // function.
11330   ResolveExceptionSpec(CurrentLocation,
11331                        Destructor->getType()->castAs<FunctionProtoType>());
11332   MarkVTableUsed(CurrentLocation, ClassDecl);
11333 
11334   // Add a context note for diagnostics produced after this point.
11335   Scope.addContextNote(CurrentLocation);
11336 
11337   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11338                                          Destructor->getParent());
11339 
11340   if (CheckDestructor(Destructor)) {
11341     Destructor->setInvalidDecl();
11342     return;
11343   }
11344 
11345   SourceLocation Loc = Destructor->getEndLoc().isValid()
11346                            ? Destructor->getEndLoc()
11347                            : Destructor->getLocation();
11348   Destructor->setBody(new (Context) CompoundStmt(Loc));
11349   Destructor->markUsed(Context);
11350 
11351   if (ASTMutationListener *L = getASTMutationListener()) {
11352     L->CompletedImplicitDefinition(Destructor);
11353   }
11354 }
11355 
11356 /// Perform any semantic analysis which needs to be delayed until all
11357 /// pending class member declarations have been parsed.
11358 void Sema::ActOnFinishCXXMemberDecls() {
11359   // If the context is an invalid C++ class, just suppress these checks.
11360   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11361     if (Record->isInvalidDecl()) {
11362       DelayedOverridingExceptionSpecChecks.clear();
11363       DelayedEquivalentExceptionSpecChecks.clear();
11364       return;
11365     }
11366     checkForMultipleExportedDefaultConstructors(*this, Record);
11367   }
11368 }
11369 
11370 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11371   referenceDLLExportedClassMethods();
11372 }
11373 
11374 void Sema::referenceDLLExportedClassMethods() {
11375   if (!DelayedDllExportClasses.empty()) {
11376     // Calling ReferenceDllExportedMembers might cause the current function to
11377     // be called again, so use a local copy of DelayedDllExportClasses.
11378     SmallVector<CXXRecordDecl *, 4> WorkList;
11379     std::swap(DelayedDllExportClasses, WorkList);
11380     for (CXXRecordDecl *Class : WorkList)
11381       ReferenceDllExportedMembers(*this, Class);
11382   }
11383 }
11384 
11385 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11386   assert(getLangOpts().CPlusPlus11 &&
11387          "adjusting dtor exception specs was introduced in c++11");
11388 
11389   if (Destructor->isDependentContext())
11390     return;
11391 
11392   // C++11 [class.dtor]p3:
11393   //   A declaration of a destructor that does not have an exception-
11394   //   specification is implicitly considered to have the same exception-
11395   //   specification as an implicit declaration.
11396   const FunctionProtoType *DtorType = Destructor->getType()->
11397                                         getAs<FunctionProtoType>();
11398   if (DtorType->hasExceptionSpec())
11399     return;
11400 
11401   // Replace the destructor's type, building off the existing one. Fortunately,
11402   // the only thing of interest in the destructor type is its extended info.
11403   // The return and arguments are fixed.
11404   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11405   EPI.ExceptionSpec.Type = EST_Unevaluated;
11406   EPI.ExceptionSpec.SourceDecl = Destructor;
11407   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11408 
11409   // FIXME: If the destructor has a body that could throw, and the newly created
11410   // spec doesn't allow exceptions, we should emit a warning, because this
11411   // change in behavior can break conforming C++03 programs at runtime.
11412   // However, we don't have a body or an exception specification yet, so it
11413   // needs to be done somewhere else.
11414 }
11415 
11416 namespace {
11417 /// An abstract base class for all helper classes used in building the
11418 //  copy/move operators. These classes serve as factory functions and help us
11419 //  avoid using the same Expr* in the AST twice.
11420 class ExprBuilder {
11421   ExprBuilder(const ExprBuilder&) = delete;
11422   ExprBuilder &operator=(const ExprBuilder&) = delete;
11423 
11424 protected:
11425   static Expr *assertNotNull(Expr *E) {
11426     assert(E && "Expression construction must not fail.");
11427     return E;
11428   }
11429 
11430 public:
11431   ExprBuilder() {}
11432   virtual ~ExprBuilder() {}
11433 
11434   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11435 };
11436 
11437 class RefBuilder: public ExprBuilder {
11438   VarDecl *Var;
11439   QualType VarType;
11440 
11441 public:
11442   Expr *build(Sema &S, SourceLocation Loc) const override {
11443     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11444   }
11445 
11446   RefBuilder(VarDecl *Var, QualType VarType)
11447       : Var(Var), VarType(VarType) {}
11448 };
11449 
11450 class ThisBuilder: public ExprBuilder {
11451 public:
11452   Expr *build(Sema &S, SourceLocation Loc) const override {
11453     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11454   }
11455 };
11456 
11457 class CastBuilder: public ExprBuilder {
11458   const ExprBuilder &Builder;
11459   QualType Type;
11460   ExprValueKind Kind;
11461   const CXXCastPath &Path;
11462 
11463 public:
11464   Expr *build(Sema &S, SourceLocation Loc) const override {
11465     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11466                                              CK_UncheckedDerivedToBase, Kind,
11467                                              &Path).get());
11468   }
11469 
11470   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11471               const CXXCastPath &Path)
11472       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11473 };
11474 
11475 class DerefBuilder: public ExprBuilder {
11476   const ExprBuilder &Builder;
11477 
11478 public:
11479   Expr *build(Sema &S, SourceLocation Loc) const override {
11480     return assertNotNull(
11481         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11482   }
11483 
11484   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11485 };
11486 
11487 class MemberBuilder: public ExprBuilder {
11488   const ExprBuilder &Builder;
11489   QualType Type;
11490   CXXScopeSpec SS;
11491   bool IsArrow;
11492   LookupResult &MemberLookup;
11493 
11494 public:
11495   Expr *build(Sema &S, SourceLocation Loc) const override {
11496     return assertNotNull(S.BuildMemberReferenceExpr(
11497         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11498         nullptr, MemberLookup, nullptr, nullptr).get());
11499   }
11500 
11501   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11502                 LookupResult &MemberLookup)
11503       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11504         MemberLookup(MemberLookup) {}
11505 };
11506 
11507 class MoveCastBuilder: public ExprBuilder {
11508   const ExprBuilder &Builder;
11509 
11510 public:
11511   Expr *build(Sema &S, SourceLocation Loc) const override {
11512     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11513   }
11514 
11515   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11516 };
11517 
11518 class LvalueConvBuilder: public ExprBuilder {
11519   const ExprBuilder &Builder;
11520 
11521 public:
11522   Expr *build(Sema &S, SourceLocation Loc) const override {
11523     return assertNotNull(
11524         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11525   }
11526 
11527   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11528 };
11529 
11530 class SubscriptBuilder: public ExprBuilder {
11531   const ExprBuilder &Base;
11532   const ExprBuilder &Index;
11533 
11534 public:
11535   Expr *build(Sema &S, SourceLocation Loc) const override {
11536     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11537         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11538   }
11539 
11540   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11541       : Base(Base), Index(Index) {}
11542 };
11543 
11544 } // end anonymous namespace
11545 
11546 /// When generating a defaulted copy or move assignment operator, if a field
11547 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11548 /// do so. This optimization only applies for arrays of scalars, and for arrays
11549 /// of class type where the selected copy/move-assignment operator is trivial.
11550 static StmtResult
11551 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11552                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11553   // Compute the size of the memory buffer to be copied.
11554   QualType SizeType = S.Context.getSizeType();
11555   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11556                    S.Context.getTypeSizeInChars(T).getQuantity());
11557 
11558   // Take the address of the field references for "from" and "to". We
11559   // directly construct UnaryOperators here because semantic analysis
11560   // does not permit us to take the address of an xvalue.
11561   Expr *From = FromB.build(S, Loc);
11562   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11563                          S.Context.getPointerType(From->getType()),
11564                          VK_RValue, OK_Ordinary, Loc, false);
11565   Expr *To = ToB.build(S, Loc);
11566   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11567                        S.Context.getPointerType(To->getType()),
11568                        VK_RValue, OK_Ordinary, Loc, false);
11569 
11570   const Type *E = T->getBaseElementTypeUnsafe();
11571   bool NeedsCollectableMemCpy =
11572     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11573 
11574   // Create a reference to the __builtin_objc_memmove_collectable function
11575   StringRef MemCpyName = NeedsCollectableMemCpy ?
11576     "__builtin_objc_memmove_collectable" :
11577     "__builtin_memcpy";
11578   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11579                  Sema::LookupOrdinaryName);
11580   S.LookupName(R, S.TUScope, true);
11581 
11582   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11583   if (!MemCpy)
11584     // Something went horribly wrong earlier, and we will have complained
11585     // about it.
11586     return StmtError();
11587 
11588   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11589                                             VK_RValue, Loc, nullptr);
11590   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11591 
11592   Expr *CallArgs[] = {
11593     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11594   };
11595   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11596                                     Loc, CallArgs, Loc);
11597 
11598   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11599   return Call.getAs<Stmt>();
11600 }
11601 
11602 /// Builds a statement that copies/moves the given entity from \p From to
11603 /// \c To.
11604 ///
11605 /// This routine is used to copy/move the members of a class with an
11606 /// implicitly-declared copy/move assignment operator. When the entities being
11607 /// copied are arrays, this routine builds for loops to copy them.
11608 ///
11609 /// \param S The Sema object used for type-checking.
11610 ///
11611 /// \param Loc The location where the implicit copy/move is being generated.
11612 ///
11613 /// \param T The type of the expressions being copied/moved. Both expressions
11614 /// must have this type.
11615 ///
11616 /// \param To The expression we are copying/moving to.
11617 ///
11618 /// \param From The expression we are copying/moving from.
11619 ///
11620 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11621 /// Otherwise, it's a non-static member subobject.
11622 ///
11623 /// \param Copying Whether we're copying or moving.
11624 ///
11625 /// \param Depth Internal parameter recording the depth of the recursion.
11626 ///
11627 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11628 /// if a memcpy should be used instead.
11629 static StmtResult
11630 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11631                                  const ExprBuilder &To, const ExprBuilder &From,
11632                                  bool CopyingBaseSubobject, bool Copying,
11633                                  unsigned Depth = 0) {
11634   // C++11 [class.copy]p28:
11635   //   Each subobject is assigned in the manner appropriate to its type:
11636   //
11637   //     - if the subobject is of class type, as if by a call to operator= with
11638   //       the subobject as the object expression and the corresponding
11639   //       subobject of x as a single function argument (as if by explicit
11640   //       qualification; that is, ignoring any possible virtual overriding
11641   //       functions in more derived classes);
11642   //
11643   // C++03 [class.copy]p13:
11644   //     - if the subobject is of class type, the copy assignment operator for
11645   //       the class is used (as if by explicit qualification; that is,
11646   //       ignoring any possible virtual overriding functions in more derived
11647   //       classes);
11648   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11649     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11650 
11651     // Look for operator=.
11652     DeclarationName Name
11653       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11654     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11655     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11656 
11657     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11658     // operator.
11659     if (!S.getLangOpts().CPlusPlus11) {
11660       LookupResult::Filter F = OpLookup.makeFilter();
11661       while (F.hasNext()) {
11662         NamedDecl *D = F.next();
11663         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11664           if (Method->isCopyAssignmentOperator() ||
11665               (!Copying && Method->isMoveAssignmentOperator()))
11666             continue;
11667 
11668         F.erase();
11669       }
11670       F.done();
11671     }
11672 
11673     // Suppress the protected check (C++ [class.protected]) for each of the
11674     // assignment operators we found. This strange dance is required when
11675     // we're assigning via a base classes's copy-assignment operator. To
11676     // ensure that we're getting the right base class subobject (without
11677     // ambiguities), we need to cast "this" to that subobject type; to
11678     // ensure that we don't go through the virtual call mechanism, we need
11679     // to qualify the operator= name with the base class (see below). However,
11680     // this means that if the base class has a protected copy assignment
11681     // operator, the protected member access check will fail. So, we
11682     // rewrite "protected" access to "public" access in this case, since we
11683     // know by construction that we're calling from a derived class.
11684     if (CopyingBaseSubobject) {
11685       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11686            L != LEnd; ++L) {
11687         if (L.getAccess() == AS_protected)
11688           L.setAccess(AS_public);
11689       }
11690     }
11691 
11692     // Create the nested-name-specifier that will be used to qualify the
11693     // reference to operator=; this is required to suppress the virtual
11694     // call mechanism.
11695     CXXScopeSpec SS;
11696     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11697     SS.MakeTrivial(S.Context,
11698                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11699                                                CanonicalT),
11700                    Loc);
11701 
11702     // Create the reference to operator=.
11703     ExprResult OpEqualRef
11704       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11705                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11706                                    /*FirstQualifierInScope=*/nullptr,
11707                                    OpLookup,
11708                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11709                                    /*SuppressQualifierCheck=*/true);
11710     if (OpEqualRef.isInvalid())
11711       return StmtError();
11712 
11713     // Build the call to the assignment operator.
11714 
11715     Expr *FromInst = From.build(S, Loc);
11716     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11717                                                   OpEqualRef.getAs<Expr>(),
11718                                                   Loc, FromInst, Loc);
11719     if (Call.isInvalid())
11720       return StmtError();
11721 
11722     // If we built a call to a trivial 'operator=' while copying an array,
11723     // bail out. We'll replace the whole shebang with a memcpy.
11724     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11725     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11726       return StmtResult((Stmt*)nullptr);
11727 
11728     // Convert to an expression-statement, and clean up any produced
11729     // temporaries.
11730     return S.ActOnExprStmt(Call);
11731   }
11732 
11733   //     - if the subobject is of scalar type, the built-in assignment
11734   //       operator is used.
11735   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11736   if (!ArrayTy) {
11737     ExprResult Assignment = S.CreateBuiltinBinOp(
11738         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11739     if (Assignment.isInvalid())
11740       return StmtError();
11741     return S.ActOnExprStmt(Assignment);
11742   }
11743 
11744   //     - if the subobject is an array, each element is assigned, in the
11745   //       manner appropriate to the element type;
11746 
11747   // Construct a loop over the array bounds, e.g.,
11748   //
11749   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11750   //
11751   // that will copy each of the array elements.
11752   QualType SizeType = S.Context.getSizeType();
11753 
11754   // Create the iteration variable.
11755   IdentifierInfo *IterationVarName = nullptr;
11756   {
11757     SmallString<8> Str;
11758     llvm::raw_svector_ostream OS(Str);
11759     OS << "__i" << Depth;
11760     IterationVarName = &S.Context.Idents.get(OS.str());
11761   }
11762   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11763                                           IterationVarName, SizeType,
11764                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11765                                           SC_None);
11766 
11767   // Initialize the iteration variable to zero.
11768   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11769   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11770 
11771   // Creates a reference to the iteration variable.
11772   RefBuilder IterationVarRef(IterationVar, SizeType);
11773   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11774 
11775   // Create the DeclStmt that holds the iteration variable.
11776   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11777 
11778   // Subscript the "from" and "to" expressions with the iteration variable.
11779   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11780   MoveCastBuilder FromIndexMove(FromIndexCopy);
11781   const ExprBuilder *FromIndex;
11782   if (Copying)
11783     FromIndex = &FromIndexCopy;
11784   else
11785     FromIndex = &FromIndexMove;
11786 
11787   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11788 
11789   // Build the copy/move for an individual element of the array.
11790   StmtResult Copy =
11791     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11792                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11793                                      Copying, Depth + 1);
11794   // Bail out if copying fails or if we determined that we should use memcpy.
11795   if (Copy.isInvalid() || !Copy.get())
11796     return Copy;
11797 
11798   // Create the comparison against the array bound.
11799   llvm::APInt Upper
11800     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11801   Expr *Comparison
11802     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11803                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11804                                      BO_NE, S.Context.BoolTy,
11805                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11806 
11807   // Create the pre-increment of the iteration variable. We can determine
11808   // whether the increment will overflow based on the value of the array
11809   // bound.
11810   Expr *Increment = new (S.Context)
11811       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11812                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11813 
11814   // Construct the loop that copies all elements of this array.
11815   return S.ActOnForStmt(
11816       Loc, Loc, InitStmt,
11817       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11818       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11819 }
11820 
11821 static StmtResult
11822 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11823                       const ExprBuilder &To, const ExprBuilder &From,
11824                       bool CopyingBaseSubobject, bool Copying) {
11825   // Maybe we should use a memcpy?
11826   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11827       T.isTriviallyCopyableType(S.Context))
11828     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11829 
11830   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11831                                                      CopyingBaseSubobject,
11832                                                      Copying, 0));
11833 
11834   // If we ended up picking a trivial assignment operator for an array of a
11835   // non-trivially-copyable class type, just emit a memcpy.
11836   if (!Result.isInvalid() && !Result.get())
11837     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11838 
11839   return Result;
11840 }
11841 
11842 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11843   // Note: The following rules are largely analoguous to the copy
11844   // constructor rules. Note that virtual bases are not taken into account
11845   // for determining the argument type of the operator. Note also that
11846   // operators taking an object instead of a reference are allowed.
11847   assert(ClassDecl->needsImplicitCopyAssignment());
11848 
11849   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11850   if (DSM.isAlreadyBeingDeclared())
11851     return nullptr;
11852 
11853   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11854   if (Context.getLangOpts().OpenCLCPlusPlus)
11855     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
11856   QualType RetType = Context.getLValueReferenceType(ArgType);
11857   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11858   if (Const)
11859     ArgType = ArgType.withConst();
11860 
11861   ArgType = Context.getLValueReferenceType(ArgType);
11862 
11863   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11864                                                      CXXCopyAssignment,
11865                                                      Const);
11866 
11867   //   An implicitly-declared copy assignment operator is an inline public
11868   //   member of its class.
11869   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11870   SourceLocation ClassLoc = ClassDecl->getLocation();
11871   DeclarationNameInfo NameInfo(Name, ClassLoc);
11872   CXXMethodDecl *CopyAssignment =
11873       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11874                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11875                             /*isInline=*/true, Constexpr, SourceLocation());
11876   CopyAssignment->setAccess(AS_public);
11877   CopyAssignment->setDefaulted();
11878   CopyAssignment->setImplicit();
11879 
11880   if (getLangOpts().CUDA) {
11881     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11882                                             CopyAssignment,
11883                                             /* ConstRHS */ Const,
11884                                             /* Diagnose */ false);
11885   }
11886 
11887   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
11888 
11889   // Add the parameter to the operator.
11890   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11891                                                ClassLoc, ClassLoc,
11892                                                /*Id=*/nullptr, ArgType,
11893                                                /*TInfo=*/nullptr, SC_None,
11894                                                nullptr);
11895   CopyAssignment->setParams(FromParam);
11896 
11897   CopyAssignment->setTrivial(
11898     ClassDecl->needsOverloadResolutionForCopyAssignment()
11899       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11900       : ClassDecl->hasTrivialCopyAssignment());
11901 
11902   // Note that we have added this copy-assignment operator.
11903   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
11904 
11905   Scope *S = getScopeForContext(ClassDecl);
11906   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11907 
11908   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11909     SetDeclDeleted(CopyAssignment, ClassLoc);
11910 
11911   if (S)
11912     PushOnScopeChains(CopyAssignment, S, false);
11913   ClassDecl->addDecl(CopyAssignment);
11914 
11915   return CopyAssignment;
11916 }
11917 
11918 /// Diagnose an implicit copy operation for a class which is odr-used, but
11919 /// which is deprecated because the class has a user-declared copy constructor,
11920 /// copy assignment operator, or destructor.
11921 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11922   assert(CopyOp->isImplicit());
11923 
11924   CXXRecordDecl *RD = CopyOp->getParent();
11925   CXXMethodDecl *UserDeclaredOperation = nullptr;
11926 
11927   // In Microsoft mode, assignment operations don't affect constructors and
11928   // vice versa.
11929   if (RD->hasUserDeclaredDestructor()) {
11930     UserDeclaredOperation = RD->getDestructor();
11931   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11932              RD->hasUserDeclaredCopyConstructor() &&
11933              !S.getLangOpts().MSVCCompat) {
11934     // Find any user-declared copy constructor.
11935     for (auto *I : RD->ctors()) {
11936       if (I->isCopyConstructor()) {
11937         UserDeclaredOperation = I;
11938         break;
11939       }
11940     }
11941     assert(UserDeclaredOperation);
11942   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11943              RD->hasUserDeclaredCopyAssignment() &&
11944              !S.getLangOpts().MSVCCompat) {
11945     // Find any user-declared move assignment operator.
11946     for (auto *I : RD->methods()) {
11947       if (I->isCopyAssignmentOperator()) {
11948         UserDeclaredOperation = I;
11949         break;
11950       }
11951     }
11952     assert(UserDeclaredOperation);
11953   }
11954 
11955   if (UserDeclaredOperation) {
11956     S.Diag(UserDeclaredOperation->getLocation(),
11957          diag::warn_deprecated_copy_operation)
11958       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11959       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11960   }
11961 }
11962 
11963 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11964                                         CXXMethodDecl *CopyAssignOperator) {
11965   assert((CopyAssignOperator->isDefaulted() &&
11966           CopyAssignOperator->isOverloadedOperator() &&
11967           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11968           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11969           !CopyAssignOperator->isDeleted()) &&
11970          "DefineImplicitCopyAssignment called for wrong function");
11971   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11972     return;
11973 
11974   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11975   if (ClassDecl->isInvalidDecl()) {
11976     CopyAssignOperator->setInvalidDecl();
11977     return;
11978   }
11979 
11980   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11981 
11982   // The exception specification is needed because we are defining the
11983   // function.
11984   ResolveExceptionSpec(CurrentLocation,
11985                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11986 
11987   // Add a context note for diagnostics produced after this point.
11988   Scope.addContextNote(CurrentLocation);
11989 
11990   // C++11 [class.copy]p18:
11991   //   The [definition of an implicitly declared copy assignment operator] is
11992   //   deprecated if the class has a user-declared copy constructor or a
11993   //   user-declared destructor.
11994   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11995     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11996 
11997   // C++0x [class.copy]p30:
11998   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11999   //   for a non-union class X performs memberwise copy assignment of its
12000   //   subobjects. The direct base classes of X are assigned first, in the
12001   //   order of their declaration in the base-specifier-list, and then the
12002   //   immediate non-static data members of X are assigned, in the order in
12003   //   which they were declared in the class definition.
12004 
12005   // The statements that form the synthesized function body.
12006   SmallVector<Stmt*, 8> Statements;
12007 
12008   // The parameter for the "other" object, which we are copying from.
12009   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
12010   Qualifiers OtherQuals = Other->getType().getQualifiers();
12011   QualType OtherRefType = Other->getType();
12012   if (const LValueReferenceType *OtherRef
12013                                 = OtherRefType->getAs<LValueReferenceType>()) {
12014     OtherRefType = OtherRef->getPointeeType();
12015     OtherQuals = OtherRefType.getQualifiers();
12016   }
12017 
12018   // Our location for everything implicitly-generated.
12019   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
12020                            ? CopyAssignOperator->getEndLoc()
12021                            : CopyAssignOperator->getLocation();
12022 
12023   // Builds a DeclRefExpr for the "other" object.
12024   RefBuilder OtherRef(Other, OtherRefType);
12025 
12026   // Builds the "this" pointer.
12027   ThisBuilder This;
12028 
12029   // Assign base classes.
12030   bool Invalid = false;
12031   for (auto &Base : ClassDecl->bases()) {
12032     // Form the assignment:
12033     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
12034     QualType BaseType = Base.getType().getUnqualifiedType();
12035     if (!BaseType->isRecordType()) {
12036       Invalid = true;
12037       continue;
12038     }
12039 
12040     CXXCastPath BasePath;
12041     BasePath.push_back(&Base);
12042 
12043     // Construct the "from" expression, which is an implicit cast to the
12044     // appropriately-qualified base type.
12045     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
12046                      VK_LValue, BasePath);
12047 
12048     // Dereference "this".
12049     DerefBuilder DerefThis(This);
12050     CastBuilder To(DerefThis,
12051                    Context.getQualifiedType(
12052                        BaseType, CopyAssignOperator->getMethodQualifiers()),
12053                    VK_LValue, BasePath);
12054 
12055     // Build the copy.
12056     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12057                                             To, From,
12058                                             /*CopyingBaseSubobject=*/true,
12059                                             /*Copying=*/true);
12060     if (Copy.isInvalid()) {
12061       CopyAssignOperator->setInvalidDecl();
12062       return;
12063     }
12064 
12065     // Success! Record the copy.
12066     Statements.push_back(Copy.getAs<Expr>());
12067   }
12068 
12069   // Assign non-static members.
12070   for (auto *Field : ClassDecl->fields()) {
12071     // FIXME: We should form some kind of AST representation for the implied
12072     // memcpy in a union copy operation.
12073     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12074       continue;
12075 
12076     if (Field->isInvalidDecl()) {
12077       Invalid = true;
12078       continue;
12079     }
12080 
12081     // Check for members of reference type; we can't copy those.
12082     if (Field->getType()->isReferenceType()) {
12083       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12084         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12085       Diag(Field->getLocation(), diag::note_declared_at);
12086       Invalid = true;
12087       continue;
12088     }
12089 
12090     // Check for members of const-qualified, non-class type.
12091     QualType BaseType = Context.getBaseElementType(Field->getType());
12092     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12093       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12094         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12095       Diag(Field->getLocation(), diag::note_declared_at);
12096       Invalid = true;
12097       continue;
12098     }
12099 
12100     // Suppress assigning zero-width bitfields.
12101     if (Field->isZeroLengthBitField(Context))
12102       continue;
12103 
12104     QualType FieldType = Field->getType().getNonReferenceType();
12105     if (FieldType->isIncompleteArrayType()) {
12106       assert(ClassDecl->hasFlexibleArrayMember() &&
12107              "Incomplete array type is not valid");
12108       continue;
12109     }
12110 
12111     // Build references to the field in the object we're copying from and to.
12112     CXXScopeSpec SS; // Intentionally empty
12113     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12114                               LookupMemberName);
12115     MemberLookup.addDecl(Field);
12116     MemberLookup.resolveKind();
12117 
12118     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12119 
12120     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12121 
12122     // Build the copy of this field.
12123     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12124                                             To, From,
12125                                             /*CopyingBaseSubobject=*/false,
12126                                             /*Copying=*/true);
12127     if (Copy.isInvalid()) {
12128       CopyAssignOperator->setInvalidDecl();
12129       return;
12130     }
12131 
12132     // Success! Record the copy.
12133     Statements.push_back(Copy.getAs<Stmt>());
12134   }
12135 
12136   if (!Invalid) {
12137     // Add a "return *this;"
12138     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12139 
12140     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12141     if (Return.isInvalid())
12142       Invalid = true;
12143     else
12144       Statements.push_back(Return.getAs<Stmt>());
12145   }
12146 
12147   if (Invalid) {
12148     CopyAssignOperator->setInvalidDecl();
12149     return;
12150   }
12151 
12152   StmtResult Body;
12153   {
12154     CompoundScopeRAII CompoundScope(*this);
12155     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12156                              /*isStmtExpr=*/false);
12157     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12158   }
12159   CopyAssignOperator->setBody(Body.getAs<Stmt>());
12160   CopyAssignOperator->markUsed(Context);
12161 
12162   if (ASTMutationListener *L = getASTMutationListener()) {
12163     L->CompletedImplicitDefinition(CopyAssignOperator);
12164   }
12165 }
12166 
12167 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12168   assert(ClassDecl->needsImplicitMoveAssignment());
12169 
12170   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12171   if (DSM.isAlreadyBeingDeclared())
12172     return nullptr;
12173 
12174   // Note: The following rules are largely analoguous to the move
12175   // constructor rules.
12176 
12177   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12178   if (Context.getLangOpts().OpenCLCPlusPlus)
12179     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12180   QualType RetType = Context.getLValueReferenceType(ArgType);
12181   ArgType = Context.getRValueReferenceType(ArgType);
12182 
12183   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12184                                                      CXXMoveAssignment,
12185                                                      false);
12186 
12187   //   An implicitly-declared move assignment operator is an inline public
12188   //   member of its class.
12189   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12190   SourceLocation ClassLoc = ClassDecl->getLocation();
12191   DeclarationNameInfo NameInfo(Name, ClassLoc);
12192   CXXMethodDecl *MoveAssignment =
12193       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12194                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12195                             /*isInline=*/true, Constexpr, SourceLocation());
12196   MoveAssignment->setAccess(AS_public);
12197   MoveAssignment->setDefaulted();
12198   MoveAssignment->setImplicit();
12199 
12200   if (getLangOpts().CUDA) {
12201     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12202                                             MoveAssignment,
12203                                             /* ConstRHS */ false,
12204                                             /* Diagnose */ false);
12205   }
12206 
12207   // Build an exception specification pointing back at this member.
12208   FunctionProtoType::ExtProtoInfo EPI =
12209       getImplicitMethodEPI(*this, MoveAssignment);
12210   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12211 
12212   // Add the parameter to the operator.
12213   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12214                                                ClassLoc, ClassLoc,
12215                                                /*Id=*/nullptr, ArgType,
12216                                                /*TInfo=*/nullptr, SC_None,
12217                                                nullptr);
12218   MoveAssignment->setParams(FromParam);
12219 
12220   MoveAssignment->setTrivial(
12221     ClassDecl->needsOverloadResolutionForMoveAssignment()
12222       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12223       : ClassDecl->hasTrivialMoveAssignment());
12224 
12225   // Note that we have added this copy-assignment operator.
12226   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
12227 
12228   Scope *S = getScopeForContext(ClassDecl);
12229   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12230 
12231   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12232     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12233     SetDeclDeleted(MoveAssignment, ClassLoc);
12234   }
12235 
12236   if (S)
12237     PushOnScopeChains(MoveAssignment, S, false);
12238   ClassDecl->addDecl(MoveAssignment);
12239 
12240   return MoveAssignment;
12241 }
12242 
12243 /// Check if we're implicitly defining a move assignment operator for a class
12244 /// with virtual bases. Such a move assignment might move-assign the virtual
12245 /// base multiple times.
12246 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12247                                                SourceLocation CurrentLocation) {
12248   assert(!Class->isDependentContext() && "should not define dependent move");
12249 
12250   // Only a virtual base could get implicitly move-assigned multiple times.
12251   // Only a non-trivial move assignment can observe this. We only want to
12252   // diagnose if we implicitly define an assignment operator that assigns
12253   // two base classes, both of which move-assign the same virtual base.
12254   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12255       Class->getNumBases() < 2)
12256     return;
12257 
12258   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12259   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12260   VBaseMap VBases;
12261 
12262   for (auto &BI : Class->bases()) {
12263     Worklist.push_back(&BI);
12264     while (!Worklist.empty()) {
12265       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12266       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12267 
12268       // If the base has no non-trivial move assignment operators,
12269       // we don't care about moves from it.
12270       if (!Base->hasNonTrivialMoveAssignment())
12271         continue;
12272 
12273       // If there's nothing virtual here, skip it.
12274       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12275         continue;
12276 
12277       // If we're not actually going to call a move assignment for this base,
12278       // or the selected move assignment is trivial, skip it.
12279       Sema::SpecialMemberOverloadResult SMOR =
12280         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12281                               /*ConstArg*/false, /*VolatileArg*/false,
12282                               /*RValueThis*/true, /*ConstThis*/false,
12283                               /*VolatileThis*/false);
12284       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12285           !SMOR.getMethod()->isMoveAssignmentOperator())
12286         continue;
12287 
12288       if (BaseSpec->isVirtual()) {
12289         // We're going to move-assign this virtual base, and its move
12290         // assignment operator is not trivial. If this can happen for
12291         // multiple distinct direct bases of Class, diagnose it. (If it
12292         // only happens in one base, we'll diagnose it when synthesizing
12293         // that base class's move assignment operator.)
12294         CXXBaseSpecifier *&Existing =
12295             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12296                 .first->second;
12297         if (Existing && Existing != &BI) {
12298           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12299             << Class << Base;
12300           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12301               << (Base->getCanonicalDecl() ==
12302                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12303               << Base << Existing->getType() << Existing->getSourceRange();
12304           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12305               << (Base->getCanonicalDecl() ==
12306                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12307               << Base << BI.getType() << BaseSpec->getSourceRange();
12308 
12309           // Only diagnose each vbase once.
12310           Existing = nullptr;
12311         }
12312       } else {
12313         // Only walk over bases that have defaulted move assignment operators.
12314         // We assume that any user-provided move assignment operator handles
12315         // the multiple-moves-of-vbase case itself somehow.
12316         if (!SMOR.getMethod()->isDefaulted())
12317           continue;
12318 
12319         // We're going to move the base classes of Base. Add them to the list.
12320         for (auto &BI : Base->bases())
12321           Worklist.push_back(&BI);
12322       }
12323     }
12324   }
12325 }
12326 
12327 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12328                                         CXXMethodDecl *MoveAssignOperator) {
12329   assert((MoveAssignOperator->isDefaulted() &&
12330           MoveAssignOperator->isOverloadedOperator() &&
12331           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12332           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12333           !MoveAssignOperator->isDeleted()) &&
12334          "DefineImplicitMoveAssignment called for wrong function");
12335   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12336     return;
12337 
12338   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12339   if (ClassDecl->isInvalidDecl()) {
12340     MoveAssignOperator->setInvalidDecl();
12341     return;
12342   }
12343 
12344   // C++0x [class.copy]p28:
12345   //   The implicitly-defined or move assignment operator for a non-union class
12346   //   X performs memberwise move assignment of its subobjects. The direct base
12347   //   classes of X are assigned first, in the order of their declaration in the
12348   //   base-specifier-list, and then the immediate non-static data members of X
12349   //   are assigned, in the order in which they were declared in the class
12350   //   definition.
12351 
12352   // Issue a warning if our implicit move assignment operator will move
12353   // from a virtual base more than once.
12354   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12355 
12356   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12357 
12358   // The exception specification is needed because we are defining the
12359   // function.
12360   ResolveExceptionSpec(CurrentLocation,
12361                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12362 
12363   // Add a context note for diagnostics produced after this point.
12364   Scope.addContextNote(CurrentLocation);
12365 
12366   // The statements that form the synthesized function body.
12367   SmallVector<Stmt*, 8> Statements;
12368 
12369   // The parameter for the "other" object, which we are move from.
12370   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12371   QualType OtherRefType = Other->getType()->
12372       getAs<RValueReferenceType>()->getPointeeType();
12373 
12374   // Our location for everything implicitly-generated.
12375   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12376                            ? MoveAssignOperator->getEndLoc()
12377                            : MoveAssignOperator->getLocation();
12378 
12379   // Builds a reference to the "other" object.
12380   RefBuilder OtherRef(Other, OtherRefType);
12381   // Cast to rvalue.
12382   MoveCastBuilder MoveOther(OtherRef);
12383 
12384   // Builds the "this" pointer.
12385   ThisBuilder This;
12386 
12387   // Assign base classes.
12388   bool Invalid = false;
12389   for (auto &Base : ClassDecl->bases()) {
12390     // C++11 [class.copy]p28:
12391     //   It is unspecified whether subobjects representing virtual base classes
12392     //   are assigned more than once by the implicitly-defined copy assignment
12393     //   operator.
12394     // FIXME: Do not assign to a vbase that will be assigned by some other base
12395     // class. For a move-assignment, this can result in the vbase being moved
12396     // multiple times.
12397 
12398     // Form the assignment:
12399     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12400     QualType BaseType = Base.getType().getUnqualifiedType();
12401     if (!BaseType->isRecordType()) {
12402       Invalid = true;
12403       continue;
12404     }
12405 
12406     CXXCastPath BasePath;
12407     BasePath.push_back(&Base);
12408 
12409     // Construct the "from" expression, which is an implicit cast to the
12410     // appropriately-qualified base type.
12411     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12412 
12413     // Dereference "this".
12414     DerefBuilder DerefThis(This);
12415 
12416     // Implicitly cast "this" to the appropriately-qualified base type.
12417     CastBuilder To(DerefThis,
12418                    Context.getQualifiedType(
12419                        BaseType, MoveAssignOperator->getMethodQualifiers()),
12420                    VK_LValue, BasePath);
12421 
12422     // Build the move.
12423     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12424                                             To, From,
12425                                             /*CopyingBaseSubobject=*/true,
12426                                             /*Copying=*/false);
12427     if (Move.isInvalid()) {
12428       MoveAssignOperator->setInvalidDecl();
12429       return;
12430     }
12431 
12432     // Success! Record the move.
12433     Statements.push_back(Move.getAs<Expr>());
12434   }
12435 
12436   // Assign non-static members.
12437   for (auto *Field : ClassDecl->fields()) {
12438     // FIXME: We should form some kind of AST representation for the implied
12439     // memcpy in a union copy operation.
12440     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12441       continue;
12442 
12443     if (Field->isInvalidDecl()) {
12444       Invalid = true;
12445       continue;
12446     }
12447 
12448     // Check for members of reference type; we can't move those.
12449     if (Field->getType()->isReferenceType()) {
12450       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12451         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12452       Diag(Field->getLocation(), diag::note_declared_at);
12453       Invalid = true;
12454       continue;
12455     }
12456 
12457     // Check for members of const-qualified, non-class type.
12458     QualType BaseType = Context.getBaseElementType(Field->getType());
12459     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12460       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12461         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12462       Diag(Field->getLocation(), diag::note_declared_at);
12463       Invalid = true;
12464       continue;
12465     }
12466 
12467     // Suppress assigning zero-width bitfields.
12468     if (Field->isZeroLengthBitField(Context))
12469       continue;
12470 
12471     QualType FieldType = Field->getType().getNonReferenceType();
12472     if (FieldType->isIncompleteArrayType()) {
12473       assert(ClassDecl->hasFlexibleArrayMember() &&
12474              "Incomplete array type is not valid");
12475       continue;
12476     }
12477 
12478     // Build references to the field in the object we're copying from and to.
12479     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12480                               LookupMemberName);
12481     MemberLookup.addDecl(Field);
12482     MemberLookup.resolveKind();
12483     MemberBuilder From(MoveOther, OtherRefType,
12484                        /*IsArrow=*/false, MemberLookup);
12485     MemberBuilder To(This, getCurrentThisType(),
12486                      /*IsArrow=*/true, MemberLookup);
12487 
12488     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12489         "Member reference with rvalue base must be rvalue except for reference "
12490         "members, which aren't allowed for move assignment.");
12491 
12492     // Build the move of this field.
12493     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12494                                             To, From,
12495                                             /*CopyingBaseSubobject=*/false,
12496                                             /*Copying=*/false);
12497     if (Move.isInvalid()) {
12498       MoveAssignOperator->setInvalidDecl();
12499       return;
12500     }
12501 
12502     // Success! Record the copy.
12503     Statements.push_back(Move.getAs<Stmt>());
12504   }
12505 
12506   if (!Invalid) {
12507     // Add a "return *this;"
12508     ExprResult ThisObj =
12509         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12510 
12511     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12512     if (Return.isInvalid())
12513       Invalid = true;
12514     else
12515       Statements.push_back(Return.getAs<Stmt>());
12516   }
12517 
12518   if (Invalid) {
12519     MoveAssignOperator->setInvalidDecl();
12520     return;
12521   }
12522 
12523   StmtResult Body;
12524   {
12525     CompoundScopeRAII CompoundScope(*this);
12526     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12527                              /*isStmtExpr=*/false);
12528     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12529   }
12530   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12531   MoveAssignOperator->markUsed(Context);
12532 
12533   if (ASTMutationListener *L = getASTMutationListener()) {
12534     L->CompletedImplicitDefinition(MoveAssignOperator);
12535   }
12536 }
12537 
12538 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12539                                                     CXXRecordDecl *ClassDecl) {
12540   // C++ [class.copy]p4:
12541   //   If the class definition does not explicitly declare a copy
12542   //   constructor, one is declared implicitly.
12543   assert(ClassDecl->needsImplicitCopyConstructor());
12544 
12545   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12546   if (DSM.isAlreadyBeingDeclared())
12547     return nullptr;
12548 
12549   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12550   QualType ArgType = ClassType;
12551   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12552   if (Const)
12553     ArgType = ArgType.withConst();
12554 
12555   if (Context.getLangOpts().OpenCLCPlusPlus)
12556     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12557 
12558   ArgType = Context.getLValueReferenceType(ArgType);
12559 
12560   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12561                                                      CXXCopyConstructor,
12562                                                      Const);
12563 
12564   DeclarationName Name
12565     = Context.DeclarationNames.getCXXConstructorName(
12566                                            Context.getCanonicalType(ClassType));
12567   SourceLocation ClassLoc = ClassDecl->getLocation();
12568   DeclarationNameInfo NameInfo(Name, ClassLoc);
12569 
12570   //   An implicitly-declared copy constructor is an inline public
12571   //   member of its class.
12572   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12573       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12574       ExplicitSpecifier(),
12575       /*isInline=*/true,
12576       /*isImplicitlyDeclared=*/true, Constexpr);
12577   CopyConstructor->setAccess(AS_public);
12578   CopyConstructor->setDefaulted();
12579 
12580   if (getLangOpts().CUDA) {
12581     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12582                                             CopyConstructor,
12583                                             /* ConstRHS */ Const,
12584                                             /* Diagnose */ false);
12585   }
12586 
12587   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
12588 
12589   // Add the parameter to the constructor.
12590   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12591                                                ClassLoc, ClassLoc,
12592                                                /*IdentifierInfo=*/nullptr,
12593                                                ArgType, /*TInfo=*/nullptr,
12594                                                SC_None, nullptr);
12595   CopyConstructor->setParams(FromParam);
12596 
12597   CopyConstructor->setTrivial(
12598       ClassDecl->needsOverloadResolutionForCopyConstructor()
12599           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12600           : ClassDecl->hasTrivialCopyConstructor());
12601 
12602   CopyConstructor->setTrivialForCall(
12603       ClassDecl->hasAttr<TrivialABIAttr>() ||
12604       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12605            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12606              TAH_ConsiderTrivialABI)
12607            : ClassDecl->hasTrivialCopyConstructorForCall()));
12608 
12609   // Note that we have declared this constructor.
12610   ++getASTContext().NumImplicitCopyConstructorsDeclared;
12611 
12612   Scope *S = getScopeForContext(ClassDecl);
12613   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12614 
12615   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12616     ClassDecl->setImplicitCopyConstructorIsDeleted();
12617     SetDeclDeleted(CopyConstructor, ClassLoc);
12618   }
12619 
12620   if (S)
12621     PushOnScopeChains(CopyConstructor, S, false);
12622   ClassDecl->addDecl(CopyConstructor);
12623 
12624   return CopyConstructor;
12625 }
12626 
12627 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12628                                          CXXConstructorDecl *CopyConstructor) {
12629   assert((CopyConstructor->isDefaulted() &&
12630           CopyConstructor->isCopyConstructor() &&
12631           !CopyConstructor->doesThisDeclarationHaveABody() &&
12632           !CopyConstructor->isDeleted()) &&
12633          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12634   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12635     return;
12636 
12637   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12638   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12639 
12640   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12641 
12642   // The exception specification is needed because we are defining the
12643   // function.
12644   ResolveExceptionSpec(CurrentLocation,
12645                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12646   MarkVTableUsed(CurrentLocation, ClassDecl);
12647 
12648   // Add a context note for diagnostics produced after this point.
12649   Scope.addContextNote(CurrentLocation);
12650 
12651   // C++11 [class.copy]p7:
12652   //   The [definition of an implicitly declared copy constructor] is
12653   //   deprecated if the class has a user-declared copy assignment operator
12654   //   or a user-declared destructor.
12655   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12656     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12657 
12658   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12659     CopyConstructor->setInvalidDecl();
12660   }  else {
12661     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12662                              ? CopyConstructor->getEndLoc()
12663                              : CopyConstructor->getLocation();
12664     Sema::CompoundScopeRAII CompoundScope(*this);
12665     CopyConstructor->setBody(
12666         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12667     CopyConstructor->markUsed(Context);
12668   }
12669 
12670   if (ASTMutationListener *L = getASTMutationListener()) {
12671     L->CompletedImplicitDefinition(CopyConstructor);
12672   }
12673 }
12674 
12675 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12676                                                     CXXRecordDecl *ClassDecl) {
12677   assert(ClassDecl->needsImplicitMoveConstructor());
12678 
12679   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12680   if (DSM.isAlreadyBeingDeclared())
12681     return nullptr;
12682 
12683   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12684 
12685   QualType ArgType = ClassType;
12686   if (Context.getLangOpts().OpenCLCPlusPlus)
12687     ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
12688   ArgType = Context.getRValueReferenceType(ArgType);
12689 
12690   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12691                                                      CXXMoveConstructor,
12692                                                      false);
12693 
12694   DeclarationName Name
12695     = Context.DeclarationNames.getCXXConstructorName(
12696                                            Context.getCanonicalType(ClassType));
12697   SourceLocation ClassLoc = ClassDecl->getLocation();
12698   DeclarationNameInfo NameInfo(Name, ClassLoc);
12699 
12700   // C++11 [class.copy]p11:
12701   //   An implicitly-declared copy/move constructor is an inline public
12702   //   member of its class.
12703   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12704       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12705       ExplicitSpecifier(),
12706       /*isInline=*/true,
12707       /*isImplicitlyDeclared=*/true, Constexpr);
12708   MoveConstructor->setAccess(AS_public);
12709   MoveConstructor->setDefaulted();
12710 
12711   if (getLangOpts().CUDA) {
12712     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12713                                             MoveConstructor,
12714                                             /* ConstRHS */ false,
12715                                             /* Diagnose */ false);
12716   }
12717 
12718   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
12719 
12720   // Add the parameter to the constructor.
12721   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12722                                                ClassLoc, ClassLoc,
12723                                                /*IdentifierInfo=*/nullptr,
12724                                                ArgType, /*TInfo=*/nullptr,
12725                                                SC_None, nullptr);
12726   MoveConstructor->setParams(FromParam);
12727 
12728   MoveConstructor->setTrivial(
12729       ClassDecl->needsOverloadResolutionForMoveConstructor()
12730           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12731           : ClassDecl->hasTrivialMoveConstructor());
12732 
12733   MoveConstructor->setTrivialForCall(
12734       ClassDecl->hasAttr<TrivialABIAttr>() ||
12735       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12736            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12737                                     TAH_ConsiderTrivialABI)
12738            : ClassDecl->hasTrivialMoveConstructorForCall()));
12739 
12740   // Note that we have declared this constructor.
12741   ++getASTContext().NumImplicitMoveConstructorsDeclared;
12742 
12743   Scope *S = getScopeForContext(ClassDecl);
12744   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12745 
12746   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12747     ClassDecl->setImplicitMoveConstructorIsDeleted();
12748     SetDeclDeleted(MoveConstructor, ClassLoc);
12749   }
12750 
12751   if (S)
12752     PushOnScopeChains(MoveConstructor, S, false);
12753   ClassDecl->addDecl(MoveConstructor);
12754 
12755   return MoveConstructor;
12756 }
12757 
12758 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12759                                          CXXConstructorDecl *MoveConstructor) {
12760   assert((MoveConstructor->isDefaulted() &&
12761           MoveConstructor->isMoveConstructor() &&
12762           !MoveConstructor->doesThisDeclarationHaveABody() &&
12763           !MoveConstructor->isDeleted()) &&
12764          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12765   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12766     return;
12767 
12768   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12769   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12770 
12771   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12772 
12773   // The exception specification is needed because we are defining the
12774   // function.
12775   ResolveExceptionSpec(CurrentLocation,
12776                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12777   MarkVTableUsed(CurrentLocation, ClassDecl);
12778 
12779   // Add a context note for diagnostics produced after this point.
12780   Scope.addContextNote(CurrentLocation);
12781 
12782   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12783     MoveConstructor->setInvalidDecl();
12784   } else {
12785     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12786                              ? MoveConstructor->getEndLoc()
12787                              : MoveConstructor->getLocation();
12788     Sema::CompoundScopeRAII CompoundScope(*this);
12789     MoveConstructor->setBody(ActOnCompoundStmt(
12790         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12791     MoveConstructor->markUsed(Context);
12792   }
12793 
12794   if (ASTMutationListener *L = getASTMutationListener()) {
12795     L->CompletedImplicitDefinition(MoveConstructor);
12796   }
12797 }
12798 
12799 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12800   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12801 }
12802 
12803 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12804                             SourceLocation CurrentLocation,
12805                             CXXConversionDecl *Conv) {
12806   SynthesizedFunctionScope Scope(*this, Conv);
12807   assert(!Conv->getReturnType()->isUndeducedType());
12808 
12809   CXXRecordDecl *Lambda = Conv->getParent();
12810   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12811   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12812 
12813   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12814     CallOp = InstantiateFunctionDeclaration(
12815         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12816     if (!CallOp)
12817       return;
12818 
12819     Invoker = InstantiateFunctionDeclaration(
12820         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12821     if (!Invoker)
12822       return;
12823   }
12824 
12825   if (CallOp->isInvalidDecl())
12826     return;
12827 
12828   // Mark the call operator referenced (and add to pending instantiations
12829   // if necessary).
12830   // For both the conversion and static-invoker template specializations
12831   // we construct their body's in this function, so no need to add them
12832   // to the PendingInstantiations.
12833   MarkFunctionReferenced(CurrentLocation, CallOp);
12834 
12835   // Fill in the __invoke function with a dummy implementation. IR generation
12836   // will fill in the actual details. Update its type in case it contained
12837   // an 'auto'.
12838   Invoker->markUsed(Context);
12839   Invoker->setReferenced();
12840   Invoker->setType(Conv->getReturnType()->getPointeeType());
12841   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12842 
12843   // Construct the body of the conversion function { return __invoke; }.
12844   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12845                                        VK_LValue, Conv->getLocation()).get();
12846   assert(FunctionRef && "Can't refer to __invoke function?");
12847   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12848   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12849                                      Conv->getLocation()));
12850   Conv->markUsed(Context);
12851   Conv->setReferenced();
12852 
12853   if (ASTMutationListener *L = getASTMutationListener()) {
12854     L->CompletedImplicitDefinition(Conv);
12855     L->CompletedImplicitDefinition(Invoker);
12856   }
12857 }
12858 
12859 
12860 
12861 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12862        SourceLocation CurrentLocation,
12863        CXXConversionDecl *Conv)
12864 {
12865   assert(!Conv->getParent()->isGenericLambda());
12866 
12867   SynthesizedFunctionScope Scope(*this, Conv);
12868 
12869   // Copy-initialize the lambda object as needed to capture it.
12870   Expr *This = ActOnCXXThis(CurrentLocation).get();
12871   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12872 
12873   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12874                                                         Conv->getLocation(),
12875                                                         Conv, DerefThis);
12876 
12877   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12878   // behavior.  Note that only the general conversion function does this
12879   // (since it's unusable otherwise); in the case where we inline the
12880   // block literal, it has block literal lifetime semantics.
12881   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12882     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12883                                           CK_CopyAndAutoreleaseBlockObject,
12884                                           BuildBlock.get(), nullptr, VK_RValue);
12885 
12886   if (BuildBlock.isInvalid()) {
12887     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12888     Conv->setInvalidDecl();
12889     return;
12890   }
12891 
12892   // Create the return statement that returns the block from the conversion
12893   // function.
12894   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12895   if (Return.isInvalid()) {
12896     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12897     Conv->setInvalidDecl();
12898     return;
12899   }
12900 
12901   // Set the body of the conversion function.
12902   Stmt *ReturnS = Return.get();
12903   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12904                                      Conv->getLocation()));
12905   Conv->markUsed(Context);
12906 
12907   // We're done; notify the mutation listener, if any.
12908   if (ASTMutationListener *L = getASTMutationListener()) {
12909     L->CompletedImplicitDefinition(Conv);
12910   }
12911 }
12912 
12913 /// Determine whether the given list arguments contains exactly one
12914 /// "real" (non-default) argument.
12915 static bool hasOneRealArgument(MultiExprArg Args) {
12916   switch (Args.size()) {
12917   case 0:
12918     return false;
12919 
12920   default:
12921     if (!Args[1]->isDefaultArgument())
12922       return false;
12923 
12924     LLVM_FALLTHROUGH;
12925   case 1:
12926     return !Args[0]->isDefaultArgument();
12927   }
12928 
12929   return false;
12930 }
12931 
12932 ExprResult
12933 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12934                             NamedDecl *FoundDecl,
12935                             CXXConstructorDecl *Constructor,
12936                             MultiExprArg ExprArgs,
12937                             bool HadMultipleCandidates,
12938                             bool IsListInitialization,
12939                             bool IsStdInitListInitialization,
12940                             bool RequiresZeroInit,
12941                             unsigned ConstructKind,
12942                             SourceRange ParenRange) {
12943   bool Elidable = false;
12944 
12945   // C++0x [class.copy]p34:
12946   //   When certain criteria are met, an implementation is allowed to
12947   //   omit the copy/move construction of a class object, even if the
12948   //   copy/move constructor and/or destructor for the object have
12949   //   side effects. [...]
12950   //     - when a temporary class object that has not been bound to a
12951   //       reference (12.2) would be copied/moved to a class object
12952   //       with the same cv-unqualified type, the copy/move operation
12953   //       can be omitted by constructing the temporary object
12954   //       directly into the target of the omitted copy/move
12955   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12956       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12957     Expr *SubExpr = ExprArgs[0];
12958     Elidable = SubExpr->isTemporaryObject(
12959         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12960   }
12961 
12962   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12963                                FoundDecl, Constructor,
12964                                Elidable, ExprArgs, HadMultipleCandidates,
12965                                IsListInitialization,
12966                                IsStdInitListInitialization, RequiresZeroInit,
12967                                ConstructKind, ParenRange);
12968 }
12969 
12970 ExprResult
12971 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12972                             NamedDecl *FoundDecl,
12973                             CXXConstructorDecl *Constructor,
12974                             bool Elidable,
12975                             MultiExprArg ExprArgs,
12976                             bool HadMultipleCandidates,
12977                             bool IsListInitialization,
12978                             bool IsStdInitListInitialization,
12979                             bool RequiresZeroInit,
12980                             unsigned ConstructKind,
12981                             SourceRange ParenRange) {
12982   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12983     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12984     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12985       return ExprError();
12986   }
12987 
12988   return BuildCXXConstructExpr(
12989       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12990       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12991       RequiresZeroInit, ConstructKind, ParenRange);
12992 }
12993 
12994 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12995 /// including handling of its default argument expressions.
12996 ExprResult
12997 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12998                             CXXConstructorDecl *Constructor,
12999                             bool Elidable,
13000                             MultiExprArg ExprArgs,
13001                             bool HadMultipleCandidates,
13002                             bool IsListInitialization,
13003                             bool IsStdInitListInitialization,
13004                             bool RequiresZeroInit,
13005                             unsigned ConstructKind,
13006                             SourceRange ParenRange) {
13007   assert(declaresSameEntity(
13008              Constructor->getParent(),
13009              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
13010          "given constructor for wrong type");
13011   MarkFunctionReferenced(ConstructLoc, Constructor);
13012   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
13013     return ExprError();
13014 
13015   return CXXConstructExpr::Create(
13016       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
13017       ExprArgs, HadMultipleCandidates, IsListInitialization,
13018       IsStdInitListInitialization, RequiresZeroInit,
13019       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
13020       ParenRange);
13021 }
13022 
13023 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
13024   assert(Field->hasInClassInitializer());
13025 
13026   // If we already have the in-class initializer nothing needs to be done.
13027   if (Field->getInClassInitializer())
13028     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13029 
13030   // If we might have already tried and failed to instantiate, don't try again.
13031   if (Field->isInvalidDecl())
13032     return ExprError();
13033 
13034   // Maybe we haven't instantiated the in-class initializer. Go check the
13035   // pattern FieldDecl to see if it has one.
13036   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
13037 
13038   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
13039     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
13040     DeclContext::lookup_result Lookup =
13041         ClassPattern->lookup(Field->getDeclName());
13042 
13043     // Lookup can return at most two results: the pattern for the field, or the
13044     // injected class name of the parent record. No other member can have the
13045     // same name as the field.
13046     // In modules mode, lookup can return multiple results (coming from
13047     // different modules).
13048     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
13049            "more than two lookup results for field name");
13050     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
13051     if (!Pattern) {
13052       assert(isa<CXXRecordDecl>(Lookup[0]) &&
13053              "cannot have other non-field member with same name");
13054       for (auto L : Lookup)
13055         if (isa<FieldDecl>(L)) {
13056           Pattern = cast<FieldDecl>(L);
13057           break;
13058         }
13059       assert(Pattern && "We must have set the Pattern!");
13060     }
13061 
13062     if (!Pattern->hasInClassInitializer() ||
13063         InstantiateInClassInitializer(Loc, Field, Pattern,
13064                                       getTemplateInstantiationArgs(Field))) {
13065       // Don't diagnose this again.
13066       Field->setInvalidDecl();
13067       return ExprError();
13068     }
13069     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13070   }
13071 
13072   // DR1351:
13073   //   If the brace-or-equal-initializer of a non-static data member
13074   //   invokes a defaulted default constructor of its class or of an
13075   //   enclosing class in a potentially evaluated subexpression, the
13076   //   program is ill-formed.
13077   //
13078   // This resolution is unworkable: the exception specification of the
13079   // default constructor can be needed in an unevaluated context, in
13080   // particular, in the operand of a noexcept-expression, and we can be
13081   // unable to compute an exception specification for an enclosed class.
13082   //
13083   // Any attempt to resolve the exception specification of a defaulted default
13084   // constructor before the initializer is lexically complete will ultimately
13085   // come here at which point we can diagnose it.
13086   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13087   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13088       << OutermostClass << Field;
13089   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13090   // Recover by marking the field invalid, unless we're in a SFINAE context.
13091   if (!isSFINAEContext())
13092     Field->setInvalidDecl();
13093   return ExprError();
13094 }
13095 
13096 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13097   if (VD->isInvalidDecl()) return;
13098 
13099   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13100   if (ClassDecl->isInvalidDecl()) return;
13101   if (ClassDecl->hasIrrelevantDestructor()) return;
13102   if (ClassDecl->isDependentContext()) return;
13103 
13104   if (VD->isNoDestroy(getASTContext()))
13105     return;
13106 
13107   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13108 
13109   // If this is an array, we'll require the destructor during initialization, so
13110   // we can skip over this. We still want to emit exit-time destructor warnings
13111   // though.
13112   if (!VD->getType()->isArrayType()) {
13113     MarkFunctionReferenced(VD->getLocation(), Destructor);
13114     CheckDestructorAccess(VD->getLocation(), Destructor,
13115                           PDiag(diag::err_access_dtor_var)
13116                               << VD->getDeclName() << VD->getType());
13117     DiagnoseUseOfDecl(Destructor, VD->getLocation());
13118   }
13119 
13120   if (Destructor->isTrivial()) return;
13121   if (!VD->hasGlobalStorage()) return;
13122 
13123   // Emit warning for non-trivial dtor in global scope (a real global,
13124   // class-static, function-static).
13125   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13126 
13127   // TODO: this should be re-enabled for static locals by !CXAAtExit
13128   if (!VD->isStaticLocal())
13129     Diag(VD->getLocation(), diag::warn_global_destructor);
13130 }
13131 
13132 /// Given a constructor and the set of arguments provided for the
13133 /// constructor, convert the arguments and add any required default arguments
13134 /// to form a proper call to this constructor.
13135 ///
13136 /// \returns true if an error occurred, false otherwise.
13137 bool
13138 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13139                               MultiExprArg ArgsPtr,
13140                               SourceLocation Loc,
13141                               SmallVectorImpl<Expr*> &ConvertedArgs,
13142                               bool AllowExplicit,
13143                               bool IsListInitialization) {
13144   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13145   unsigned NumArgs = ArgsPtr.size();
13146   Expr **Args = ArgsPtr.data();
13147 
13148   const FunctionProtoType *Proto
13149     = Constructor->getType()->getAs<FunctionProtoType>();
13150   assert(Proto && "Constructor without a prototype?");
13151   unsigned NumParams = Proto->getNumParams();
13152 
13153   // If too few arguments are available, we'll fill in the rest with defaults.
13154   if (NumArgs < NumParams)
13155     ConvertedArgs.reserve(NumParams);
13156   else
13157     ConvertedArgs.reserve(NumArgs);
13158 
13159   VariadicCallType CallType =
13160     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13161   SmallVector<Expr *, 8> AllArgs;
13162   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13163                                         Proto, 0,
13164                                         llvm::makeArrayRef(Args, NumArgs),
13165                                         AllArgs,
13166                                         CallType, AllowExplicit,
13167                                         IsListInitialization);
13168   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13169 
13170   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13171 
13172   CheckConstructorCall(Constructor,
13173                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13174                        Proto, Loc);
13175 
13176   return Invalid;
13177 }
13178 
13179 static inline bool
13180 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13181                                        const FunctionDecl *FnDecl) {
13182   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13183   if (isa<NamespaceDecl>(DC)) {
13184     return SemaRef.Diag(FnDecl->getLocation(),
13185                         diag::err_operator_new_delete_declared_in_namespace)
13186       << FnDecl->getDeclName();
13187   }
13188 
13189   if (isa<TranslationUnitDecl>(DC) &&
13190       FnDecl->getStorageClass() == SC_Static) {
13191     return SemaRef.Diag(FnDecl->getLocation(),
13192                         diag::err_operator_new_delete_declared_static)
13193       << FnDecl->getDeclName();
13194   }
13195 
13196   return false;
13197 }
13198 
13199 static QualType
13200 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13201   QualType QTy = PtrTy->getPointeeType();
13202   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13203   return SemaRef.Context.getPointerType(QTy);
13204 }
13205 
13206 static inline bool
13207 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13208                             CanQualType ExpectedResultType,
13209                             CanQualType ExpectedFirstParamType,
13210                             unsigned DependentParamTypeDiag,
13211                             unsigned InvalidParamTypeDiag) {
13212   QualType ResultType =
13213       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13214 
13215   // Check that the result type is not dependent.
13216   if (ResultType->isDependentType())
13217     return SemaRef.Diag(FnDecl->getLocation(),
13218                         diag::err_operator_new_delete_dependent_result_type)
13219     << FnDecl->getDeclName() << ExpectedResultType;
13220 
13221   // OpenCL C++: the operator is valid on any address space.
13222   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13223     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13224       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13225     }
13226   }
13227 
13228   // Check that the result type is what we expect.
13229   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13230     return SemaRef.Diag(FnDecl->getLocation(),
13231                         diag::err_operator_new_delete_invalid_result_type)
13232     << FnDecl->getDeclName() << ExpectedResultType;
13233 
13234   // A function template must have at least 2 parameters.
13235   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13236     return SemaRef.Diag(FnDecl->getLocation(),
13237                       diag::err_operator_new_delete_template_too_few_parameters)
13238         << FnDecl->getDeclName();
13239 
13240   // The function decl must have at least 1 parameter.
13241   if (FnDecl->getNumParams() == 0)
13242     return SemaRef.Diag(FnDecl->getLocation(),
13243                         diag::err_operator_new_delete_too_few_parameters)
13244       << FnDecl->getDeclName();
13245 
13246   // Check the first parameter type is not dependent.
13247   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13248   if (FirstParamType->isDependentType())
13249     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13250       << FnDecl->getDeclName() << ExpectedFirstParamType;
13251 
13252   // Check that the first parameter type is what we expect.
13253   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13254     // OpenCL C++: the operator is valid on any address space.
13255     if (auto *PtrTy =
13256             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13257       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13258     }
13259   }
13260   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13261       ExpectedFirstParamType)
13262     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13263     << FnDecl->getDeclName() << ExpectedFirstParamType;
13264 
13265   return false;
13266 }
13267 
13268 static bool
13269 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13270   // C++ [basic.stc.dynamic.allocation]p1:
13271   //   A program is ill-formed if an allocation function is declared in a
13272   //   namespace scope other than global scope or declared static in global
13273   //   scope.
13274   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13275     return true;
13276 
13277   CanQualType SizeTy =
13278     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13279 
13280   // C++ [basic.stc.dynamic.allocation]p1:
13281   //  The return type shall be void*. The first parameter shall have type
13282   //  std::size_t.
13283   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13284                                   SizeTy,
13285                                   diag::err_operator_new_dependent_param_type,
13286                                   diag::err_operator_new_param_type))
13287     return true;
13288 
13289   // C++ [basic.stc.dynamic.allocation]p1:
13290   //  The first parameter shall not have an associated default argument.
13291   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13292     return SemaRef.Diag(FnDecl->getLocation(),
13293                         diag::err_operator_new_default_arg)
13294       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13295 
13296   return false;
13297 }
13298 
13299 static bool
13300 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13301   // C++ [basic.stc.dynamic.deallocation]p1:
13302   //   A program is ill-formed if deallocation functions are declared in a
13303   //   namespace scope other than global scope or declared static in global
13304   //   scope.
13305   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13306     return true;
13307 
13308   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13309 
13310   // C++ P0722:
13311   //   Within a class C, the first parameter of a destroying operator delete
13312   //   shall be of type C *. The first parameter of any other deallocation
13313   //   function shall be of type void *.
13314   CanQualType ExpectedFirstParamType =
13315       MD && MD->isDestroyingOperatorDelete()
13316           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13317                 SemaRef.Context.getRecordType(MD->getParent())))
13318           : SemaRef.Context.VoidPtrTy;
13319 
13320   // C++ [basic.stc.dynamic.deallocation]p2:
13321   //   Each deallocation function shall return void
13322   if (CheckOperatorNewDeleteTypes(
13323           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13324           diag::err_operator_delete_dependent_param_type,
13325           diag::err_operator_delete_param_type))
13326     return true;
13327 
13328   // C++ P0722:
13329   //   A destroying operator delete shall be a usual deallocation function.
13330   if (MD && !MD->getParent()->isDependentContext() &&
13331       MD->isDestroyingOperatorDelete() &&
13332       !SemaRef.isUsualDeallocationFunction(MD)) {
13333     SemaRef.Diag(MD->getLocation(),
13334                  diag::err_destroying_operator_delete_not_usual);
13335     return true;
13336   }
13337 
13338   return false;
13339 }
13340 
13341 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13342 /// of this overloaded operator is well-formed. If so, returns false;
13343 /// otherwise, emits appropriate diagnostics and returns true.
13344 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13345   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13346          "Expected an overloaded operator declaration");
13347 
13348   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13349 
13350   // C++ [over.oper]p5:
13351   //   The allocation and deallocation functions, operator new,
13352   //   operator new[], operator delete and operator delete[], are
13353   //   described completely in 3.7.3. The attributes and restrictions
13354   //   found in the rest of this subclause do not apply to them unless
13355   //   explicitly stated in 3.7.3.
13356   if (Op == OO_Delete || Op == OO_Array_Delete)
13357     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13358 
13359   if (Op == OO_New || Op == OO_Array_New)
13360     return CheckOperatorNewDeclaration(*this, FnDecl);
13361 
13362   // C++ [over.oper]p6:
13363   //   An operator function shall either be a non-static member
13364   //   function or be a non-member function and have at least one
13365   //   parameter whose type is a class, a reference to a class, an
13366   //   enumeration, or a reference to an enumeration.
13367   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13368     if (MethodDecl->isStatic())
13369       return Diag(FnDecl->getLocation(),
13370                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13371   } else {
13372     bool ClassOrEnumParam = false;
13373     for (auto Param : FnDecl->parameters()) {
13374       QualType ParamType = Param->getType().getNonReferenceType();
13375       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13376           ParamType->isEnumeralType()) {
13377         ClassOrEnumParam = true;
13378         break;
13379       }
13380     }
13381 
13382     if (!ClassOrEnumParam)
13383       return Diag(FnDecl->getLocation(),
13384                   diag::err_operator_overload_needs_class_or_enum)
13385         << FnDecl->getDeclName();
13386   }
13387 
13388   // C++ [over.oper]p8:
13389   //   An operator function cannot have default arguments (8.3.6),
13390   //   except where explicitly stated below.
13391   //
13392   // Only the function-call operator allows default arguments
13393   // (C++ [over.call]p1).
13394   if (Op != OO_Call) {
13395     for (auto Param : FnDecl->parameters()) {
13396       if (Param->hasDefaultArg())
13397         return Diag(Param->getLocation(),
13398                     diag::err_operator_overload_default_arg)
13399           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13400     }
13401   }
13402 
13403   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13404     { false, false, false }
13405 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13406     , { Unary, Binary, MemberOnly }
13407 #include "clang/Basic/OperatorKinds.def"
13408   };
13409 
13410   bool CanBeUnaryOperator = OperatorUses[Op][0];
13411   bool CanBeBinaryOperator = OperatorUses[Op][1];
13412   bool MustBeMemberOperator = OperatorUses[Op][2];
13413 
13414   // C++ [over.oper]p8:
13415   //   [...] Operator functions cannot have more or fewer parameters
13416   //   than the number required for the corresponding operator, as
13417   //   described in the rest of this subclause.
13418   unsigned NumParams = FnDecl->getNumParams()
13419                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13420   if (Op != OO_Call &&
13421       ((NumParams == 1 && !CanBeUnaryOperator) ||
13422        (NumParams == 2 && !CanBeBinaryOperator) ||
13423        (NumParams < 1) || (NumParams > 2))) {
13424     // We have the wrong number of parameters.
13425     unsigned ErrorKind;
13426     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13427       ErrorKind = 2;  // 2 -> unary or binary.
13428     } else if (CanBeUnaryOperator) {
13429       ErrorKind = 0;  // 0 -> unary
13430     } else {
13431       assert(CanBeBinaryOperator &&
13432              "All non-call overloaded operators are unary or binary!");
13433       ErrorKind = 1;  // 1 -> binary
13434     }
13435 
13436     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13437       << FnDecl->getDeclName() << NumParams << ErrorKind;
13438   }
13439 
13440   // Overloaded operators other than operator() cannot be variadic.
13441   if (Op != OO_Call &&
13442       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13443     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13444       << FnDecl->getDeclName();
13445   }
13446 
13447   // Some operators must be non-static member functions.
13448   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13449     return Diag(FnDecl->getLocation(),
13450                 diag::err_operator_overload_must_be_member)
13451       << FnDecl->getDeclName();
13452   }
13453 
13454   // C++ [over.inc]p1:
13455   //   The user-defined function called operator++ implements the
13456   //   prefix and postfix ++ operator. If this function is a member
13457   //   function with no parameters, or a non-member function with one
13458   //   parameter of class or enumeration type, it defines the prefix
13459   //   increment operator ++ for objects of that type. If the function
13460   //   is a member function with one parameter (which shall be of type
13461   //   int) or a non-member function with two parameters (the second
13462   //   of which shall be of type int), it defines the postfix
13463   //   increment operator ++ for objects of that type.
13464   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13465     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13466     QualType ParamType = LastParam->getType();
13467 
13468     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13469         !ParamType->isDependentType())
13470       return Diag(LastParam->getLocation(),
13471                   diag::err_operator_overload_post_incdec_must_be_int)
13472         << LastParam->getType() << (Op == OO_MinusMinus);
13473   }
13474 
13475   return false;
13476 }
13477 
13478 static bool
13479 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13480                                           FunctionTemplateDecl *TpDecl) {
13481   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13482 
13483   // Must have one or two template parameters.
13484   if (TemplateParams->size() == 1) {
13485     NonTypeTemplateParmDecl *PmDecl =
13486         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13487 
13488     // The template parameter must be a char parameter pack.
13489     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13490         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13491       return false;
13492 
13493   } else if (TemplateParams->size() == 2) {
13494     TemplateTypeParmDecl *PmType =
13495         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13496     NonTypeTemplateParmDecl *PmArgs =
13497         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13498 
13499     // The second template parameter must be a parameter pack with the
13500     // first template parameter as its type.
13501     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13502         PmArgs->isTemplateParameterPack()) {
13503       const TemplateTypeParmType *TArgs =
13504           PmArgs->getType()->getAs<TemplateTypeParmType>();
13505       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13506           TArgs->getIndex() == PmType->getIndex()) {
13507         if (!SemaRef.inTemplateInstantiation())
13508           SemaRef.Diag(TpDecl->getLocation(),
13509                        diag::ext_string_literal_operator_template);
13510         return false;
13511       }
13512     }
13513   }
13514 
13515   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13516                diag::err_literal_operator_template)
13517       << TpDecl->getTemplateParameters()->getSourceRange();
13518   return true;
13519 }
13520 
13521 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13522 /// of this literal operator function is well-formed. If so, returns
13523 /// false; otherwise, emits appropriate diagnostics and returns true.
13524 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13525   if (isa<CXXMethodDecl>(FnDecl)) {
13526     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13527       << FnDecl->getDeclName();
13528     return true;
13529   }
13530 
13531   if (FnDecl->isExternC()) {
13532     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13533     if (const LinkageSpecDecl *LSD =
13534             FnDecl->getDeclContext()->getExternCContext())
13535       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13536     return true;
13537   }
13538 
13539   // This might be the definition of a literal operator template.
13540   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13541 
13542   // This might be a specialization of a literal operator template.
13543   if (!TpDecl)
13544     TpDecl = FnDecl->getPrimaryTemplate();
13545 
13546   // template <char...> type operator "" name() and
13547   // template <class T, T...> type operator "" name() are the only valid
13548   // template signatures, and the only valid signatures with no parameters.
13549   if (TpDecl) {
13550     if (FnDecl->param_size() != 0) {
13551       Diag(FnDecl->getLocation(),
13552            diag::err_literal_operator_template_with_params);
13553       return true;
13554     }
13555 
13556     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13557       return true;
13558 
13559   } else if (FnDecl->param_size() == 1) {
13560     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13561 
13562     QualType ParamType = Param->getType().getUnqualifiedType();
13563 
13564     // Only unsigned long long int, long double, any character type, and const
13565     // char * are allowed as the only parameters.
13566     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13567         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13568         Context.hasSameType(ParamType, Context.CharTy) ||
13569         Context.hasSameType(ParamType, Context.WideCharTy) ||
13570         Context.hasSameType(ParamType, Context.Char8Ty) ||
13571         Context.hasSameType(ParamType, Context.Char16Ty) ||
13572         Context.hasSameType(ParamType, Context.Char32Ty)) {
13573     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13574       QualType InnerType = Ptr->getPointeeType();
13575 
13576       // Pointer parameter must be a const char *.
13577       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13578                                 Context.CharTy) &&
13579             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13580         Diag(Param->getSourceRange().getBegin(),
13581              diag::err_literal_operator_param)
13582             << ParamType << "'const char *'" << Param->getSourceRange();
13583         return true;
13584       }
13585 
13586     } else if (ParamType->isRealFloatingType()) {
13587       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13588           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13589       return true;
13590 
13591     } else if (ParamType->isIntegerType()) {
13592       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13593           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13594       return true;
13595 
13596     } else {
13597       Diag(Param->getSourceRange().getBegin(),
13598            diag::err_literal_operator_invalid_param)
13599           << ParamType << Param->getSourceRange();
13600       return true;
13601     }
13602 
13603   } else if (FnDecl->param_size() == 2) {
13604     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13605 
13606     // First, verify that the first parameter is correct.
13607 
13608     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13609 
13610     // Two parameter function must have a pointer to const as a
13611     // first parameter; let's strip those qualifiers.
13612     const PointerType *PT = FirstParamType->getAs<PointerType>();
13613 
13614     if (!PT) {
13615       Diag((*Param)->getSourceRange().getBegin(),
13616            diag::err_literal_operator_param)
13617           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13618       return true;
13619     }
13620 
13621     QualType PointeeType = PT->getPointeeType();
13622     // First parameter must be const
13623     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13624       Diag((*Param)->getSourceRange().getBegin(),
13625            diag::err_literal_operator_param)
13626           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13627       return true;
13628     }
13629 
13630     QualType InnerType = PointeeType.getUnqualifiedType();
13631     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13632     // const char32_t* are allowed as the first parameter to a two-parameter
13633     // function
13634     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13635           Context.hasSameType(InnerType, Context.WideCharTy) ||
13636           Context.hasSameType(InnerType, Context.Char8Ty) ||
13637           Context.hasSameType(InnerType, Context.Char16Ty) ||
13638           Context.hasSameType(InnerType, Context.Char32Ty))) {
13639       Diag((*Param)->getSourceRange().getBegin(),
13640            diag::err_literal_operator_param)
13641           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13642       return true;
13643     }
13644 
13645     // Move on to the second and final parameter.
13646     ++Param;
13647 
13648     // The second parameter must be a std::size_t.
13649     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13650     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13651       Diag((*Param)->getSourceRange().getBegin(),
13652            diag::err_literal_operator_param)
13653           << SecondParamType << Context.getSizeType()
13654           << (*Param)->getSourceRange();
13655       return true;
13656     }
13657   } else {
13658     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13659     return true;
13660   }
13661 
13662   // Parameters are good.
13663 
13664   // A parameter-declaration-clause containing a default argument is not
13665   // equivalent to any of the permitted forms.
13666   for (auto Param : FnDecl->parameters()) {
13667     if (Param->hasDefaultArg()) {
13668       Diag(Param->getDefaultArgRange().getBegin(),
13669            diag::err_literal_operator_default_argument)
13670         << Param->getDefaultArgRange();
13671       break;
13672     }
13673   }
13674 
13675   StringRef LiteralName
13676     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13677   if (LiteralName[0] != '_' &&
13678       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13679     // C++11 [usrlit.suffix]p1:
13680     //   Literal suffix identifiers that do not start with an underscore
13681     //   are reserved for future standardization.
13682     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13683       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13684   }
13685 
13686   return false;
13687 }
13688 
13689 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13690 /// linkage specification, including the language and (if present)
13691 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13692 /// language string literal. LBraceLoc, if valid, provides the location of
13693 /// the '{' brace. Otherwise, this linkage specification does not
13694 /// have any braces.
13695 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13696                                            Expr *LangStr,
13697                                            SourceLocation LBraceLoc) {
13698   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13699   if (!Lit->isAscii()) {
13700     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13701       << LangStr->getSourceRange();
13702     return nullptr;
13703   }
13704 
13705   StringRef Lang = Lit->getString();
13706   LinkageSpecDecl::LanguageIDs Language;
13707   if (Lang == "C")
13708     Language = LinkageSpecDecl::lang_c;
13709   else if (Lang == "C++")
13710     Language = LinkageSpecDecl::lang_cxx;
13711   else {
13712     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13713       << LangStr->getSourceRange();
13714     return nullptr;
13715   }
13716 
13717   // FIXME: Add all the various semantics of linkage specifications
13718 
13719   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13720                                                LangStr->getExprLoc(), Language,
13721                                                LBraceLoc.isValid());
13722   CurContext->addDecl(D);
13723   PushDeclContext(S, D);
13724   return D;
13725 }
13726 
13727 /// ActOnFinishLinkageSpecification - Complete the definition of
13728 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13729 /// valid, it's the position of the closing '}' brace in a linkage
13730 /// specification that uses braces.
13731 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13732                                             Decl *LinkageSpec,
13733                                             SourceLocation RBraceLoc) {
13734   if (RBraceLoc.isValid()) {
13735     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13736     LSDecl->setRBraceLoc(RBraceLoc);
13737   }
13738   PopDeclContext();
13739   return LinkageSpec;
13740 }
13741 
13742 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13743                                   const ParsedAttributesView &AttrList,
13744                                   SourceLocation SemiLoc) {
13745   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13746   // Attribute declarations appertain to empty declaration so we handle
13747   // them here.
13748   ProcessDeclAttributeList(S, ED, AttrList);
13749 
13750   CurContext->addDecl(ED);
13751   return ED;
13752 }
13753 
13754 /// Perform semantic analysis for the variable declaration that
13755 /// occurs within a C++ catch clause, returning the newly-created
13756 /// variable.
13757 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13758                                          TypeSourceInfo *TInfo,
13759                                          SourceLocation StartLoc,
13760                                          SourceLocation Loc,
13761                                          IdentifierInfo *Name) {
13762   bool Invalid = false;
13763   QualType ExDeclType = TInfo->getType();
13764 
13765   // Arrays and functions decay.
13766   if (ExDeclType->isArrayType())
13767     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13768   else if (ExDeclType->isFunctionType())
13769     ExDeclType = Context.getPointerType(ExDeclType);
13770 
13771   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13772   // The exception-declaration shall not denote a pointer or reference to an
13773   // incomplete type, other than [cv] void*.
13774   // N2844 forbids rvalue references.
13775   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13776     Diag(Loc, diag::err_catch_rvalue_ref);
13777     Invalid = true;
13778   }
13779 
13780   if (ExDeclType->isVariablyModifiedType()) {
13781     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13782     Invalid = true;
13783   }
13784 
13785   QualType BaseType = ExDeclType;
13786   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13787   unsigned DK = diag::err_catch_incomplete;
13788   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13789     BaseType = Ptr->getPointeeType();
13790     Mode = 1;
13791     DK = diag::err_catch_incomplete_ptr;
13792   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13793     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13794     BaseType = Ref->getPointeeType();
13795     Mode = 2;
13796     DK = diag::err_catch_incomplete_ref;
13797   }
13798   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13799       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13800     Invalid = true;
13801 
13802   if (!Invalid && !ExDeclType->isDependentType() &&
13803       RequireNonAbstractType(Loc, ExDeclType,
13804                              diag::err_abstract_type_in_decl,
13805                              AbstractVariableType))
13806     Invalid = true;
13807 
13808   // Only the non-fragile NeXT runtime currently supports C++ catches
13809   // of ObjC types, and no runtime supports catching ObjC types by value.
13810   if (!Invalid && getLangOpts().ObjC) {
13811     QualType T = ExDeclType;
13812     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13813       T = RT->getPointeeType();
13814 
13815     if (T->isObjCObjectType()) {
13816       Diag(Loc, diag::err_objc_object_catch);
13817       Invalid = true;
13818     } else if (T->isObjCObjectPointerType()) {
13819       // FIXME: should this be a test for macosx-fragile specifically?
13820       if (getLangOpts().ObjCRuntime.isFragile())
13821         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13822     }
13823   }
13824 
13825   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13826                                     ExDeclType, TInfo, SC_None);
13827   ExDecl->setExceptionVariable(true);
13828 
13829   // In ARC, infer 'retaining' for variables of retainable type.
13830   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13831     Invalid = true;
13832 
13833   if (!Invalid && !ExDeclType->isDependentType()) {
13834     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13835       // Insulate this from anything else we might currently be parsing.
13836       EnterExpressionEvaluationContext scope(
13837           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13838 
13839       // C++ [except.handle]p16:
13840       //   The object declared in an exception-declaration or, if the
13841       //   exception-declaration does not specify a name, a temporary (12.2) is
13842       //   copy-initialized (8.5) from the exception object. [...]
13843       //   The object is destroyed when the handler exits, after the destruction
13844       //   of any automatic objects initialized within the handler.
13845       //
13846       // We just pretend to initialize the object with itself, then make sure
13847       // it can be destroyed later.
13848       QualType initType = Context.getExceptionObjectType(ExDeclType);
13849 
13850       InitializedEntity entity =
13851         InitializedEntity::InitializeVariable(ExDecl);
13852       InitializationKind initKind =
13853         InitializationKind::CreateCopy(Loc, SourceLocation());
13854 
13855       Expr *opaqueValue =
13856         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13857       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13858       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13859       if (result.isInvalid())
13860         Invalid = true;
13861       else {
13862         // If the constructor used was non-trivial, set this as the
13863         // "initializer".
13864         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13865         if (!construct->getConstructor()->isTrivial()) {
13866           Expr *init = MaybeCreateExprWithCleanups(construct);
13867           ExDecl->setInit(init);
13868         }
13869 
13870         // And make sure it's destructable.
13871         FinalizeVarWithDestructor(ExDecl, recordType);
13872       }
13873     }
13874   }
13875 
13876   if (Invalid)
13877     ExDecl->setInvalidDecl();
13878 
13879   return ExDecl;
13880 }
13881 
13882 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13883 /// handler.
13884 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13885   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13886   bool Invalid = D.isInvalidType();
13887 
13888   // Check for unexpanded parameter packs.
13889   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13890                                       UPPC_ExceptionType)) {
13891     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13892                                              D.getIdentifierLoc());
13893     Invalid = true;
13894   }
13895 
13896   IdentifierInfo *II = D.getIdentifier();
13897   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13898                                              LookupOrdinaryName,
13899                                              ForVisibleRedeclaration)) {
13900     // The scope should be freshly made just for us. There is just no way
13901     // it contains any previous declaration, except for function parameters in
13902     // a function-try-block's catch statement.
13903     assert(!S->isDeclScope(PrevDecl));
13904     if (isDeclInScope(PrevDecl, CurContext, S)) {
13905       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13906         << D.getIdentifier();
13907       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13908       Invalid = true;
13909     } else if (PrevDecl->isTemplateParameter())
13910       // Maybe we will complain about the shadowed template parameter.
13911       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13912   }
13913 
13914   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13915     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13916       << D.getCXXScopeSpec().getRange();
13917     Invalid = true;
13918   }
13919 
13920   VarDecl *ExDecl = BuildExceptionDeclaration(
13921       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
13922   if (Invalid)
13923     ExDecl->setInvalidDecl();
13924 
13925   // Add the exception declaration into this scope.
13926   if (II)
13927     PushOnScopeChains(ExDecl, S);
13928   else
13929     CurContext->addDecl(ExDecl);
13930 
13931   ProcessDeclAttributes(S, ExDecl, D);
13932   return ExDecl;
13933 }
13934 
13935 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13936                                          Expr *AssertExpr,
13937                                          Expr *AssertMessageExpr,
13938                                          SourceLocation RParenLoc) {
13939   StringLiteral *AssertMessage =
13940       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13941 
13942   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13943     return nullptr;
13944 
13945   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13946                                       AssertMessage, RParenLoc, false);
13947 }
13948 
13949 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13950                                          Expr *AssertExpr,
13951                                          StringLiteral *AssertMessage,
13952                                          SourceLocation RParenLoc,
13953                                          bool Failed) {
13954   assert(AssertExpr != nullptr && "Expected non-null condition");
13955   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13956       !Failed) {
13957     // In a static_assert-declaration, the constant-expression shall be a
13958     // constant expression that can be contextually converted to bool.
13959     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13960     if (Converted.isInvalid())
13961       Failed = true;
13962     else
13963       Converted = ConstantExpr::Create(Context, Converted.get());
13964 
13965     llvm::APSInt Cond;
13966     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13967           diag::err_static_assert_expression_is_not_constant,
13968           /*AllowFold=*/false).isInvalid())
13969       Failed = true;
13970 
13971     if (!Failed && !Cond) {
13972       SmallString<256> MsgBuffer;
13973       llvm::raw_svector_ostream Msg(MsgBuffer);
13974       if (AssertMessage)
13975         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13976 
13977       Expr *InnerCond = nullptr;
13978       std::string InnerCondDescription;
13979       std::tie(InnerCond, InnerCondDescription) =
13980         findFailedBooleanCondition(Converted.get());
13981       if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
13982                     && !isa<IntegerLiteral>(InnerCond)) {
13983         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13984           << InnerCondDescription << !AssertMessage
13985           << Msg.str() << InnerCond->getSourceRange();
13986       } else {
13987         Diag(StaticAssertLoc, diag::err_static_assert_failed)
13988           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13989       }
13990       Failed = true;
13991     }
13992   }
13993 
13994   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13995                                                   /*DiscardedValue*/false,
13996                                                   /*IsConstexpr*/true);
13997   if (FullAssertExpr.isInvalid())
13998     Failed = true;
13999   else
14000     AssertExpr = FullAssertExpr.get();
14001 
14002   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
14003                                         AssertExpr, AssertMessage, RParenLoc,
14004                                         Failed);
14005 
14006   CurContext->addDecl(Decl);
14007   return Decl;
14008 }
14009 
14010 /// Perform semantic analysis of the given friend type declaration.
14011 ///
14012 /// \returns A friend declaration that.
14013 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
14014                                       SourceLocation FriendLoc,
14015                                       TypeSourceInfo *TSInfo) {
14016   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
14017 
14018   QualType T = TSInfo->getType();
14019   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
14020 
14021   // C++03 [class.friend]p2:
14022   //   An elaborated-type-specifier shall be used in a friend declaration
14023   //   for a class.*
14024   //
14025   //   * The class-key of the elaborated-type-specifier is required.
14026   if (!CodeSynthesisContexts.empty()) {
14027     // Do not complain about the form of friend template types during any kind
14028     // of code synthesis. For template instantiation, we will have complained
14029     // when the template was defined.
14030   } else {
14031     if (!T->isElaboratedTypeSpecifier()) {
14032       // If we evaluated the type to a record type, suggest putting
14033       // a tag in front.
14034       if (const RecordType *RT = T->getAs<RecordType>()) {
14035         RecordDecl *RD = RT->getDecl();
14036 
14037         SmallString<16> InsertionText(" ");
14038         InsertionText += RD->getKindName();
14039 
14040         Diag(TypeRange.getBegin(),
14041              getLangOpts().CPlusPlus11 ?
14042                diag::warn_cxx98_compat_unelaborated_friend_type :
14043                diag::ext_unelaborated_friend_type)
14044           << (unsigned) RD->getTagKind()
14045           << T
14046           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
14047                                         InsertionText);
14048       } else {
14049         Diag(FriendLoc,
14050              getLangOpts().CPlusPlus11 ?
14051                diag::warn_cxx98_compat_nonclass_type_friend :
14052                diag::ext_nonclass_type_friend)
14053           << T
14054           << TypeRange;
14055       }
14056     } else if (T->getAs<EnumType>()) {
14057       Diag(FriendLoc,
14058            getLangOpts().CPlusPlus11 ?
14059              diag::warn_cxx98_compat_enum_friend :
14060              diag::ext_enum_friend)
14061         << T
14062         << TypeRange;
14063     }
14064 
14065     // C++11 [class.friend]p3:
14066     //   A friend declaration that does not declare a function shall have one
14067     //   of the following forms:
14068     //     friend elaborated-type-specifier ;
14069     //     friend simple-type-specifier ;
14070     //     friend typename-specifier ;
14071     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14072       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14073   }
14074 
14075   //   If the type specifier in a friend declaration designates a (possibly
14076   //   cv-qualified) class type, that class is declared as a friend; otherwise,
14077   //   the friend declaration is ignored.
14078   return FriendDecl::Create(Context, CurContext,
14079                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14080                             FriendLoc);
14081 }
14082 
14083 /// Handle a friend tag declaration where the scope specifier was
14084 /// templated.
14085 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
14086                                     unsigned TagSpec, SourceLocation TagLoc,
14087                                     CXXScopeSpec &SS, IdentifierInfo *Name,
14088                                     SourceLocation NameLoc,
14089                                     const ParsedAttributesView &Attr,
14090                                     MultiTemplateParamsArg TempParamLists) {
14091   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14092 
14093   bool IsMemberSpecialization = false;
14094   bool Invalid = false;
14095 
14096   if (TemplateParameterList *TemplateParams =
14097           MatchTemplateParametersToScopeSpecifier(
14098               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14099               IsMemberSpecialization, Invalid)) {
14100     if (TemplateParams->size() > 0) {
14101       // This is a declaration of a class template.
14102       if (Invalid)
14103         return nullptr;
14104 
14105       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14106                                 NameLoc, Attr, TemplateParams, AS_public,
14107                                 /*ModulePrivateLoc=*/SourceLocation(),
14108                                 FriendLoc, TempParamLists.size() - 1,
14109                                 TempParamLists.data()).get();
14110     } else {
14111       // The "template<>" header is extraneous.
14112       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14113         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14114       IsMemberSpecialization = true;
14115     }
14116   }
14117 
14118   if (Invalid) return nullptr;
14119 
14120   bool isAllExplicitSpecializations = true;
14121   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14122     if (TempParamLists[I]->size()) {
14123       isAllExplicitSpecializations = false;
14124       break;
14125     }
14126   }
14127 
14128   // FIXME: don't ignore attributes.
14129 
14130   // If it's explicit specializations all the way down, just forget
14131   // about the template header and build an appropriate non-templated
14132   // friend.  TODO: for source fidelity, remember the headers.
14133   if (isAllExplicitSpecializations) {
14134     if (SS.isEmpty()) {
14135       bool Owned = false;
14136       bool IsDependent = false;
14137       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14138                       Attr, AS_public,
14139                       /*ModulePrivateLoc=*/SourceLocation(),
14140                       MultiTemplateParamsArg(), Owned, IsDependent,
14141                       /*ScopedEnumKWLoc=*/SourceLocation(),
14142                       /*ScopedEnumUsesClassTag=*/false,
14143                       /*UnderlyingType=*/TypeResult(),
14144                       /*IsTypeSpecifier=*/false,
14145                       /*IsTemplateParamOrArg=*/false);
14146     }
14147 
14148     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14149     ElaboratedTypeKeyword Keyword
14150       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14151     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14152                                    *Name, NameLoc);
14153     if (T.isNull())
14154       return nullptr;
14155 
14156     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14157     if (isa<DependentNameType>(T)) {
14158       DependentNameTypeLoc TL =
14159           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14160       TL.setElaboratedKeywordLoc(TagLoc);
14161       TL.setQualifierLoc(QualifierLoc);
14162       TL.setNameLoc(NameLoc);
14163     } else {
14164       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14165       TL.setElaboratedKeywordLoc(TagLoc);
14166       TL.setQualifierLoc(QualifierLoc);
14167       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14168     }
14169 
14170     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14171                                             TSI, FriendLoc, TempParamLists);
14172     Friend->setAccess(AS_public);
14173     CurContext->addDecl(Friend);
14174     return Friend;
14175   }
14176 
14177   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14178 
14179 
14180 
14181   // Handle the case of a templated-scope friend class.  e.g.
14182   //   template <class T> class A<T>::B;
14183   // FIXME: we don't support these right now.
14184   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14185     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14186   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14187   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14188   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14189   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14190   TL.setElaboratedKeywordLoc(TagLoc);
14191   TL.setQualifierLoc(SS.getWithLocInContext(Context));
14192   TL.setNameLoc(NameLoc);
14193 
14194   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14195                                           TSI, FriendLoc, TempParamLists);
14196   Friend->setAccess(AS_public);
14197   Friend->setUnsupportedFriend(true);
14198   CurContext->addDecl(Friend);
14199   return Friend;
14200 }
14201 
14202 /// Handle a friend type declaration.  This works in tandem with
14203 /// ActOnTag.
14204 ///
14205 /// Notes on friend class templates:
14206 ///
14207 /// We generally treat friend class declarations as if they were
14208 /// declaring a class.  So, for example, the elaborated type specifier
14209 /// in a friend declaration is required to obey the restrictions of a
14210 /// class-head (i.e. no typedefs in the scope chain), template
14211 /// parameters are required to match up with simple template-ids, &c.
14212 /// However, unlike when declaring a template specialization, it's
14213 /// okay to refer to a template specialization without an empty
14214 /// template parameter declaration, e.g.
14215 ///   friend class A<T>::B<unsigned>;
14216 /// We permit this as a special case; if there are any template
14217 /// parameters present at all, require proper matching, i.e.
14218 ///   template <> template \<class T> friend class A<int>::B;
14219 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14220                                 MultiTemplateParamsArg TempParams) {
14221   SourceLocation Loc = DS.getBeginLoc();
14222 
14223   assert(DS.isFriendSpecified());
14224   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14225 
14226   // C++ [class.friend]p3:
14227   // A friend declaration that does not declare a function shall have one of
14228   // the following forms:
14229   //     friend elaborated-type-specifier ;
14230   //     friend simple-type-specifier ;
14231   //     friend typename-specifier ;
14232   //
14233   // Any declaration with a type qualifier does not have that form. (It's
14234   // legal to specify a qualified type as a friend, you just can't write the
14235   // keywords.)
14236   if (DS.getTypeQualifiers()) {
14237     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14238       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14239     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14240       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14241     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14242       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14243     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14244       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14245     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14246       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14247   }
14248 
14249   // Try to convert the decl specifier to a type.  This works for
14250   // friend templates because ActOnTag never produces a ClassTemplateDecl
14251   // for a TUK_Friend.
14252   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14253   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14254   QualType T = TSI->getType();
14255   if (TheDeclarator.isInvalidType())
14256     return nullptr;
14257 
14258   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14259     return nullptr;
14260 
14261   // This is definitely an error in C++98.  It's probably meant to
14262   // be forbidden in C++0x, too, but the specification is just
14263   // poorly written.
14264   //
14265   // The problem is with declarations like the following:
14266   //   template <T> friend A<T>::foo;
14267   // where deciding whether a class C is a friend or not now hinges
14268   // on whether there exists an instantiation of A that causes
14269   // 'foo' to equal C.  There are restrictions on class-heads
14270   // (which we declare (by fiat) elaborated friend declarations to
14271   // be) that makes this tractable.
14272   //
14273   // FIXME: handle "template <> friend class A<T>;", which
14274   // is possibly well-formed?  Who even knows?
14275   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14276     Diag(Loc, diag::err_tagless_friend_type_template)
14277       << DS.getSourceRange();
14278     return nullptr;
14279   }
14280 
14281   // C++98 [class.friend]p1: A friend of a class is a function
14282   //   or class that is not a member of the class . . .
14283   // This is fixed in DR77, which just barely didn't make the C++03
14284   // deadline.  It's also a very silly restriction that seriously
14285   // affects inner classes and which nobody else seems to implement;
14286   // thus we never diagnose it, not even in -pedantic.
14287   //
14288   // But note that we could warn about it: it's always useless to
14289   // friend one of your own members (it's not, however, worthless to
14290   // friend a member of an arbitrary specialization of your template).
14291 
14292   Decl *D;
14293   if (!TempParams.empty())
14294     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14295                                    TempParams,
14296                                    TSI,
14297                                    DS.getFriendSpecLoc());
14298   else
14299     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14300 
14301   if (!D)
14302     return nullptr;
14303 
14304   D->setAccess(AS_public);
14305   CurContext->addDecl(D);
14306 
14307   return D;
14308 }
14309 
14310 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14311                                         MultiTemplateParamsArg TemplateParams) {
14312   const DeclSpec &DS = D.getDeclSpec();
14313 
14314   assert(DS.isFriendSpecified());
14315   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14316 
14317   SourceLocation Loc = D.getIdentifierLoc();
14318   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14319 
14320   // C++ [class.friend]p1
14321   //   A friend of a class is a function or class....
14322   // Note that this sees through typedefs, which is intended.
14323   // It *doesn't* see through dependent types, which is correct
14324   // according to [temp.arg.type]p3:
14325   //   If a declaration acquires a function type through a
14326   //   type dependent on a template-parameter and this causes
14327   //   a declaration that does not use the syntactic form of a
14328   //   function declarator to have a function type, the program
14329   //   is ill-formed.
14330   if (!TInfo->getType()->isFunctionType()) {
14331     Diag(Loc, diag::err_unexpected_friend);
14332 
14333     // It might be worthwhile to try to recover by creating an
14334     // appropriate declaration.
14335     return nullptr;
14336   }
14337 
14338   // C++ [namespace.memdef]p3
14339   //  - If a friend declaration in a non-local class first declares a
14340   //    class or function, the friend class or function is a member
14341   //    of the innermost enclosing namespace.
14342   //  - The name of the friend is not found by simple name lookup
14343   //    until a matching declaration is provided in that namespace
14344   //    scope (either before or after the class declaration granting
14345   //    friendship).
14346   //  - If a friend function is called, its name may be found by the
14347   //    name lookup that considers functions from namespaces and
14348   //    classes associated with the types of the function arguments.
14349   //  - When looking for a prior declaration of a class or a function
14350   //    declared as a friend, scopes outside the innermost enclosing
14351   //    namespace scope are not considered.
14352 
14353   CXXScopeSpec &SS = D.getCXXScopeSpec();
14354   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14355   assert(NameInfo.getName());
14356 
14357   // Check for unexpanded parameter packs.
14358   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14359       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14360       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14361     return nullptr;
14362 
14363   // The context we found the declaration in, or in which we should
14364   // create the declaration.
14365   DeclContext *DC;
14366   Scope *DCScope = S;
14367   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14368                         ForExternalRedeclaration);
14369 
14370   // There are five cases here.
14371   //   - There's no scope specifier and we're in a local class. Only look
14372   //     for functions declared in the immediately-enclosing block scope.
14373   // We recover from invalid scope qualifiers as if they just weren't there.
14374   FunctionDecl *FunctionContainingLocalClass = nullptr;
14375   if ((SS.isInvalid() || !SS.isSet()) &&
14376       (FunctionContainingLocalClass =
14377            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14378     // C++11 [class.friend]p11:
14379     //   If a friend declaration appears in a local class and the name
14380     //   specified is an unqualified name, a prior declaration is
14381     //   looked up without considering scopes that are outside the
14382     //   innermost enclosing non-class scope. For a friend function
14383     //   declaration, if there is no prior declaration, the program is
14384     //   ill-formed.
14385 
14386     // Find the innermost enclosing non-class scope. This is the block
14387     // scope containing the local class definition (or for a nested class,
14388     // the outer local class).
14389     DCScope = S->getFnParent();
14390 
14391     // Look up the function name in the scope.
14392     Previous.clear(LookupLocalFriendName);
14393     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14394 
14395     if (!Previous.empty()) {
14396       // All possible previous declarations must have the same context:
14397       // either they were declared at block scope or they are members of
14398       // one of the enclosing local classes.
14399       DC = Previous.getRepresentativeDecl()->getDeclContext();
14400     } else {
14401       // This is ill-formed, but provide the context that we would have
14402       // declared the function in, if we were permitted to, for error recovery.
14403       DC = FunctionContainingLocalClass;
14404     }
14405     adjustContextForLocalExternDecl(DC);
14406 
14407     // C++ [class.friend]p6:
14408     //   A function can be defined in a friend declaration of a class if and
14409     //   only if the class is a non-local class (9.8), the function name is
14410     //   unqualified, and the function has namespace scope.
14411     if (D.isFunctionDefinition()) {
14412       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14413     }
14414 
14415   //   - There's no scope specifier, in which case we just go to the
14416   //     appropriate scope and look for a function or function template
14417   //     there as appropriate.
14418   } else if (SS.isInvalid() || !SS.isSet()) {
14419     // C++11 [namespace.memdef]p3:
14420     //   If the name in a friend declaration is neither qualified nor
14421     //   a template-id and the declaration is a function or an
14422     //   elaborated-type-specifier, the lookup to determine whether
14423     //   the entity has been previously declared shall not consider
14424     //   any scopes outside the innermost enclosing namespace.
14425     bool isTemplateId =
14426         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14427 
14428     // Find the appropriate context according to the above.
14429     DC = CurContext;
14430 
14431     // Skip class contexts.  If someone can cite chapter and verse
14432     // for this behavior, that would be nice --- it's what GCC and
14433     // EDG do, and it seems like a reasonable intent, but the spec
14434     // really only says that checks for unqualified existing
14435     // declarations should stop at the nearest enclosing namespace,
14436     // not that they should only consider the nearest enclosing
14437     // namespace.
14438     while (DC->isRecord())
14439       DC = DC->getParent();
14440 
14441     DeclContext *LookupDC = DC;
14442     while (LookupDC->isTransparentContext())
14443       LookupDC = LookupDC->getParent();
14444 
14445     while (true) {
14446       LookupQualifiedName(Previous, LookupDC);
14447 
14448       if (!Previous.empty()) {
14449         DC = LookupDC;
14450         break;
14451       }
14452 
14453       if (isTemplateId) {
14454         if (isa<TranslationUnitDecl>(LookupDC)) break;
14455       } else {
14456         if (LookupDC->isFileContext()) break;
14457       }
14458       LookupDC = LookupDC->getParent();
14459     }
14460 
14461     DCScope = getScopeForDeclContext(S, DC);
14462 
14463   //   - There's a non-dependent scope specifier, in which case we
14464   //     compute it and do a previous lookup there for a function
14465   //     or function template.
14466   } else if (!SS.getScopeRep()->isDependent()) {
14467     DC = computeDeclContext(SS);
14468     if (!DC) return nullptr;
14469 
14470     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14471 
14472     LookupQualifiedName(Previous, DC);
14473 
14474     // C++ [class.friend]p1: A friend of a class is a function or
14475     //   class that is not a member of the class . . .
14476     if (DC->Equals(CurContext))
14477       Diag(DS.getFriendSpecLoc(),
14478            getLangOpts().CPlusPlus11 ?
14479              diag::warn_cxx98_compat_friend_is_member :
14480              diag::err_friend_is_member);
14481 
14482     if (D.isFunctionDefinition()) {
14483       // C++ [class.friend]p6:
14484       //   A function can be defined in a friend declaration of a class if and
14485       //   only if the class is a non-local class (9.8), the function name is
14486       //   unqualified, and the function has namespace scope.
14487       //
14488       // FIXME: We should only do this if the scope specifier names the
14489       // innermost enclosing namespace; otherwise the fixit changes the
14490       // meaning of the code.
14491       SemaDiagnosticBuilder DB
14492         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14493 
14494       DB << SS.getScopeRep();
14495       if (DC->isFileContext())
14496         DB << FixItHint::CreateRemoval(SS.getRange());
14497       SS.clear();
14498     }
14499 
14500   //   - There's a scope specifier that does not match any template
14501   //     parameter lists, in which case we use some arbitrary context,
14502   //     create a method or method template, and wait for instantiation.
14503   //   - There's a scope specifier that does match some template
14504   //     parameter lists, which we don't handle right now.
14505   } else {
14506     if (D.isFunctionDefinition()) {
14507       // C++ [class.friend]p6:
14508       //   A function can be defined in a friend declaration of a class if and
14509       //   only if the class is a non-local class (9.8), the function name is
14510       //   unqualified, and the function has namespace scope.
14511       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14512         << SS.getScopeRep();
14513     }
14514 
14515     DC = CurContext;
14516     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14517   }
14518 
14519   if (!DC->isRecord()) {
14520     int DiagArg = -1;
14521     switch (D.getName().getKind()) {
14522     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14523     case UnqualifiedIdKind::IK_ConstructorName:
14524       DiagArg = 0;
14525       break;
14526     case UnqualifiedIdKind::IK_DestructorName:
14527       DiagArg = 1;
14528       break;
14529     case UnqualifiedIdKind::IK_ConversionFunctionId:
14530       DiagArg = 2;
14531       break;
14532     case UnqualifiedIdKind::IK_DeductionGuideName:
14533       DiagArg = 3;
14534       break;
14535     case UnqualifiedIdKind::IK_Identifier:
14536     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14537     case UnqualifiedIdKind::IK_LiteralOperatorId:
14538     case UnqualifiedIdKind::IK_OperatorFunctionId:
14539     case UnqualifiedIdKind::IK_TemplateId:
14540       break;
14541     }
14542     // This implies that it has to be an operator or function.
14543     if (DiagArg >= 0) {
14544       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14545       return nullptr;
14546     }
14547   }
14548 
14549   // FIXME: This is an egregious hack to cope with cases where the scope stack
14550   // does not contain the declaration context, i.e., in an out-of-line
14551   // definition of a class.
14552   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14553   if (!DCScope) {
14554     FakeDCScope.setEntity(DC);
14555     DCScope = &FakeDCScope;
14556   }
14557 
14558   bool AddToScope = true;
14559   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14560                                           TemplateParams, AddToScope);
14561   if (!ND) return nullptr;
14562 
14563   assert(ND->getLexicalDeclContext() == CurContext);
14564 
14565   // If we performed typo correction, we might have added a scope specifier
14566   // and changed the decl context.
14567   DC = ND->getDeclContext();
14568 
14569   // Add the function declaration to the appropriate lookup tables,
14570   // adjusting the redeclarations list as necessary.  We don't
14571   // want to do this yet if the friending class is dependent.
14572   //
14573   // Also update the scope-based lookup if the target context's
14574   // lookup context is in lexical scope.
14575   if (!CurContext->isDependentContext()) {
14576     DC = DC->getRedeclContext();
14577     DC->makeDeclVisibleInContext(ND);
14578     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14579       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14580   }
14581 
14582   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14583                                        D.getIdentifierLoc(), ND,
14584                                        DS.getFriendSpecLoc());
14585   FrD->setAccess(AS_public);
14586   CurContext->addDecl(FrD);
14587 
14588   if (ND->isInvalidDecl()) {
14589     FrD->setInvalidDecl();
14590   } else {
14591     if (DC->isRecord()) CheckFriendAccess(ND);
14592 
14593     FunctionDecl *FD;
14594     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14595       FD = FTD->getTemplatedDecl();
14596     else
14597       FD = cast<FunctionDecl>(ND);
14598 
14599     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14600     // default argument expression, that declaration shall be a definition
14601     // and shall be the only declaration of the function or function
14602     // template in the translation unit.
14603     if (functionDeclHasDefaultArgument(FD)) {
14604       // We can't look at FD->getPreviousDecl() because it may not have been set
14605       // if we're in a dependent context. If the function is known to be a
14606       // redeclaration, we will have narrowed Previous down to the right decl.
14607       if (D.isRedeclaration()) {
14608         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14609         Diag(Previous.getRepresentativeDecl()->getLocation(),
14610              diag::note_previous_declaration);
14611       } else if (!D.isFunctionDefinition())
14612         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14613     }
14614 
14615     // Mark templated-scope function declarations as unsupported.
14616     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14617       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14618         << SS.getScopeRep() << SS.getRange()
14619         << cast<CXXRecordDecl>(CurContext);
14620       FrD->setUnsupportedFriend(true);
14621     }
14622   }
14623 
14624   return ND;
14625 }
14626 
14627 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14628   AdjustDeclIfTemplate(Dcl);
14629 
14630   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14631   if (!Fn) {
14632     Diag(DelLoc, diag::err_deleted_non_function);
14633     return;
14634   }
14635 
14636   // Deleted function does not have a body.
14637   Fn->setWillHaveBody(false);
14638 
14639   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14640     // Don't consider the implicit declaration we generate for explicit
14641     // specializations. FIXME: Do not generate these implicit declarations.
14642     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14643          Prev->getPreviousDecl()) &&
14644         !Prev->isDefined()) {
14645       Diag(DelLoc, diag::err_deleted_decl_not_first);
14646       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14647            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14648                               : diag::note_previous_declaration);
14649     }
14650     // If the declaration wasn't the first, we delete the function anyway for
14651     // recovery.
14652     Fn = Fn->getCanonicalDecl();
14653   }
14654 
14655   // dllimport/dllexport cannot be deleted.
14656   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14657     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14658     Fn->setInvalidDecl();
14659   }
14660 
14661   if (Fn->isDeleted())
14662     return;
14663 
14664   // See if we're deleting a function which is already known to override a
14665   // non-deleted virtual function.
14666   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14667     bool IssuedDiagnostic = false;
14668     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14669       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14670         if (!IssuedDiagnostic) {
14671           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14672           IssuedDiagnostic = true;
14673         }
14674         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14675       }
14676     }
14677     // If this function was implicitly deleted because it was defaulted,
14678     // explain why it was deleted.
14679     if (IssuedDiagnostic && MD->isDefaulted())
14680       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14681                                 /*Diagnose*/true);
14682   }
14683 
14684   // C++11 [basic.start.main]p3:
14685   //   A program that defines main as deleted [...] is ill-formed.
14686   if (Fn->isMain())
14687     Diag(DelLoc, diag::err_deleted_main);
14688 
14689   // C++11 [dcl.fct.def.delete]p4:
14690   //  A deleted function is implicitly inline.
14691   Fn->setImplicitlyInline();
14692   Fn->setDeletedAsWritten();
14693 }
14694 
14695 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14696   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14697 
14698   if (MD) {
14699     if (MD->getParent()->isDependentType()) {
14700       MD->setDefaulted();
14701       MD->setExplicitlyDefaulted();
14702       return;
14703     }
14704 
14705     CXXSpecialMember Member = getSpecialMember(MD);
14706     if (Member == CXXInvalid) {
14707       if (!MD->isInvalidDecl())
14708         Diag(DefaultLoc, diag::err_default_special_members);
14709       return;
14710     }
14711 
14712     MD->setDefaulted();
14713     MD->setExplicitlyDefaulted();
14714 
14715     // Unset that we will have a body for this function. We might not,
14716     // if it turns out to be trivial, and we don't need this marking now
14717     // that we've marked it as defaulted.
14718     MD->setWillHaveBody(false);
14719 
14720     // If this definition appears within the record, do the checking when
14721     // the record is complete.
14722     const FunctionDecl *Primary = MD;
14723     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14724       // Ask the template instantiation pattern that actually had the
14725       // '= default' on it.
14726       Primary = Pattern;
14727 
14728     // If the method was defaulted on its first declaration, we will have
14729     // already performed the checking in CheckCompletedCXXClass. Such a
14730     // declaration doesn't trigger an implicit definition.
14731     if (Primary->getCanonicalDecl()->isDefaulted())
14732       return;
14733 
14734     CheckExplicitlyDefaultedSpecialMember(MD);
14735 
14736     if (!MD->isInvalidDecl())
14737       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14738   } else {
14739     Diag(DefaultLoc, diag::err_default_special_members);
14740   }
14741 }
14742 
14743 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14744   for (Stmt *SubStmt : S->children()) {
14745     if (!SubStmt)
14746       continue;
14747     if (isa<ReturnStmt>(SubStmt))
14748       Self.Diag(SubStmt->getBeginLoc(),
14749                 diag::err_return_in_constructor_handler);
14750     if (!isa<Expr>(SubStmt))
14751       SearchForReturnInStmt(Self, SubStmt);
14752   }
14753 }
14754 
14755 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14756   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14757     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14758     SearchForReturnInStmt(*this, Handler);
14759   }
14760 }
14761 
14762 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14763                                              const CXXMethodDecl *Old) {
14764   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14765   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14766 
14767   if (OldFT->hasExtParameterInfos()) {
14768     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14769       // A parameter of the overriding method should be annotated with noescape
14770       // if the corresponding parameter of the overridden method is annotated.
14771       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14772           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14773         Diag(New->getParamDecl(I)->getLocation(),
14774              diag::warn_overriding_method_missing_noescape);
14775         Diag(Old->getParamDecl(I)->getLocation(),
14776              diag::note_overridden_marked_noescape);
14777       }
14778   }
14779 
14780   // Virtual overrides must have the same code_seg.
14781   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14782   const auto *NewCSA = New->getAttr<CodeSegAttr>();
14783   if ((NewCSA || OldCSA) &&
14784       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14785     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14786     Diag(Old->getLocation(), diag::note_previous_declaration);
14787     return true;
14788   }
14789 
14790   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14791 
14792   // If the calling conventions match, everything is fine
14793   if (NewCC == OldCC)
14794     return false;
14795 
14796   // If the calling conventions mismatch because the new function is static,
14797   // suppress the calling convention mismatch error; the error about static
14798   // function override (err_static_overrides_virtual from
14799   // Sema::CheckFunctionDeclaration) is more clear.
14800   if (New->getStorageClass() == SC_Static)
14801     return false;
14802 
14803   Diag(New->getLocation(),
14804        diag::err_conflicting_overriding_cc_attributes)
14805     << New->getDeclName() << New->getType() << Old->getType();
14806   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14807   return true;
14808 }
14809 
14810 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14811                                              const CXXMethodDecl *Old) {
14812   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14813   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14814 
14815   if (Context.hasSameType(NewTy, OldTy) ||
14816       NewTy->isDependentType() || OldTy->isDependentType())
14817     return false;
14818 
14819   // Check if the return types are covariant
14820   QualType NewClassTy, OldClassTy;
14821 
14822   /// Both types must be pointers or references to classes.
14823   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14824     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14825       NewClassTy = NewPT->getPointeeType();
14826       OldClassTy = OldPT->getPointeeType();
14827     }
14828   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14829     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14830       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14831         NewClassTy = NewRT->getPointeeType();
14832         OldClassTy = OldRT->getPointeeType();
14833       }
14834     }
14835   }
14836 
14837   // The return types aren't either both pointers or references to a class type.
14838   if (NewClassTy.isNull()) {
14839     Diag(New->getLocation(),
14840          diag::err_different_return_type_for_overriding_virtual_function)
14841         << New->getDeclName() << NewTy << OldTy
14842         << New->getReturnTypeSourceRange();
14843     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14844         << Old->getReturnTypeSourceRange();
14845 
14846     return true;
14847   }
14848 
14849   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14850     // C++14 [class.virtual]p8:
14851     //   If the class type in the covariant return type of D::f differs from
14852     //   that of B::f, the class type in the return type of D::f shall be
14853     //   complete at the point of declaration of D::f or shall be the class
14854     //   type D.
14855     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14856       if (!RT->isBeingDefined() &&
14857           RequireCompleteType(New->getLocation(), NewClassTy,
14858                               diag::err_covariant_return_incomplete,
14859                               New->getDeclName()))
14860         return true;
14861     }
14862 
14863     // Check if the new class derives from the old class.
14864     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14865       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14866           << New->getDeclName() << NewTy << OldTy
14867           << New->getReturnTypeSourceRange();
14868       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14869           << Old->getReturnTypeSourceRange();
14870       return true;
14871     }
14872 
14873     // Check if we the conversion from derived to base is valid.
14874     if (CheckDerivedToBaseConversion(
14875             NewClassTy, OldClassTy,
14876             diag::err_covariant_return_inaccessible_base,
14877             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14878             New->getLocation(), New->getReturnTypeSourceRange(),
14879             New->getDeclName(), nullptr)) {
14880       // FIXME: this note won't trigger for delayed access control
14881       // diagnostics, and it's impossible to get an undelayed error
14882       // here from access control during the original parse because
14883       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14884       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14885           << Old->getReturnTypeSourceRange();
14886       return true;
14887     }
14888   }
14889 
14890   // The qualifiers of the return types must be the same.
14891   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14892     Diag(New->getLocation(),
14893          diag::err_covariant_return_type_different_qualifications)
14894         << New->getDeclName() << NewTy << OldTy
14895         << New->getReturnTypeSourceRange();
14896     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14897         << Old->getReturnTypeSourceRange();
14898     return true;
14899   }
14900 
14901 
14902   // The new class type must have the same or less qualifiers as the old type.
14903   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14904     Diag(New->getLocation(),
14905          diag::err_covariant_return_type_class_type_more_qualified)
14906         << New->getDeclName() << NewTy << OldTy
14907         << New->getReturnTypeSourceRange();
14908     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14909         << Old->getReturnTypeSourceRange();
14910     return true;
14911   }
14912 
14913   return false;
14914 }
14915 
14916 /// Mark the given method pure.
14917 ///
14918 /// \param Method the method to be marked pure.
14919 ///
14920 /// \param InitRange the source range that covers the "0" initializer.
14921 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14922   SourceLocation EndLoc = InitRange.getEnd();
14923   if (EndLoc.isValid())
14924     Method->setRangeEnd(EndLoc);
14925 
14926   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14927     Method->setPure();
14928     return false;
14929   }
14930 
14931   if (!Method->isInvalidDecl())
14932     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14933       << Method->getDeclName() << InitRange;
14934   return true;
14935 }
14936 
14937 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14938   if (D->getFriendObjectKind())
14939     Diag(D->getLocation(), diag::err_pure_friend);
14940   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14941     CheckPureMethod(M, ZeroLoc);
14942   else
14943     Diag(D->getLocation(), diag::err_illegal_initializer);
14944 }
14945 
14946 /// Determine whether the given declaration is a global variable or
14947 /// static data member.
14948 static bool isNonlocalVariable(const Decl *D) {
14949   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14950     return Var->hasGlobalStorage();
14951 
14952   return false;
14953 }
14954 
14955 /// Invoked when we are about to parse an initializer for the declaration
14956 /// 'Dcl'.
14957 ///
14958 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14959 /// static data member of class X, names should be looked up in the scope of
14960 /// class X. If the declaration had a scope specifier, a scope will have
14961 /// been created and passed in for this purpose. Otherwise, S will be null.
14962 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14963   // If there is no declaration, there was an error parsing it.
14964   if (!D || D->isInvalidDecl())
14965     return;
14966 
14967   // We will always have a nested name specifier here, but this declaration
14968   // might not be out of line if the specifier names the current namespace:
14969   //   extern int n;
14970   //   int ::n = 0;
14971   if (S && D->isOutOfLine())
14972     EnterDeclaratorContext(S, D->getDeclContext());
14973 
14974   // If we are parsing the initializer for a static data member, push a
14975   // new expression evaluation context that is associated with this static
14976   // data member.
14977   if (isNonlocalVariable(D))
14978     PushExpressionEvaluationContext(
14979         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14980 }
14981 
14982 /// Invoked after we are finished parsing an initializer for the declaration D.
14983 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14984   // If there is no declaration, there was an error parsing it.
14985   if (!D || D->isInvalidDecl())
14986     return;
14987 
14988   if (isNonlocalVariable(D))
14989     PopExpressionEvaluationContext();
14990 
14991   if (S && D->isOutOfLine())
14992     ExitDeclaratorContext(S);
14993 }
14994 
14995 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14996 /// C++ if/switch/while/for statement.
14997 /// e.g: "if (int x = f()) {...}"
14998 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14999   // C++ 6.4p2:
15000   // The declarator shall not specify a function or an array.
15001   // The type-specifier-seq shall not contain typedef and shall not declare a
15002   // new class or enumeration.
15003   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
15004          "Parser allowed 'typedef' as storage class of condition decl.");
15005 
15006   Decl *Dcl = ActOnDeclarator(S, D);
15007   if (!Dcl)
15008     return true;
15009 
15010   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
15011     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
15012       << D.getSourceRange();
15013     return true;
15014   }
15015 
15016   return Dcl;
15017 }
15018 
15019 void Sema::LoadExternalVTableUses() {
15020   if (!ExternalSource)
15021     return;
15022 
15023   SmallVector<ExternalVTableUse, 4> VTables;
15024   ExternalSource->ReadUsedVTables(VTables);
15025   SmallVector<VTableUse, 4> NewUses;
15026   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
15027     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
15028       = VTablesUsed.find(VTables[I].Record);
15029     // Even if a definition wasn't required before, it may be required now.
15030     if (Pos != VTablesUsed.end()) {
15031       if (!Pos->second && VTables[I].DefinitionRequired)
15032         Pos->second = true;
15033       continue;
15034     }
15035 
15036     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
15037     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
15038   }
15039 
15040   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
15041 }
15042 
15043 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
15044                           bool DefinitionRequired) {
15045   // Ignore any vtable uses in unevaluated operands or for classes that do
15046   // not have a vtable.
15047   if (!Class->isDynamicClass() || Class->isDependentContext() ||
15048       CurContext->isDependentContext() || isUnevaluatedContext())
15049     return;
15050   // Do not mark as used if compiling for the device outside of the target
15051   // region.
15052   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15053       !isInOpenMPDeclareTargetContext() &&
15054       !isInOpenMPTargetExecutionDirective()) {
15055     if (!DefinitionRequired)
15056       MarkVirtualMembersReferenced(Loc, Class);
15057     return;
15058   }
15059 
15060   // Try to insert this class into the map.
15061   LoadExternalVTableUses();
15062   Class = Class->getCanonicalDecl();
15063   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15064     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15065   if (!Pos.second) {
15066     // If we already had an entry, check to see if we are promoting this vtable
15067     // to require a definition. If so, we need to reappend to the VTableUses
15068     // list, since we may have already processed the first entry.
15069     if (DefinitionRequired && !Pos.first->second) {
15070       Pos.first->second = true;
15071     } else {
15072       // Otherwise, we can early exit.
15073       return;
15074     }
15075   } else {
15076     // The Microsoft ABI requires that we perform the destructor body
15077     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15078     // the deleting destructor is emitted with the vtable, not with the
15079     // destructor definition as in the Itanium ABI.
15080     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15081       CXXDestructorDecl *DD = Class->getDestructor();
15082       if (DD && DD->isVirtual() && !DD->isDeleted()) {
15083         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15084           // If this is an out-of-line declaration, marking it referenced will
15085           // not do anything. Manually call CheckDestructor to look up operator
15086           // delete().
15087           ContextRAII SavedContext(*this, DD);
15088           CheckDestructor(DD);
15089         } else {
15090           MarkFunctionReferenced(Loc, Class->getDestructor());
15091         }
15092       }
15093     }
15094   }
15095 
15096   // Local classes need to have their virtual members marked
15097   // immediately. For all other classes, we mark their virtual members
15098   // at the end of the translation unit.
15099   if (Class->isLocalClass())
15100     MarkVirtualMembersReferenced(Loc, Class);
15101   else
15102     VTableUses.push_back(std::make_pair(Class, Loc));
15103 }
15104 
15105 bool Sema::DefineUsedVTables() {
15106   LoadExternalVTableUses();
15107   if (VTableUses.empty())
15108     return false;
15109 
15110   // Note: The VTableUses vector could grow as a result of marking
15111   // the members of a class as "used", so we check the size each
15112   // time through the loop and prefer indices (which are stable) to
15113   // iterators (which are not).
15114   bool DefinedAnything = false;
15115   for (unsigned I = 0; I != VTableUses.size(); ++I) {
15116     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15117     if (!Class)
15118       continue;
15119     TemplateSpecializationKind ClassTSK =
15120         Class->getTemplateSpecializationKind();
15121 
15122     SourceLocation Loc = VTableUses[I].second;
15123 
15124     bool DefineVTable = true;
15125 
15126     // If this class has a key function, but that key function is
15127     // defined in another translation unit, we don't need to emit the
15128     // vtable even though we're using it.
15129     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15130     if (KeyFunction && !KeyFunction->hasBody()) {
15131       // The key function is in another translation unit.
15132       DefineVTable = false;
15133       TemplateSpecializationKind TSK =
15134           KeyFunction->getTemplateSpecializationKind();
15135       assert(TSK != TSK_ExplicitInstantiationDefinition &&
15136              TSK != TSK_ImplicitInstantiation &&
15137              "Instantiations don't have key functions");
15138       (void)TSK;
15139     } else if (!KeyFunction) {
15140       // If we have a class with no key function that is the subject
15141       // of an explicit instantiation declaration, suppress the
15142       // vtable; it will live with the explicit instantiation
15143       // definition.
15144       bool IsExplicitInstantiationDeclaration =
15145           ClassTSK == TSK_ExplicitInstantiationDeclaration;
15146       for (auto R : Class->redecls()) {
15147         TemplateSpecializationKind TSK
15148           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15149         if (TSK == TSK_ExplicitInstantiationDeclaration)
15150           IsExplicitInstantiationDeclaration = true;
15151         else if (TSK == TSK_ExplicitInstantiationDefinition) {
15152           IsExplicitInstantiationDeclaration = false;
15153           break;
15154         }
15155       }
15156 
15157       if (IsExplicitInstantiationDeclaration)
15158         DefineVTable = false;
15159     }
15160 
15161     // The exception specifications for all virtual members may be needed even
15162     // if we are not providing an authoritative form of the vtable in this TU.
15163     // We may choose to emit it available_externally anyway.
15164     if (!DefineVTable) {
15165       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15166       continue;
15167     }
15168 
15169     // Mark all of the virtual members of this class as referenced, so
15170     // that we can build a vtable. Then, tell the AST consumer that a
15171     // vtable for this class is required.
15172     DefinedAnything = true;
15173     MarkVirtualMembersReferenced(Loc, Class);
15174     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15175     if (VTablesUsed[Canonical])
15176       Consumer.HandleVTable(Class);
15177 
15178     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15179     // no key function or the key function is inlined. Don't warn in C++ ABIs
15180     // that lack key functions, since the user won't be able to make one.
15181     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15182         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15183       const FunctionDecl *KeyFunctionDef = nullptr;
15184       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15185                            KeyFunctionDef->isInlined())) {
15186         Diag(Class->getLocation(),
15187              ClassTSK == TSK_ExplicitInstantiationDefinition
15188                  ? diag::warn_weak_template_vtable
15189                  : diag::warn_weak_vtable)
15190             << Class;
15191       }
15192     }
15193   }
15194   VTableUses.clear();
15195 
15196   return DefinedAnything;
15197 }
15198 
15199 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15200                                                  const CXXRecordDecl *RD) {
15201   for (const auto *I : RD->methods())
15202     if (I->isVirtual() && !I->isPure())
15203       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15204 }
15205 
15206 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15207                                         const CXXRecordDecl *RD,
15208                                         bool ConstexprOnly) {
15209   // Mark all functions which will appear in RD's vtable as used.
15210   CXXFinalOverriderMap FinalOverriders;
15211   RD->getFinalOverriders(FinalOverriders);
15212   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15213                                             E = FinalOverriders.end();
15214        I != E; ++I) {
15215     for (OverridingMethods::const_iterator OI = I->second.begin(),
15216                                            OE = I->second.end();
15217          OI != OE; ++OI) {
15218       assert(OI->second.size() > 0 && "no final overrider");
15219       CXXMethodDecl *Overrider = OI->second.front().Method;
15220 
15221       // C++ [basic.def.odr]p2:
15222       //   [...] A virtual member function is used if it is not pure. [...]
15223       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
15224         MarkFunctionReferenced(Loc, Overrider);
15225     }
15226   }
15227 
15228   // Only classes that have virtual bases need a VTT.
15229   if (RD->getNumVBases() == 0)
15230     return;
15231 
15232   for (const auto &I : RD->bases()) {
15233     const CXXRecordDecl *Base =
15234         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15235     if (Base->getNumVBases() == 0)
15236       continue;
15237     MarkVirtualMembersReferenced(Loc, Base);
15238   }
15239 }
15240 
15241 /// SetIvarInitializers - This routine builds initialization ASTs for the
15242 /// Objective-C implementation whose ivars need be initialized.
15243 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15244   if (!getLangOpts().CPlusPlus)
15245     return;
15246   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15247     SmallVector<ObjCIvarDecl*, 8> ivars;
15248     CollectIvarsToConstructOrDestruct(OID, ivars);
15249     if (ivars.empty())
15250       return;
15251     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15252     for (unsigned i = 0; i < ivars.size(); i++) {
15253       FieldDecl *Field = ivars[i];
15254       if (Field->isInvalidDecl())
15255         continue;
15256 
15257       CXXCtorInitializer *Member;
15258       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15259       InitializationKind InitKind =
15260         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15261 
15262       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15263       ExprResult MemberInit =
15264         InitSeq.Perform(*this, InitEntity, InitKind, None);
15265       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15266       // Note, MemberInit could actually come back empty if no initialization
15267       // is required (e.g., because it would call a trivial default constructor)
15268       if (!MemberInit.get() || MemberInit.isInvalid())
15269         continue;
15270 
15271       Member =
15272         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15273                                          SourceLocation(),
15274                                          MemberInit.getAs<Expr>(),
15275                                          SourceLocation());
15276       AllToInit.push_back(Member);
15277 
15278       // Be sure that the destructor is accessible and is marked as referenced.
15279       if (const RecordType *RecordTy =
15280               Context.getBaseElementType(Field->getType())
15281                   ->getAs<RecordType>()) {
15282         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15283         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15284           MarkFunctionReferenced(Field->getLocation(), Destructor);
15285           CheckDestructorAccess(Field->getLocation(), Destructor,
15286                             PDiag(diag::err_access_dtor_ivar)
15287                               << Context.getBaseElementType(Field->getType()));
15288         }
15289       }
15290     }
15291     ObjCImplementation->setIvarInitializers(Context,
15292                                             AllToInit.data(), AllToInit.size());
15293   }
15294 }
15295 
15296 static
15297 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15298                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15299                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15300                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15301                            Sema &S) {
15302   if (Ctor->isInvalidDecl())
15303     return;
15304 
15305   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15306 
15307   // Target may not be determinable yet, for instance if this is a dependent
15308   // call in an uninstantiated template.
15309   if (Target) {
15310     const FunctionDecl *FNTarget = nullptr;
15311     (void)Target->hasBody(FNTarget);
15312     Target = const_cast<CXXConstructorDecl*>(
15313       cast_or_null<CXXConstructorDecl>(FNTarget));
15314   }
15315 
15316   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15317                      // Avoid dereferencing a null pointer here.
15318                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15319 
15320   if (!Current.insert(Canonical).second)
15321     return;
15322 
15323   // We know that beyond here, we aren't chaining into a cycle.
15324   if (!Target || !Target->isDelegatingConstructor() ||
15325       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15326     Valid.insert(Current.begin(), Current.end());
15327     Current.clear();
15328   // We've hit a cycle.
15329   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15330              Current.count(TCanonical)) {
15331     // If we haven't diagnosed this cycle yet, do so now.
15332     if (!Invalid.count(TCanonical)) {
15333       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15334              diag::warn_delegating_ctor_cycle)
15335         << Ctor;
15336 
15337       // Don't add a note for a function delegating directly to itself.
15338       if (TCanonical != Canonical)
15339         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15340 
15341       CXXConstructorDecl *C = Target;
15342       while (C->getCanonicalDecl() != Canonical) {
15343         const FunctionDecl *FNTarget = nullptr;
15344         (void)C->getTargetConstructor()->hasBody(FNTarget);
15345         assert(FNTarget && "Ctor cycle through bodiless function");
15346 
15347         C = const_cast<CXXConstructorDecl*>(
15348           cast<CXXConstructorDecl>(FNTarget));
15349         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15350       }
15351     }
15352 
15353     Invalid.insert(Current.begin(), Current.end());
15354     Current.clear();
15355   } else {
15356     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15357   }
15358 }
15359 
15360 
15361 void Sema::CheckDelegatingCtorCycles() {
15362   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15363 
15364   for (DelegatingCtorDeclsType::iterator
15365          I = DelegatingCtorDecls.begin(ExternalSource),
15366          E = DelegatingCtorDecls.end();
15367        I != E; ++I)
15368     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15369 
15370   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15371     (*CI)->setInvalidDecl();
15372 }
15373 
15374 namespace {
15375   /// AST visitor that finds references to the 'this' expression.
15376   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15377     Sema &S;
15378 
15379   public:
15380     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15381 
15382     bool VisitCXXThisExpr(CXXThisExpr *E) {
15383       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15384         << E->isImplicit();
15385       return false;
15386     }
15387   };
15388 }
15389 
15390 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15391   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15392   if (!TSInfo)
15393     return false;
15394 
15395   TypeLoc TL = TSInfo->getTypeLoc();
15396   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15397   if (!ProtoTL)
15398     return false;
15399 
15400   // C++11 [expr.prim.general]p3:
15401   //   [The expression this] shall not appear before the optional
15402   //   cv-qualifier-seq and it shall not appear within the declaration of a
15403   //   static member function (although its type and value category are defined
15404   //   within a static member function as they are within a non-static member
15405   //   function). [ Note: this is because declaration matching does not occur
15406   //  until the complete declarator is known. - end note ]
15407   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15408   FindCXXThisExpr Finder(*this);
15409 
15410   // If the return type came after the cv-qualifier-seq, check it now.
15411   if (Proto->hasTrailingReturn() &&
15412       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15413     return true;
15414 
15415   // Check the exception specification.
15416   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15417     return true;
15418 
15419   return checkThisInStaticMemberFunctionAttributes(Method);
15420 }
15421 
15422 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15423   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15424   if (!TSInfo)
15425     return false;
15426 
15427   TypeLoc TL = TSInfo->getTypeLoc();
15428   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15429   if (!ProtoTL)
15430     return false;
15431 
15432   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15433   FindCXXThisExpr Finder(*this);
15434 
15435   switch (Proto->getExceptionSpecType()) {
15436   case EST_Unparsed:
15437   case EST_Uninstantiated:
15438   case EST_Unevaluated:
15439   case EST_BasicNoexcept:
15440   case EST_DynamicNone:
15441   case EST_MSAny:
15442   case EST_None:
15443     break;
15444 
15445   case EST_DependentNoexcept:
15446   case EST_NoexceptFalse:
15447   case EST_NoexceptTrue:
15448     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15449       return true;
15450     LLVM_FALLTHROUGH;
15451 
15452   case EST_Dynamic:
15453     for (const auto &E : Proto->exceptions()) {
15454       if (!Finder.TraverseType(E))
15455         return true;
15456     }
15457     break;
15458   }
15459 
15460   return false;
15461 }
15462 
15463 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15464   FindCXXThisExpr Finder(*this);
15465 
15466   // Check attributes.
15467   for (const auto *A : Method->attrs()) {
15468     // FIXME: This should be emitted by tblgen.
15469     Expr *Arg = nullptr;
15470     ArrayRef<Expr *> Args;
15471     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15472       Arg = G->getArg();
15473     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15474       Arg = G->getArg();
15475     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15476       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15477     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15478       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15479     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15480       Arg = ETLF->getSuccessValue();
15481       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15482     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15483       Arg = STLF->getSuccessValue();
15484       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15485     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15486       Arg = LR->getArg();
15487     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15488       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15489     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15490       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15491     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15492       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15493     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15494       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15495     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15496       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15497 
15498     if (Arg && !Finder.TraverseStmt(Arg))
15499       return true;
15500 
15501     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15502       if (!Finder.TraverseStmt(Args[I]))
15503         return true;
15504     }
15505   }
15506 
15507   return false;
15508 }
15509 
15510 void Sema::checkExceptionSpecification(
15511     bool IsTopLevel, ExceptionSpecificationType EST,
15512     ArrayRef<ParsedType> DynamicExceptions,
15513     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15514     SmallVectorImpl<QualType> &Exceptions,
15515     FunctionProtoType::ExceptionSpecInfo &ESI) {
15516   Exceptions.clear();
15517   ESI.Type = EST;
15518   if (EST == EST_Dynamic) {
15519     Exceptions.reserve(DynamicExceptions.size());
15520     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15521       // FIXME: Preserve type source info.
15522       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15523 
15524       if (IsTopLevel) {
15525         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15526         collectUnexpandedParameterPacks(ET, Unexpanded);
15527         if (!Unexpanded.empty()) {
15528           DiagnoseUnexpandedParameterPacks(
15529               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15530               Unexpanded);
15531           continue;
15532         }
15533       }
15534 
15535       // Check that the type is valid for an exception spec, and
15536       // drop it if not.
15537       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15538         Exceptions.push_back(ET);
15539     }
15540     ESI.Exceptions = Exceptions;
15541     return;
15542   }
15543 
15544   if (isComputedNoexcept(EST)) {
15545     assert((NoexceptExpr->isTypeDependent() ||
15546             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15547             Context.BoolTy) &&
15548            "Parser should have made sure that the expression is boolean");
15549     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15550       ESI.Type = EST_BasicNoexcept;
15551       return;
15552     }
15553 
15554     ESI.NoexceptExpr = NoexceptExpr;
15555     return;
15556   }
15557 }
15558 
15559 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15560              ExceptionSpecificationType EST,
15561              SourceRange SpecificationRange,
15562              ArrayRef<ParsedType> DynamicExceptions,
15563              ArrayRef<SourceRange> DynamicExceptionRanges,
15564              Expr *NoexceptExpr) {
15565   if (!MethodD)
15566     return;
15567 
15568   // Dig out the method we're referring to.
15569   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15570     MethodD = FunTmpl->getTemplatedDecl();
15571 
15572   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15573   if (!Method)
15574     return;
15575 
15576   // Check the exception specification.
15577   llvm::SmallVector<QualType, 4> Exceptions;
15578   FunctionProtoType::ExceptionSpecInfo ESI;
15579   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15580                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15581                               ESI);
15582 
15583   // Update the exception specification on the function type.
15584   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15585 
15586   if (Method->isStatic())
15587     checkThisInStaticMemberFunctionExceptionSpec(Method);
15588 
15589   if (Method->isVirtual()) {
15590     // Check overrides, which we previously had to delay.
15591     for (const CXXMethodDecl *O : Method->overridden_methods())
15592       CheckOverridingFunctionExceptionSpec(Method, O);
15593   }
15594 }
15595 
15596 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15597 ///
15598 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15599                                        SourceLocation DeclStart, Declarator &D,
15600                                        Expr *BitWidth,
15601                                        InClassInitStyle InitStyle,
15602                                        AccessSpecifier AS,
15603                                        const ParsedAttr &MSPropertyAttr) {
15604   IdentifierInfo *II = D.getIdentifier();
15605   if (!II) {
15606     Diag(DeclStart, diag::err_anonymous_property);
15607     return nullptr;
15608   }
15609   SourceLocation Loc = D.getIdentifierLoc();
15610 
15611   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15612   QualType T = TInfo->getType();
15613   if (getLangOpts().CPlusPlus) {
15614     CheckExtraCXXDefaultArguments(D);
15615 
15616     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15617                                         UPPC_DataMemberType)) {
15618       D.setInvalidType();
15619       T = Context.IntTy;
15620       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15621     }
15622   }
15623 
15624   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15625 
15626   if (D.getDeclSpec().isInlineSpecified())
15627     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15628         << getLangOpts().CPlusPlus17;
15629   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15630     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15631          diag::err_invalid_thread)
15632       << DeclSpec::getSpecifierName(TSCS);
15633 
15634   // Check to see if this name was declared as a member previously
15635   NamedDecl *PrevDecl = nullptr;
15636   LookupResult Previous(*this, II, Loc, LookupMemberName,
15637                         ForVisibleRedeclaration);
15638   LookupName(Previous, S);
15639   switch (Previous.getResultKind()) {
15640   case LookupResult::Found:
15641   case LookupResult::FoundUnresolvedValue:
15642     PrevDecl = Previous.getAsSingle<NamedDecl>();
15643     break;
15644 
15645   case LookupResult::FoundOverloaded:
15646     PrevDecl = Previous.getRepresentativeDecl();
15647     break;
15648 
15649   case LookupResult::NotFound:
15650   case LookupResult::NotFoundInCurrentInstantiation:
15651   case LookupResult::Ambiguous:
15652     break;
15653   }
15654 
15655   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15656     // Maybe we will complain about the shadowed template parameter.
15657     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15658     // Just pretend that we didn't see the previous declaration.
15659     PrevDecl = nullptr;
15660   }
15661 
15662   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15663     PrevDecl = nullptr;
15664 
15665   SourceLocation TSSL = D.getBeginLoc();
15666   MSPropertyDecl *NewPD =
15667       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15668                              MSPropertyAttr.getPropertyDataGetter(),
15669                              MSPropertyAttr.getPropertyDataSetter());
15670   ProcessDeclAttributes(TUScope, NewPD, D);
15671   NewPD->setAccess(AS);
15672 
15673   if (NewPD->isInvalidDecl())
15674     Record->setInvalidDecl();
15675 
15676   if (D.getDeclSpec().isModulePrivateSpecified())
15677     NewPD->setModulePrivate();
15678 
15679   if (NewPD->isInvalidDecl() && PrevDecl) {
15680     // Don't introduce NewFD into scope; there's already something
15681     // with the same name in the same scope.
15682   } else if (II) {
15683     PushOnScopeChains(NewPD, S);
15684   } else
15685     Record->addDecl(NewPD);
15686 
15687   return NewPD;
15688 }
15689