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   case EST_NoThrow:
196     return;
197   // If we're still at noexcept(true) and there's a throw() callee,
198   // change to that specification.
199   case EST_DynamicNone:
200     if (ComputedEST == EST_BasicNoexcept)
201       ComputedEST = EST_DynamicNone;
202     return;
203   case EST_DependentNoexcept:
204     llvm_unreachable(
205         "should not generate implicit declarations for dependent cases");
206   case EST_Dynamic:
207     break;
208   }
209   assert(EST == EST_Dynamic && "EST case not considered earlier.");
210   assert(ComputedEST != EST_None &&
211          "Shouldn't collect exceptions when throw-all is guaranteed.");
212   ComputedEST = EST_Dynamic;
213   // Record the exceptions in this function's exception specification.
214   for (const auto &E : Proto->exceptions())
215     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
216       Exceptions.push_back(E);
217 }
218 
219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
220   if (!E || ComputedEST == EST_MSAny)
221     return;
222 
223   // FIXME:
224   //
225   // C++0x [except.spec]p14:
226   //   [An] implicit exception-specification specifies the type-id T if and
227   // only if T is allowed by the exception-specification of a function directly
228   // invoked by f's implicit definition; f shall allow all exceptions if any
229   // function it directly invokes allows all exceptions, and f shall allow no
230   // exceptions if every function it directly invokes allows no exceptions.
231   //
232   // Note in particular that if an implicit exception-specification is generated
233   // for a function containing a throw-expression, that specification can still
234   // be noexcept(true).
235   //
236   // Note also that 'directly invoked' is not defined in the standard, and there
237   // is no indication that we should only consider potentially-evaluated calls.
238   //
239   // Ultimately we should implement the intent of the standard: the exception
240   // specification should be the set of exceptions which can be thrown by the
241   // implicit definition. For now, we assume that any non-nothrow expression can
242   // throw any exception.
243 
244   if (Self->canThrow(E))
245     ComputedEST = EST_None;
246 }
247 
248 bool
249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
250                               SourceLocation EqualLoc) {
251   if (RequireCompleteType(Param->getLocation(), Param->getType(),
252                           diag::err_typecheck_decl_incomplete_type)) {
253     Param->setInvalidDecl();
254     return true;
255   }
256 
257   // C++ [dcl.fct.default]p5
258   //   A default argument expression is implicitly converted (clause
259   //   4) to the parameter type. The default argument expression has
260   //   the same semantic constraints as the initializer expression in
261   //   a declaration of a variable of the parameter type, using the
262   //   copy-initialization semantics (8.5).
263   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264                                                                     Param);
265   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266                                                            EqualLoc);
267   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269   if (Result.isInvalid())
270     return true;
271   Arg = Result.getAs<Expr>();
272 
273   CheckCompletedExpr(Arg, EqualLoc);
274   Arg = MaybeCreateExprWithCleanups(Arg);
275 
276   // Okay: add the default argument to the parameter
277   Param->setDefaultArg(Arg);
278 
279   // We have already instantiated this parameter; provide each of the
280   // instantiations with the uninstantiated default argument.
281   UnparsedDefaultArgInstantiationsMap::iterator InstPos
282     = UnparsedDefaultArgInstantiations.find(Param);
283   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286 
287     // We're done tracking this parameter's instantiations.
288     UnparsedDefaultArgInstantiations.erase(InstPos);
289   }
290 
291   return false;
292 }
293 
294 /// ActOnParamDefaultArgument - Check whether the default argument
295 /// provided for a function parameter is well-formed. If so, attach it
296 /// to the parameter declaration.
297 void
298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
299                                 Expr *DefaultArg) {
300   if (!param || !DefaultArg)
301     return;
302 
303   ParmVarDecl *Param = cast<ParmVarDecl>(param);
304   UnparsedDefaultArgLocs.erase(Param);
305 
306   // Default arguments are only permitted in C++
307   if (!getLangOpts().CPlusPlus) {
308     Diag(EqualLoc, diag::err_param_default_argument)
309       << DefaultArg->getSourceRange();
310     Param->setInvalidDecl();
311     return;
312   }
313 
314   // Check for unexpanded parameter packs.
315   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316     Param->setInvalidDecl();
317     return;
318   }
319 
320   // C++11 [dcl.fct.default]p3
321   //   A default argument expression [...] shall not be specified for a
322   //   parameter pack.
323   if (Param->isParameterPack()) {
324     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325         << DefaultArg->getSourceRange();
326     return;
327   }
328 
329   // Check that the default argument is well-formed
330   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331   if (DefaultArgChecker.Visit(DefaultArg)) {
332     Param->setInvalidDecl();
333     return;
334   }
335 
336   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
337 }
338 
339 /// ActOnParamUnparsedDefaultArgument - We've seen a default
340 /// argument for a function parameter, but we can't parse it yet
341 /// because we're inside a class definition. Note that this default
342 /// argument will be parsed later.
343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
344                                              SourceLocation EqualLoc,
345                                              SourceLocation ArgLoc) {
346   if (!param)
347     return;
348 
349   ParmVarDecl *Param = cast<ParmVarDecl>(param);
350   Param->setUnparsedDefaultArg();
351   UnparsedDefaultArgLocs[Param] = ArgLoc;
352 }
353 
354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355 /// the default argument for the parameter param failed.
356 void Sema::ActOnParamDefaultArgumentError(Decl *param,
357                                           SourceLocation EqualLoc) {
358   if (!param)
359     return;
360 
361   ParmVarDecl *Param = cast<ParmVarDecl>(param);
362   Param->setInvalidDecl();
363   UnparsedDefaultArgLocs.erase(Param);
364   Param->setDefaultArg(new(Context)
365                        OpaqueValueExpr(EqualLoc,
366                                        Param->getType().getNonReferenceType(),
367                                        VK_RValue));
368 }
369 
370 /// CheckExtraCXXDefaultArguments - Check for any extra default
371 /// arguments in the declarator, which is not a function declaration
372 /// or definition and therefore is not permitted to have default
373 /// arguments. This routine should be invoked for every declarator
374 /// that is not a function declaration or definition.
375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
376   // C++ [dcl.fct.default]p3
377   //   A default argument expression shall be specified only in the
378   //   parameter-declaration-clause of a function declaration or in a
379   //   template-parameter (14.1). It shall not be specified for a
380   //   parameter pack. If it is specified in a
381   //   parameter-declaration-clause, it shall not occur within a
382   //   declarator or abstract-declarator of a parameter-declaration.
383   bool MightBeFunction = D.isFunctionDeclarationContext();
384   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
385     DeclaratorChunk &chunk = D.getTypeObject(i);
386     if (chunk.Kind == DeclaratorChunk::Function) {
387       if (MightBeFunction) {
388         // This is a function declaration. It can have default arguments, but
389         // keep looking in case its return type is a function type with default
390         // arguments.
391         MightBeFunction = false;
392         continue;
393       }
394       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395            ++argIdx) {
396         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
397         if (Param->hasUnparsedDefaultArg()) {
398           std::unique_ptr<CachedTokens> Toks =
399               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
400           SourceRange SR;
401           if (Toks->size() > 1)
402             SR = SourceRange((*Toks)[1].getLocation(),
403                              Toks->back().getLocation());
404           else
405             SR = UnparsedDefaultArgLocs[Param];
406           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
407             << SR;
408         } else if (Param->getDefaultArg()) {
409           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410             << Param->getDefaultArg()->getSourceRange();
411           Param->setDefaultArg(nullptr);
412         }
413       }
414     } else if (chunk.Kind != DeclaratorChunk::Paren) {
415       MightBeFunction = false;
416     }
417   }
418 }
419 
420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423     if (!PVD->hasDefaultArg())
424       return false;
425     if (!PVD->hasInheritedDefaultArg())
426       return true;
427   }
428   return false;
429 }
430 
431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
432 /// function, once we already know that they have the same
433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434 /// error, false otherwise.
435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
436                                 Scope *S) {
437   bool Invalid = false;
438 
439   // The declaration context corresponding to the scope is the semantic
440   // parent, unless this is a local function declaration, in which case
441   // it is that surrounding function.
442   DeclContext *ScopeDC = New->isLocalExternDecl()
443                              ? New->getLexicalDeclContext()
444                              : New->getDeclContext();
445 
446   // Find the previous declaration for the purpose of default arguments.
447   FunctionDecl *PrevForDefaultArgs = Old;
448   for (/**/; PrevForDefaultArgs;
449        // Don't bother looking back past the latest decl if this is a local
450        // extern declaration; nothing else could work.
451        PrevForDefaultArgs = New->isLocalExternDecl()
452                                 ? nullptr
453                                 : PrevForDefaultArgs->getPreviousDecl()) {
454     // Ignore hidden declarations.
455     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456       continue;
457 
458     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459         !New->isCXXClassMember()) {
460       // Ignore default arguments of old decl if they are not in
461       // the same scope and this is not an out-of-line definition of
462       // a member function.
463       continue;
464     }
465 
466     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467       // If only one of these is a local function declaration, then they are
468       // declared in different scopes, even though isDeclInScope may think
469       // they're in the same scope. (If both are local, the scope check is
470       // sufficient, and if neither is local, then they are in the same scope.)
471       continue;
472     }
473 
474     // We found the right previous declaration.
475     break;
476   }
477 
478   // C++ [dcl.fct.default]p4:
479   //   For non-template functions, default arguments can be added in
480   //   later declarations of a function in the same
481   //   scope. Declarations in different scopes have completely
482   //   distinct sets of default arguments. That is, declarations in
483   //   inner scopes do not acquire default arguments from
484   //   declarations in outer scopes, and vice versa. In a given
485   //   function declaration, all parameters subsequent to a
486   //   parameter with a default argument shall have default
487   //   arguments supplied in this or previous declarations. A
488   //   default argument shall not be redefined by a later
489   //   declaration (not even to the same value).
490   //
491   // C++ [dcl.fct.default]p6:
492   //   Except for member functions of class templates, the default arguments
493   //   in a member function definition that appears outside of the class
494   //   definition are added to the set of default arguments provided by the
495   //   member function declaration in the class definition.
496   for (unsigned p = 0, NumParams = PrevForDefaultArgs
497                                        ? PrevForDefaultArgs->getNumParams()
498                                        : 0;
499        p < NumParams; ++p) {
500     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
501     ParmVarDecl *NewParam = New->getParamDecl(p);
502 
503     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
504     bool NewParamHasDfl = NewParam->hasDefaultArg();
505 
506     if (OldParamHasDfl && NewParamHasDfl) {
507       unsigned DiagDefaultParamID =
508         diag::err_param_default_argument_redefinition;
509 
510       // MSVC accepts that default parameters be redefined for member functions
511       // of template class. The new default parameter's value is ignored.
512       Invalid = true;
513       if (getLangOpts().MicrosoftExt) {
514         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
515         if (MD && MD->getParent()->getDescribedClassTemplate()) {
516           // Merge the old default argument into the new parameter.
517           NewParam->setHasInheritedDefaultArg();
518           if (OldParam->hasUninstantiatedDefaultArg())
519             NewParam->setUninstantiatedDefaultArg(
520                                       OldParam->getUninstantiatedDefaultArg());
521           else
522             NewParam->setDefaultArg(OldParam->getInit());
523           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
524           Invalid = false;
525         }
526       }
527 
528       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529       // hint here. Alternatively, we could walk the type-source information
530       // for NewParam to find the last source location in the type... but it
531       // isn't worth the effort right now. This is the kind of test case that
532       // is hard to get right:
533       //   int f(int);
534       //   void g(int (*fp)(int) = f);
535       //   void g(int (*fp)(int) = &f);
536       Diag(NewParam->getLocation(), DiagDefaultParamID)
537         << NewParam->getDefaultArgRange();
538 
539       // Look for the function declaration where the default argument was
540       // actually written, which may be a declaration prior to Old.
541       for (auto Older = PrevForDefaultArgs;
542            OldParam->hasInheritedDefaultArg(); /**/) {
543         Older = Older->getPreviousDecl();
544         OldParam = Older->getParamDecl(p);
545       }
546 
547       Diag(OldParam->getLocation(), diag::note_previous_definition)
548         << OldParam->getDefaultArgRange();
549     } else if (OldParamHasDfl) {
550       // Merge the old default argument into the new parameter unless the new
551       // function is a friend declaration in a template class. In the latter
552       // case the default arguments will be inherited when the friend
553       // declaration will be instantiated.
554       if (New->getFriendObjectKind() == Decl::FOK_None ||
555           !New->getLexicalDeclContext()->isDependentContext()) {
556         // It's important to use getInit() here;  getDefaultArg()
557         // strips off any top-level ExprWithCleanups.
558         NewParam->setHasInheritedDefaultArg();
559         if (OldParam->hasUnparsedDefaultArg())
560           NewParam->setUnparsedDefaultArg();
561         else if (OldParam->hasUninstantiatedDefaultArg())
562           NewParam->setUninstantiatedDefaultArg(
563                                        OldParam->getUninstantiatedDefaultArg());
564         else
565           NewParam->setDefaultArg(OldParam->getInit());
566       }
567     } else if (NewParamHasDfl) {
568       if (New->getDescribedFunctionTemplate()) {
569         // Paragraph 4, quoted above, only applies to non-template functions.
570         Diag(NewParam->getLocation(),
571              diag::err_param_default_argument_template_redecl)
572           << NewParam->getDefaultArgRange();
573         Diag(PrevForDefaultArgs->getLocation(),
574              diag::note_template_prev_declaration)
575             << false;
576       } else if (New->getTemplateSpecializationKind()
577                    != TSK_ImplicitInstantiation &&
578                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
579         // C++ [temp.expr.spec]p21:
580         //   Default function arguments shall not be specified in a declaration
581         //   or a definition for one of the following explicit specializations:
582         //     - the explicit specialization of a function template;
583         //     - the explicit specialization of a member function template;
584         //     - the explicit specialization of a member function of a class
585         //       template where the class template specialization to which the
586         //       member function specialization belongs is implicitly
587         //       instantiated.
588         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
589           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
590           << New->getDeclName()
591           << NewParam->getDefaultArgRange();
592       } else if (New->getDeclContext()->isDependentContext()) {
593         // C++ [dcl.fct.default]p6 (DR217):
594         //   Default arguments for a member function of a class template shall
595         //   be specified on the initial declaration of the member function
596         //   within the class template.
597         //
598         // Reading the tea leaves a bit in DR217 and its reference to DR205
599         // leads me to the conclusion that one cannot add default function
600         // arguments for an out-of-line definition of a member function of a
601         // dependent type.
602         int WhichKind = 2;
603         if (CXXRecordDecl *Record
604               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
605           if (Record->getDescribedClassTemplate())
606             WhichKind = 0;
607           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
608             WhichKind = 1;
609           else
610             WhichKind = 2;
611         }
612 
613         Diag(NewParam->getLocation(),
614              diag::err_param_default_argument_member_template_redecl)
615           << WhichKind
616           << NewParam->getDefaultArgRange();
617       }
618     }
619   }
620 
621   // DR1344: If a default argument is added outside a class definition and that
622   // default argument makes the function a special member function, the program
623   // is ill-formed. This can only happen for constructors.
624   if (isa<CXXConstructorDecl>(New) &&
625       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
626     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
627                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
628     if (NewSM != OldSM) {
629       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
630       assert(NewParam->hasDefaultArg());
631       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
632         << NewParam->getDefaultArgRange() << NewSM;
633       Diag(Old->getLocation(), diag::note_previous_declaration);
634     }
635   }
636 
637   const FunctionDecl *Def;
638   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
639   // template has a constexpr specifier then all its declarations shall
640   // contain the constexpr specifier.
641   if (New->getConstexprKind() != Old->getConstexprKind()) {
642     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
643         << New << New->getConstexprKind() << Old->getConstexprKind();
644     Diag(Old->getLocation(), diag::note_previous_declaration);
645     Invalid = true;
646   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
647              Old->isDefined(Def) &&
648              // If a friend function is inlined but does not have 'inline'
649              // specifier, it is a definition. Do not report attribute conflict
650              // in this case, redefinition will be diagnosed later.
651              (New->isInlineSpecified() ||
652               New->getFriendObjectKind() == Decl::FOK_None)) {
653     // C++11 [dcl.fcn.spec]p4:
654     //   If the definition of a function appears in a translation unit before its
655     //   first declaration as inline, the program is ill-formed.
656     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
657     Diag(Def->getLocation(), diag::note_previous_definition);
658     Invalid = true;
659   }
660 
661   // C++17 [temp.deduct.guide]p3:
662   //   Two deduction guide declarations in the same translation unit
663   //   for the same class template shall not have equivalent
664   //   parameter-declaration-clauses.
665   if (isa<CXXDeductionGuideDecl>(New) &&
666       !New->isFunctionTemplateSpecialization()) {
667     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
668     Diag(Old->getLocation(), diag::note_previous_declaration);
669   }
670 
671   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
672   // argument expression, that declaration shall be a definition and shall be
673   // the only declaration of the function or function template in the
674   // translation unit.
675   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
676       functionDeclHasDefaultArgument(Old)) {
677     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
678     Diag(Old->getLocation(), diag::note_previous_declaration);
679     Invalid = true;
680   }
681 
682   return Invalid;
683 }
684 
685 NamedDecl *
686 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
687                                    MultiTemplateParamsArg TemplateParamLists) {
688   assert(D.isDecompositionDeclarator());
689   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
690 
691   // The syntax only allows a decomposition declarator as a simple-declaration,
692   // a for-range-declaration, or a condition in Clang, but we parse it in more
693   // cases than that.
694   if (!D.mayHaveDecompositionDeclarator()) {
695     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
696       << Decomp.getSourceRange();
697     return nullptr;
698   }
699 
700   if (!TemplateParamLists.empty()) {
701     // FIXME: There's no rule against this, but there are also no rules that
702     // would actually make it usable, so we reject it for now.
703     Diag(TemplateParamLists.front()->getTemplateLoc(),
704          diag::err_decomp_decl_template);
705     return nullptr;
706   }
707 
708   Diag(Decomp.getLSquareLoc(),
709        !getLangOpts().CPlusPlus17
710            ? diag::ext_decomp_decl
711            : D.getContext() == DeclaratorContext::ConditionContext
712                  ? diag::ext_decomp_decl_cond
713                  : diag::warn_cxx14_compat_decomp_decl)
714       << Decomp.getSourceRange();
715 
716   // The semantic context is always just the current context.
717   DeclContext *const DC = CurContext;
718 
719   // C++17 [dcl.dcl]/8:
720   //   The decl-specifier-seq shall contain only the type-specifier auto
721   //   and cv-qualifiers.
722   // C++2a [dcl.dcl]/8:
723   //   If decl-specifier-seq contains any decl-specifier other than static,
724   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
725   auto &DS = D.getDeclSpec();
726   {
727     SmallVector<StringRef, 8> BadSpecifiers;
728     SmallVector<SourceLocation, 8> BadSpecifierLocs;
729     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
730     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
731     if (auto SCS = DS.getStorageClassSpec()) {
732       if (SCS == DeclSpec::SCS_static) {
733         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
734         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
735       } else {
736         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
737         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
738       }
739     }
740     if (auto TSCS = DS.getThreadStorageClassSpec()) {
741       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
742       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
743     }
744     if (DS.hasConstexprSpecifier()) {
745       BadSpecifiers.push_back(
746           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
747       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
748     }
749     if (DS.isInlineSpecified()) {
750       BadSpecifiers.push_back("inline");
751       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
752     }
753     if (!BadSpecifiers.empty()) {
754       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
755       Err << (int)BadSpecifiers.size()
756           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
757       // Don't add FixItHints to remove the specifiers; we do still respect
758       // them when building the underlying variable.
759       for (auto Loc : BadSpecifierLocs)
760         Err << SourceRange(Loc, Loc);
761     } else if (!CPlusPlus20Specifiers.empty()) {
762       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
763                          getLangOpts().CPlusPlus2a
764                              ? diag::warn_cxx17_compat_decomp_decl_spec
765                              : diag::ext_decomp_decl_spec);
766       Warn << (int)CPlusPlus20Specifiers.size()
767            << llvm::join(CPlusPlus20Specifiers.begin(),
768                          CPlusPlus20Specifiers.end(), " ");
769       for (auto Loc : CPlusPlus20SpecifierLocs)
770         Warn << SourceRange(Loc, Loc);
771     }
772     // We can't recover from it being declared as a typedef.
773     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
774       return nullptr;
775   }
776 
777   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
778   QualType R = TInfo->getType();
779 
780   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
781                                       UPPC_DeclarationType))
782     D.setInvalidType();
783 
784   // The syntax only allows a single ref-qualifier prior to the decomposition
785   // declarator. No other declarator chunks are permitted. Also check the type
786   // specifier here.
787   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
788       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
789       (D.getNumTypeObjects() == 1 &&
790        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
791     Diag(Decomp.getLSquareLoc(),
792          (D.hasGroupingParens() ||
793           (D.getNumTypeObjects() &&
794            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
795              ? diag::err_decomp_decl_parens
796              : diag::err_decomp_decl_type)
797         << R;
798 
799     // In most cases, there's no actual problem with an explicitly-specified
800     // type, but a function type won't work here, and ActOnVariableDeclarator
801     // shouldn't be called for such a type.
802     if (R->isFunctionType())
803       D.setInvalidType();
804   }
805 
806   // Build the BindingDecls.
807   SmallVector<BindingDecl*, 8> Bindings;
808 
809   // Build the BindingDecls.
810   for (auto &B : D.getDecompositionDeclarator().bindings()) {
811     // Check for name conflicts.
812     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
813     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
814                           ForVisibleRedeclaration);
815     LookupName(Previous, S,
816                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
817 
818     // It's not permitted to shadow a template parameter name.
819     if (Previous.isSingleResult() &&
820         Previous.getFoundDecl()->isTemplateParameter()) {
821       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
822                                       Previous.getFoundDecl());
823       Previous.clear();
824     }
825 
826     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
827                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
828     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
829                          /*AllowInlineNamespace*/false);
830     if (!Previous.empty()) {
831       auto *Old = Previous.getRepresentativeDecl();
832       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
833       Diag(Old->getLocation(), diag::note_previous_definition);
834     }
835 
836     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
837     PushOnScopeChains(BD, S, true);
838     Bindings.push_back(BD);
839     ParsingInitForAutoVars.insert(BD);
840   }
841 
842   // There are no prior lookup results for the variable itself, because it
843   // is unnamed.
844   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
845                                Decomp.getLSquareLoc());
846   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
847                         ForVisibleRedeclaration);
848 
849   // Build the variable that holds the non-decomposed object.
850   bool AddToScope = true;
851   NamedDecl *New =
852       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
853                               MultiTemplateParamsArg(), AddToScope, Bindings);
854   if (AddToScope) {
855     S->AddDecl(New);
856     CurContext->addHiddenDecl(New);
857   }
858 
859   if (isInOpenMPDeclareTargetContext())
860     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
861 
862   return New;
863 }
864 
865 static bool checkSimpleDecomposition(
866     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
867     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
868     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
869   if ((int64_t)Bindings.size() != NumElems) {
870     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
871         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
872         << (NumElems < Bindings.size());
873     return true;
874   }
875 
876   unsigned I = 0;
877   for (auto *B : Bindings) {
878     SourceLocation Loc = B->getLocation();
879     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
880     if (E.isInvalid())
881       return true;
882     E = GetInit(Loc, E.get(), I++);
883     if (E.isInvalid())
884       return true;
885     B->setBinding(ElemType, E.get());
886   }
887 
888   return false;
889 }
890 
891 static bool checkArrayLikeDecomposition(Sema &S,
892                                         ArrayRef<BindingDecl *> Bindings,
893                                         ValueDecl *Src, QualType DecompType,
894                                         const llvm::APSInt &NumElems,
895                                         QualType ElemType) {
896   return checkSimpleDecomposition(
897       S, Bindings, Src, DecompType, NumElems, ElemType,
898       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
899         ExprResult E = S.ActOnIntegerConstant(Loc, I);
900         if (E.isInvalid())
901           return ExprError();
902         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
903       });
904 }
905 
906 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
907                                     ValueDecl *Src, QualType DecompType,
908                                     const ConstantArrayType *CAT) {
909   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
910                                      llvm::APSInt(CAT->getSize()),
911                                      CAT->getElementType());
912 }
913 
914 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
915                                      ValueDecl *Src, QualType DecompType,
916                                      const VectorType *VT) {
917   return checkArrayLikeDecomposition(
918       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
919       S.Context.getQualifiedType(VT->getElementType(),
920                                  DecompType.getQualifiers()));
921 }
922 
923 static bool checkComplexDecomposition(Sema &S,
924                                       ArrayRef<BindingDecl *> Bindings,
925                                       ValueDecl *Src, QualType DecompType,
926                                       const ComplexType *CT) {
927   return checkSimpleDecomposition(
928       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
929       S.Context.getQualifiedType(CT->getElementType(),
930                                  DecompType.getQualifiers()),
931       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
932         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
933       });
934 }
935 
936 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
937                                      TemplateArgumentListInfo &Args) {
938   SmallString<128> SS;
939   llvm::raw_svector_ostream OS(SS);
940   bool First = true;
941   for (auto &Arg : Args.arguments()) {
942     if (!First)
943       OS << ", ";
944     Arg.getArgument().print(PrintingPolicy, OS);
945     First = false;
946   }
947   return OS.str();
948 }
949 
950 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
951                                      SourceLocation Loc, StringRef Trait,
952                                      TemplateArgumentListInfo &Args,
953                                      unsigned DiagID) {
954   auto DiagnoseMissing = [&] {
955     if (DiagID)
956       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
957                                                Args);
958     return true;
959   };
960 
961   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
962   NamespaceDecl *Std = S.getStdNamespace();
963   if (!Std)
964     return DiagnoseMissing();
965 
966   // Look up the trait itself, within namespace std. We can diagnose various
967   // problems with this lookup even if we've been asked to not diagnose a
968   // missing specialization, because this can only fail if the user has been
969   // declaring their own names in namespace std or we don't support the
970   // standard library implementation in use.
971   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
972                       Loc, Sema::LookupOrdinaryName);
973   if (!S.LookupQualifiedName(Result, Std))
974     return DiagnoseMissing();
975   if (Result.isAmbiguous())
976     return true;
977 
978   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
979   if (!TraitTD) {
980     Result.suppressDiagnostics();
981     NamedDecl *Found = *Result.begin();
982     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
983     S.Diag(Found->getLocation(), diag::note_declared_at);
984     return true;
985   }
986 
987   // Build the template-id.
988   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
989   if (TraitTy.isNull())
990     return true;
991   if (!S.isCompleteType(Loc, TraitTy)) {
992     if (DiagID)
993       S.RequireCompleteType(
994           Loc, TraitTy, DiagID,
995           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
996     return true;
997   }
998 
999   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1000   assert(RD && "specialization of class template is not a class?");
1001 
1002   // Look up the member of the trait type.
1003   S.LookupQualifiedName(TraitMemberLookup, RD);
1004   return TraitMemberLookup.isAmbiguous();
1005 }
1006 
1007 static TemplateArgumentLoc
1008 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1009                                    uint64_t I) {
1010   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1011   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1012 }
1013 
1014 static TemplateArgumentLoc
1015 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1016   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1017 }
1018 
1019 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1020 
1021 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1022                                llvm::APSInt &Size) {
1023   EnterExpressionEvaluationContext ContextRAII(
1024       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1025 
1026   DeclarationName Value = S.PP.getIdentifierInfo("value");
1027   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1028 
1029   // Form template argument list for tuple_size<T>.
1030   TemplateArgumentListInfo Args(Loc, Loc);
1031   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1032 
1033   // If there's no tuple_size specialization, it's not tuple-like.
1034   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1035     return IsTupleLike::NotTupleLike;
1036 
1037   // If we get this far, we've committed to the tuple interpretation, but
1038   // we can still fail if there actually isn't a usable ::value.
1039 
1040   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1041     LookupResult &R;
1042     TemplateArgumentListInfo &Args;
1043     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1044         : R(R), Args(Args) {}
1045     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1046       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1047           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1048     }
1049   } Diagnoser(R, Args);
1050 
1051   if (R.empty()) {
1052     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1053     return IsTupleLike::Error;
1054   }
1055 
1056   ExprResult E =
1057       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1058   if (E.isInvalid())
1059     return IsTupleLike::Error;
1060 
1061   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1062   if (E.isInvalid())
1063     return IsTupleLike::Error;
1064 
1065   return IsTupleLike::TupleLike;
1066 }
1067 
1068 /// \return std::tuple_element<I, T>::type.
1069 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1070                                         unsigned I, QualType T) {
1071   // Form template argument list for tuple_element<I, T>.
1072   TemplateArgumentListInfo Args(Loc, Loc);
1073   Args.addArgument(
1074       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1075   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1076 
1077   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1078   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1079   if (lookupStdTypeTraitMember(
1080           S, R, Loc, "tuple_element", Args,
1081           diag::err_decomp_decl_std_tuple_element_not_specialized))
1082     return QualType();
1083 
1084   auto *TD = R.getAsSingle<TypeDecl>();
1085   if (!TD) {
1086     R.suppressDiagnostics();
1087     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1088       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1089     if (!R.empty())
1090       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1091     return QualType();
1092   }
1093 
1094   return S.Context.getTypeDeclType(TD);
1095 }
1096 
1097 namespace {
1098 struct BindingDiagnosticTrap {
1099   Sema &S;
1100   DiagnosticErrorTrap Trap;
1101   BindingDecl *BD;
1102 
1103   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1104       : S(S), Trap(S.Diags), BD(BD) {}
1105   ~BindingDiagnosticTrap() {
1106     if (Trap.hasErrorOccurred())
1107       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1108   }
1109 };
1110 }
1111 
1112 static bool checkTupleLikeDecomposition(Sema &S,
1113                                         ArrayRef<BindingDecl *> Bindings,
1114                                         VarDecl *Src, QualType DecompType,
1115                                         const llvm::APSInt &TupleSize) {
1116   if ((int64_t)Bindings.size() != TupleSize) {
1117     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1118         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1119         << (TupleSize < Bindings.size());
1120     return true;
1121   }
1122 
1123   if (Bindings.empty())
1124     return false;
1125 
1126   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1127 
1128   // [dcl.decomp]p3:
1129   //   The unqualified-id get is looked up in the scope of E by class member
1130   //   access lookup ...
1131   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1132   bool UseMemberGet = false;
1133   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1134     if (auto *RD = DecompType->getAsCXXRecordDecl())
1135       S.LookupQualifiedName(MemberGet, RD);
1136     if (MemberGet.isAmbiguous())
1137       return true;
1138     //   ... and if that finds at least one declaration that is a function
1139     //   template whose first template parameter is a non-type parameter ...
1140     for (NamedDecl *D : MemberGet) {
1141       if (FunctionTemplateDecl *FTD =
1142               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1143         TemplateParameterList *TPL = FTD->getTemplateParameters();
1144         if (TPL->size() != 0 &&
1145             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1146           //   ... the initializer is e.get<i>().
1147           UseMemberGet = true;
1148           break;
1149         }
1150       }
1151     }
1152   }
1153 
1154   unsigned I = 0;
1155   for (auto *B : Bindings) {
1156     BindingDiagnosticTrap Trap(S, B);
1157     SourceLocation Loc = B->getLocation();
1158 
1159     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1160     if (E.isInvalid())
1161       return true;
1162 
1163     //   e is an lvalue if the type of the entity is an lvalue reference and
1164     //   an xvalue otherwise
1165     if (!Src->getType()->isLValueReferenceType())
1166       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1167                                    E.get(), nullptr, VK_XValue);
1168 
1169     TemplateArgumentListInfo Args(Loc, Loc);
1170     Args.addArgument(
1171         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1172 
1173     if (UseMemberGet) {
1174       //   if [lookup of member get] finds at least one declaration, the
1175       //   initializer is e.get<i-1>().
1176       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1177                                      CXXScopeSpec(), SourceLocation(), nullptr,
1178                                      MemberGet, &Args, nullptr);
1179       if (E.isInvalid())
1180         return true;
1181 
1182       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1183     } else {
1184       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1185       //   in the associated namespaces.
1186       Expr *Get = UnresolvedLookupExpr::Create(
1187           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1188           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1189           UnresolvedSetIterator(), UnresolvedSetIterator());
1190 
1191       Expr *Arg = E.get();
1192       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1193     }
1194     if (E.isInvalid())
1195       return true;
1196     Expr *Init = E.get();
1197 
1198     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1199     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1200     if (T.isNull())
1201       return true;
1202 
1203     //   each vi is a variable of type "reference to T" initialized with the
1204     //   initializer, where the reference is an lvalue reference if the
1205     //   initializer is an lvalue and an rvalue reference otherwise
1206     QualType RefType =
1207         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1208     if (RefType.isNull())
1209       return true;
1210     auto *RefVD = VarDecl::Create(
1211         S.Context, Src->getDeclContext(), Loc, Loc,
1212         B->getDeclName().getAsIdentifierInfo(), RefType,
1213         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1214     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1215     RefVD->setTSCSpec(Src->getTSCSpec());
1216     RefVD->setImplicit();
1217     if (Src->isInlineSpecified())
1218       RefVD->setInlineSpecified();
1219     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1220 
1221     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1222     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1223     InitializationSequence Seq(S, Entity, Kind, Init);
1224     E = Seq.Perform(S, Entity, Kind, Init);
1225     if (E.isInvalid())
1226       return true;
1227     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1228     if (E.isInvalid())
1229       return true;
1230     RefVD->setInit(E.get());
1231     RefVD->checkInitIsICE();
1232 
1233     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1234                                    DeclarationNameInfo(B->getDeclName(), Loc),
1235                                    RefVD);
1236     if (E.isInvalid())
1237       return true;
1238 
1239     B->setBinding(T, E.get());
1240     I++;
1241   }
1242 
1243   return false;
1244 }
1245 
1246 /// Find the base class to decompose in a built-in decomposition of a class type.
1247 /// This base class search is, unfortunately, not quite like any other that we
1248 /// perform anywhere else in C++.
1249 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1250                                                 const CXXRecordDecl *RD,
1251                                                 CXXCastPath &BasePath) {
1252   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1253                           CXXBasePath &Path) {
1254     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1255   };
1256 
1257   const CXXRecordDecl *ClassWithFields = nullptr;
1258   AccessSpecifier AS = AS_public;
1259   if (RD->hasDirectFields())
1260     // [dcl.decomp]p4:
1261     //   Otherwise, all of E's non-static data members shall be public direct
1262     //   members of E ...
1263     ClassWithFields = RD;
1264   else {
1265     //   ... or of ...
1266     CXXBasePaths Paths;
1267     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1268     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1269       // If no classes have fields, just decompose RD itself. (This will work
1270       // if and only if zero bindings were provided.)
1271       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1272     }
1273 
1274     CXXBasePath *BestPath = nullptr;
1275     for (auto &P : Paths) {
1276       if (!BestPath)
1277         BestPath = &P;
1278       else if (!S.Context.hasSameType(P.back().Base->getType(),
1279                                       BestPath->back().Base->getType())) {
1280         //   ... the same ...
1281         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1282           << false << RD << BestPath->back().Base->getType()
1283           << P.back().Base->getType();
1284         return DeclAccessPair();
1285       } else if (P.Access < BestPath->Access) {
1286         BestPath = &P;
1287       }
1288     }
1289 
1290     //   ... unambiguous ...
1291     QualType BaseType = BestPath->back().Base->getType();
1292     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1293       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1294         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1295       return DeclAccessPair();
1296     }
1297 
1298     //   ... [accessible, implied by other rules] base class of E.
1299     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1300                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1301     AS = BestPath->Access;
1302 
1303     ClassWithFields = BaseType->getAsCXXRecordDecl();
1304     S.BuildBasePathArray(Paths, BasePath);
1305   }
1306 
1307   // The above search did not check whether the selected class itself has base
1308   // classes with fields, so check that now.
1309   CXXBasePaths Paths;
1310   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1311     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1312       << (ClassWithFields == RD) << RD << ClassWithFields
1313       << Paths.front().back().Base->getType();
1314     return DeclAccessPair();
1315   }
1316 
1317   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1318 }
1319 
1320 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1321                                      ValueDecl *Src, QualType DecompType,
1322                                      const CXXRecordDecl *OrigRD) {
1323   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1324                             diag::err_incomplete_type))
1325     return true;
1326 
1327   CXXCastPath BasePath;
1328   DeclAccessPair BasePair =
1329       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1330   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1331   if (!RD)
1332     return true;
1333   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1334                                                  DecompType.getQualifiers());
1335 
1336   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1337     unsigned NumFields =
1338         std::count_if(RD->field_begin(), RD->field_end(),
1339                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1340     assert(Bindings.size() != NumFields);
1341     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1342         << DecompType << (unsigned)Bindings.size() << NumFields
1343         << (NumFields < Bindings.size());
1344     return true;
1345   };
1346 
1347   //   all of E's non-static data members shall be [...] well-formed
1348   //   when named as e.name in the context of the structured binding,
1349   //   E shall not have an anonymous union member, ...
1350   unsigned I = 0;
1351   for (auto *FD : RD->fields()) {
1352     if (FD->isUnnamedBitfield())
1353       continue;
1354 
1355     if (FD->isAnonymousStructOrUnion()) {
1356       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1357         << DecompType << FD->getType()->isUnionType();
1358       S.Diag(FD->getLocation(), diag::note_declared_at);
1359       return true;
1360     }
1361 
1362     // We have a real field to bind.
1363     if (I >= Bindings.size())
1364       return DiagnoseBadNumberOfBindings();
1365     auto *B = Bindings[I++];
1366     SourceLocation Loc = B->getLocation();
1367 
1368     // The field must be accessible in the context of the structured binding.
1369     // We already checked that the base class is accessible.
1370     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1371     // const_cast here.
1372     S.CheckStructuredBindingMemberAccess(
1373         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1374         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1375                                      BasePair.getAccess(), FD->getAccess())));
1376 
1377     // Initialize the binding to Src.FD.
1378     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1379     if (E.isInvalid())
1380       return true;
1381     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1382                             VK_LValue, &BasePath);
1383     if (E.isInvalid())
1384       return true;
1385     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1386                                   CXXScopeSpec(), FD,
1387                                   DeclAccessPair::make(FD, FD->getAccess()),
1388                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1389     if (E.isInvalid())
1390       return true;
1391 
1392     // If the type of the member is T, the referenced type is cv T, where cv is
1393     // the cv-qualification of the decomposition expression.
1394     //
1395     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1396     // 'const' to the type of the field.
1397     Qualifiers Q = DecompType.getQualifiers();
1398     if (FD->isMutable())
1399       Q.removeConst();
1400     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1401   }
1402 
1403   if (I != Bindings.size())
1404     return DiagnoseBadNumberOfBindings();
1405 
1406   return false;
1407 }
1408 
1409 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1410   QualType DecompType = DD->getType();
1411 
1412   // If the type of the decomposition is dependent, then so is the type of
1413   // each binding.
1414   if (DecompType->isDependentType()) {
1415     for (auto *B : DD->bindings())
1416       B->setType(Context.DependentTy);
1417     return;
1418   }
1419 
1420   DecompType = DecompType.getNonReferenceType();
1421   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1422 
1423   // C++1z [dcl.decomp]/2:
1424   //   If E is an array type [...]
1425   // As an extension, we also support decomposition of built-in complex and
1426   // vector types.
1427   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1428     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1429       DD->setInvalidDecl();
1430     return;
1431   }
1432   if (auto *VT = DecompType->getAs<VectorType>()) {
1433     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1434       DD->setInvalidDecl();
1435     return;
1436   }
1437   if (auto *CT = DecompType->getAs<ComplexType>()) {
1438     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1439       DD->setInvalidDecl();
1440     return;
1441   }
1442 
1443   // C++1z [dcl.decomp]/3:
1444   //   if the expression std::tuple_size<E>::value is a well-formed integral
1445   //   constant expression, [...]
1446   llvm::APSInt TupleSize(32);
1447   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1448   case IsTupleLike::Error:
1449     DD->setInvalidDecl();
1450     return;
1451 
1452   case IsTupleLike::TupleLike:
1453     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1454       DD->setInvalidDecl();
1455     return;
1456 
1457   case IsTupleLike::NotTupleLike:
1458     break;
1459   }
1460 
1461   // C++1z [dcl.dcl]/8:
1462   //   [E shall be of array or non-union class type]
1463   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1464   if (!RD || RD->isUnion()) {
1465     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1466         << DD << !RD << DecompType;
1467     DD->setInvalidDecl();
1468     return;
1469   }
1470 
1471   // C++1z [dcl.decomp]/4:
1472   //   all of E's non-static data members shall be [...] direct members of
1473   //   E or of the same unambiguous public base class of E, ...
1474   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1475     DD->setInvalidDecl();
1476 }
1477 
1478 /// Merge the exception specifications of two variable declarations.
1479 ///
1480 /// This is called when there's a redeclaration of a VarDecl. The function
1481 /// checks if the redeclaration might have an exception specification and
1482 /// validates compatibility and merges the specs if necessary.
1483 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1484   // Shortcut if exceptions are disabled.
1485   if (!getLangOpts().CXXExceptions)
1486     return;
1487 
1488   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1489          "Should only be called if types are otherwise the same.");
1490 
1491   QualType NewType = New->getType();
1492   QualType OldType = Old->getType();
1493 
1494   // We're only interested in pointers and references to functions, as well
1495   // as pointers to member functions.
1496   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1497     NewType = R->getPointeeType();
1498     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1499   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1500     NewType = P->getPointeeType();
1501     OldType = OldType->getAs<PointerType>()->getPointeeType();
1502   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1503     NewType = M->getPointeeType();
1504     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1505   }
1506 
1507   if (!NewType->isFunctionProtoType())
1508     return;
1509 
1510   // There's lots of special cases for functions. For function pointers, system
1511   // libraries are hopefully not as broken so that we don't need these
1512   // workarounds.
1513   if (CheckEquivalentExceptionSpec(
1514         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1515         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1516     New->setInvalidDecl();
1517   }
1518 }
1519 
1520 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1521 /// function declaration are well-formed according to C++
1522 /// [dcl.fct.default].
1523 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1524   unsigned NumParams = FD->getNumParams();
1525   unsigned p;
1526 
1527   // Find first parameter with a default argument
1528   for (p = 0; p < NumParams; ++p) {
1529     ParmVarDecl *Param = FD->getParamDecl(p);
1530     if (Param->hasDefaultArg())
1531       break;
1532   }
1533 
1534   // C++11 [dcl.fct.default]p4:
1535   //   In a given function declaration, each parameter subsequent to a parameter
1536   //   with a default argument shall have a default argument supplied in this or
1537   //   a previous declaration or shall be a function parameter pack. A default
1538   //   argument shall not be redefined by a later declaration (not even to the
1539   //   same value).
1540   unsigned LastMissingDefaultArg = 0;
1541   for (; p < NumParams; ++p) {
1542     ParmVarDecl *Param = FD->getParamDecl(p);
1543     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1544       if (Param->isInvalidDecl())
1545         /* We already complained about this parameter. */;
1546       else if (Param->getIdentifier())
1547         Diag(Param->getLocation(),
1548              diag::err_param_default_argument_missing_name)
1549           << Param->getIdentifier();
1550       else
1551         Diag(Param->getLocation(),
1552              diag::err_param_default_argument_missing);
1553 
1554       LastMissingDefaultArg = p;
1555     }
1556   }
1557 
1558   if (LastMissingDefaultArg > 0) {
1559     // Some default arguments were missing. Clear out all of the
1560     // default arguments up to (and including) the last missing
1561     // default argument, so that we leave the function parameters
1562     // in a semantically valid state.
1563     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1564       ParmVarDecl *Param = FD->getParamDecl(p);
1565       if (Param->hasDefaultArg()) {
1566         Param->setDefaultArg(nullptr);
1567       }
1568     }
1569   }
1570 }
1571 
1572 // CheckConstexprParameterTypes - Check whether a function's parameter types
1573 // are all literal types. If so, return true. If not, produce a suitable
1574 // diagnostic and return false.
1575 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1576                                          const FunctionDecl *FD) {
1577   unsigned ArgIndex = 0;
1578   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1579   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1580                                               e = FT->param_type_end();
1581        i != e; ++i, ++ArgIndex) {
1582     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1583     SourceLocation ParamLoc = PD->getLocation();
1584     if (!(*i)->isDependentType() &&
1585         SemaRef.RequireLiteralType(
1586             ParamLoc, *i, diag::err_constexpr_non_literal_param, ArgIndex + 1,
1587             PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1588             FD->isConsteval()))
1589       return false;
1590   }
1591   return true;
1592 }
1593 
1594 /// Get diagnostic %select index for tag kind for
1595 /// record diagnostic message.
1596 /// WARNING: Indexes apply to particular diagnostics only!
1597 ///
1598 /// \returns diagnostic %select index.
1599 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1600   switch (Tag) {
1601   case TTK_Struct: return 0;
1602   case TTK_Interface: return 1;
1603   case TTK_Class:  return 2;
1604   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1605   }
1606 }
1607 
1608 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1609 // the requirements of a constexpr function definition or a constexpr
1610 // constructor definition. If so, return true. If not, produce appropriate
1611 // diagnostics and return false.
1612 //
1613 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1614 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1615   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1616   if (MD && MD->isInstance()) {
1617     // C++11 [dcl.constexpr]p4:
1618     //  The definition of a constexpr constructor shall satisfy the following
1619     //  constraints:
1620     //  - the class shall not have any virtual base classes;
1621     //
1622     // FIXME: This only applies to constructors, not arbitrary member
1623     // functions.
1624     const CXXRecordDecl *RD = MD->getParent();
1625     if (RD->getNumVBases()) {
1626       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1627         << isa<CXXConstructorDecl>(NewFD)
1628         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1629       for (const auto &I : RD->vbases())
1630         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1631             << I.getSourceRange();
1632       return false;
1633     }
1634   }
1635 
1636   if (!isa<CXXConstructorDecl>(NewFD)) {
1637     // C++11 [dcl.constexpr]p3:
1638     //  The definition of a constexpr function shall satisfy the following
1639     //  constraints:
1640     // - it shall not be virtual; (removed in C++20)
1641     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1642     if (Method && Method->isVirtual()) {
1643       if (getLangOpts().CPlusPlus2a) {
1644         Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1645       } else {
1646         Method = Method->getCanonicalDecl();
1647         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1648 
1649         // If it's not obvious why this function is virtual, find an overridden
1650         // function which uses the 'virtual' keyword.
1651         const CXXMethodDecl *WrittenVirtual = Method;
1652         while (!WrittenVirtual->isVirtualAsWritten())
1653           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1654         if (WrittenVirtual != Method)
1655           Diag(WrittenVirtual->getLocation(),
1656                diag::note_overridden_virtual_function);
1657         return false;
1658       }
1659     }
1660 
1661     // - its return type shall be a literal type;
1662     QualType RT = NewFD->getReturnType();
1663     if (!RT->isDependentType() &&
1664         RequireLiteralType(NewFD->getLocation(), RT,
1665                            diag::err_constexpr_non_literal_return,
1666                            NewFD->isConsteval()))
1667       return false;
1668   }
1669 
1670   // - each of its parameter types shall be a literal type;
1671   if (!CheckConstexprParameterTypes(*this, NewFD))
1672     return false;
1673 
1674   return true;
1675 }
1676 
1677 /// Check the given declaration statement is legal within a constexpr function
1678 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1679 ///
1680 /// \return true if the body is OK (maybe only as an extension), false if we
1681 ///         have diagnosed a problem.
1682 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1683                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1684   // C++11 [dcl.constexpr]p3 and p4:
1685   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1686   //  contain only
1687   for (const auto *DclIt : DS->decls()) {
1688     switch (DclIt->getKind()) {
1689     case Decl::StaticAssert:
1690     case Decl::Using:
1691     case Decl::UsingShadow:
1692     case Decl::UsingDirective:
1693     case Decl::UnresolvedUsingTypename:
1694     case Decl::UnresolvedUsingValue:
1695       //   - static_assert-declarations
1696       //   - using-declarations,
1697       //   - using-directives,
1698       continue;
1699 
1700     case Decl::Typedef:
1701     case Decl::TypeAlias: {
1702       //   - typedef declarations and alias-declarations that do not define
1703       //     classes or enumerations,
1704       const auto *TN = cast<TypedefNameDecl>(DclIt);
1705       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1706         // Don't allow variably-modified types in constexpr functions.
1707         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1708         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1709           << TL.getSourceRange() << TL.getType()
1710           << isa<CXXConstructorDecl>(Dcl);
1711         return false;
1712       }
1713       continue;
1714     }
1715 
1716     case Decl::Enum:
1717     case Decl::CXXRecord:
1718       // C++1y allows types to be defined, not just declared.
1719       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1720         SemaRef.Diag(DS->getBeginLoc(),
1721                      SemaRef.getLangOpts().CPlusPlus14
1722                          ? diag::warn_cxx11_compat_constexpr_type_definition
1723                          : diag::ext_constexpr_type_definition)
1724             << isa<CXXConstructorDecl>(Dcl);
1725       continue;
1726 
1727     case Decl::EnumConstant:
1728     case Decl::IndirectField:
1729     case Decl::ParmVar:
1730       // These can only appear with other declarations which are banned in
1731       // C++11 and permitted in C++1y, so ignore them.
1732       continue;
1733 
1734     case Decl::Var:
1735     case Decl::Decomposition: {
1736       // C++1y [dcl.constexpr]p3 allows anything except:
1737       //   a definition of a variable of non-literal type or of static or
1738       //   thread storage duration or for which no initialization is performed.
1739       const auto *VD = cast<VarDecl>(DclIt);
1740       if (VD->isThisDeclarationADefinition()) {
1741         if (VD->isStaticLocal()) {
1742           SemaRef.Diag(VD->getLocation(),
1743                        diag::err_constexpr_local_var_static)
1744             << isa<CXXConstructorDecl>(Dcl)
1745             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1746           return false;
1747         }
1748         if (!VD->getType()->isDependentType() &&
1749             SemaRef.RequireLiteralType(
1750               VD->getLocation(), VD->getType(),
1751               diag::err_constexpr_local_var_non_literal_type,
1752               isa<CXXConstructorDecl>(Dcl)))
1753           return false;
1754         if (!VD->getType()->isDependentType() &&
1755             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1756           SemaRef.Diag(VD->getLocation(),
1757                        diag::err_constexpr_local_var_no_init)
1758             << isa<CXXConstructorDecl>(Dcl);
1759           return false;
1760         }
1761       }
1762       SemaRef.Diag(VD->getLocation(),
1763                    SemaRef.getLangOpts().CPlusPlus14
1764                     ? diag::warn_cxx11_compat_constexpr_local_var
1765                     : diag::ext_constexpr_local_var)
1766         << isa<CXXConstructorDecl>(Dcl);
1767       continue;
1768     }
1769 
1770     case Decl::NamespaceAlias:
1771     case Decl::Function:
1772       // These are disallowed in C++11 and permitted in C++1y. Allow them
1773       // everywhere as an extension.
1774       if (!Cxx1yLoc.isValid())
1775         Cxx1yLoc = DS->getBeginLoc();
1776       continue;
1777 
1778     default:
1779       SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1780           << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1781       return false;
1782     }
1783   }
1784 
1785   return true;
1786 }
1787 
1788 /// Check that the given field is initialized within a constexpr constructor.
1789 ///
1790 /// \param Dcl The constexpr constructor being checked.
1791 /// \param Field The field being checked. This may be a member of an anonymous
1792 ///        struct or union nested within the class being checked.
1793 /// \param Inits All declarations, including anonymous struct/union members and
1794 ///        indirect members, for which any initialization was provided.
1795 /// \param Diagnosed Set to true if an error is produced.
1796 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1797                                           const FunctionDecl *Dcl,
1798                                           FieldDecl *Field,
1799                                           llvm::SmallSet<Decl*, 16> &Inits,
1800                                           bool &Diagnosed) {
1801   if (Field->isInvalidDecl())
1802     return;
1803 
1804   if (Field->isUnnamedBitfield())
1805     return;
1806 
1807   // Anonymous unions with no variant members and empty anonymous structs do not
1808   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1809   // indirect fields don't need initializing.
1810   if (Field->isAnonymousStructOrUnion() &&
1811       (Field->getType()->isUnionType()
1812            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1813            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1814     return;
1815 
1816   if (!Inits.count(Field)) {
1817     if (!Diagnosed) {
1818       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1819       Diagnosed = true;
1820     }
1821     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1822   } else if (Field->isAnonymousStructOrUnion()) {
1823     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1824     for (auto *I : RD->fields())
1825       // If an anonymous union contains an anonymous struct of which any member
1826       // is initialized, all members must be initialized.
1827       if (!RD->isUnion() || Inits.count(I))
1828         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1829   }
1830 }
1831 
1832 /// Check the provided statement is allowed in a constexpr function
1833 /// definition.
1834 static bool
1835 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1836                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1837                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc) {
1838   // - its function-body shall be [...] a compound-statement that contains only
1839   switch (S->getStmtClass()) {
1840   case Stmt::NullStmtClass:
1841     //   - null statements,
1842     return true;
1843 
1844   case Stmt::DeclStmtClass:
1845     //   - static_assert-declarations
1846     //   - using-declarations,
1847     //   - using-directives,
1848     //   - typedef declarations and alias-declarations that do not define
1849     //     classes or enumerations,
1850     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1851       return false;
1852     return true;
1853 
1854   case Stmt::ReturnStmtClass:
1855     //   - and exactly one return statement;
1856     if (isa<CXXConstructorDecl>(Dcl)) {
1857       // C++1y allows return statements in constexpr constructors.
1858       if (!Cxx1yLoc.isValid())
1859         Cxx1yLoc = S->getBeginLoc();
1860       return true;
1861     }
1862 
1863     ReturnStmts.push_back(S->getBeginLoc());
1864     return true;
1865 
1866   case Stmt::CompoundStmtClass: {
1867     // C++1y allows compound-statements.
1868     if (!Cxx1yLoc.isValid())
1869       Cxx1yLoc = S->getBeginLoc();
1870 
1871     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1872     for (auto *BodyIt : CompStmt->body()) {
1873       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1874                                       Cxx1yLoc, Cxx2aLoc))
1875         return false;
1876     }
1877     return true;
1878   }
1879 
1880   case Stmt::AttributedStmtClass:
1881     if (!Cxx1yLoc.isValid())
1882       Cxx1yLoc = S->getBeginLoc();
1883     return true;
1884 
1885   case Stmt::IfStmtClass: {
1886     // C++1y allows if-statements.
1887     if (!Cxx1yLoc.isValid())
1888       Cxx1yLoc = S->getBeginLoc();
1889 
1890     IfStmt *If = cast<IfStmt>(S);
1891     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1892                                     Cxx1yLoc, Cxx2aLoc))
1893       return false;
1894     if (If->getElse() &&
1895         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1896                                     Cxx1yLoc, Cxx2aLoc))
1897       return false;
1898     return true;
1899   }
1900 
1901   case Stmt::WhileStmtClass:
1902   case Stmt::DoStmtClass:
1903   case Stmt::ForStmtClass:
1904   case Stmt::CXXForRangeStmtClass:
1905   case Stmt::ContinueStmtClass:
1906     // C++1y allows all of these. We don't allow them as extensions in C++11,
1907     // because they don't make sense without variable mutation.
1908     if (!SemaRef.getLangOpts().CPlusPlus14)
1909       break;
1910     if (!Cxx1yLoc.isValid())
1911       Cxx1yLoc = S->getBeginLoc();
1912     for (Stmt *SubStmt : S->children())
1913       if (SubStmt &&
1914           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1915                                       Cxx1yLoc, Cxx2aLoc))
1916         return false;
1917     return true;
1918 
1919   case Stmt::SwitchStmtClass:
1920   case Stmt::CaseStmtClass:
1921   case Stmt::DefaultStmtClass:
1922   case Stmt::BreakStmtClass:
1923     // C++1y allows switch-statements, and since they don't need variable
1924     // mutation, we can reasonably allow them in C++11 as an extension.
1925     if (!Cxx1yLoc.isValid())
1926       Cxx1yLoc = S->getBeginLoc();
1927     for (Stmt *SubStmt : S->children())
1928       if (SubStmt &&
1929           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1930                                       Cxx1yLoc, Cxx2aLoc))
1931         return false;
1932     return true;
1933 
1934   case Stmt::CXXTryStmtClass:
1935     if (Cxx2aLoc.isInvalid())
1936       Cxx2aLoc = S->getBeginLoc();
1937     for (Stmt *SubStmt : S->children()) {
1938       if (SubStmt &&
1939           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1940                                       Cxx1yLoc, Cxx2aLoc))
1941         return false;
1942     }
1943     return true;
1944 
1945   case Stmt::CXXCatchStmtClass:
1946     // Do not bother checking the language mode (already covered by the
1947     // try block check).
1948     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
1949                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
1950                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc))
1951       return false;
1952     return true;
1953 
1954   default:
1955     if (!isa<Expr>(S))
1956       break;
1957 
1958     // C++1y allows expression-statements.
1959     if (!Cxx1yLoc.isValid())
1960       Cxx1yLoc = S->getBeginLoc();
1961     return true;
1962   }
1963 
1964   SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1965       << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1966   return false;
1967 }
1968 
1969 /// Check the body for the given constexpr function declaration only contains
1970 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1971 ///
1972 /// \return true if the body is OK, false if we have diagnosed a problem.
1973 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1974   SmallVector<SourceLocation, 4> ReturnStmts;
1975 
1976   if (isa<CXXTryStmt>(Body)) {
1977     // C++11 [dcl.constexpr]p3:
1978     //  The definition of a constexpr function shall satisfy the following
1979     //  constraints: [...]
1980     // - its function-body shall be = delete, = default, or a
1981     //   compound-statement
1982     //
1983     // C++11 [dcl.constexpr]p4:
1984     //  In the definition of a constexpr constructor, [...]
1985     // - its function-body shall not be a function-try-block;
1986     //
1987     // This restriction is lifted in C++2a, as long as inner statements also
1988     // apply the general constexpr rules.
1989     Diag(Body->getBeginLoc(),
1990          !getLangOpts().CPlusPlus2a
1991              ? diag::ext_constexpr_function_try_block_cxx2a
1992              : diag::warn_cxx17_compat_constexpr_function_try_block)
1993         << isa<CXXConstructorDecl>(Dcl);
1994   }
1995 
1996   // - its function-body shall be [...] a compound-statement that contains only
1997   //   [... list of cases ...]
1998   //
1999   // Note that walking the children here is enough to properly check for
2000   // CompoundStmt and CXXTryStmt body.
2001   SourceLocation Cxx1yLoc, Cxx2aLoc;
2002   for (Stmt *SubStmt : Body->children()) {
2003     if (SubStmt &&
2004         !CheckConstexprFunctionStmt(*this, Dcl, SubStmt, ReturnStmts,
2005                                     Cxx1yLoc, Cxx2aLoc))
2006       return false;
2007   }
2008 
2009   if (Cxx2aLoc.isValid())
2010     Diag(Cxx2aLoc,
2011          getLangOpts().CPlusPlus2a
2012            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2013            : diag::ext_constexpr_body_invalid_stmt_cxx2a)
2014       << isa<CXXConstructorDecl>(Dcl);
2015   if (Cxx1yLoc.isValid())
2016     Diag(Cxx1yLoc,
2017          getLangOpts().CPlusPlus14
2018            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2019            : diag::ext_constexpr_body_invalid_stmt)
2020       << isa<CXXConstructorDecl>(Dcl);
2021 
2022   if (const CXXConstructorDecl *Constructor
2023         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2024     const CXXRecordDecl *RD = Constructor->getParent();
2025     // DR1359:
2026     // - every non-variant non-static data member and base class sub-object
2027     //   shall be initialized;
2028     // DR1460:
2029     // - if the class is a union having variant members, exactly one of them
2030     //   shall be initialized;
2031     if (RD->isUnion()) {
2032       if (Constructor->getNumCtorInitializers() == 0 &&
2033           RD->hasVariantMembers()) {
2034         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
2035         return false;
2036       }
2037     } else if (!Constructor->isDependentContext() &&
2038                !Constructor->isDelegatingConstructor()) {
2039       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2040 
2041       // Skip detailed checking if we have enough initializers, and we would
2042       // allow at most one initializer per member.
2043       bool AnyAnonStructUnionMembers = false;
2044       unsigned Fields = 0;
2045       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2046            E = RD->field_end(); I != E; ++I, ++Fields) {
2047         if (I->isAnonymousStructOrUnion()) {
2048           AnyAnonStructUnionMembers = true;
2049           break;
2050         }
2051       }
2052       // DR1460:
2053       // - if the class is a union-like class, but is not a union, for each of
2054       //   its anonymous union members having variant members, exactly one of
2055       //   them shall be initialized;
2056       if (AnyAnonStructUnionMembers ||
2057           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2058         // Check initialization of non-static data members. Base classes are
2059         // always initialized so do not need to be checked. Dependent bases
2060         // might not have initializers in the member initializer list.
2061         llvm::SmallSet<Decl*, 16> Inits;
2062         for (const auto *I: Constructor->inits()) {
2063           if (FieldDecl *FD = I->getMember())
2064             Inits.insert(FD);
2065           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2066             Inits.insert(ID->chain_begin(), ID->chain_end());
2067         }
2068 
2069         bool Diagnosed = false;
2070         for (auto *I : RD->fields())
2071           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2072         if (Diagnosed)
2073           return false;
2074       }
2075     }
2076   } else {
2077     if (ReturnStmts.empty()) {
2078       // C++1y doesn't require constexpr functions to contain a 'return'
2079       // statement. We still do, unless the return type might be void, because
2080       // otherwise if there's no return statement, the function cannot
2081       // be used in a core constant expression.
2082       bool OK = getLangOpts().CPlusPlus14 &&
2083                 (Dcl->getReturnType()->isVoidType() ||
2084                  Dcl->getReturnType()->isDependentType());
2085       Diag(Dcl->getLocation(),
2086            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2087               : diag::err_constexpr_body_no_return)
2088           << Dcl->isConsteval();
2089       if (!OK)
2090         return false;
2091     } else if (ReturnStmts.size() > 1) {
2092       Diag(ReturnStmts.back(),
2093            getLangOpts().CPlusPlus14
2094              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2095              : diag::ext_constexpr_body_multiple_return);
2096       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2097         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2098     }
2099   }
2100 
2101   // C++11 [dcl.constexpr]p5:
2102   //   if no function argument values exist such that the function invocation
2103   //   substitution would produce a constant expression, the program is
2104   //   ill-formed; no diagnostic required.
2105   // C++11 [dcl.constexpr]p3:
2106   //   - every constructor call and implicit conversion used in initializing the
2107   //     return value shall be one of those allowed in a constant expression.
2108   // C++11 [dcl.constexpr]p4:
2109   //   - every constructor involved in initializing non-static data members and
2110   //     base class sub-objects shall be a constexpr constructor.
2111   SmallVector<PartialDiagnosticAt, 8> Diags;
2112   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2113     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2114       << isa<CXXConstructorDecl>(Dcl);
2115     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2116       Diag(Diags[I].first, Diags[I].second);
2117     // Don't return false here: we allow this for compatibility in
2118     // system headers.
2119   }
2120 
2121   return true;
2122 }
2123 
2124 /// Get the class that is directly named by the current context. This is the
2125 /// class for which an unqualified-id in this scope could name a constructor
2126 /// or destructor.
2127 ///
2128 /// If the scope specifier denotes a class, this will be that class.
2129 /// If the scope specifier is empty, this will be the class whose
2130 /// member-specification we are currently within. Otherwise, there
2131 /// is no such class.
2132 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2133   assert(getLangOpts().CPlusPlus && "No class names in C!");
2134 
2135   if (SS && SS->isInvalid())
2136     return nullptr;
2137 
2138   if (SS && SS->isNotEmpty()) {
2139     DeclContext *DC = computeDeclContext(*SS, true);
2140     return dyn_cast_or_null<CXXRecordDecl>(DC);
2141   }
2142 
2143   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2144 }
2145 
2146 /// isCurrentClassName - Determine whether the identifier II is the
2147 /// name of the class type currently being defined. In the case of
2148 /// nested classes, this will only return true if II is the name of
2149 /// the innermost class.
2150 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2151                               const CXXScopeSpec *SS) {
2152   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2153   return CurDecl && &II == CurDecl->getIdentifier();
2154 }
2155 
2156 /// Determine whether the identifier II is a typo for the name of
2157 /// the class type currently being defined. If so, update it to the identifier
2158 /// that should have been used.
2159 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2160   assert(getLangOpts().CPlusPlus && "No class names in C!");
2161 
2162   if (!getLangOpts().SpellChecking)
2163     return false;
2164 
2165   CXXRecordDecl *CurDecl;
2166   if (SS && SS->isSet() && !SS->isInvalid()) {
2167     DeclContext *DC = computeDeclContext(*SS, true);
2168     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2169   } else
2170     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2171 
2172   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2173       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2174           < II->getLength()) {
2175     II = CurDecl->getIdentifier();
2176     return true;
2177   }
2178 
2179   return false;
2180 }
2181 
2182 /// Determine whether the given class is a base class of the given
2183 /// class, including looking at dependent bases.
2184 static bool findCircularInheritance(const CXXRecordDecl *Class,
2185                                     const CXXRecordDecl *Current) {
2186   SmallVector<const CXXRecordDecl*, 8> Queue;
2187 
2188   Class = Class->getCanonicalDecl();
2189   while (true) {
2190     for (const auto &I : Current->bases()) {
2191       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2192       if (!Base)
2193         continue;
2194 
2195       Base = Base->getDefinition();
2196       if (!Base)
2197         continue;
2198 
2199       if (Base->getCanonicalDecl() == Class)
2200         return true;
2201 
2202       Queue.push_back(Base);
2203     }
2204 
2205     if (Queue.empty())
2206       return false;
2207 
2208     Current = Queue.pop_back_val();
2209   }
2210 
2211   return false;
2212 }
2213 
2214 /// Check the validity of a C++ base class specifier.
2215 ///
2216 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2217 /// and returns NULL otherwise.
2218 CXXBaseSpecifier *
2219 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2220                          SourceRange SpecifierRange,
2221                          bool Virtual, AccessSpecifier Access,
2222                          TypeSourceInfo *TInfo,
2223                          SourceLocation EllipsisLoc) {
2224   QualType BaseType = TInfo->getType();
2225 
2226   // C++ [class.union]p1:
2227   //   A union shall not have base classes.
2228   if (Class->isUnion()) {
2229     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2230       << SpecifierRange;
2231     return nullptr;
2232   }
2233 
2234   if (EllipsisLoc.isValid() &&
2235       !TInfo->getType()->containsUnexpandedParameterPack()) {
2236     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2237       << TInfo->getTypeLoc().getSourceRange();
2238     EllipsisLoc = SourceLocation();
2239   }
2240 
2241   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2242 
2243   if (BaseType->isDependentType()) {
2244     // Make sure that we don't have circular inheritance among our dependent
2245     // bases. For non-dependent bases, the check for completeness below handles
2246     // this.
2247     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2248       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2249           ((BaseDecl = BaseDecl->getDefinition()) &&
2250            findCircularInheritance(Class, BaseDecl))) {
2251         Diag(BaseLoc, diag::err_circular_inheritance)
2252           << BaseType << Context.getTypeDeclType(Class);
2253 
2254         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2255           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2256             << BaseType;
2257 
2258         return nullptr;
2259       }
2260     }
2261 
2262     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2263                                           Class->getTagKind() == TTK_Class,
2264                                           Access, TInfo, EllipsisLoc);
2265   }
2266 
2267   // Base specifiers must be record types.
2268   if (!BaseType->isRecordType()) {
2269     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2270     return nullptr;
2271   }
2272 
2273   // C++ [class.union]p1:
2274   //   A union shall not be used as a base class.
2275   if (BaseType->isUnionType()) {
2276     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2277     return nullptr;
2278   }
2279 
2280   // For the MS ABI, propagate DLL attributes to base class templates.
2281   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2282     if (Attr *ClassAttr = getDLLAttr(Class)) {
2283       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2284               BaseType->getAsCXXRecordDecl())) {
2285         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2286                                             BaseLoc);
2287       }
2288     }
2289   }
2290 
2291   // C++ [class.derived]p2:
2292   //   The class-name in a base-specifier shall not be an incompletely
2293   //   defined class.
2294   if (RequireCompleteType(BaseLoc, BaseType,
2295                           diag::err_incomplete_base_class, SpecifierRange)) {
2296     Class->setInvalidDecl();
2297     return nullptr;
2298   }
2299 
2300   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2301   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2302   assert(BaseDecl && "Record type has no declaration");
2303   BaseDecl = BaseDecl->getDefinition();
2304   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2305   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2306   assert(CXXBaseDecl && "Base type is not a C++ type");
2307 
2308   // Microsoft docs say:
2309   // "If a base-class has a code_seg attribute, derived classes must have the
2310   // same attribute."
2311   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2312   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2313   if ((DerivedCSA || BaseCSA) &&
2314       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2315     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2316     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2317       << CXXBaseDecl;
2318     return nullptr;
2319   }
2320 
2321   // A class which contains a flexible array member is not suitable for use as a
2322   // base class:
2323   //   - If the layout determines that a base comes before another base,
2324   //     the flexible array member would index into the subsequent base.
2325   //   - If the layout determines that base comes before the derived class,
2326   //     the flexible array member would index into the derived class.
2327   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2328     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2329       << CXXBaseDecl->getDeclName();
2330     return nullptr;
2331   }
2332 
2333   // C++ [class]p3:
2334   //   If a class is marked final and it appears as a base-type-specifier in
2335   //   base-clause, the program is ill-formed.
2336   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2337     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2338       << CXXBaseDecl->getDeclName()
2339       << FA->isSpelledAsSealed();
2340     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2341         << CXXBaseDecl->getDeclName() << FA->getRange();
2342     return nullptr;
2343   }
2344 
2345   if (BaseDecl->isInvalidDecl())
2346     Class->setInvalidDecl();
2347 
2348   // Create the base specifier.
2349   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2350                                         Class->getTagKind() == TTK_Class,
2351                                         Access, TInfo, EllipsisLoc);
2352 }
2353 
2354 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2355 /// one entry in the base class list of a class specifier, for
2356 /// example:
2357 ///    class foo : public bar, virtual private baz {
2358 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2359 BaseResult
2360 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2361                          ParsedAttributes &Attributes,
2362                          bool Virtual, AccessSpecifier Access,
2363                          ParsedType basetype, SourceLocation BaseLoc,
2364                          SourceLocation EllipsisLoc) {
2365   if (!classdecl)
2366     return true;
2367 
2368   AdjustDeclIfTemplate(classdecl);
2369   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2370   if (!Class)
2371     return true;
2372 
2373   // We haven't yet attached the base specifiers.
2374   Class->setIsParsingBaseSpecifiers();
2375 
2376   // We do not support any C++11 attributes on base-specifiers yet.
2377   // Diagnose any attributes we see.
2378   for (const ParsedAttr &AL : Attributes) {
2379     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2380       continue;
2381     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2382                           ? (unsigned)diag::warn_unknown_attribute_ignored
2383                           : (unsigned)diag::err_base_specifier_attribute)
2384         << AL.getName();
2385   }
2386 
2387   TypeSourceInfo *TInfo = nullptr;
2388   GetTypeFromParser(basetype, &TInfo);
2389 
2390   if (EllipsisLoc.isInvalid() &&
2391       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2392                                       UPPC_BaseType))
2393     return true;
2394 
2395   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2396                                                       Virtual, Access, TInfo,
2397                                                       EllipsisLoc))
2398     return BaseSpec;
2399   else
2400     Class->setInvalidDecl();
2401 
2402   return true;
2403 }
2404 
2405 /// Use small set to collect indirect bases.  As this is only used
2406 /// locally, there's no need to abstract the small size parameter.
2407 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2408 
2409 /// Recursively add the bases of Type.  Don't add Type itself.
2410 static void
2411 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2412                   const QualType &Type)
2413 {
2414   // Even though the incoming type is a base, it might not be
2415   // a class -- it could be a template parm, for instance.
2416   if (auto Rec = Type->getAs<RecordType>()) {
2417     auto Decl = Rec->getAsCXXRecordDecl();
2418 
2419     // Iterate over its bases.
2420     for (const auto &BaseSpec : Decl->bases()) {
2421       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2422         .getUnqualifiedType();
2423       if (Set.insert(Base).second)
2424         // If we've not already seen it, recurse.
2425         NoteIndirectBases(Context, Set, Base);
2426     }
2427   }
2428 }
2429 
2430 /// Performs the actual work of attaching the given base class
2431 /// specifiers to a C++ class.
2432 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2433                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2434  if (Bases.empty())
2435     return false;
2436 
2437   // Used to keep track of which base types we have already seen, so
2438   // that we can properly diagnose redundant direct base types. Note
2439   // that the key is always the unqualified canonical type of the base
2440   // class.
2441   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2442 
2443   // Used to track indirect bases so we can see if a direct base is
2444   // ambiguous.
2445   IndirectBaseSet IndirectBaseTypes;
2446 
2447   // Copy non-redundant base specifiers into permanent storage.
2448   unsigned NumGoodBases = 0;
2449   bool Invalid = false;
2450   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2451     QualType NewBaseType
2452       = Context.getCanonicalType(Bases[idx]->getType());
2453     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2454 
2455     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2456     if (KnownBase) {
2457       // C++ [class.mi]p3:
2458       //   A class shall not be specified as a direct base class of a
2459       //   derived class more than once.
2460       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2461           << KnownBase->getType() << Bases[idx]->getSourceRange();
2462 
2463       // Delete the duplicate base class specifier; we're going to
2464       // overwrite its pointer later.
2465       Context.Deallocate(Bases[idx]);
2466 
2467       Invalid = true;
2468     } else {
2469       // Okay, add this new base class.
2470       KnownBase = Bases[idx];
2471       Bases[NumGoodBases++] = Bases[idx];
2472 
2473       // Note this base's direct & indirect bases, if there could be ambiguity.
2474       if (Bases.size() > 1)
2475         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2476 
2477       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2478         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2479         if (Class->isInterface() &&
2480               (!RD->isInterfaceLike() ||
2481                KnownBase->getAccessSpecifier() != AS_public)) {
2482           // The Microsoft extension __interface does not permit bases that
2483           // are not themselves public interfaces.
2484           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2485               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2486               << RD->getSourceRange();
2487           Invalid = true;
2488         }
2489         if (RD->hasAttr<WeakAttr>())
2490           Class->addAttr(WeakAttr::CreateImplicit(Context));
2491       }
2492     }
2493   }
2494 
2495   // Attach the remaining base class specifiers to the derived class.
2496   Class->setBases(Bases.data(), NumGoodBases);
2497 
2498   // Check that the only base classes that are duplicate are virtual.
2499   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2500     // Check whether this direct base is inaccessible due to ambiguity.
2501     QualType BaseType = Bases[idx]->getType();
2502 
2503     // Skip all dependent types in templates being used as base specifiers.
2504     // Checks below assume that the base specifier is a CXXRecord.
2505     if (BaseType->isDependentType())
2506       continue;
2507 
2508     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2509       .getUnqualifiedType();
2510 
2511     if (IndirectBaseTypes.count(CanonicalBase)) {
2512       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2513                          /*DetectVirtual=*/true);
2514       bool found
2515         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2516       assert(found);
2517       (void)found;
2518 
2519       if (Paths.isAmbiguous(CanonicalBase))
2520         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2521             << BaseType << getAmbiguousPathsDisplayString(Paths)
2522             << Bases[idx]->getSourceRange();
2523       else
2524         assert(Bases[idx]->isVirtual());
2525     }
2526 
2527     // Delete the base class specifier, since its data has been copied
2528     // into the CXXRecordDecl.
2529     Context.Deallocate(Bases[idx]);
2530   }
2531 
2532   return Invalid;
2533 }
2534 
2535 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2536 /// class, after checking whether there are any duplicate base
2537 /// classes.
2538 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2539                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2540   if (!ClassDecl || Bases.empty())
2541     return;
2542 
2543   AdjustDeclIfTemplate(ClassDecl);
2544   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2545 }
2546 
2547 /// Determine whether the type \p Derived is a C++ class that is
2548 /// derived from the type \p Base.
2549 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2550   if (!getLangOpts().CPlusPlus)
2551     return false;
2552 
2553   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2554   if (!DerivedRD)
2555     return false;
2556 
2557   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2558   if (!BaseRD)
2559     return false;
2560 
2561   // If either the base or the derived type is invalid, don't try to
2562   // check whether one is derived from the other.
2563   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2564     return false;
2565 
2566   // FIXME: In a modules build, do we need the entire path to be visible for us
2567   // to be able to use the inheritance relationship?
2568   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2569     return false;
2570 
2571   return DerivedRD->isDerivedFrom(BaseRD);
2572 }
2573 
2574 /// Determine whether the type \p Derived is a C++ class that is
2575 /// derived from the type \p Base.
2576 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2577                          CXXBasePaths &Paths) {
2578   if (!getLangOpts().CPlusPlus)
2579     return false;
2580 
2581   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2582   if (!DerivedRD)
2583     return false;
2584 
2585   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2586   if (!BaseRD)
2587     return false;
2588 
2589   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2590     return false;
2591 
2592   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2593 }
2594 
2595 static void BuildBasePathArray(const CXXBasePath &Path,
2596                                CXXCastPath &BasePathArray) {
2597   // We first go backward and check if we have a virtual base.
2598   // FIXME: It would be better if CXXBasePath had the base specifier for
2599   // the nearest virtual base.
2600   unsigned Start = 0;
2601   for (unsigned I = Path.size(); I != 0; --I) {
2602     if (Path[I - 1].Base->isVirtual()) {
2603       Start = I - 1;
2604       break;
2605     }
2606   }
2607 
2608   // Now add all bases.
2609   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2610     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2611 }
2612 
2613 
2614 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2615                               CXXCastPath &BasePathArray) {
2616   assert(BasePathArray.empty() && "Base path array must be empty!");
2617   assert(Paths.isRecordingPaths() && "Must record paths!");
2618   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2619 }
2620 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2621 /// conversion (where Derived and Base are class types) is
2622 /// well-formed, meaning that the conversion is unambiguous (and
2623 /// that all of the base classes are accessible). Returns true
2624 /// and emits a diagnostic if the code is ill-formed, returns false
2625 /// otherwise. Loc is the location where this routine should point to
2626 /// if there is an error, and Range is the source range to highlight
2627 /// if there is an error.
2628 ///
2629 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2630 /// diagnostic for the respective type of error will be suppressed, but the
2631 /// check for ill-formed code will still be performed.
2632 bool
2633 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2634                                    unsigned InaccessibleBaseID,
2635                                    unsigned AmbigiousBaseConvID,
2636                                    SourceLocation Loc, SourceRange Range,
2637                                    DeclarationName Name,
2638                                    CXXCastPath *BasePath,
2639                                    bool IgnoreAccess) {
2640   // First, determine whether the path from Derived to Base is
2641   // ambiguous. This is slightly more expensive than checking whether
2642   // the Derived to Base conversion exists, because here we need to
2643   // explore multiple paths to determine if there is an ambiguity.
2644   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2645                      /*DetectVirtual=*/false);
2646   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2647   if (!DerivationOkay)
2648     return true;
2649 
2650   const CXXBasePath *Path = nullptr;
2651   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2652     Path = &Paths.front();
2653 
2654   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2655   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2656   // user to access such bases.
2657   if (!Path && getLangOpts().MSVCCompat) {
2658     for (const CXXBasePath &PossiblePath : Paths) {
2659       if (PossiblePath.size() == 1) {
2660         Path = &PossiblePath;
2661         if (AmbigiousBaseConvID)
2662           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2663               << Base << Derived << Range;
2664         break;
2665       }
2666     }
2667   }
2668 
2669   if (Path) {
2670     if (!IgnoreAccess) {
2671       // Check that the base class can be accessed.
2672       switch (
2673           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2674       case AR_inaccessible:
2675         return true;
2676       case AR_accessible:
2677       case AR_dependent:
2678       case AR_delayed:
2679         break;
2680       }
2681     }
2682 
2683     // Build a base path if necessary.
2684     if (BasePath)
2685       ::BuildBasePathArray(*Path, *BasePath);
2686     return false;
2687   }
2688 
2689   if (AmbigiousBaseConvID) {
2690     // We know that the derived-to-base conversion is ambiguous, and
2691     // we're going to produce a diagnostic. Perform the derived-to-base
2692     // search just one more time to compute all of the possible paths so
2693     // that we can print them out. This is more expensive than any of
2694     // the previous derived-to-base checks we've done, but at this point
2695     // performance isn't as much of an issue.
2696     Paths.clear();
2697     Paths.setRecordingPaths(true);
2698     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2699     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2700     (void)StillOkay;
2701 
2702     // Build up a textual representation of the ambiguous paths, e.g.,
2703     // D -> B -> A, that will be used to illustrate the ambiguous
2704     // conversions in the diagnostic. We only print one of the paths
2705     // to each base class subobject.
2706     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2707 
2708     Diag(Loc, AmbigiousBaseConvID)
2709     << Derived << Base << PathDisplayStr << Range << Name;
2710   }
2711   return true;
2712 }
2713 
2714 bool
2715 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2716                                    SourceLocation Loc, SourceRange Range,
2717                                    CXXCastPath *BasePath,
2718                                    bool IgnoreAccess) {
2719   return CheckDerivedToBaseConversion(
2720       Derived, Base, diag::err_upcast_to_inaccessible_base,
2721       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2722       BasePath, IgnoreAccess);
2723 }
2724 
2725 
2726 /// Builds a string representing ambiguous paths from a
2727 /// specific derived class to different subobjects of the same base
2728 /// class.
2729 ///
2730 /// This function builds a string that can be used in error messages
2731 /// to show the different paths that one can take through the
2732 /// inheritance hierarchy to go from the derived class to different
2733 /// subobjects of a base class. The result looks something like this:
2734 /// @code
2735 /// struct D -> struct B -> struct A
2736 /// struct D -> struct C -> struct A
2737 /// @endcode
2738 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2739   std::string PathDisplayStr;
2740   std::set<unsigned> DisplayedPaths;
2741   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2742        Path != Paths.end(); ++Path) {
2743     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2744       // We haven't displayed a path to this particular base
2745       // class subobject yet.
2746       PathDisplayStr += "\n    ";
2747       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2748       for (CXXBasePath::const_iterator Element = Path->begin();
2749            Element != Path->end(); ++Element)
2750         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2751     }
2752   }
2753 
2754   return PathDisplayStr;
2755 }
2756 
2757 //===----------------------------------------------------------------------===//
2758 // C++ class member Handling
2759 //===----------------------------------------------------------------------===//
2760 
2761 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2762 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2763                                 SourceLocation ColonLoc,
2764                                 const ParsedAttributesView &Attrs) {
2765   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2766   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2767                                                   ASLoc, ColonLoc);
2768   CurContext->addHiddenDecl(ASDecl);
2769   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2770 }
2771 
2772 /// CheckOverrideControl - Check C++11 override control semantics.
2773 void Sema::CheckOverrideControl(NamedDecl *D) {
2774   if (D->isInvalidDecl())
2775     return;
2776 
2777   // We only care about "override" and "final" declarations.
2778   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2779     return;
2780 
2781   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2782 
2783   // We can't check dependent instance methods.
2784   if (MD && MD->isInstance() &&
2785       (MD->getParent()->hasAnyDependentBases() ||
2786        MD->getType()->isDependentType()))
2787     return;
2788 
2789   if (MD && !MD->isVirtual()) {
2790     // If we have a non-virtual method, check if if hides a virtual method.
2791     // (In that case, it's most likely the method has the wrong type.)
2792     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2793     FindHiddenVirtualMethods(MD, OverloadedMethods);
2794 
2795     if (!OverloadedMethods.empty()) {
2796       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2797         Diag(OA->getLocation(),
2798              diag::override_keyword_hides_virtual_member_function)
2799           << "override" << (OverloadedMethods.size() > 1);
2800       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2801         Diag(FA->getLocation(),
2802              diag::override_keyword_hides_virtual_member_function)
2803           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2804           << (OverloadedMethods.size() > 1);
2805       }
2806       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2807       MD->setInvalidDecl();
2808       return;
2809     }
2810     // Fall through into the general case diagnostic.
2811     // FIXME: We might want to attempt typo correction here.
2812   }
2813 
2814   if (!MD || !MD->isVirtual()) {
2815     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2816       Diag(OA->getLocation(),
2817            diag::override_keyword_only_allowed_on_virtual_member_functions)
2818         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2819       D->dropAttr<OverrideAttr>();
2820     }
2821     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2822       Diag(FA->getLocation(),
2823            diag::override_keyword_only_allowed_on_virtual_member_functions)
2824         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2825         << FixItHint::CreateRemoval(FA->getLocation());
2826       D->dropAttr<FinalAttr>();
2827     }
2828     return;
2829   }
2830 
2831   // C++11 [class.virtual]p5:
2832   //   If a function is marked with the virt-specifier override and
2833   //   does not override a member function of a base class, the program is
2834   //   ill-formed.
2835   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2836   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2837     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2838       << MD->getDeclName();
2839 }
2840 
2841 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2842   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2843     return;
2844   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2845   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2846     return;
2847 
2848   SourceLocation Loc = MD->getLocation();
2849   SourceLocation SpellingLoc = Loc;
2850   if (getSourceManager().isMacroArgExpansion(Loc))
2851     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2852   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2853   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2854       return;
2855 
2856   if (MD->size_overridden_methods() > 0) {
2857     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2858                           ? diag::warn_destructor_marked_not_override_overriding
2859                           : diag::warn_function_marked_not_override_overriding;
2860     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2861     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2862     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2863   }
2864 }
2865 
2866 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2867 /// function overrides a virtual member function marked 'final', according to
2868 /// C++11 [class.virtual]p4.
2869 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2870                                                   const CXXMethodDecl *Old) {
2871   FinalAttr *FA = Old->getAttr<FinalAttr>();
2872   if (!FA)
2873     return false;
2874 
2875   Diag(New->getLocation(), diag::err_final_function_overridden)
2876     << New->getDeclName()
2877     << FA->isSpelledAsSealed();
2878   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2879   return true;
2880 }
2881 
2882 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2883   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2884   // FIXME: Destruction of ObjC lifetime types has side-effects.
2885   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2886     return !RD->isCompleteDefinition() ||
2887            !RD->hasTrivialDefaultConstructor() ||
2888            !RD->hasTrivialDestructor();
2889   return false;
2890 }
2891 
2892 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
2893   ParsedAttributesView::const_iterator Itr =
2894       llvm::find_if(list, [](const ParsedAttr &AL) {
2895         return AL.isDeclspecPropertyAttribute();
2896       });
2897   if (Itr != list.end())
2898     return &*Itr;
2899   return nullptr;
2900 }
2901 
2902 // Check if there is a field shadowing.
2903 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2904                                       DeclarationName FieldName,
2905                                       const CXXRecordDecl *RD,
2906                                       bool DeclIsField) {
2907   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2908     return;
2909 
2910   // To record a shadowed field in a base
2911   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2912   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2913                            CXXBasePath &Path) {
2914     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2915     // Record an ambiguous path directly
2916     if (Bases.find(Base) != Bases.end())
2917       return true;
2918     for (const auto Field : Base->lookup(FieldName)) {
2919       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2920           Field->getAccess() != AS_private) {
2921         assert(Field->getAccess() != AS_none);
2922         assert(Bases.find(Base) == Bases.end());
2923         Bases[Base] = Field;
2924         return true;
2925       }
2926     }
2927     return false;
2928   };
2929 
2930   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2931                      /*DetectVirtual=*/true);
2932   if (!RD->lookupInBases(FieldShadowed, Paths))
2933     return;
2934 
2935   for (const auto &P : Paths) {
2936     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2937     auto It = Bases.find(Base);
2938     // Skip duplicated bases
2939     if (It == Bases.end())
2940       continue;
2941     auto BaseField = It->second;
2942     assert(BaseField->getAccess() != AS_private);
2943     if (AS_none !=
2944         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2945       Diag(Loc, diag::warn_shadow_field)
2946         << FieldName << RD << Base << DeclIsField;
2947       Diag(BaseField->getLocation(), diag::note_shadow_field);
2948       Bases.erase(It);
2949     }
2950   }
2951 }
2952 
2953 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2954 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2955 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2956 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2957 /// present (but parsing it has been deferred).
2958 NamedDecl *
2959 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2960                                MultiTemplateParamsArg TemplateParameterLists,
2961                                Expr *BW, const VirtSpecifiers &VS,
2962                                InClassInitStyle InitStyle) {
2963   const DeclSpec &DS = D.getDeclSpec();
2964   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2965   DeclarationName Name = NameInfo.getName();
2966   SourceLocation Loc = NameInfo.getLoc();
2967 
2968   // For anonymous bitfields, the location should point to the type.
2969   if (Loc.isInvalid())
2970     Loc = D.getBeginLoc();
2971 
2972   Expr *BitWidth = static_cast<Expr*>(BW);
2973 
2974   assert(isa<CXXRecordDecl>(CurContext));
2975   assert(!DS.isFriendSpecified());
2976 
2977   bool isFunc = D.isDeclarationOfFunction();
2978   const ParsedAttr *MSPropertyAttr =
2979       getMSPropertyAttr(D.getDeclSpec().getAttributes());
2980 
2981   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2982     // The Microsoft extension __interface only permits public member functions
2983     // and prohibits constructors, destructors, operators, non-public member
2984     // functions, static methods and data members.
2985     unsigned InvalidDecl;
2986     bool ShowDeclName = true;
2987     if (!isFunc &&
2988         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2989       InvalidDecl = 0;
2990     else if (!isFunc)
2991       InvalidDecl = 1;
2992     else if (AS != AS_public)
2993       InvalidDecl = 2;
2994     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2995       InvalidDecl = 3;
2996     else switch (Name.getNameKind()) {
2997       case DeclarationName::CXXConstructorName:
2998         InvalidDecl = 4;
2999         ShowDeclName = false;
3000         break;
3001 
3002       case DeclarationName::CXXDestructorName:
3003         InvalidDecl = 5;
3004         ShowDeclName = false;
3005         break;
3006 
3007       case DeclarationName::CXXOperatorName:
3008       case DeclarationName::CXXConversionFunctionName:
3009         InvalidDecl = 6;
3010         break;
3011 
3012       default:
3013         InvalidDecl = 0;
3014         break;
3015     }
3016 
3017     if (InvalidDecl) {
3018       if (ShowDeclName)
3019         Diag(Loc, diag::err_invalid_member_in_interface)
3020           << (InvalidDecl-1) << Name;
3021       else
3022         Diag(Loc, diag::err_invalid_member_in_interface)
3023           << (InvalidDecl-1) << "";
3024       return nullptr;
3025     }
3026   }
3027 
3028   // C++ 9.2p6: A member shall not be declared to have automatic storage
3029   // duration (auto, register) or with the extern storage-class-specifier.
3030   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3031   // data members and cannot be applied to names declared const or static,
3032   // and cannot be applied to reference members.
3033   switch (DS.getStorageClassSpec()) {
3034   case DeclSpec::SCS_unspecified:
3035   case DeclSpec::SCS_typedef:
3036   case DeclSpec::SCS_static:
3037     break;
3038   case DeclSpec::SCS_mutable:
3039     if (isFunc) {
3040       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3041 
3042       // FIXME: It would be nicer if the keyword was ignored only for this
3043       // declarator. Otherwise we could get follow-up errors.
3044       D.getMutableDeclSpec().ClearStorageClassSpecs();
3045     }
3046     break;
3047   default:
3048     Diag(DS.getStorageClassSpecLoc(),
3049          diag::err_storageclass_invalid_for_member);
3050     D.getMutableDeclSpec().ClearStorageClassSpecs();
3051     break;
3052   }
3053 
3054   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3055                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3056                       !isFunc);
3057 
3058   if (DS.hasConstexprSpecifier() && isInstField) {
3059     SemaDiagnosticBuilder B =
3060         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3061     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3062     if (InitStyle == ICIS_NoInit) {
3063       B << 0 << 0;
3064       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3065         B << FixItHint::CreateRemoval(ConstexprLoc);
3066       else {
3067         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3068         D.getMutableDeclSpec().ClearConstexprSpec();
3069         const char *PrevSpec;
3070         unsigned DiagID;
3071         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3072             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3073         (void)Failed;
3074         assert(!Failed && "Making a constexpr member const shouldn't fail");
3075       }
3076     } else {
3077       B << 1;
3078       const char *PrevSpec;
3079       unsigned DiagID;
3080       if (D.getMutableDeclSpec().SetStorageClassSpec(
3081           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3082           Context.getPrintingPolicy())) {
3083         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3084                "This is the only DeclSpec that should fail to be applied");
3085         B << 1;
3086       } else {
3087         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3088         isInstField = false;
3089       }
3090     }
3091   }
3092 
3093   NamedDecl *Member;
3094   if (isInstField) {
3095     CXXScopeSpec &SS = D.getCXXScopeSpec();
3096 
3097     // Data members must have identifiers for names.
3098     if (!Name.isIdentifier()) {
3099       Diag(Loc, diag::err_bad_variable_name)
3100         << Name;
3101       return nullptr;
3102     }
3103 
3104     IdentifierInfo *II = Name.getAsIdentifierInfo();
3105 
3106     // Member field could not be with "template" keyword.
3107     // So TemplateParameterLists should be empty in this case.
3108     if (TemplateParameterLists.size()) {
3109       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3110       if (TemplateParams->size()) {
3111         // There is no such thing as a member field template.
3112         Diag(D.getIdentifierLoc(), diag::err_template_member)
3113             << II
3114             << SourceRange(TemplateParams->getTemplateLoc(),
3115                 TemplateParams->getRAngleLoc());
3116       } else {
3117         // There is an extraneous 'template<>' for this member.
3118         Diag(TemplateParams->getTemplateLoc(),
3119             diag::err_template_member_noparams)
3120             << II
3121             << SourceRange(TemplateParams->getTemplateLoc(),
3122                 TemplateParams->getRAngleLoc());
3123       }
3124       return nullptr;
3125     }
3126 
3127     if (SS.isSet() && !SS.isInvalid()) {
3128       // The user provided a superfluous scope specifier inside a class
3129       // definition:
3130       //
3131       // class X {
3132       //   int X::member;
3133       // };
3134       if (DeclContext *DC = computeDeclContext(SS, false))
3135         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3136                                      D.getName().getKind() ==
3137                                          UnqualifiedIdKind::IK_TemplateId);
3138       else
3139         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3140           << Name << SS.getRange();
3141 
3142       SS.clear();
3143     }
3144 
3145     if (MSPropertyAttr) {
3146       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3147                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3148       if (!Member)
3149         return nullptr;
3150       isInstField = false;
3151     } else {
3152       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3153                                 BitWidth, InitStyle, AS);
3154       if (!Member)
3155         return nullptr;
3156     }
3157 
3158     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3159   } else {
3160     Member = HandleDeclarator(S, D, TemplateParameterLists);
3161     if (!Member)
3162       return nullptr;
3163 
3164     // Non-instance-fields can't have a bitfield.
3165     if (BitWidth) {
3166       if (Member->isInvalidDecl()) {
3167         // don't emit another diagnostic.
3168       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3169         // C++ 9.6p3: A bit-field shall not be a static member.
3170         // "static member 'A' cannot be a bit-field"
3171         Diag(Loc, diag::err_static_not_bitfield)
3172           << Name << BitWidth->getSourceRange();
3173       } else if (isa<TypedefDecl>(Member)) {
3174         // "typedef member 'x' cannot be a bit-field"
3175         Diag(Loc, diag::err_typedef_not_bitfield)
3176           << Name << BitWidth->getSourceRange();
3177       } else {
3178         // A function typedef ("typedef int f(); f a;").
3179         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3180         Diag(Loc, diag::err_not_integral_type_bitfield)
3181           << Name << cast<ValueDecl>(Member)->getType()
3182           << BitWidth->getSourceRange();
3183       }
3184 
3185       BitWidth = nullptr;
3186       Member->setInvalidDecl();
3187     }
3188 
3189     NamedDecl *NonTemplateMember = Member;
3190     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3191       NonTemplateMember = FunTmpl->getTemplatedDecl();
3192     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3193       NonTemplateMember = VarTmpl->getTemplatedDecl();
3194 
3195     Member->setAccess(AS);
3196 
3197     // If we have declared a member function template or static data member
3198     // template, set the access of the templated declaration as well.
3199     if (NonTemplateMember != Member)
3200       NonTemplateMember->setAccess(AS);
3201 
3202     // C++ [temp.deduct.guide]p3:
3203     //   A deduction guide [...] for a member class template [shall be
3204     //   declared] with the same access [as the template].
3205     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3206       auto *TD = DG->getDeducedTemplate();
3207       // Access specifiers are only meaningful if both the template and the
3208       // deduction guide are from the same scope.
3209       if (AS != TD->getAccess() &&
3210           TD->getDeclContext()->getRedeclContext()->Equals(
3211               DG->getDeclContext()->getRedeclContext())) {
3212         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3213         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3214             << TD->getAccess();
3215         const AccessSpecDecl *LastAccessSpec = nullptr;
3216         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3217           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3218             LastAccessSpec = AccessSpec;
3219         }
3220         assert(LastAccessSpec && "differing access with no access specifier");
3221         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3222             << AS;
3223       }
3224     }
3225   }
3226 
3227   if (VS.isOverrideSpecified())
3228     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3229   if (VS.isFinalSpecified())
3230     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3231                                             VS.isFinalSpelledSealed()));
3232 
3233   if (VS.getLastLocation().isValid()) {
3234     // Update the end location of a method that has a virt-specifiers.
3235     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3236       MD->setRangeEnd(VS.getLastLocation());
3237   }
3238 
3239   CheckOverrideControl(Member);
3240 
3241   assert((Name || isInstField) && "No identifier for non-field ?");
3242 
3243   if (isInstField) {
3244     FieldDecl *FD = cast<FieldDecl>(Member);
3245     FieldCollector->Add(FD);
3246 
3247     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3248       // Remember all explicit private FieldDecls that have a name, no side
3249       // effects and are not part of a dependent type declaration.
3250       if (!FD->isImplicit() && FD->getDeclName() &&
3251           FD->getAccess() == AS_private &&
3252           !FD->hasAttr<UnusedAttr>() &&
3253           !FD->getParent()->isDependentContext() &&
3254           !InitializationHasSideEffects(*FD))
3255         UnusedPrivateFields.insert(FD);
3256     }
3257   }
3258 
3259   return Member;
3260 }
3261 
3262 namespace {
3263   class UninitializedFieldVisitor
3264       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3265     Sema &S;
3266     // List of Decls to generate a warning on.  Also remove Decls that become
3267     // initialized.
3268     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3269     // List of base classes of the record.  Classes are removed after their
3270     // initializers.
3271     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3272     // Vector of decls to be removed from the Decl set prior to visiting the
3273     // nodes.  These Decls may have been initialized in the prior initializer.
3274     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3275     // If non-null, add a note to the warning pointing back to the constructor.
3276     const CXXConstructorDecl *Constructor;
3277     // Variables to hold state when processing an initializer list.  When
3278     // InitList is true, special case initialization of FieldDecls matching
3279     // InitListFieldDecl.
3280     bool InitList;
3281     FieldDecl *InitListFieldDecl;
3282     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3283 
3284   public:
3285     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3286     UninitializedFieldVisitor(Sema &S,
3287                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3288                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3289       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3290         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3291 
3292     // Returns true if the use of ME is not an uninitialized use.
3293     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3294                                          bool CheckReferenceOnly) {
3295       llvm::SmallVector<FieldDecl*, 4> Fields;
3296       bool ReferenceField = false;
3297       while (ME) {
3298         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3299         if (!FD)
3300           return false;
3301         Fields.push_back(FD);
3302         if (FD->getType()->isReferenceType())
3303           ReferenceField = true;
3304         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3305       }
3306 
3307       // Binding a reference to an uninitialized field is not an
3308       // uninitialized use.
3309       if (CheckReferenceOnly && !ReferenceField)
3310         return true;
3311 
3312       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3313       // Discard the first field since it is the field decl that is being
3314       // initialized.
3315       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3316         UsedFieldIndex.push_back((*I)->getFieldIndex());
3317       }
3318 
3319       for (auto UsedIter = UsedFieldIndex.begin(),
3320                 UsedEnd = UsedFieldIndex.end(),
3321                 OrigIter = InitFieldIndex.begin(),
3322                 OrigEnd = InitFieldIndex.end();
3323            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3324         if (*UsedIter < *OrigIter)
3325           return true;
3326         if (*UsedIter > *OrigIter)
3327           break;
3328       }
3329 
3330       return false;
3331     }
3332 
3333     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3334                           bool AddressOf) {
3335       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3336         return;
3337 
3338       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3339       // or union.
3340       MemberExpr *FieldME = ME;
3341 
3342       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3343 
3344       Expr *Base = ME;
3345       while (MemberExpr *SubME =
3346                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3347 
3348         if (isa<VarDecl>(SubME->getMemberDecl()))
3349           return;
3350 
3351         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3352           if (!FD->isAnonymousStructOrUnion())
3353             FieldME = SubME;
3354 
3355         if (!FieldME->getType().isPODType(S.Context))
3356           AllPODFields = false;
3357 
3358         Base = SubME->getBase();
3359       }
3360 
3361       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3362         return;
3363 
3364       if (AddressOf && AllPODFields)
3365         return;
3366 
3367       ValueDecl* FoundVD = FieldME->getMemberDecl();
3368 
3369       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3370         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3371           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3372         }
3373 
3374         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3375           QualType T = BaseCast->getType();
3376           if (T->isPointerType() &&
3377               BaseClasses.count(T->getPointeeType())) {
3378             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3379                 << T->getPointeeType() << FoundVD;
3380           }
3381         }
3382       }
3383 
3384       if (!Decls.count(FoundVD))
3385         return;
3386 
3387       const bool IsReference = FoundVD->getType()->isReferenceType();
3388 
3389       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3390         // Special checking for initializer lists.
3391         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3392           return;
3393         }
3394       } else {
3395         // Prevent double warnings on use of unbounded references.
3396         if (CheckReferenceOnly && !IsReference)
3397           return;
3398       }
3399 
3400       unsigned diag = IsReference
3401           ? diag::warn_reference_field_is_uninit
3402           : diag::warn_field_is_uninit;
3403       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3404       if (Constructor)
3405         S.Diag(Constructor->getLocation(),
3406                diag::note_uninit_in_this_constructor)
3407           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3408 
3409     }
3410 
3411     void HandleValue(Expr *E, bool AddressOf) {
3412       E = E->IgnoreParens();
3413 
3414       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3415         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3416                          AddressOf /*AddressOf*/);
3417         return;
3418       }
3419 
3420       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3421         Visit(CO->getCond());
3422         HandleValue(CO->getTrueExpr(), AddressOf);
3423         HandleValue(CO->getFalseExpr(), AddressOf);
3424         return;
3425       }
3426 
3427       if (BinaryConditionalOperator *BCO =
3428               dyn_cast<BinaryConditionalOperator>(E)) {
3429         Visit(BCO->getCond());
3430         HandleValue(BCO->getFalseExpr(), AddressOf);
3431         return;
3432       }
3433 
3434       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3435         HandleValue(OVE->getSourceExpr(), AddressOf);
3436         return;
3437       }
3438 
3439       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3440         switch (BO->getOpcode()) {
3441         default:
3442           break;
3443         case(BO_PtrMemD):
3444         case(BO_PtrMemI):
3445           HandleValue(BO->getLHS(), AddressOf);
3446           Visit(BO->getRHS());
3447           return;
3448         case(BO_Comma):
3449           Visit(BO->getLHS());
3450           HandleValue(BO->getRHS(), AddressOf);
3451           return;
3452         }
3453       }
3454 
3455       Visit(E);
3456     }
3457 
3458     void CheckInitListExpr(InitListExpr *ILE) {
3459       InitFieldIndex.push_back(0);
3460       for (auto Child : ILE->children()) {
3461         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3462           CheckInitListExpr(SubList);
3463         } else {
3464           Visit(Child);
3465         }
3466         ++InitFieldIndex.back();
3467       }
3468       InitFieldIndex.pop_back();
3469     }
3470 
3471     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3472                           FieldDecl *Field, const Type *BaseClass) {
3473       // Remove Decls that may have been initialized in the previous
3474       // initializer.
3475       for (ValueDecl* VD : DeclsToRemove)
3476         Decls.erase(VD);
3477       DeclsToRemove.clear();
3478 
3479       Constructor = FieldConstructor;
3480       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3481 
3482       if (ILE && Field) {
3483         InitList = true;
3484         InitListFieldDecl = Field;
3485         InitFieldIndex.clear();
3486         CheckInitListExpr(ILE);
3487       } else {
3488         InitList = false;
3489         Visit(E);
3490       }
3491 
3492       if (Field)
3493         Decls.erase(Field);
3494       if (BaseClass)
3495         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3496     }
3497 
3498     void VisitMemberExpr(MemberExpr *ME) {
3499       // All uses of unbounded reference fields will warn.
3500       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3501     }
3502 
3503     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3504       if (E->getCastKind() == CK_LValueToRValue) {
3505         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3506         return;
3507       }
3508 
3509       Inherited::VisitImplicitCastExpr(E);
3510     }
3511 
3512     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3513       if (E->getConstructor()->isCopyConstructor()) {
3514         Expr *ArgExpr = E->getArg(0);
3515         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3516           if (ILE->getNumInits() == 1)
3517             ArgExpr = ILE->getInit(0);
3518         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3519           if (ICE->getCastKind() == CK_NoOp)
3520             ArgExpr = ICE->getSubExpr();
3521         HandleValue(ArgExpr, false /*AddressOf*/);
3522         return;
3523       }
3524       Inherited::VisitCXXConstructExpr(E);
3525     }
3526 
3527     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3528       Expr *Callee = E->getCallee();
3529       if (isa<MemberExpr>(Callee)) {
3530         HandleValue(Callee, false /*AddressOf*/);
3531         for (auto Arg : E->arguments())
3532           Visit(Arg);
3533         return;
3534       }
3535 
3536       Inherited::VisitCXXMemberCallExpr(E);
3537     }
3538 
3539     void VisitCallExpr(CallExpr *E) {
3540       // Treat std::move as a use.
3541       if (E->isCallToStdMove()) {
3542         HandleValue(E->getArg(0), /*AddressOf=*/false);
3543         return;
3544       }
3545 
3546       Inherited::VisitCallExpr(E);
3547     }
3548 
3549     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3550       Expr *Callee = E->getCallee();
3551 
3552       if (isa<UnresolvedLookupExpr>(Callee))
3553         return Inherited::VisitCXXOperatorCallExpr(E);
3554 
3555       Visit(Callee);
3556       for (auto Arg : E->arguments())
3557         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3558     }
3559 
3560     void VisitBinaryOperator(BinaryOperator *E) {
3561       // If a field assignment is detected, remove the field from the
3562       // uninitiailized field set.
3563       if (E->getOpcode() == BO_Assign)
3564         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3565           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3566             if (!FD->getType()->isReferenceType())
3567               DeclsToRemove.push_back(FD);
3568 
3569       if (E->isCompoundAssignmentOp()) {
3570         HandleValue(E->getLHS(), false /*AddressOf*/);
3571         Visit(E->getRHS());
3572         return;
3573       }
3574 
3575       Inherited::VisitBinaryOperator(E);
3576     }
3577 
3578     void VisitUnaryOperator(UnaryOperator *E) {
3579       if (E->isIncrementDecrementOp()) {
3580         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3581         return;
3582       }
3583       if (E->getOpcode() == UO_AddrOf) {
3584         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3585           HandleValue(ME->getBase(), true /*AddressOf*/);
3586           return;
3587         }
3588       }
3589 
3590       Inherited::VisitUnaryOperator(E);
3591     }
3592   };
3593 
3594   // Diagnose value-uses of fields to initialize themselves, e.g.
3595   //   foo(foo)
3596   // where foo is not also a parameter to the constructor.
3597   // Also diagnose across field uninitialized use such as
3598   //   x(y), y(x)
3599   // TODO: implement -Wuninitialized and fold this into that framework.
3600   static void DiagnoseUninitializedFields(
3601       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3602 
3603     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3604                                            Constructor->getLocation())) {
3605       return;
3606     }
3607 
3608     if (Constructor->isInvalidDecl())
3609       return;
3610 
3611     const CXXRecordDecl *RD = Constructor->getParent();
3612 
3613     if (RD->getDescribedClassTemplate())
3614       return;
3615 
3616     // Holds fields that are uninitialized.
3617     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3618 
3619     // At the beginning, all fields are uninitialized.
3620     for (auto *I : RD->decls()) {
3621       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3622         UninitializedFields.insert(FD);
3623       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3624         UninitializedFields.insert(IFD->getAnonField());
3625       }
3626     }
3627 
3628     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3629     for (auto I : RD->bases())
3630       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3631 
3632     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3633       return;
3634 
3635     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3636                                                    UninitializedFields,
3637                                                    UninitializedBaseClasses);
3638 
3639     for (const auto *FieldInit : Constructor->inits()) {
3640       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3641         break;
3642 
3643       Expr *InitExpr = FieldInit->getInit();
3644       if (!InitExpr)
3645         continue;
3646 
3647       if (CXXDefaultInitExpr *Default =
3648               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3649         InitExpr = Default->getExpr();
3650         if (!InitExpr)
3651           continue;
3652         // In class initializers will point to the constructor.
3653         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3654                                               FieldInit->getAnyMember(),
3655                                               FieldInit->getBaseClass());
3656       } else {
3657         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3658                                               FieldInit->getAnyMember(),
3659                                               FieldInit->getBaseClass());
3660       }
3661     }
3662   }
3663 } // namespace
3664 
3665 /// Enter a new C++ default initializer scope. After calling this, the
3666 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3667 /// parsing or instantiating the initializer failed.
3668 void Sema::ActOnStartCXXInClassMemberInitializer() {
3669   // Create a synthetic function scope to represent the call to the constructor
3670   // that notionally surrounds a use of this initializer.
3671   PushFunctionScope();
3672 }
3673 
3674 /// This is invoked after parsing an in-class initializer for a
3675 /// non-static C++ class member, and after instantiating an in-class initializer
3676 /// in a class template. Such actions are deferred until the class is complete.
3677 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3678                                                   SourceLocation InitLoc,
3679                                                   Expr *InitExpr) {
3680   // Pop the notional constructor scope we created earlier.
3681   PopFunctionScopeInfo(nullptr, D);
3682 
3683   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3684   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3685          "must set init style when field is created");
3686 
3687   if (!InitExpr) {
3688     D->setInvalidDecl();
3689     if (FD)
3690       FD->removeInClassInitializer();
3691     return;
3692   }
3693 
3694   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3695     FD->setInvalidDecl();
3696     FD->removeInClassInitializer();
3697     return;
3698   }
3699 
3700   ExprResult Init = InitExpr;
3701   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3702     InitializedEntity Entity =
3703         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3704     InitializationKind Kind =
3705         FD->getInClassInitStyle() == ICIS_ListInit
3706             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3707                                                    InitExpr->getBeginLoc(),
3708                                                    InitExpr->getEndLoc())
3709             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3710     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3711     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3712     if (Init.isInvalid()) {
3713       FD->setInvalidDecl();
3714       return;
3715     }
3716   }
3717 
3718   // C++11 [class.base.init]p7:
3719   //   The initialization of each base and member constitutes a
3720   //   full-expression.
3721   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3722   if (Init.isInvalid()) {
3723     FD->setInvalidDecl();
3724     return;
3725   }
3726 
3727   InitExpr = Init.get();
3728 
3729   FD->setInClassInitializer(InitExpr);
3730 }
3731 
3732 /// Find the direct and/or virtual base specifiers that
3733 /// correspond to the given base type, for use in base initialization
3734 /// within a constructor.
3735 static bool FindBaseInitializer(Sema &SemaRef,
3736                                 CXXRecordDecl *ClassDecl,
3737                                 QualType BaseType,
3738                                 const CXXBaseSpecifier *&DirectBaseSpec,
3739                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3740   // First, check for a direct base class.
3741   DirectBaseSpec = nullptr;
3742   for (const auto &Base : ClassDecl->bases()) {
3743     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3744       // We found a direct base of this type. That's what we're
3745       // initializing.
3746       DirectBaseSpec = &Base;
3747       break;
3748     }
3749   }
3750 
3751   // Check for a virtual base class.
3752   // FIXME: We might be able to short-circuit this if we know in advance that
3753   // there are no virtual bases.
3754   VirtualBaseSpec = nullptr;
3755   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3756     // We haven't found a base yet; search the class hierarchy for a
3757     // virtual base class.
3758     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3759                        /*DetectVirtual=*/false);
3760     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3761                               SemaRef.Context.getTypeDeclType(ClassDecl),
3762                               BaseType, Paths)) {
3763       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3764            Path != Paths.end(); ++Path) {
3765         if (Path->back().Base->isVirtual()) {
3766           VirtualBaseSpec = Path->back().Base;
3767           break;
3768         }
3769       }
3770     }
3771   }
3772 
3773   return DirectBaseSpec || VirtualBaseSpec;
3774 }
3775 
3776 /// Handle a C++ member initializer using braced-init-list syntax.
3777 MemInitResult
3778 Sema::ActOnMemInitializer(Decl *ConstructorD,
3779                           Scope *S,
3780                           CXXScopeSpec &SS,
3781                           IdentifierInfo *MemberOrBase,
3782                           ParsedType TemplateTypeTy,
3783                           const DeclSpec &DS,
3784                           SourceLocation IdLoc,
3785                           Expr *InitList,
3786                           SourceLocation EllipsisLoc) {
3787   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3788                              DS, IdLoc, InitList,
3789                              EllipsisLoc);
3790 }
3791 
3792 /// Handle a C++ member initializer using parentheses syntax.
3793 MemInitResult
3794 Sema::ActOnMemInitializer(Decl *ConstructorD,
3795                           Scope *S,
3796                           CXXScopeSpec &SS,
3797                           IdentifierInfo *MemberOrBase,
3798                           ParsedType TemplateTypeTy,
3799                           const DeclSpec &DS,
3800                           SourceLocation IdLoc,
3801                           SourceLocation LParenLoc,
3802                           ArrayRef<Expr *> Args,
3803                           SourceLocation RParenLoc,
3804                           SourceLocation EllipsisLoc) {
3805   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3806   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3807                              DS, IdLoc, List, EllipsisLoc);
3808 }
3809 
3810 namespace {
3811 
3812 // Callback to only accept typo corrections that can be a valid C++ member
3813 // intializer: either a non-static field member or a base class.
3814 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
3815 public:
3816   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3817       : ClassDecl(ClassDecl) {}
3818 
3819   bool ValidateCandidate(const TypoCorrection &candidate) override {
3820     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3821       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3822         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3823       return isa<TypeDecl>(ND);
3824     }
3825     return false;
3826   }
3827 
3828   std::unique_ptr<CorrectionCandidateCallback> clone() override {
3829     return llvm::make_unique<MemInitializerValidatorCCC>(*this);
3830   }
3831 
3832 private:
3833   CXXRecordDecl *ClassDecl;
3834 };
3835 
3836 }
3837 
3838 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3839                                              CXXScopeSpec &SS,
3840                                              ParsedType TemplateTypeTy,
3841                                              IdentifierInfo *MemberOrBase) {
3842   if (SS.getScopeRep() || TemplateTypeTy)
3843     return nullptr;
3844   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3845   if (Result.empty())
3846     return nullptr;
3847   ValueDecl *Member;
3848   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3849       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3850     return Member;
3851   return nullptr;
3852 }
3853 
3854 /// Handle a C++ member initializer.
3855 MemInitResult
3856 Sema::BuildMemInitializer(Decl *ConstructorD,
3857                           Scope *S,
3858                           CXXScopeSpec &SS,
3859                           IdentifierInfo *MemberOrBase,
3860                           ParsedType TemplateTypeTy,
3861                           const DeclSpec &DS,
3862                           SourceLocation IdLoc,
3863                           Expr *Init,
3864                           SourceLocation EllipsisLoc) {
3865   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3866   if (!Res.isUsable())
3867     return true;
3868   Init = Res.get();
3869 
3870   if (!ConstructorD)
3871     return true;
3872 
3873   AdjustDeclIfTemplate(ConstructorD);
3874 
3875   CXXConstructorDecl *Constructor
3876     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3877   if (!Constructor) {
3878     // The user wrote a constructor initializer on a function that is
3879     // not a C++ constructor. Ignore the error for now, because we may
3880     // have more member initializers coming; we'll diagnose it just
3881     // once in ActOnMemInitializers.
3882     return true;
3883   }
3884 
3885   CXXRecordDecl *ClassDecl = Constructor->getParent();
3886 
3887   // C++ [class.base.init]p2:
3888   //   Names in a mem-initializer-id are looked up in the scope of the
3889   //   constructor's class and, if not found in that scope, are looked
3890   //   up in the scope containing the constructor's definition.
3891   //   [Note: if the constructor's class contains a member with the
3892   //   same name as a direct or virtual base class of the class, a
3893   //   mem-initializer-id naming the member or base class and composed
3894   //   of a single identifier refers to the class member. A
3895   //   mem-initializer-id for the hidden base class may be specified
3896   //   using a qualified name. ]
3897 
3898   // Look for a member, first.
3899   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
3900           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
3901     if (EllipsisLoc.isValid())
3902       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3903           << MemberOrBase
3904           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3905 
3906     return BuildMemberInitializer(Member, Init, IdLoc);
3907   }
3908   // It didn't name a member, so see if it names a class.
3909   QualType BaseType;
3910   TypeSourceInfo *TInfo = nullptr;
3911 
3912   if (TemplateTypeTy) {
3913     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3914     if (BaseType.isNull())
3915       return true;
3916   } else if (DS.getTypeSpecType() == TST_decltype) {
3917     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3918   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3919     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3920     return true;
3921   } else {
3922     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3923     LookupParsedName(R, S, &SS);
3924 
3925     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3926     if (!TyD) {
3927       if (R.isAmbiguous()) return true;
3928 
3929       // We don't want access-control diagnostics here.
3930       R.suppressDiagnostics();
3931 
3932       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3933         bool NotUnknownSpecialization = false;
3934         DeclContext *DC = computeDeclContext(SS, false);
3935         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3936           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3937 
3938         if (!NotUnknownSpecialization) {
3939           // When the scope specifier can refer to a member of an unknown
3940           // specialization, we take it as a type name.
3941           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3942                                        SS.getWithLocInContext(Context),
3943                                        *MemberOrBase, IdLoc);
3944           if (BaseType.isNull())
3945             return true;
3946 
3947           TInfo = Context.CreateTypeSourceInfo(BaseType);
3948           DependentNameTypeLoc TL =
3949               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3950           if (!TL.isNull()) {
3951             TL.setNameLoc(IdLoc);
3952             TL.setElaboratedKeywordLoc(SourceLocation());
3953             TL.setQualifierLoc(SS.getWithLocInContext(Context));
3954           }
3955 
3956           R.clear();
3957           R.setLookupName(MemberOrBase);
3958         }
3959       }
3960 
3961       // If no results were found, try to correct typos.
3962       TypoCorrection Corr;
3963       MemInitializerValidatorCCC CCC(ClassDecl);
3964       if (R.empty() && BaseType.isNull() &&
3965           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3966                               CCC, CTK_ErrorRecovery, ClassDecl))) {
3967         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3968           // We have found a non-static data member with a similar
3969           // name to what was typed; complain and initialize that
3970           // member.
3971           diagnoseTypo(Corr,
3972                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3973                          << MemberOrBase << true);
3974           return BuildMemberInitializer(Member, Init, IdLoc);
3975         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3976           const CXXBaseSpecifier *DirectBaseSpec;
3977           const CXXBaseSpecifier *VirtualBaseSpec;
3978           if (FindBaseInitializer(*this, ClassDecl,
3979                                   Context.getTypeDeclType(Type),
3980                                   DirectBaseSpec, VirtualBaseSpec)) {
3981             // We have found a direct or virtual base class with a
3982             // similar name to what was typed; complain and initialize
3983             // that base class.
3984             diagnoseTypo(Corr,
3985                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3986                            << MemberOrBase << false,
3987                          PDiag() /*Suppress note, we provide our own.*/);
3988 
3989             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3990                                                               : VirtualBaseSpec;
3991             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
3992                 << BaseSpec->getType() << BaseSpec->getSourceRange();
3993 
3994             TyD = Type;
3995           }
3996         }
3997       }
3998 
3999       if (!TyD && BaseType.isNull()) {
4000         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4001           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4002         return true;
4003       }
4004     }
4005 
4006     if (BaseType.isNull()) {
4007       BaseType = Context.getTypeDeclType(TyD);
4008       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4009       if (SS.isSet()) {
4010         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4011                                              BaseType);
4012         TInfo = Context.CreateTypeSourceInfo(BaseType);
4013         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4014         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4015         TL.setElaboratedKeywordLoc(SourceLocation());
4016         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4017       }
4018     }
4019   }
4020 
4021   if (!TInfo)
4022     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4023 
4024   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4025 }
4026 
4027 MemInitResult
4028 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4029                              SourceLocation IdLoc) {
4030   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4031   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4032   assert((DirectMember || IndirectMember) &&
4033          "Member must be a FieldDecl or IndirectFieldDecl");
4034 
4035   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4036     return true;
4037 
4038   if (Member->isInvalidDecl())
4039     return true;
4040 
4041   MultiExprArg Args;
4042   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4043     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4044   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4045     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4046   } else {
4047     // Template instantiation doesn't reconstruct ParenListExprs for us.
4048     Args = Init;
4049   }
4050 
4051   SourceRange InitRange = Init->getSourceRange();
4052 
4053   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4054     // Can't check initialization for a member of dependent type or when
4055     // any of the arguments are type-dependent expressions.
4056     DiscardCleanupsInEvaluationContext();
4057   } else {
4058     bool InitList = false;
4059     if (isa<InitListExpr>(Init)) {
4060       InitList = true;
4061       Args = Init;
4062     }
4063 
4064     // Initialize the member.
4065     InitializedEntity MemberEntity =
4066       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4067                    : InitializedEntity::InitializeMember(IndirectMember,
4068                                                          nullptr);
4069     InitializationKind Kind =
4070         InitList ? InitializationKind::CreateDirectList(
4071                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4072                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4073                                                     InitRange.getEnd());
4074 
4075     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4076     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4077                                             nullptr);
4078     if (MemberInit.isInvalid())
4079       return true;
4080 
4081     // C++11 [class.base.init]p7:
4082     //   The initialization of each base and member constitutes a
4083     //   full-expression.
4084     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4085                                      /*DiscardedValue*/ false);
4086     if (MemberInit.isInvalid())
4087       return true;
4088 
4089     Init = MemberInit.get();
4090   }
4091 
4092   if (DirectMember) {
4093     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4094                                             InitRange.getBegin(), Init,
4095                                             InitRange.getEnd());
4096   } else {
4097     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4098                                             InitRange.getBegin(), Init,
4099                                             InitRange.getEnd());
4100   }
4101 }
4102 
4103 MemInitResult
4104 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4105                                  CXXRecordDecl *ClassDecl) {
4106   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4107   if (!LangOpts.CPlusPlus11)
4108     return Diag(NameLoc, diag::err_delegating_ctor)
4109       << TInfo->getTypeLoc().getLocalSourceRange();
4110   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4111 
4112   bool InitList = true;
4113   MultiExprArg Args = Init;
4114   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4115     InitList = false;
4116     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4117   }
4118 
4119   SourceRange InitRange = Init->getSourceRange();
4120   // Initialize the object.
4121   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4122                                      QualType(ClassDecl->getTypeForDecl(), 0));
4123   InitializationKind Kind =
4124       InitList ? InitializationKind::CreateDirectList(
4125                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4126                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4127                                                   InitRange.getEnd());
4128   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4129   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4130                                               Args, nullptr);
4131   if (DelegationInit.isInvalid())
4132     return true;
4133 
4134   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4135          "Delegating constructor with no target?");
4136 
4137   // C++11 [class.base.init]p7:
4138   //   The initialization of each base and member constitutes a
4139   //   full-expression.
4140   DelegationInit = ActOnFinishFullExpr(
4141       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4142   if (DelegationInit.isInvalid())
4143     return true;
4144 
4145   // If we are in a dependent context, template instantiation will
4146   // perform this type-checking again. Just save the arguments that we
4147   // received in a ParenListExpr.
4148   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4149   // of the information that we have about the base
4150   // initializer. However, deconstructing the ASTs is a dicey process,
4151   // and this approach is far more likely to get the corner cases right.
4152   if (CurContext->isDependentContext())
4153     DelegationInit = Init;
4154 
4155   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4156                                           DelegationInit.getAs<Expr>(),
4157                                           InitRange.getEnd());
4158 }
4159 
4160 MemInitResult
4161 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4162                            Expr *Init, CXXRecordDecl *ClassDecl,
4163                            SourceLocation EllipsisLoc) {
4164   SourceLocation BaseLoc
4165     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4166 
4167   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4168     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4169              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4170 
4171   // C++ [class.base.init]p2:
4172   //   [...] Unless the mem-initializer-id names a nonstatic data
4173   //   member of the constructor's class or a direct or virtual base
4174   //   of that class, the mem-initializer is ill-formed. A
4175   //   mem-initializer-list can initialize a base class using any
4176   //   name that denotes that base class type.
4177   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4178 
4179   SourceRange InitRange = Init->getSourceRange();
4180   if (EllipsisLoc.isValid()) {
4181     // This is a pack expansion.
4182     if (!BaseType->containsUnexpandedParameterPack())  {
4183       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4184         << SourceRange(BaseLoc, InitRange.getEnd());
4185 
4186       EllipsisLoc = SourceLocation();
4187     }
4188   } else {
4189     // Check for any unexpanded parameter packs.
4190     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4191       return true;
4192 
4193     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4194       return true;
4195   }
4196 
4197   // Check for direct and virtual base classes.
4198   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4199   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4200   if (!Dependent) {
4201     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4202                                        BaseType))
4203       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4204 
4205     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4206                         VirtualBaseSpec);
4207 
4208     // C++ [base.class.init]p2:
4209     // Unless the mem-initializer-id names a nonstatic data member of the
4210     // constructor's class or a direct or virtual base of that class, the
4211     // mem-initializer is ill-formed.
4212     if (!DirectBaseSpec && !VirtualBaseSpec) {
4213       // If the class has any dependent bases, then it's possible that
4214       // one of those types will resolve to the same type as
4215       // BaseType. Therefore, just treat this as a dependent base
4216       // class initialization.  FIXME: Should we try to check the
4217       // initialization anyway? It seems odd.
4218       if (ClassDecl->hasAnyDependentBases())
4219         Dependent = true;
4220       else
4221         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4222           << BaseType << Context.getTypeDeclType(ClassDecl)
4223           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4224     }
4225   }
4226 
4227   if (Dependent) {
4228     DiscardCleanupsInEvaluationContext();
4229 
4230     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4231                                             /*IsVirtual=*/false,
4232                                             InitRange.getBegin(), Init,
4233                                             InitRange.getEnd(), EllipsisLoc);
4234   }
4235 
4236   // C++ [base.class.init]p2:
4237   //   If a mem-initializer-id is ambiguous because it designates both
4238   //   a direct non-virtual base class and an inherited virtual base
4239   //   class, the mem-initializer is ill-formed.
4240   if (DirectBaseSpec && VirtualBaseSpec)
4241     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4242       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4243 
4244   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4245   if (!BaseSpec)
4246     BaseSpec = VirtualBaseSpec;
4247 
4248   // Initialize the base.
4249   bool InitList = true;
4250   MultiExprArg Args = Init;
4251   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4252     InitList = false;
4253     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4254   }
4255 
4256   InitializedEntity BaseEntity =
4257     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4258   InitializationKind Kind =
4259       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4260                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4261                                                   InitRange.getEnd());
4262   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4263   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4264   if (BaseInit.isInvalid())
4265     return true;
4266 
4267   // C++11 [class.base.init]p7:
4268   //   The initialization of each base and member constitutes a
4269   //   full-expression.
4270   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4271                                  /*DiscardedValue*/ false);
4272   if (BaseInit.isInvalid())
4273     return true;
4274 
4275   // If we are in a dependent context, template instantiation will
4276   // perform this type-checking again. Just save the arguments that we
4277   // received in a ParenListExpr.
4278   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4279   // of the information that we have about the base
4280   // initializer. However, deconstructing the ASTs is a dicey process,
4281   // and this approach is far more likely to get the corner cases right.
4282   if (CurContext->isDependentContext())
4283     BaseInit = Init;
4284 
4285   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4286                                           BaseSpec->isVirtual(),
4287                                           InitRange.getBegin(),
4288                                           BaseInit.getAs<Expr>(),
4289                                           InitRange.getEnd(), EllipsisLoc);
4290 }
4291 
4292 // Create a static_cast\<T&&>(expr).
4293 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4294   if (T.isNull()) T = E->getType();
4295   QualType TargetType = SemaRef.BuildReferenceType(
4296       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4297   SourceLocation ExprLoc = E->getBeginLoc();
4298   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4299       TargetType, ExprLoc);
4300 
4301   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4302                                    SourceRange(ExprLoc, ExprLoc),
4303                                    E->getSourceRange()).get();
4304 }
4305 
4306 /// ImplicitInitializerKind - How an implicit base or member initializer should
4307 /// initialize its base or member.
4308 enum ImplicitInitializerKind {
4309   IIK_Default,
4310   IIK_Copy,
4311   IIK_Move,
4312   IIK_Inherit
4313 };
4314 
4315 static bool
4316 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4317                              ImplicitInitializerKind ImplicitInitKind,
4318                              CXXBaseSpecifier *BaseSpec,
4319                              bool IsInheritedVirtualBase,
4320                              CXXCtorInitializer *&CXXBaseInit) {
4321   InitializedEntity InitEntity
4322     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4323                                         IsInheritedVirtualBase);
4324 
4325   ExprResult BaseInit;
4326 
4327   switch (ImplicitInitKind) {
4328   case IIK_Inherit:
4329   case IIK_Default: {
4330     InitializationKind InitKind
4331       = InitializationKind::CreateDefault(Constructor->getLocation());
4332     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4333     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4334     break;
4335   }
4336 
4337   case IIK_Move:
4338   case IIK_Copy: {
4339     bool Moving = ImplicitInitKind == IIK_Move;
4340     ParmVarDecl *Param = Constructor->getParamDecl(0);
4341     QualType ParamType = Param->getType().getNonReferenceType();
4342 
4343     Expr *CopyCtorArg =
4344       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4345                           SourceLocation(), Param, false,
4346                           Constructor->getLocation(), ParamType,
4347                           VK_LValue, nullptr);
4348 
4349     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4350 
4351     // Cast to the base class to avoid ambiguities.
4352     QualType ArgTy =
4353       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4354                                        ParamType.getQualifiers());
4355 
4356     if (Moving) {
4357       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4358     }
4359 
4360     CXXCastPath BasePath;
4361     BasePath.push_back(BaseSpec);
4362     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4363                                             CK_UncheckedDerivedToBase,
4364                                             Moving ? VK_XValue : VK_LValue,
4365                                             &BasePath).get();
4366 
4367     InitializationKind InitKind
4368       = InitializationKind::CreateDirect(Constructor->getLocation(),
4369                                          SourceLocation(), SourceLocation());
4370     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4371     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4372     break;
4373   }
4374   }
4375 
4376   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4377   if (BaseInit.isInvalid())
4378     return true;
4379 
4380   CXXBaseInit =
4381     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4382                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4383                                                         SourceLocation()),
4384                                              BaseSpec->isVirtual(),
4385                                              SourceLocation(),
4386                                              BaseInit.getAs<Expr>(),
4387                                              SourceLocation(),
4388                                              SourceLocation());
4389 
4390   return false;
4391 }
4392 
4393 static bool RefersToRValueRef(Expr *MemRef) {
4394   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4395   return Referenced->getType()->isRValueReferenceType();
4396 }
4397 
4398 static bool
4399 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4400                                ImplicitInitializerKind ImplicitInitKind,
4401                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4402                                CXXCtorInitializer *&CXXMemberInit) {
4403   if (Field->isInvalidDecl())
4404     return true;
4405 
4406   SourceLocation Loc = Constructor->getLocation();
4407 
4408   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4409     bool Moving = ImplicitInitKind == IIK_Move;
4410     ParmVarDecl *Param = Constructor->getParamDecl(0);
4411     QualType ParamType = Param->getType().getNonReferenceType();
4412 
4413     // Suppress copying zero-width bitfields.
4414     if (Field->isZeroLengthBitField(SemaRef.Context))
4415       return false;
4416 
4417     Expr *MemberExprBase =
4418       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4419                           SourceLocation(), Param, false,
4420                           Loc, ParamType, VK_LValue, nullptr);
4421 
4422     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4423 
4424     if (Moving) {
4425       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4426     }
4427 
4428     // Build a reference to this field within the parameter.
4429     CXXScopeSpec SS;
4430     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4431                               Sema::LookupMemberName);
4432     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4433                                   : cast<ValueDecl>(Field), AS_public);
4434     MemberLookup.resolveKind();
4435     ExprResult CtorArg
4436       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4437                                          ParamType, Loc,
4438                                          /*IsArrow=*/false,
4439                                          SS,
4440                                          /*TemplateKWLoc=*/SourceLocation(),
4441                                          /*FirstQualifierInScope=*/nullptr,
4442                                          MemberLookup,
4443                                          /*TemplateArgs=*/nullptr,
4444                                          /*S*/nullptr);
4445     if (CtorArg.isInvalid())
4446       return true;
4447 
4448     // C++11 [class.copy]p15:
4449     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4450     //     with static_cast<T&&>(x.m);
4451     if (RefersToRValueRef(CtorArg.get())) {
4452       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4453     }
4454 
4455     InitializedEntity Entity =
4456         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4457                                                        /*Implicit*/ true)
4458                  : InitializedEntity::InitializeMember(Field, nullptr,
4459                                                        /*Implicit*/ true);
4460 
4461     // Direct-initialize to use the copy constructor.
4462     InitializationKind InitKind =
4463       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4464 
4465     Expr *CtorArgE = CtorArg.getAs<Expr>();
4466     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4467     ExprResult MemberInit =
4468         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4469     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4470     if (MemberInit.isInvalid())
4471       return true;
4472 
4473     if (Indirect)
4474       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4475           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4476     else
4477       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4478           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4479     return false;
4480   }
4481 
4482   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4483          "Unhandled implicit init kind!");
4484 
4485   QualType FieldBaseElementType =
4486     SemaRef.Context.getBaseElementType(Field->getType());
4487 
4488   if (FieldBaseElementType->isRecordType()) {
4489     InitializedEntity InitEntity =
4490         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4491                                                        /*Implicit*/ true)
4492                  : InitializedEntity::InitializeMember(Field, nullptr,
4493                                                        /*Implicit*/ true);
4494     InitializationKind InitKind =
4495       InitializationKind::CreateDefault(Loc);
4496 
4497     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4498     ExprResult MemberInit =
4499       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4500 
4501     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4502     if (MemberInit.isInvalid())
4503       return true;
4504 
4505     if (Indirect)
4506       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4507                                                                Indirect, Loc,
4508                                                                Loc,
4509                                                                MemberInit.get(),
4510                                                                Loc);
4511     else
4512       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4513                                                                Field, Loc, Loc,
4514                                                                MemberInit.get(),
4515                                                                Loc);
4516     return false;
4517   }
4518 
4519   if (!Field->getParent()->isUnion()) {
4520     if (FieldBaseElementType->isReferenceType()) {
4521       SemaRef.Diag(Constructor->getLocation(),
4522                    diag::err_uninitialized_member_in_ctor)
4523       << (int)Constructor->isImplicit()
4524       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4525       << 0 << Field->getDeclName();
4526       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4527       return true;
4528     }
4529 
4530     if (FieldBaseElementType.isConstQualified()) {
4531       SemaRef.Diag(Constructor->getLocation(),
4532                    diag::err_uninitialized_member_in_ctor)
4533       << (int)Constructor->isImplicit()
4534       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4535       << 1 << Field->getDeclName();
4536       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4537       return true;
4538     }
4539   }
4540 
4541   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4542     // ARC and Weak:
4543     //   Default-initialize Objective-C pointers to NULL.
4544     CXXMemberInit
4545       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4546                                                  Loc, Loc,
4547                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4548                                                  Loc);
4549     return false;
4550   }
4551 
4552   // Nothing to initialize.
4553   CXXMemberInit = nullptr;
4554   return false;
4555 }
4556 
4557 namespace {
4558 struct BaseAndFieldInfo {
4559   Sema &S;
4560   CXXConstructorDecl *Ctor;
4561   bool AnyErrorsInInits;
4562   ImplicitInitializerKind IIK;
4563   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4564   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4565   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4566 
4567   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4568     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4569     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4570     if (Ctor->getInheritedConstructor())
4571       IIK = IIK_Inherit;
4572     else if (Generated && Ctor->isCopyConstructor())
4573       IIK = IIK_Copy;
4574     else if (Generated && Ctor->isMoveConstructor())
4575       IIK = IIK_Move;
4576     else
4577       IIK = IIK_Default;
4578   }
4579 
4580   bool isImplicitCopyOrMove() const {
4581     switch (IIK) {
4582     case IIK_Copy:
4583     case IIK_Move:
4584       return true;
4585 
4586     case IIK_Default:
4587     case IIK_Inherit:
4588       return false;
4589     }
4590 
4591     llvm_unreachable("Invalid ImplicitInitializerKind!");
4592   }
4593 
4594   bool addFieldInitializer(CXXCtorInitializer *Init) {
4595     AllToInit.push_back(Init);
4596 
4597     // Check whether this initializer makes the field "used".
4598     if (Init->getInit()->HasSideEffects(S.Context))
4599       S.UnusedPrivateFields.remove(Init->getAnyMember());
4600 
4601     return false;
4602   }
4603 
4604   bool isInactiveUnionMember(FieldDecl *Field) {
4605     RecordDecl *Record = Field->getParent();
4606     if (!Record->isUnion())
4607       return false;
4608 
4609     if (FieldDecl *Active =
4610             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4611       return Active != Field->getCanonicalDecl();
4612 
4613     // In an implicit copy or move constructor, ignore any in-class initializer.
4614     if (isImplicitCopyOrMove())
4615       return true;
4616 
4617     // If there's no explicit initialization, the field is active only if it
4618     // has an in-class initializer...
4619     if (Field->hasInClassInitializer())
4620       return false;
4621     // ... or it's an anonymous struct or union whose class has an in-class
4622     // initializer.
4623     if (!Field->isAnonymousStructOrUnion())
4624       return true;
4625     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4626     return !FieldRD->hasInClassInitializer();
4627   }
4628 
4629   /// Determine whether the given field is, or is within, a union member
4630   /// that is inactive (because there was an initializer given for a different
4631   /// member of the union, or because the union was not initialized at all).
4632   bool isWithinInactiveUnionMember(FieldDecl *Field,
4633                                    IndirectFieldDecl *Indirect) {
4634     if (!Indirect)
4635       return isInactiveUnionMember(Field);
4636 
4637     for (auto *C : Indirect->chain()) {
4638       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4639       if (Field && isInactiveUnionMember(Field))
4640         return true;
4641     }
4642     return false;
4643   }
4644 };
4645 }
4646 
4647 /// Determine whether the given type is an incomplete or zero-lenfgth
4648 /// array type.
4649 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4650   if (T->isIncompleteArrayType())
4651     return true;
4652 
4653   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4654     if (!ArrayT->getSize())
4655       return true;
4656 
4657     T = ArrayT->getElementType();
4658   }
4659 
4660   return false;
4661 }
4662 
4663 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4664                                     FieldDecl *Field,
4665                                     IndirectFieldDecl *Indirect = nullptr) {
4666   if (Field->isInvalidDecl())
4667     return false;
4668 
4669   // Overwhelmingly common case: we have a direct initializer for this field.
4670   if (CXXCtorInitializer *Init =
4671           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4672     return Info.addFieldInitializer(Init);
4673 
4674   // C++11 [class.base.init]p8:
4675   //   if the entity is a non-static data member that has a
4676   //   brace-or-equal-initializer and either
4677   //   -- the constructor's class is a union and no other variant member of that
4678   //      union is designated by a mem-initializer-id or
4679   //   -- the constructor's class is not a union, and, if the entity is a member
4680   //      of an anonymous union, no other member of that union is designated by
4681   //      a mem-initializer-id,
4682   //   the entity is initialized as specified in [dcl.init].
4683   //
4684   // We also apply the same rules to handle anonymous structs within anonymous
4685   // unions.
4686   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4687     return false;
4688 
4689   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4690     ExprResult DIE =
4691         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4692     if (DIE.isInvalid())
4693       return true;
4694 
4695     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4696     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4697 
4698     CXXCtorInitializer *Init;
4699     if (Indirect)
4700       Init = new (SemaRef.Context)
4701           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4702                              SourceLocation(), DIE.get(), SourceLocation());
4703     else
4704       Init = new (SemaRef.Context)
4705           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4706                              SourceLocation(), DIE.get(), SourceLocation());
4707     return Info.addFieldInitializer(Init);
4708   }
4709 
4710   // Don't initialize incomplete or zero-length arrays.
4711   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4712     return false;
4713 
4714   // Don't try to build an implicit initializer if there were semantic
4715   // errors in any of the initializers (and therefore we might be
4716   // missing some that the user actually wrote).
4717   if (Info.AnyErrorsInInits)
4718     return false;
4719 
4720   CXXCtorInitializer *Init = nullptr;
4721   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4722                                      Indirect, Init))
4723     return true;
4724 
4725   if (!Init)
4726     return false;
4727 
4728   return Info.addFieldInitializer(Init);
4729 }
4730 
4731 bool
4732 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4733                                CXXCtorInitializer *Initializer) {
4734   assert(Initializer->isDelegatingInitializer());
4735   Constructor->setNumCtorInitializers(1);
4736   CXXCtorInitializer **initializer =
4737     new (Context) CXXCtorInitializer*[1];
4738   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4739   Constructor->setCtorInitializers(initializer);
4740 
4741   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4742     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4743     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4744   }
4745 
4746   DelegatingCtorDecls.push_back(Constructor);
4747 
4748   DiagnoseUninitializedFields(*this, Constructor);
4749 
4750   return false;
4751 }
4752 
4753 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4754                                ArrayRef<CXXCtorInitializer *> Initializers) {
4755   if (Constructor->isDependentContext()) {
4756     // Just store the initializers as written, they will be checked during
4757     // instantiation.
4758     if (!Initializers.empty()) {
4759       Constructor->setNumCtorInitializers(Initializers.size());
4760       CXXCtorInitializer **baseOrMemberInitializers =
4761         new (Context) CXXCtorInitializer*[Initializers.size()];
4762       memcpy(baseOrMemberInitializers, Initializers.data(),
4763              Initializers.size() * sizeof(CXXCtorInitializer*));
4764       Constructor->setCtorInitializers(baseOrMemberInitializers);
4765     }
4766 
4767     // Let template instantiation know whether we had errors.
4768     if (AnyErrors)
4769       Constructor->setInvalidDecl();
4770 
4771     return false;
4772   }
4773 
4774   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4775 
4776   // We need to build the initializer AST according to order of construction
4777   // and not what user specified in the Initializers list.
4778   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4779   if (!ClassDecl)
4780     return true;
4781 
4782   bool HadError = false;
4783 
4784   for (unsigned i = 0; i < Initializers.size(); i++) {
4785     CXXCtorInitializer *Member = Initializers[i];
4786 
4787     if (Member->isBaseInitializer())
4788       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4789     else {
4790       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4791 
4792       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4793         for (auto *C : F->chain()) {
4794           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4795           if (FD && FD->getParent()->isUnion())
4796             Info.ActiveUnionMember.insert(std::make_pair(
4797                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4798         }
4799       } else if (FieldDecl *FD = Member->getMember()) {
4800         if (FD->getParent()->isUnion())
4801           Info.ActiveUnionMember.insert(std::make_pair(
4802               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4803       }
4804     }
4805   }
4806 
4807   // Keep track of the direct virtual bases.
4808   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4809   for (auto &I : ClassDecl->bases()) {
4810     if (I.isVirtual())
4811       DirectVBases.insert(&I);
4812   }
4813 
4814   // Push virtual bases before others.
4815   for (auto &VBase : ClassDecl->vbases()) {
4816     if (CXXCtorInitializer *Value
4817         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4818       // [class.base.init]p7, per DR257:
4819       //   A mem-initializer where the mem-initializer-id names a virtual base
4820       //   class is ignored during execution of a constructor of any class that
4821       //   is not the most derived class.
4822       if (ClassDecl->isAbstract()) {
4823         // FIXME: Provide a fixit to remove the base specifier. This requires
4824         // tracking the location of the associated comma for a base specifier.
4825         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4826           << VBase.getType() << ClassDecl;
4827         DiagnoseAbstractType(ClassDecl);
4828       }
4829 
4830       Info.AllToInit.push_back(Value);
4831     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4832       // [class.base.init]p8, per DR257:
4833       //   If a given [...] base class is not named by a mem-initializer-id
4834       //   [...] and the entity is not a virtual base class of an abstract
4835       //   class, then [...] the entity is default-initialized.
4836       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4837       CXXCtorInitializer *CXXBaseInit;
4838       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4839                                        &VBase, IsInheritedVirtualBase,
4840                                        CXXBaseInit)) {
4841         HadError = true;
4842         continue;
4843       }
4844 
4845       Info.AllToInit.push_back(CXXBaseInit);
4846     }
4847   }
4848 
4849   // Non-virtual bases.
4850   for (auto &Base : ClassDecl->bases()) {
4851     // Virtuals are in the virtual base list and already constructed.
4852     if (Base.isVirtual())
4853       continue;
4854 
4855     if (CXXCtorInitializer *Value
4856           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4857       Info.AllToInit.push_back(Value);
4858     } else if (!AnyErrors) {
4859       CXXCtorInitializer *CXXBaseInit;
4860       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4861                                        &Base, /*IsInheritedVirtualBase=*/false,
4862                                        CXXBaseInit)) {
4863         HadError = true;
4864         continue;
4865       }
4866 
4867       Info.AllToInit.push_back(CXXBaseInit);
4868     }
4869   }
4870 
4871   // Fields.
4872   for (auto *Mem : ClassDecl->decls()) {
4873     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4874       // C++ [class.bit]p2:
4875       //   A declaration for a bit-field that omits the identifier declares an
4876       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4877       //   initialized.
4878       if (F->isUnnamedBitfield())
4879         continue;
4880 
4881       // If we're not generating the implicit copy/move constructor, then we'll
4882       // handle anonymous struct/union fields based on their individual
4883       // indirect fields.
4884       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4885         continue;
4886 
4887       if (CollectFieldInitializer(*this, Info, F))
4888         HadError = true;
4889       continue;
4890     }
4891 
4892     // Beyond this point, we only consider default initialization.
4893     if (Info.isImplicitCopyOrMove())
4894       continue;
4895 
4896     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4897       if (F->getType()->isIncompleteArrayType()) {
4898         assert(ClassDecl->hasFlexibleArrayMember() &&
4899                "Incomplete array type is not valid");
4900         continue;
4901       }
4902 
4903       // Initialize each field of an anonymous struct individually.
4904       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4905         HadError = true;
4906 
4907       continue;
4908     }
4909   }
4910 
4911   unsigned NumInitializers = Info.AllToInit.size();
4912   if (NumInitializers > 0) {
4913     Constructor->setNumCtorInitializers(NumInitializers);
4914     CXXCtorInitializer **baseOrMemberInitializers =
4915       new (Context) CXXCtorInitializer*[NumInitializers];
4916     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4917            NumInitializers * sizeof(CXXCtorInitializer*));
4918     Constructor->setCtorInitializers(baseOrMemberInitializers);
4919 
4920     // Constructors implicitly reference the base and member
4921     // destructors.
4922     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4923                                            Constructor->getParent());
4924   }
4925 
4926   return HadError;
4927 }
4928 
4929 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4930   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4931     const RecordDecl *RD = RT->getDecl();
4932     if (RD->isAnonymousStructOrUnion()) {
4933       for (auto *Field : RD->fields())
4934         PopulateKeysForFields(Field, IdealInits);
4935       return;
4936     }
4937   }
4938   IdealInits.push_back(Field->getCanonicalDecl());
4939 }
4940 
4941 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4942   return Context.getCanonicalType(BaseType).getTypePtr();
4943 }
4944 
4945 static const void *GetKeyForMember(ASTContext &Context,
4946                                    CXXCtorInitializer *Member) {
4947   if (!Member->isAnyMemberInitializer())
4948     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4949 
4950   return Member->getAnyMember()->getCanonicalDecl();
4951 }
4952 
4953 static void DiagnoseBaseOrMemInitializerOrder(
4954     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4955     ArrayRef<CXXCtorInitializer *> Inits) {
4956   if (Constructor->getDeclContext()->isDependentContext())
4957     return;
4958 
4959   // Don't check initializers order unless the warning is enabled at the
4960   // location of at least one initializer.
4961   bool ShouldCheckOrder = false;
4962   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4963     CXXCtorInitializer *Init = Inits[InitIndex];
4964     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4965                                  Init->getSourceLocation())) {
4966       ShouldCheckOrder = true;
4967       break;
4968     }
4969   }
4970   if (!ShouldCheckOrder)
4971     return;
4972 
4973   // Build the list of bases and members in the order that they'll
4974   // actually be initialized.  The explicit initializers should be in
4975   // this same order but may be missing things.
4976   SmallVector<const void*, 32> IdealInitKeys;
4977 
4978   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4979 
4980   // 1. Virtual bases.
4981   for (const auto &VBase : ClassDecl->vbases())
4982     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4983 
4984   // 2. Non-virtual bases.
4985   for (const auto &Base : ClassDecl->bases()) {
4986     if (Base.isVirtual())
4987       continue;
4988     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4989   }
4990 
4991   // 3. Direct fields.
4992   for (auto *Field : ClassDecl->fields()) {
4993     if (Field->isUnnamedBitfield())
4994       continue;
4995 
4996     PopulateKeysForFields(Field, IdealInitKeys);
4997   }
4998 
4999   unsigned NumIdealInits = IdealInitKeys.size();
5000   unsigned IdealIndex = 0;
5001 
5002   CXXCtorInitializer *PrevInit = nullptr;
5003   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5004     CXXCtorInitializer *Init = Inits[InitIndex];
5005     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5006 
5007     // Scan forward to try to find this initializer in the idealized
5008     // initializers list.
5009     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5010       if (InitKey == IdealInitKeys[IdealIndex])
5011         break;
5012 
5013     // If we didn't find this initializer, it must be because we
5014     // scanned past it on a previous iteration.  That can only
5015     // happen if we're out of order;  emit a warning.
5016     if (IdealIndex == NumIdealInits && PrevInit) {
5017       Sema::SemaDiagnosticBuilder D =
5018         SemaRef.Diag(PrevInit->getSourceLocation(),
5019                      diag::warn_initializer_out_of_order);
5020 
5021       if (PrevInit->isAnyMemberInitializer())
5022         D << 0 << PrevInit->getAnyMember()->getDeclName();
5023       else
5024         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5025 
5026       if (Init->isAnyMemberInitializer())
5027         D << 0 << Init->getAnyMember()->getDeclName();
5028       else
5029         D << 1 << Init->getTypeSourceInfo()->getType();
5030 
5031       // Move back to the initializer's location in the ideal list.
5032       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5033         if (InitKey == IdealInitKeys[IdealIndex])
5034           break;
5035 
5036       assert(IdealIndex < NumIdealInits &&
5037              "initializer not found in initializer list");
5038     }
5039 
5040     PrevInit = Init;
5041   }
5042 }
5043 
5044 namespace {
5045 bool CheckRedundantInit(Sema &S,
5046                         CXXCtorInitializer *Init,
5047                         CXXCtorInitializer *&PrevInit) {
5048   if (!PrevInit) {
5049     PrevInit = Init;
5050     return false;
5051   }
5052 
5053   if (FieldDecl *Field = Init->getAnyMember())
5054     S.Diag(Init->getSourceLocation(),
5055            diag::err_multiple_mem_initialization)
5056       << Field->getDeclName()
5057       << Init->getSourceRange();
5058   else {
5059     const Type *BaseClass = Init->getBaseClass();
5060     assert(BaseClass && "neither field nor base");
5061     S.Diag(Init->getSourceLocation(),
5062            diag::err_multiple_base_initialization)
5063       << QualType(BaseClass, 0)
5064       << Init->getSourceRange();
5065   }
5066   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5067     << 0 << PrevInit->getSourceRange();
5068 
5069   return true;
5070 }
5071 
5072 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5073 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5074 
5075 bool CheckRedundantUnionInit(Sema &S,
5076                              CXXCtorInitializer *Init,
5077                              RedundantUnionMap &Unions) {
5078   FieldDecl *Field = Init->getAnyMember();
5079   RecordDecl *Parent = Field->getParent();
5080   NamedDecl *Child = Field;
5081 
5082   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5083     if (Parent->isUnion()) {
5084       UnionEntry &En = Unions[Parent];
5085       if (En.first && En.first != Child) {
5086         S.Diag(Init->getSourceLocation(),
5087                diag::err_multiple_mem_union_initialization)
5088           << Field->getDeclName()
5089           << Init->getSourceRange();
5090         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5091           << 0 << En.second->getSourceRange();
5092         return true;
5093       }
5094       if (!En.first) {
5095         En.first = Child;
5096         En.second = Init;
5097       }
5098       if (!Parent->isAnonymousStructOrUnion())
5099         return false;
5100     }
5101 
5102     Child = Parent;
5103     Parent = cast<RecordDecl>(Parent->getDeclContext());
5104   }
5105 
5106   return false;
5107 }
5108 }
5109 
5110 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5111 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5112                                 SourceLocation ColonLoc,
5113                                 ArrayRef<CXXCtorInitializer*> MemInits,
5114                                 bool AnyErrors) {
5115   if (!ConstructorDecl)
5116     return;
5117 
5118   AdjustDeclIfTemplate(ConstructorDecl);
5119 
5120   CXXConstructorDecl *Constructor
5121     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5122 
5123   if (!Constructor) {
5124     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5125     return;
5126   }
5127 
5128   // Mapping for the duplicate initializers check.
5129   // For member initializers, this is keyed with a FieldDecl*.
5130   // For base initializers, this is keyed with a Type*.
5131   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5132 
5133   // Mapping for the inconsistent anonymous-union initializers check.
5134   RedundantUnionMap MemberUnions;
5135 
5136   bool HadError = false;
5137   for (unsigned i = 0; i < MemInits.size(); i++) {
5138     CXXCtorInitializer *Init = MemInits[i];
5139 
5140     // Set the source order index.
5141     Init->setSourceOrder(i);
5142 
5143     if (Init->isAnyMemberInitializer()) {
5144       const void *Key = GetKeyForMember(Context, Init);
5145       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5146           CheckRedundantUnionInit(*this, Init, MemberUnions))
5147         HadError = true;
5148     } else if (Init->isBaseInitializer()) {
5149       const void *Key = GetKeyForMember(Context, Init);
5150       if (CheckRedundantInit(*this, Init, Members[Key]))
5151         HadError = true;
5152     } else {
5153       assert(Init->isDelegatingInitializer());
5154       // This must be the only initializer
5155       if (MemInits.size() != 1) {
5156         Diag(Init->getSourceLocation(),
5157              diag::err_delegating_initializer_alone)
5158           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5159         // We will treat this as being the only initializer.
5160       }
5161       SetDelegatingInitializer(Constructor, MemInits[i]);
5162       // Return immediately as the initializer is set.
5163       return;
5164     }
5165   }
5166 
5167   if (HadError)
5168     return;
5169 
5170   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5171 
5172   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5173 
5174   DiagnoseUninitializedFields(*this, Constructor);
5175 }
5176 
5177 void
5178 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5179                                              CXXRecordDecl *ClassDecl) {
5180   // Ignore dependent contexts. Also ignore unions, since their members never
5181   // have destructors implicitly called.
5182   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5183     return;
5184 
5185   // FIXME: all the access-control diagnostics are positioned on the
5186   // field/base declaration.  That's probably good; that said, the
5187   // user might reasonably want to know why the destructor is being
5188   // emitted, and we currently don't say.
5189 
5190   // Non-static data members.
5191   for (auto *Field : ClassDecl->fields()) {
5192     if (Field->isInvalidDecl())
5193       continue;
5194 
5195     // Don't destroy incomplete or zero-length arrays.
5196     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5197       continue;
5198 
5199     QualType FieldType = Context.getBaseElementType(Field->getType());
5200 
5201     const RecordType* RT = FieldType->getAs<RecordType>();
5202     if (!RT)
5203       continue;
5204 
5205     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5206     if (FieldClassDecl->isInvalidDecl())
5207       continue;
5208     if (FieldClassDecl->hasIrrelevantDestructor())
5209       continue;
5210     // The destructor for an implicit anonymous union member is never invoked.
5211     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5212       continue;
5213 
5214     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5215     assert(Dtor && "No dtor found for FieldClassDecl!");
5216     CheckDestructorAccess(Field->getLocation(), Dtor,
5217                           PDiag(diag::err_access_dtor_field)
5218                             << Field->getDeclName()
5219                             << FieldType);
5220 
5221     MarkFunctionReferenced(Location, Dtor);
5222     DiagnoseUseOfDecl(Dtor, Location);
5223   }
5224 
5225   // We only potentially invoke the destructors of potentially constructed
5226   // subobjects.
5227   bool VisitVirtualBases = !ClassDecl->isAbstract();
5228 
5229   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5230 
5231   // Bases.
5232   for (const auto &Base : ClassDecl->bases()) {
5233     // Bases are always records in a well-formed non-dependent class.
5234     const RecordType *RT = Base.getType()->getAs<RecordType>();
5235 
5236     // Remember direct virtual bases.
5237     if (Base.isVirtual()) {
5238       if (!VisitVirtualBases)
5239         continue;
5240       DirectVirtualBases.insert(RT);
5241     }
5242 
5243     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5244     // If our base class is invalid, we probably can't get its dtor anyway.
5245     if (BaseClassDecl->isInvalidDecl())
5246       continue;
5247     if (BaseClassDecl->hasIrrelevantDestructor())
5248       continue;
5249 
5250     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5251     assert(Dtor && "No dtor found for BaseClassDecl!");
5252 
5253     // FIXME: caret should be on the start of the class name
5254     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5255                           PDiag(diag::err_access_dtor_base)
5256                               << Base.getType() << Base.getSourceRange(),
5257                           Context.getTypeDeclType(ClassDecl));
5258 
5259     MarkFunctionReferenced(Location, Dtor);
5260     DiagnoseUseOfDecl(Dtor, Location);
5261   }
5262 
5263   if (!VisitVirtualBases)
5264     return;
5265 
5266   // Virtual bases.
5267   for (const auto &VBase : ClassDecl->vbases()) {
5268     // Bases are always records in a well-formed non-dependent class.
5269     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5270 
5271     // Ignore direct virtual bases.
5272     if (DirectVirtualBases.count(RT))
5273       continue;
5274 
5275     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5276     // If our base class is invalid, we probably can't get its dtor anyway.
5277     if (BaseClassDecl->isInvalidDecl())
5278       continue;
5279     if (BaseClassDecl->hasIrrelevantDestructor())
5280       continue;
5281 
5282     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5283     assert(Dtor && "No dtor found for BaseClassDecl!");
5284     if (CheckDestructorAccess(
5285             ClassDecl->getLocation(), Dtor,
5286             PDiag(diag::err_access_dtor_vbase)
5287                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5288             Context.getTypeDeclType(ClassDecl)) ==
5289         AR_accessible) {
5290       CheckDerivedToBaseConversion(
5291           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5292           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5293           SourceRange(), DeclarationName(), nullptr);
5294     }
5295 
5296     MarkFunctionReferenced(Location, Dtor);
5297     DiagnoseUseOfDecl(Dtor, Location);
5298   }
5299 }
5300 
5301 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5302   if (!CDtorDecl)
5303     return;
5304 
5305   if (CXXConstructorDecl *Constructor
5306       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5307     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5308     DiagnoseUninitializedFields(*this, Constructor);
5309   }
5310 }
5311 
5312 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5313   if (!getLangOpts().CPlusPlus)
5314     return false;
5315 
5316   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5317   if (!RD)
5318     return false;
5319 
5320   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5321   // class template specialization here, but doing so breaks a lot of code.
5322 
5323   // We can't answer whether something is abstract until it has a
5324   // definition. If it's currently being defined, we'll walk back
5325   // over all the declarations when we have a full definition.
5326   const CXXRecordDecl *Def = RD->getDefinition();
5327   if (!Def || Def->isBeingDefined())
5328     return false;
5329 
5330   return RD->isAbstract();
5331 }
5332 
5333 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5334                                   TypeDiagnoser &Diagnoser) {
5335   if (!isAbstractType(Loc, T))
5336     return false;
5337 
5338   T = Context.getBaseElementType(T);
5339   Diagnoser.diagnose(*this, Loc, T);
5340   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5341   return true;
5342 }
5343 
5344 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5345   // Check if we've already emitted the list of pure virtual functions
5346   // for this class.
5347   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5348     return;
5349 
5350   // If the diagnostic is suppressed, don't emit the notes. We're only
5351   // going to emit them once, so try to attach them to a diagnostic we're
5352   // actually going to show.
5353   if (Diags.isLastDiagnosticIgnored())
5354     return;
5355 
5356   CXXFinalOverriderMap FinalOverriders;
5357   RD->getFinalOverriders(FinalOverriders);
5358 
5359   // Keep a set of seen pure methods so we won't diagnose the same method
5360   // more than once.
5361   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5362 
5363   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5364                                    MEnd = FinalOverriders.end();
5365        M != MEnd;
5366        ++M) {
5367     for (OverridingMethods::iterator SO = M->second.begin(),
5368                                   SOEnd = M->second.end();
5369          SO != SOEnd; ++SO) {
5370       // C++ [class.abstract]p4:
5371       //   A class is abstract if it contains or inherits at least one
5372       //   pure virtual function for which the final overrider is pure
5373       //   virtual.
5374 
5375       //
5376       if (SO->second.size() != 1)
5377         continue;
5378 
5379       if (!SO->second.front().Method->isPure())
5380         continue;
5381 
5382       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5383         continue;
5384 
5385       Diag(SO->second.front().Method->getLocation(),
5386            diag::note_pure_virtual_function)
5387         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5388     }
5389   }
5390 
5391   if (!PureVirtualClassDiagSet)
5392     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5393   PureVirtualClassDiagSet->insert(RD);
5394 }
5395 
5396 namespace {
5397 struct AbstractUsageInfo {
5398   Sema &S;
5399   CXXRecordDecl *Record;
5400   CanQualType AbstractType;
5401   bool Invalid;
5402 
5403   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5404     : S(S), Record(Record),
5405       AbstractType(S.Context.getCanonicalType(
5406                    S.Context.getTypeDeclType(Record))),
5407       Invalid(false) {}
5408 
5409   void DiagnoseAbstractType() {
5410     if (Invalid) return;
5411     S.DiagnoseAbstractType(Record);
5412     Invalid = true;
5413   }
5414 
5415   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5416 };
5417 
5418 struct CheckAbstractUsage {
5419   AbstractUsageInfo &Info;
5420   const NamedDecl *Ctx;
5421 
5422   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5423     : Info(Info), Ctx(Ctx) {}
5424 
5425   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5426     switch (TL.getTypeLocClass()) {
5427 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5428 #define TYPELOC(CLASS, PARENT) \
5429     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5430 #include "clang/AST/TypeLocNodes.def"
5431     }
5432   }
5433 
5434   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5435     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5436     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5437       if (!TL.getParam(I))
5438         continue;
5439 
5440       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5441       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5442     }
5443   }
5444 
5445   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5446     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5447   }
5448 
5449   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5450     // Visit the type parameters from a permissive context.
5451     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5452       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5453       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5454         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5455           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5456       // TODO: other template argument types?
5457     }
5458   }
5459 
5460   // Visit pointee types from a permissive context.
5461 #define CheckPolymorphic(Type) \
5462   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5463     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5464   }
5465   CheckPolymorphic(PointerTypeLoc)
5466   CheckPolymorphic(ReferenceTypeLoc)
5467   CheckPolymorphic(MemberPointerTypeLoc)
5468   CheckPolymorphic(BlockPointerTypeLoc)
5469   CheckPolymorphic(AtomicTypeLoc)
5470 
5471   /// Handle all the types we haven't given a more specific
5472   /// implementation for above.
5473   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5474     // Every other kind of type that we haven't called out already
5475     // that has an inner type is either (1) sugar or (2) contains that
5476     // inner type in some way as a subobject.
5477     if (TypeLoc Next = TL.getNextTypeLoc())
5478       return Visit(Next, Sel);
5479 
5480     // If there's no inner type and we're in a permissive context,
5481     // don't diagnose.
5482     if (Sel == Sema::AbstractNone) return;
5483 
5484     // Check whether the type matches the abstract type.
5485     QualType T = TL.getType();
5486     if (T->isArrayType()) {
5487       Sel = Sema::AbstractArrayType;
5488       T = Info.S.Context.getBaseElementType(T);
5489     }
5490     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5491     if (CT != Info.AbstractType) return;
5492 
5493     // It matched; do some magic.
5494     if (Sel == Sema::AbstractArrayType) {
5495       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5496         << T << TL.getSourceRange();
5497     } else {
5498       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5499         << Sel << T << TL.getSourceRange();
5500     }
5501     Info.DiagnoseAbstractType();
5502   }
5503 };
5504 
5505 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5506                                   Sema::AbstractDiagSelID Sel) {
5507   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5508 }
5509 
5510 }
5511 
5512 /// Check for invalid uses of an abstract type in a method declaration.
5513 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5514                                     CXXMethodDecl *MD) {
5515   // No need to do the check on definitions, which require that
5516   // the return/param types be complete.
5517   if (MD->doesThisDeclarationHaveABody())
5518     return;
5519 
5520   // For safety's sake, just ignore it if we don't have type source
5521   // information.  This should never happen for non-implicit methods,
5522   // but...
5523   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5524     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5525 }
5526 
5527 /// Check for invalid uses of an abstract type within a class definition.
5528 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5529                                     CXXRecordDecl *RD) {
5530   for (auto *D : RD->decls()) {
5531     if (D->isImplicit()) continue;
5532 
5533     // Methods and method templates.
5534     if (isa<CXXMethodDecl>(D)) {
5535       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5536     } else if (isa<FunctionTemplateDecl>(D)) {
5537       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5538       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5539 
5540     // Fields and static variables.
5541     } else if (isa<FieldDecl>(D)) {
5542       FieldDecl *FD = cast<FieldDecl>(D);
5543       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5544         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5545     } else if (isa<VarDecl>(D)) {
5546       VarDecl *VD = cast<VarDecl>(D);
5547       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5548         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5549 
5550     // Nested classes and class templates.
5551     } else if (isa<CXXRecordDecl>(D)) {
5552       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5553     } else if (isa<ClassTemplateDecl>(D)) {
5554       CheckAbstractClassUsage(Info,
5555                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5556     }
5557   }
5558 }
5559 
5560 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5561   Attr *ClassAttr = getDLLAttr(Class);
5562   if (!ClassAttr)
5563     return;
5564 
5565   assert(ClassAttr->getKind() == attr::DLLExport);
5566 
5567   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5568 
5569   if (TSK == TSK_ExplicitInstantiationDeclaration)
5570     // Don't go any further if this is just an explicit instantiation
5571     // declaration.
5572     return;
5573 
5574   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5575     S.MarkVTableUsed(Class->getLocation(), Class, true);
5576 
5577   for (Decl *Member : Class->decls()) {
5578     // Defined static variables that are members of an exported base
5579     // class must be marked export too.
5580     auto *VD = dyn_cast<VarDecl>(Member);
5581     if (VD && Member->getAttr<DLLExportAttr>() &&
5582         VD->getStorageClass() == SC_Static &&
5583         TSK == TSK_ImplicitInstantiation)
5584       S.MarkVariableReferenced(VD->getLocation(), VD);
5585 
5586     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5587     if (!MD)
5588       continue;
5589 
5590     if (Member->getAttr<DLLExportAttr>()) {
5591       if (MD->isUserProvided()) {
5592         // Instantiate non-default class member functions ...
5593 
5594         // .. except for certain kinds of template specializations.
5595         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5596           continue;
5597 
5598         S.MarkFunctionReferenced(Class->getLocation(), MD);
5599 
5600         // The function will be passed to the consumer when its definition is
5601         // encountered.
5602       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5603                  MD->isCopyAssignmentOperator() ||
5604                  MD->isMoveAssignmentOperator()) {
5605         // Synthesize and instantiate non-trivial implicit methods, explicitly
5606         // defaulted methods, and the copy and move assignment operators. The
5607         // latter are exported even if they are trivial, because the address of
5608         // an operator can be taken and should compare equal across libraries.
5609         DiagnosticErrorTrap Trap(S.Diags);
5610         S.MarkFunctionReferenced(Class->getLocation(), MD);
5611         if (Trap.hasErrorOccurred()) {
5612           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5613               << Class << !S.getLangOpts().CPlusPlus11;
5614           break;
5615         }
5616 
5617         // There is no later point when we will see the definition of this
5618         // function, so pass it to the consumer now.
5619         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5620       }
5621     }
5622   }
5623 }
5624 
5625 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5626                                                         CXXRecordDecl *Class) {
5627   // Only the MS ABI has default constructor closures, so we don't need to do
5628   // this semantic checking anywhere else.
5629   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5630     return;
5631 
5632   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5633   for (Decl *Member : Class->decls()) {
5634     // Look for exported default constructors.
5635     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5636     if (!CD || !CD->isDefaultConstructor())
5637       continue;
5638     auto *Attr = CD->getAttr<DLLExportAttr>();
5639     if (!Attr)
5640       continue;
5641 
5642     // If the class is non-dependent, mark the default arguments as ODR-used so
5643     // that we can properly codegen the constructor closure.
5644     if (!Class->isDependentContext()) {
5645       for (ParmVarDecl *PD : CD->parameters()) {
5646         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5647         S.DiscardCleanupsInEvaluationContext();
5648       }
5649     }
5650 
5651     if (LastExportedDefaultCtor) {
5652       S.Diag(LastExportedDefaultCtor->getLocation(),
5653              diag::err_attribute_dll_ambiguous_default_ctor)
5654           << Class;
5655       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5656           << CD->getDeclName();
5657       return;
5658     }
5659     LastExportedDefaultCtor = CD;
5660   }
5661 }
5662 
5663 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5664   // Mark any compiler-generated routines with the implicit code_seg attribute.
5665   for (auto *Method : Class->methods()) {
5666     if (Method->isUserProvided())
5667       continue;
5668     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5669       Method->addAttr(A);
5670   }
5671 }
5672 
5673 /// Check class-level dllimport/dllexport attribute.
5674 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5675   Attr *ClassAttr = getDLLAttr(Class);
5676 
5677   // MSVC inherits DLL attributes to partial class template specializations.
5678   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5679     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5680       if (Attr *TemplateAttr =
5681               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5682         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5683         A->setInherited(true);
5684         ClassAttr = A;
5685       }
5686     }
5687   }
5688 
5689   if (!ClassAttr)
5690     return;
5691 
5692   if (!Class->isExternallyVisible()) {
5693     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5694         << Class << ClassAttr;
5695     return;
5696   }
5697 
5698   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5699       !ClassAttr->isInherited()) {
5700     // Diagnose dll attributes on members of class with dll attribute.
5701     for (Decl *Member : Class->decls()) {
5702       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5703         continue;
5704       InheritableAttr *MemberAttr = getDLLAttr(Member);
5705       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5706         continue;
5707 
5708       Diag(MemberAttr->getLocation(),
5709              diag::err_attribute_dll_member_of_dll_class)
5710           << MemberAttr << ClassAttr;
5711       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5712       Member->setInvalidDecl();
5713     }
5714   }
5715 
5716   if (Class->getDescribedClassTemplate())
5717     // Don't inherit dll attribute until the template is instantiated.
5718     return;
5719 
5720   // The class is either imported or exported.
5721   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5722 
5723   // Check if this was a dllimport attribute propagated from a derived class to
5724   // a base class template specialization. We don't apply these attributes to
5725   // static data members.
5726   const bool PropagatedImport =
5727       !ClassExported &&
5728       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5729 
5730   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5731 
5732   // Ignore explicit dllexport on explicit class template instantiation
5733   // declarations, except in MinGW mode.
5734   if (ClassExported && !ClassAttr->isInherited() &&
5735       TSK == TSK_ExplicitInstantiationDeclaration &&
5736       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
5737     Class->dropAttr<DLLExportAttr>();
5738     return;
5739   }
5740 
5741   // Force declaration of implicit members so they can inherit the attribute.
5742   ForceDeclarationOfImplicitMembers(Class);
5743 
5744   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5745   // seem to be true in practice?
5746 
5747   for (Decl *Member : Class->decls()) {
5748     VarDecl *VD = dyn_cast<VarDecl>(Member);
5749     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5750 
5751     // Only methods and static fields inherit the attributes.
5752     if (!VD && !MD)
5753       continue;
5754 
5755     if (MD) {
5756       // Don't process deleted methods.
5757       if (MD->isDeleted())
5758         continue;
5759 
5760       if (MD->isInlined()) {
5761         // MinGW does not import or export inline methods. But do it for
5762         // template instantiations.
5763         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5764             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
5765             TSK != TSK_ExplicitInstantiationDeclaration &&
5766             TSK != TSK_ExplicitInstantiationDefinition)
5767           continue;
5768 
5769         // MSVC versions before 2015 don't export the move assignment operators
5770         // and move constructor, so don't attempt to import/export them if
5771         // we have a definition.
5772         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5773         if ((MD->isMoveAssignmentOperator() ||
5774              (Ctor && Ctor->isMoveConstructor())) &&
5775             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5776           continue;
5777 
5778         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5779         // operator is exported anyway.
5780         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5781             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5782           continue;
5783       }
5784     }
5785 
5786     // Don't apply dllimport attributes to static data members of class template
5787     // instantiations when the attribute is propagated from a derived class.
5788     if (VD && PropagatedImport)
5789       continue;
5790 
5791     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5792       continue;
5793 
5794     if (!getDLLAttr(Member)) {
5795       InheritableAttr *NewAttr = nullptr;
5796 
5797       // Do not export/import inline function when -fno-dllexport-inlines is
5798       // passed. But add attribute for later local static var check.
5799       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5800           TSK != TSK_ExplicitInstantiationDeclaration &&
5801           TSK != TSK_ExplicitInstantiationDefinition) {
5802         if (ClassExported) {
5803           NewAttr = ::new (getASTContext())
5804             DLLExportStaticLocalAttr(ClassAttr->getRange(),
5805                                      getASTContext(),
5806                                      ClassAttr->getSpellingListIndex());
5807         } else {
5808           NewAttr = ::new (getASTContext())
5809             DLLImportStaticLocalAttr(ClassAttr->getRange(),
5810                                      getASTContext(),
5811                                      ClassAttr->getSpellingListIndex());
5812         }
5813       } else {
5814         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5815       }
5816 
5817       NewAttr->setInherited(true);
5818       Member->addAttr(NewAttr);
5819 
5820       if (MD) {
5821         // Propagate DLLAttr to friend re-declarations of MD that have already
5822         // been constructed.
5823         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5824              FD = FD->getPreviousDecl()) {
5825           if (FD->getFriendObjectKind() == Decl::FOK_None)
5826             continue;
5827           assert(!getDLLAttr(FD) &&
5828                  "friend re-decl should not already have a DLLAttr");
5829           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5830           NewAttr->setInherited(true);
5831           FD->addAttr(NewAttr);
5832         }
5833       }
5834     }
5835   }
5836 
5837   if (ClassExported)
5838     DelayedDllExportClasses.push_back(Class);
5839 }
5840 
5841 /// Perform propagation of DLL attributes from a derived class to a
5842 /// templated base class for MS compatibility.
5843 void Sema::propagateDLLAttrToBaseClassTemplate(
5844     CXXRecordDecl *Class, Attr *ClassAttr,
5845     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5846   if (getDLLAttr(
5847           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5848     // If the base class template has a DLL attribute, don't try to change it.
5849     return;
5850   }
5851 
5852   auto TSK = BaseTemplateSpec->getSpecializationKind();
5853   if (!getDLLAttr(BaseTemplateSpec) &&
5854       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5855        TSK == TSK_ImplicitInstantiation)) {
5856     // The template hasn't been instantiated yet (or it has, but only as an
5857     // explicit instantiation declaration or implicit instantiation, which means
5858     // we haven't codegenned any members yet), so propagate the attribute.
5859     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5860     NewAttr->setInherited(true);
5861     BaseTemplateSpec->addAttr(NewAttr);
5862 
5863     // If this was an import, mark that we propagated it from a derived class to
5864     // a base class template specialization.
5865     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5866       ImportAttr->setPropagatedToBaseTemplate();
5867 
5868     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5869     // needs to be run again to work see the new attribute. Otherwise this will
5870     // get run whenever the template is instantiated.
5871     if (TSK != TSK_Undeclared)
5872       checkClassLevelDLLAttribute(BaseTemplateSpec);
5873 
5874     return;
5875   }
5876 
5877   if (getDLLAttr(BaseTemplateSpec)) {
5878     // The template has already been specialized or instantiated with an
5879     // attribute, explicitly or through propagation. We should not try to change
5880     // it.
5881     return;
5882   }
5883 
5884   // The template was previously instantiated or explicitly specialized without
5885   // a dll attribute, It's too late for us to add an attribute, so warn that
5886   // this is unsupported.
5887   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5888       << BaseTemplateSpec->isExplicitSpecialization();
5889   Diag(ClassAttr->getLocation(), diag::note_attribute);
5890   if (BaseTemplateSpec->isExplicitSpecialization()) {
5891     Diag(BaseTemplateSpec->getLocation(),
5892            diag::note_template_class_explicit_specialization_was_here)
5893         << BaseTemplateSpec;
5894   } else {
5895     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5896            diag::note_template_class_instantiation_was_here)
5897         << BaseTemplateSpec;
5898   }
5899 }
5900 
5901 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5902                                         SourceLocation DefaultLoc) {
5903   switch (S.getSpecialMember(MD)) {
5904   case Sema::CXXDefaultConstructor:
5905     S.DefineImplicitDefaultConstructor(DefaultLoc,
5906                                        cast<CXXConstructorDecl>(MD));
5907     break;
5908   case Sema::CXXCopyConstructor:
5909     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5910     break;
5911   case Sema::CXXCopyAssignment:
5912     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5913     break;
5914   case Sema::CXXDestructor:
5915     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5916     break;
5917   case Sema::CXXMoveConstructor:
5918     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5919     break;
5920   case Sema::CXXMoveAssignment:
5921     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5922     break;
5923   case Sema::CXXInvalid:
5924     llvm_unreachable("Invalid special member.");
5925   }
5926 }
5927 
5928 /// Determine whether a type is permitted to be passed or returned in
5929 /// registers, per C++ [class.temporary]p3.
5930 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5931                                TargetInfo::CallingConvKind CCK) {
5932   if (D->isDependentType() || D->isInvalidDecl())
5933     return false;
5934 
5935   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5936   // The PS4 platform ABI follows the behavior of Clang 3.2.
5937   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5938     return !D->hasNonTrivialDestructorForCall() &&
5939            !D->hasNonTrivialCopyConstructorForCall();
5940 
5941   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
5942     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5943     bool DtorIsTrivialForCall = false;
5944 
5945     // If a class has at least one non-deleted, trivial copy constructor, it
5946     // is passed according to the C ABI. Otherwise, it is passed indirectly.
5947     //
5948     // Note: This permits classes with non-trivial copy or move ctors to be
5949     // passed in registers, so long as they *also* have a trivial copy ctor,
5950     // which is non-conforming.
5951     if (D->needsImplicitCopyConstructor()) {
5952       if (!D->defaultedCopyConstructorIsDeleted()) {
5953         if (D->hasTrivialCopyConstructor())
5954           CopyCtorIsTrivial = true;
5955         if (D->hasTrivialCopyConstructorForCall())
5956           CopyCtorIsTrivialForCall = true;
5957       }
5958     } else {
5959       for (const CXXConstructorDecl *CD : D->ctors()) {
5960         if (CD->isCopyConstructor() && !CD->isDeleted()) {
5961           if (CD->isTrivial())
5962             CopyCtorIsTrivial = true;
5963           if (CD->isTrivialForCall())
5964             CopyCtorIsTrivialForCall = true;
5965         }
5966       }
5967     }
5968 
5969     if (D->needsImplicitDestructor()) {
5970       if (!D->defaultedDestructorIsDeleted() &&
5971           D->hasTrivialDestructorForCall())
5972         DtorIsTrivialForCall = true;
5973     } else if (const auto *DD = D->getDestructor()) {
5974       if (!DD->isDeleted() && DD->isTrivialForCall())
5975         DtorIsTrivialForCall = true;
5976     }
5977 
5978     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5979     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5980       return true;
5981 
5982     // If a class has a destructor, we'd really like to pass it indirectly
5983     // because it allows us to elide copies.  Unfortunately, MSVC makes that
5984     // impossible for small types, which it will pass in a single register or
5985     // stack slot. Most objects with dtors are large-ish, so handle that early.
5986     // We can't call out all large objects as being indirect because there are
5987     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5988     // how we pass large POD types.
5989 
5990     // Note: This permits small classes with nontrivial destructors to be
5991     // passed in registers, which is non-conforming.
5992     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5993     uint64_t TypeSize = isAArch64 ? 128 : 64;
5994 
5995     if (CopyCtorIsTrivial &&
5996         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
5997       return true;
5998     return false;
5999   }
6000 
6001   // Per C++ [class.temporary]p3, the relevant condition is:
6002   //   each copy constructor, move constructor, and destructor of X is
6003   //   either trivial or deleted, and X has at least one non-deleted copy
6004   //   or move constructor
6005   bool HasNonDeletedCopyOrMove = false;
6006 
6007   if (D->needsImplicitCopyConstructor() &&
6008       !D->defaultedCopyConstructorIsDeleted()) {
6009     if (!D->hasTrivialCopyConstructorForCall())
6010       return false;
6011     HasNonDeletedCopyOrMove = true;
6012   }
6013 
6014   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6015       !D->defaultedMoveConstructorIsDeleted()) {
6016     if (!D->hasTrivialMoveConstructorForCall())
6017       return false;
6018     HasNonDeletedCopyOrMove = true;
6019   }
6020 
6021   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6022       !D->hasTrivialDestructorForCall())
6023     return false;
6024 
6025   for (const CXXMethodDecl *MD : D->methods()) {
6026     if (MD->isDeleted())
6027       continue;
6028 
6029     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6030     if (CD && CD->isCopyOrMoveConstructor())
6031       HasNonDeletedCopyOrMove = true;
6032     else if (!isa<CXXDestructorDecl>(MD))
6033       continue;
6034 
6035     if (!MD->isTrivialForCall())
6036       return false;
6037   }
6038 
6039   return HasNonDeletedCopyOrMove;
6040 }
6041 
6042 /// Perform semantic checks on a class definition that has been
6043 /// completing, introducing implicitly-declared members, checking for
6044 /// abstract types, etc.
6045 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
6046   if (!Record)
6047     return;
6048 
6049   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6050     AbstractUsageInfo Info(*this, Record);
6051     CheckAbstractClassUsage(Info, Record);
6052   }
6053 
6054   // If this is not an aggregate type and has no user-declared constructor,
6055   // complain about any non-static data members of reference or const scalar
6056   // type, since they will never get initializers.
6057   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6058       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6059       !Record->isLambda()) {
6060     bool Complained = false;
6061     for (const auto *F : Record->fields()) {
6062       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6063         continue;
6064 
6065       if (F->getType()->isReferenceType() ||
6066           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6067         if (!Complained) {
6068           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6069             << Record->getTagKind() << Record;
6070           Complained = true;
6071         }
6072 
6073         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6074           << F->getType()->isReferenceType()
6075           << F->getDeclName();
6076       }
6077     }
6078   }
6079 
6080   if (Record->getIdentifier()) {
6081     // C++ [class.mem]p13:
6082     //   If T is the name of a class, then each of the following shall have a
6083     //   name different from T:
6084     //     - every member of every anonymous union that is a member of class T.
6085     //
6086     // C++ [class.mem]p14:
6087     //   In addition, if class T has a user-declared constructor (12.1), every
6088     //   non-static data member of class T shall have a name different from T.
6089     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6090     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6091          ++I) {
6092       NamedDecl *D = (*I)->getUnderlyingDecl();
6093       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6094            Record->hasUserDeclaredConstructor()) ||
6095           isa<IndirectFieldDecl>(D)) {
6096         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6097           << D->getDeclName();
6098         break;
6099       }
6100     }
6101   }
6102 
6103   // Warn if the class has virtual methods but non-virtual public destructor.
6104   if (Record->isPolymorphic() && !Record->isDependentType()) {
6105     CXXDestructorDecl *dtor = Record->getDestructor();
6106     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6107         !Record->hasAttr<FinalAttr>())
6108       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6109            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6110   }
6111 
6112   if (Record->isAbstract()) {
6113     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6114       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6115         << FA->isSpelledAsSealed();
6116       DiagnoseAbstractType(Record);
6117     }
6118   }
6119 
6120   // See if trivial_abi has to be dropped.
6121   if (Record->hasAttr<TrivialABIAttr>())
6122     checkIllFormedTrivialABIStruct(*Record);
6123 
6124   // Set HasTrivialSpecialMemberForCall if the record has attribute
6125   // "trivial_abi".
6126   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6127 
6128   if (HasTrivialABI)
6129     Record->setHasTrivialSpecialMemberForCall();
6130 
6131   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6132     // Check whether the explicitly-defaulted special members are valid.
6133     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6134       CheckExplicitlyDefaultedSpecialMember(M);
6135 
6136     // For an explicitly defaulted or deleted special member, we defer
6137     // determining triviality until the class is complete. That time is now!
6138     CXXSpecialMember CSM = getSpecialMember(M);
6139     if (!M->isImplicit() && !M->isUserProvided()) {
6140       if (CSM != CXXInvalid) {
6141         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6142         // Inform the class that we've finished declaring this member.
6143         Record->finishedDefaultedOrDeletedMember(M);
6144         M->setTrivialForCall(
6145             HasTrivialABI ||
6146             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6147         Record->setTrivialForCallFlags(M);
6148       }
6149     }
6150 
6151     // Set triviality for the purpose of calls if this is a user-provided
6152     // copy/move constructor or destructor.
6153     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6154          CSM == CXXDestructor) && M->isUserProvided()) {
6155       M->setTrivialForCall(HasTrivialABI);
6156       Record->setTrivialForCallFlags(M);
6157     }
6158 
6159     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6160         M->hasAttr<DLLExportAttr>()) {
6161       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6162           M->isTrivial() &&
6163           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6164            CSM == CXXDestructor))
6165         M->dropAttr<DLLExportAttr>();
6166 
6167       if (M->hasAttr<DLLExportAttr>()) {
6168         DefineImplicitSpecialMember(*this, M, M->getLocation());
6169         ActOnFinishInlineFunctionDef(M);
6170       }
6171     }
6172   };
6173 
6174   bool HasMethodWithOverrideControl = false,
6175        HasOverridingMethodWithoutOverrideControl = false;
6176   if (!Record->isDependentType()) {
6177     // Check the destructor before any other member function. We need to
6178     // determine whether it's trivial in order to determine whether the claas
6179     // type is a literal type, which is a prerequisite for determining whether
6180     // other special member functions are valid and whether they're implicitly
6181     // 'constexpr'.
6182     if (CXXDestructorDecl *Dtor = Record->getDestructor())
6183       CompleteMemberFunction(Dtor);
6184 
6185     for (auto *M : Record->methods()) {
6186       // See if a method overloads virtual methods in a base
6187       // class without overriding any.
6188       if (!M->isStatic())
6189         DiagnoseHiddenVirtualMethods(M);
6190       if (M->hasAttr<OverrideAttr>())
6191         HasMethodWithOverrideControl = true;
6192       else if (M->size_overridden_methods() > 0)
6193         HasOverridingMethodWithoutOverrideControl = true;
6194 
6195       if (!isa<CXXDestructorDecl>(M))
6196         CompleteMemberFunction(M);
6197     }
6198   }
6199 
6200   if (HasMethodWithOverrideControl &&
6201       HasOverridingMethodWithoutOverrideControl) {
6202     // At least one method has the 'override' control declared.
6203     // Diagnose all other overridden methods which do not have 'override' specified on them.
6204     for (auto *M : Record->methods())
6205       DiagnoseAbsenceOfOverrideControl(M);
6206   }
6207 
6208   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6209   // whether this class uses any C++ features that are implemented
6210   // completely differently in MSVC, and if so, emit a diagnostic.
6211   // That diagnostic defaults to an error, but we allow projects to
6212   // map it down to a warning (or ignore it).  It's a fairly common
6213   // practice among users of the ms_struct pragma to mass-annotate
6214   // headers, sweeping up a bunch of types that the project doesn't
6215   // really rely on MSVC-compatible layout for.  We must therefore
6216   // support "ms_struct except for C++ stuff" as a secondary ABI.
6217   if (Record->isMsStruct(Context) &&
6218       (Record->isPolymorphic() || Record->getNumBases())) {
6219     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6220   }
6221 
6222   checkClassLevelDLLAttribute(Record);
6223   checkClassLevelCodeSegAttribute(Record);
6224 
6225   bool ClangABICompat4 =
6226       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6227   TargetInfo::CallingConvKind CCK =
6228       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6229   bool CanPass = canPassInRegisters(*this, Record, CCK);
6230 
6231   // Do not change ArgPassingRestrictions if it has already been set to
6232   // APK_CanNeverPassInRegs.
6233   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6234     Record->setArgPassingRestrictions(CanPass
6235                                           ? RecordDecl::APK_CanPassInRegs
6236                                           : RecordDecl::APK_CannotPassInRegs);
6237 
6238   // If canPassInRegisters returns true despite the record having a non-trivial
6239   // destructor, the record is destructed in the callee. This happens only when
6240   // the record or one of its subobjects has a field annotated with trivial_abi
6241   // or a field qualified with ObjC __strong/__weak.
6242   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6243     Record->setParamDestroyedInCallee(true);
6244   else if (Record->hasNonTrivialDestructor())
6245     Record->setParamDestroyedInCallee(CanPass);
6246 
6247   if (getLangOpts().ForceEmitVTables) {
6248     // If we want to emit all the vtables, we need to mark it as used.  This
6249     // is especially required for cases like vtable assumption loads.
6250     MarkVTableUsed(Record->getInnerLocStart(), Record);
6251   }
6252 }
6253 
6254 /// Look up the special member function that would be called by a special
6255 /// member function for a subobject of class type.
6256 ///
6257 /// \param Class The class type of the subobject.
6258 /// \param CSM The kind of special member function.
6259 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6260 /// \param ConstRHS True if this is a copy operation with a const object
6261 ///        on its RHS, that is, if the argument to the outer special member
6262 ///        function is 'const' and this is not a field marked 'mutable'.
6263 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6264     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6265     unsigned FieldQuals, bool ConstRHS) {
6266   unsigned LHSQuals = 0;
6267   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6268     LHSQuals = FieldQuals;
6269 
6270   unsigned RHSQuals = FieldQuals;
6271   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6272     RHSQuals = 0;
6273   else if (ConstRHS)
6274     RHSQuals |= Qualifiers::Const;
6275 
6276   return S.LookupSpecialMember(Class, CSM,
6277                                RHSQuals & Qualifiers::Const,
6278                                RHSQuals & Qualifiers::Volatile,
6279                                false,
6280                                LHSQuals & Qualifiers::Const,
6281                                LHSQuals & Qualifiers::Volatile);
6282 }
6283 
6284 class Sema::InheritedConstructorInfo {
6285   Sema &S;
6286   SourceLocation UseLoc;
6287 
6288   /// A mapping from the base classes through which the constructor was
6289   /// inherited to the using shadow declaration in that base class (or a null
6290   /// pointer if the constructor was declared in that base class).
6291   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6292       InheritedFromBases;
6293 
6294 public:
6295   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6296                            ConstructorUsingShadowDecl *Shadow)
6297       : S(S), UseLoc(UseLoc) {
6298     bool DiagnosedMultipleConstructedBases = false;
6299     CXXRecordDecl *ConstructedBase = nullptr;
6300     UsingDecl *ConstructedBaseUsing = nullptr;
6301 
6302     // Find the set of such base class subobjects and check that there's a
6303     // unique constructed subobject.
6304     for (auto *D : Shadow->redecls()) {
6305       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6306       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6307       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6308 
6309       InheritedFromBases.insert(
6310           std::make_pair(DNominatedBase->getCanonicalDecl(),
6311                          DShadow->getNominatedBaseClassShadowDecl()));
6312       if (DShadow->constructsVirtualBase())
6313         InheritedFromBases.insert(
6314             std::make_pair(DConstructedBase->getCanonicalDecl(),
6315                            DShadow->getConstructedBaseClassShadowDecl()));
6316       else
6317         assert(DNominatedBase == DConstructedBase);
6318 
6319       // [class.inhctor.init]p2:
6320       //   If the constructor was inherited from multiple base class subobjects
6321       //   of type B, the program is ill-formed.
6322       if (!ConstructedBase) {
6323         ConstructedBase = DConstructedBase;
6324         ConstructedBaseUsing = D->getUsingDecl();
6325       } else if (ConstructedBase != DConstructedBase &&
6326                  !Shadow->isInvalidDecl()) {
6327         if (!DiagnosedMultipleConstructedBases) {
6328           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6329               << Shadow->getTargetDecl();
6330           S.Diag(ConstructedBaseUsing->getLocation(),
6331                diag::note_ambiguous_inherited_constructor_using)
6332               << ConstructedBase;
6333           DiagnosedMultipleConstructedBases = true;
6334         }
6335         S.Diag(D->getUsingDecl()->getLocation(),
6336                diag::note_ambiguous_inherited_constructor_using)
6337             << DConstructedBase;
6338       }
6339     }
6340 
6341     if (DiagnosedMultipleConstructedBases)
6342       Shadow->setInvalidDecl();
6343   }
6344 
6345   /// Find the constructor to use for inherited construction of a base class,
6346   /// and whether that base class constructor inherits the constructor from a
6347   /// virtual base class (in which case it won't actually invoke it).
6348   std::pair<CXXConstructorDecl *, bool>
6349   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6350     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6351     if (It == InheritedFromBases.end())
6352       return std::make_pair(nullptr, false);
6353 
6354     // This is an intermediary class.
6355     if (It->second)
6356       return std::make_pair(
6357           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6358           It->second->constructsVirtualBase());
6359 
6360     // This is the base class from which the constructor was inherited.
6361     return std::make_pair(Ctor, false);
6362   }
6363 };
6364 
6365 /// Is the special member function which would be selected to perform the
6366 /// specified operation on the specified class type a constexpr constructor?
6367 static bool
6368 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6369                          Sema::CXXSpecialMember CSM, unsigned Quals,
6370                          bool ConstRHS,
6371                          CXXConstructorDecl *InheritedCtor = nullptr,
6372                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6373   // If we're inheriting a constructor, see if we need to call it for this base
6374   // class.
6375   if (InheritedCtor) {
6376     assert(CSM == Sema::CXXDefaultConstructor);
6377     auto BaseCtor =
6378         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6379     if (BaseCtor)
6380       return BaseCtor->isConstexpr();
6381   }
6382 
6383   if (CSM == Sema::CXXDefaultConstructor)
6384     return ClassDecl->hasConstexprDefaultConstructor();
6385 
6386   Sema::SpecialMemberOverloadResult SMOR =
6387       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6388   if (!SMOR.getMethod())
6389     // A constructor we wouldn't select can't be "involved in initializing"
6390     // anything.
6391     return true;
6392   return SMOR.getMethod()->isConstexpr();
6393 }
6394 
6395 /// Determine whether the specified special member function would be constexpr
6396 /// if it were implicitly defined.
6397 static bool defaultedSpecialMemberIsConstexpr(
6398     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6399     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6400     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6401   if (!S.getLangOpts().CPlusPlus11)
6402     return false;
6403 
6404   // C++11 [dcl.constexpr]p4:
6405   // In the definition of a constexpr constructor [...]
6406   bool Ctor = true;
6407   switch (CSM) {
6408   case Sema::CXXDefaultConstructor:
6409     if (Inherited)
6410       break;
6411     // Since default constructor lookup is essentially trivial (and cannot
6412     // involve, for instance, template instantiation), we compute whether a
6413     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6414     //
6415     // This is important for performance; we need to know whether the default
6416     // constructor is constexpr to determine whether the type is a literal type.
6417     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6418 
6419   case Sema::CXXCopyConstructor:
6420   case Sema::CXXMoveConstructor:
6421     // For copy or move constructors, we need to perform overload resolution.
6422     break;
6423 
6424   case Sema::CXXCopyAssignment:
6425   case Sema::CXXMoveAssignment:
6426     if (!S.getLangOpts().CPlusPlus14)
6427       return false;
6428     // In C++1y, we need to perform overload resolution.
6429     Ctor = false;
6430     break;
6431 
6432   case Sema::CXXDestructor:
6433   case Sema::CXXInvalid:
6434     return false;
6435   }
6436 
6437   //   -- if the class is a non-empty union, or for each non-empty anonymous
6438   //      union member of a non-union class, exactly one non-static data member
6439   //      shall be initialized; [DR1359]
6440   //
6441   // If we squint, this is guaranteed, since exactly one non-static data member
6442   // will be initialized (if the constructor isn't deleted), we just don't know
6443   // which one.
6444   if (Ctor && ClassDecl->isUnion())
6445     return CSM == Sema::CXXDefaultConstructor
6446                ? ClassDecl->hasInClassInitializer() ||
6447                      !ClassDecl->hasVariantMembers()
6448                : true;
6449 
6450   //   -- the class shall not have any virtual base classes;
6451   if (Ctor && ClassDecl->getNumVBases())
6452     return false;
6453 
6454   // C++1y [class.copy]p26:
6455   //   -- [the class] is a literal type, and
6456   if (!Ctor && !ClassDecl->isLiteral())
6457     return false;
6458 
6459   //   -- every constructor involved in initializing [...] base class
6460   //      sub-objects shall be a constexpr constructor;
6461   //   -- the assignment operator selected to copy/move each direct base
6462   //      class is a constexpr function, and
6463   for (const auto &B : ClassDecl->bases()) {
6464     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6465     if (!BaseType) continue;
6466 
6467     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6468     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6469                                   InheritedCtor, Inherited))
6470       return false;
6471   }
6472 
6473   //   -- every constructor involved in initializing non-static data members
6474   //      [...] shall be a constexpr constructor;
6475   //   -- every non-static data member and base class sub-object shall be
6476   //      initialized
6477   //   -- for each non-static data member of X that is of class type (or array
6478   //      thereof), the assignment operator selected to copy/move that member is
6479   //      a constexpr function
6480   for (const auto *F : ClassDecl->fields()) {
6481     if (F->isInvalidDecl())
6482       continue;
6483     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6484       continue;
6485     QualType BaseType = S.Context.getBaseElementType(F->getType());
6486     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6487       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6488       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6489                                     BaseType.getCVRQualifiers(),
6490                                     ConstArg && !F->isMutable()))
6491         return false;
6492     } else if (CSM == Sema::CXXDefaultConstructor) {
6493       return false;
6494     }
6495   }
6496 
6497   // All OK, it's constexpr!
6498   return true;
6499 }
6500 
6501 static Sema::ImplicitExceptionSpecification
6502 ComputeDefaultedSpecialMemberExceptionSpec(
6503     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6504     Sema::InheritedConstructorInfo *ICI);
6505 
6506 static Sema::ImplicitExceptionSpecification
6507 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6508   auto CSM = S.getSpecialMember(MD);
6509   if (CSM != Sema::CXXInvalid)
6510     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6511 
6512   auto *CD = cast<CXXConstructorDecl>(MD);
6513   assert(CD->getInheritedConstructor() &&
6514          "only special members have implicit exception specs");
6515   Sema::InheritedConstructorInfo ICI(
6516       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6517   return ComputeDefaultedSpecialMemberExceptionSpec(
6518       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6519 }
6520 
6521 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6522                                                             CXXMethodDecl *MD) {
6523   FunctionProtoType::ExtProtoInfo EPI;
6524 
6525   // Build an exception specification pointing back at this member.
6526   EPI.ExceptionSpec.Type = EST_Unevaluated;
6527   EPI.ExceptionSpec.SourceDecl = MD;
6528 
6529   // Set the calling convention to the default for C++ instance methods.
6530   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6531       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6532                                             /*IsCXXMethod=*/true));
6533   return EPI;
6534 }
6535 
6536 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6537   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6538   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6539     return;
6540 
6541   // Evaluate the exception specification.
6542   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6543   auto ESI = IES.getExceptionSpec();
6544 
6545   // Update the type of the special member to use it.
6546   UpdateExceptionSpec(MD, ESI);
6547 
6548   // A user-provided destructor can be defined outside the class. When that
6549   // happens, be sure to update the exception specification on both
6550   // declarations.
6551   const FunctionProtoType *CanonicalFPT =
6552     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6553   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6554     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6555 }
6556 
6557 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6558   CXXRecordDecl *RD = MD->getParent();
6559   CXXSpecialMember CSM = getSpecialMember(MD);
6560 
6561   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6562          "not an explicitly-defaulted special member");
6563 
6564   // Whether this was the first-declared instance of the constructor.
6565   // This affects whether we implicitly add an exception spec and constexpr.
6566   bool First = MD == MD->getCanonicalDecl();
6567 
6568   bool HadError = false;
6569 
6570   // C++11 [dcl.fct.def.default]p1:
6571   //   A function that is explicitly defaulted shall
6572   //     -- be a special member function (checked elsewhere),
6573   //     -- have the same type (except for ref-qualifiers, and except that a
6574   //        copy operation can take a non-const reference) as an implicit
6575   //        declaration, and
6576   //     -- not have default arguments.
6577   // C++2a changes the second bullet to instead delete the function if it's
6578   // defaulted on its first declaration, unless it's "an assignment operator,
6579   // and its return type differs or its parameter type is not a reference".
6580   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6581   bool ShouldDeleteForTypeMismatch = false;
6582   unsigned ExpectedParams = 1;
6583   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6584     ExpectedParams = 0;
6585   if (MD->getNumParams() != ExpectedParams) {
6586     // This checks for default arguments: a copy or move constructor with a
6587     // default argument is classified as a default constructor, and assignment
6588     // operations and destructors can't have default arguments.
6589     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6590       << CSM << MD->getSourceRange();
6591     HadError = true;
6592   } else if (MD->isVariadic()) {
6593     if (DeleteOnTypeMismatch)
6594       ShouldDeleteForTypeMismatch = true;
6595     else {
6596       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6597         << CSM << MD->getSourceRange();
6598       HadError = true;
6599     }
6600   }
6601 
6602   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6603 
6604   bool CanHaveConstParam = false;
6605   if (CSM == CXXCopyConstructor)
6606     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6607   else if (CSM == CXXCopyAssignment)
6608     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6609 
6610   QualType ReturnType = Context.VoidTy;
6611   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6612     // Check for return type matching.
6613     ReturnType = Type->getReturnType();
6614 
6615     QualType DeclType = Context.getTypeDeclType(RD);
6616     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
6617     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
6618 
6619     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6620       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6621         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6622       HadError = true;
6623     }
6624 
6625     // A defaulted special member cannot have cv-qualifiers.
6626     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
6627       if (DeleteOnTypeMismatch)
6628         ShouldDeleteForTypeMismatch = true;
6629       else {
6630         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6631           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6632         HadError = true;
6633       }
6634     }
6635   }
6636 
6637   // Check for parameter type matching.
6638   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6639   bool HasConstParam = false;
6640   if (ExpectedParams && ArgType->isReferenceType()) {
6641     // Argument must be reference to possibly-const T.
6642     QualType ReferentType = ArgType->getPointeeType();
6643     HasConstParam = ReferentType.isConstQualified();
6644 
6645     if (ReferentType.isVolatileQualified()) {
6646       if (DeleteOnTypeMismatch)
6647         ShouldDeleteForTypeMismatch = true;
6648       else {
6649         Diag(MD->getLocation(),
6650              diag::err_defaulted_special_member_volatile_param) << CSM;
6651         HadError = true;
6652       }
6653     }
6654 
6655     if (HasConstParam && !CanHaveConstParam) {
6656       if (DeleteOnTypeMismatch)
6657         ShouldDeleteForTypeMismatch = true;
6658       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6659         Diag(MD->getLocation(),
6660              diag::err_defaulted_special_member_copy_const_param)
6661           << (CSM == CXXCopyAssignment);
6662         // FIXME: Explain why this special member can't be const.
6663         HadError = true;
6664       } else {
6665         Diag(MD->getLocation(),
6666              diag::err_defaulted_special_member_move_const_param)
6667           << (CSM == CXXMoveAssignment);
6668         HadError = true;
6669       }
6670     }
6671   } else if (ExpectedParams) {
6672     // A copy assignment operator can take its argument by value, but a
6673     // defaulted one cannot.
6674     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6675     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6676     HadError = true;
6677   }
6678 
6679   // C++11 [dcl.fct.def.default]p2:
6680   //   An explicitly-defaulted function may be declared constexpr only if it
6681   //   would have been implicitly declared as constexpr,
6682   // Do not apply this rule to members of class templates, since core issue 1358
6683   // makes such functions always instantiate to constexpr functions. For
6684   // functions which cannot be constexpr (for non-constructors in C++11 and for
6685   // destructors in C++1y), this is checked elsewhere.
6686   //
6687   // FIXME: This should not apply if the member is deleted.
6688   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6689                                                      HasConstParam);
6690   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6691                                  : isa<CXXConstructorDecl>(MD)) &&
6692       MD->isConstexpr() && !Constexpr &&
6693       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6694     Diag(MD->getBeginLoc(), MD->isConsteval()
6695                                 ? diag::err_incorrect_defaulted_consteval
6696                                 : diag::err_incorrect_defaulted_constexpr)
6697         << CSM;
6698     // FIXME: Explain why the special member can't be constexpr.
6699     HadError = true;
6700   }
6701 
6702   if (First) {
6703     // C++2a [dcl.fct.def.default]p3:
6704     //   If a function is explicitly defaulted on its first declaration, it is
6705     //   implicitly considered to be constexpr if the implicit declaration
6706     //   would be.
6707     MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified);
6708 
6709     if (!Type->hasExceptionSpec()) {
6710       // C++2a [except.spec]p3:
6711       //   If a declaration of a function does not have a noexcept-specifier
6712       //   [and] is defaulted on its first declaration, [...] the exception
6713       //   specification is as specified below
6714       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6715       EPI.ExceptionSpec.Type = EST_Unevaluated;
6716       EPI.ExceptionSpec.SourceDecl = MD;
6717       MD->setType(Context.getFunctionType(ReturnType,
6718                                           llvm::makeArrayRef(&ArgType,
6719                                                              ExpectedParams),
6720                                           EPI));
6721     }
6722   }
6723 
6724   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6725     if (First) {
6726       SetDeclDeleted(MD, MD->getLocation());
6727       if (!inTemplateInstantiation() && !HadError) {
6728         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6729         if (ShouldDeleteForTypeMismatch) {
6730           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6731         } else {
6732           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6733         }
6734       }
6735       if (ShouldDeleteForTypeMismatch && !HadError) {
6736         Diag(MD->getLocation(),
6737              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6738       }
6739     } else {
6740       // C++11 [dcl.fct.def.default]p4:
6741       //   [For a] user-provided explicitly-defaulted function [...] if such a
6742       //   function is implicitly defined as deleted, the program is ill-formed.
6743       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6744       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
6745       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6746       HadError = true;
6747     }
6748   }
6749 
6750   if (HadError)
6751     MD->setInvalidDecl();
6752 }
6753 
6754 void Sema::CheckDelayedMemberExceptionSpecs() {
6755   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6756   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6757 
6758   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6759   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6760 
6761   // Perform any deferred checking of exception specifications for virtual
6762   // destructors.
6763   for (auto &Check : Overriding)
6764     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6765 
6766   // Perform any deferred checking of exception specifications for befriended
6767   // special members.
6768   for (auto &Check : Equivalent)
6769     CheckEquivalentExceptionSpec(Check.second, Check.first);
6770 }
6771 
6772 namespace {
6773 /// CRTP base class for visiting operations performed by a special member
6774 /// function (or inherited constructor).
6775 template<typename Derived>
6776 struct SpecialMemberVisitor {
6777   Sema &S;
6778   CXXMethodDecl *MD;
6779   Sema::CXXSpecialMember CSM;
6780   Sema::InheritedConstructorInfo *ICI;
6781 
6782   // Properties of the special member, computed for convenience.
6783   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6784 
6785   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6786                        Sema::InheritedConstructorInfo *ICI)
6787       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6788     switch (CSM) {
6789     case Sema::CXXDefaultConstructor:
6790     case Sema::CXXCopyConstructor:
6791     case Sema::CXXMoveConstructor:
6792       IsConstructor = true;
6793       break;
6794     case Sema::CXXCopyAssignment:
6795     case Sema::CXXMoveAssignment:
6796       IsAssignment = true;
6797       break;
6798     case Sema::CXXDestructor:
6799       break;
6800     case Sema::CXXInvalid:
6801       llvm_unreachable("invalid special member kind");
6802     }
6803 
6804     if (MD->getNumParams()) {
6805       if (const ReferenceType *RT =
6806               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6807         ConstArg = RT->getPointeeType().isConstQualified();
6808     }
6809   }
6810 
6811   Derived &getDerived() { return static_cast<Derived&>(*this); }
6812 
6813   /// Is this a "move" special member?
6814   bool isMove() const {
6815     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6816   }
6817 
6818   /// Look up the corresponding special member in the given class.
6819   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6820                                              unsigned Quals, bool IsMutable) {
6821     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6822                                        ConstArg && !IsMutable);
6823   }
6824 
6825   /// Look up the constructor for the specified base class to see if it's
6826   /// overridden due to this being an inherited constructor.
6827   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6828     if (!ICI)
6829       return {};
6830     assert(CSM == Sema::CXXDefaultConstructor);
6831     auto *BaseCtor =
6832       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6833     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6834       return MD;
6835     return {};
6836   }
6837 
6838   /// A base or member subobject.
6839   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6840 
6841   /// Get the location to use for a subobject in diagnostics.
6842   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6843     // FIXME: For an indirect virtual base, the direct base leading to
6844     // the indirect virtual base would be a more useful choice.
6845     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6846       return B->getBaseTypeLoc();
6847     else
6848       return Subobj.get<FieldDecl*>()->getLocation();
6849   }
6850 
6851   enum BasesToVisit {
6852     /// Visit all non-virtual (direct) bases.
6853     VisitNonVirtualBases,
6854     /// Visit all direct bases, virtual or not.
6855     VisitDirectBases,
6856     /// Visit all non-virtual bases, and all virtual bases if the class
6857     /// is not abstract.
6858     VisitPotentiallyConstructedBases,
6859     /// Visit all direct or virtual bases.
6860     VisitAllBases
6861   };
6862 
6863   // Visit the bases and members of the class.
6864   bool visit(BasesToVisit Bases) {
6865     CXXRecordDecl *RD = MD->getParent();
6866 
6867     if (Bases == VisitPotentiallyConstructedBases)
6868       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6869 
6870     for (auto &B : RD->bases())
6871       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6872           getDerived().visitBase(&B))
6873         return true;
6874 
6875     if (Bases == VisitAllBases)
6876       for (auto &B : RD->vbases())
6877         if (getDerived().visitBase(&B))
6878           return true;
6879 
6880     for (auto *F : RD->fields())
6881       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6882           getDerived().visitField(F))
6883         return true;
6884 
6885     return false;
6886   }
6887 };
6888 }
6889 
6890 namespace {
6891 struct SpecialMemberDeletionInfo
6892     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6893   bool Diagnose;
6894 
6895   SourceLocation Loc;
6896 
6897   bool AllFieldsAreConst;
6898 
6899   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6900                             Sema::CXXSpecialMember CSM,
6901                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6902       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6903         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6904 
6905   bool inUnion() const { return MD->getParent()->isUnion(); }
6906 
6907   Sema::CXXSpecialMember getEffectiveCSM() {
6908     return ICI ? Sema::CXXInvalid : CSM;
6909   }
6910 
6911   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
6912 
6913   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6914   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6915 
6916   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6917   bool shouldDeleteForField(FieldDecl *FD);
6918   bool shouldDeleteForAllConstMembers();
6919 
6920   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6921                                      unsigned Quals);
6922   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6923                                     Sema::SpecialMemberOverloadResult SMOR,
6924                                     bool IsDtorCallInCtor);
6925 
6926   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6927 };
6928 }
6929 
6930 /// Is the given special member inaccessible when used on the given
6931 /// sub-object.
6932 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6933                                              CXXMethodDecl *target) {
6934   /// If we're operating on a base class, the object type is the
6935   /// type of this special member.
6936   QualType objectTy;
6937   AccessSpecifier access = target->getAccess();
6938   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6939     objectTy = S.Context.getTypeDeclType(MD->getParent());
6940     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6941 
6942   // If we're operating on a field, the object type is the type of the field.
6943   } else {
6944     objectTy = S.Context.getTypeDeclType(target->getParent());
6945   }
6946 
6947   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6948 }
6949 
6950 /// Check whether we should delete a special member due to the implicit
6951 /// definition containing a call to a special member of a subobject.
6952 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6953     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6954     bool IsDtorCallInCtor) {
6955   CXXMethodDecl *Decl = SMOR.getMethod();
6956   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6957 
6958   int DiagKind = -1;
6959 
6960   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6961     DiagKind = !Decl ? 0 : 1;
6962   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6963     DiagKind = 2;
6964   else if (!isAccessible(Subobj, Decl))
6965     DiagKind = 3;
6966   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6967            !Decl->isTrivial()) {
6968     // A member of a union must have a trivial corresponding special member.
6969     // As a weird special case, a destructor call from a union's constructor
6970     // must be accessible and non-deleted, but need not be trivial. Such a
6971     // destructor is never actually called, but is semantically checked as
6972     // if it were.
6973     DiagKind = 4;
6974   }
6975 
6976   if (DiagKind == -1)
6977     return false;
6978 
6979   if (Diagnose) {
6980     if (Field) {
6981       S.Diag(Field->getLocation(),
6982              diag::note_deleted_special_member_class_subobject)
6983         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6984         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
6985     } else {
6986       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6987       S.Diag(Base->getBeginLoc(),
6988              diag::note_deleted_special_member_class_subobject)
6989           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6990           << Base->getType() << DiagKind << IsDtorCallInCtor
6991           << /*IsObjCPtr*/false;
6992     }
6993 
6994     if (DiagKind == 1)
6995       S.NoteDeletedFunction(Decl);
6996     // FIXME: Explain inaccessibility if DiagKind == 3.
6997   }
6998 
6999   return true;
7000 }
7001 
7002 /// Check whether we should delete a special member function due to having a
7003 /// direct or virtual base class or non-static data member of class type M.
7004 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
7005     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
7006   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
7007   bool IsMutable = Field && Field->isMutable();
7008 
7009   // C++11 [class.ctor]p5:
7010   // -- any direct or virtual base class, or non-static data member with no
7011   //    brace-or-equal-initializer, has class type M (or array thereof) and
7012   //    either M has no default constructor or overload resolution as applied
7013   //    to M's default constructor results in an ambiguity or in a function
7014   //    that is deleted or inaccessible
7015   // C++11 [class.copy]p11, C++11 [class.copy]p23:
7016   // -- a direct or virtual base class B that cannot be copied/moved because
7017   //    overload resolution, as applied to B's corresponding special member,
7018   //    results in an ambiguity or a function that is deleted or inaccessible
7019   //    from the defaulted special member
7020   // C++11 [class.dtor]p5:
7021   // -- any direct or virtual base class [...] has a type with a destructor
7022   //    that is deleted or inaccessible
7023   if (!(CSM == Sema::CXXDefaultConstructor &&
7024         Field && Field->hasInClassInitializer()) &&
7025       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
7026                                    false))
7027     return true;
7028 
7029   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
7030   // -- any direct or virtual base class or non-static data member has a
7031   //    type with a destructor that is deleted or inaccessible
7032   if (IsConstructor) {
7033     Sema::SpecialMemberOverloadResult SMOR =
7034         S.LookupSpecialMember(Class, Sema::CXXDestructor,
7035                               false, false, false, false, false);
7036     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
7037       return true;
7038   }
7039 
7040   return false;
7041 }
7042 
7043 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
7044     FieldDecl *FD, QualType FieldType) {
7045   // The defaulted special functions are defined as deleted if this is a variant
7046   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
7047   // type under ARC.
7048   if (!FieldType.hasNonTrivialObjCLifetime())
7049     return false;
7050 
7051   // Don't make the defaulted default constructor defined as deleted if the
7052   // member has an in-class initializer.
7053   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
7054     return false;
7055 
7056   if (Diagnose) {
7057     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
7058     S.Diag(FD->getLocation(),
7059            diag::note_deleted_special_member_class_subobject)
7060         << getEffectiveCSM() << ParentClass << /*IsField*/true
7061         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
7062   }
7063 
7064   return true;
7065 }
7066 
7067 /// Check whether we should delete a special member function due to the class
7068 /// having a particular direct or virtual base class.
7069 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
7070   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
7071   // If program is correct, BaseClass cannot be null, but if it is, the error
7072   // must be reported elsewhere.
7073   if (!BaseClass)
7074     return false;
7075   // If we have an inheriting constructor, check whether we're calling an
7076   // inherited constructor instead of a default constructor.
7077   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
7078   if (auto *BaseCtor = SMOR.getMethod()) {
7079     // Note that we do not check access along this path; other than that,
7080     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
7081     // FIXME: Check that the base has a usable destructor! Sink this into
7082     // shouldDeleteForClassSubobject.
7083     if (BaseCtor->isDeleted() && Diagnose) {
7084       S.Diag(Base->getBeginLoc(),
7085              diag::note_deleted_special_member_class_subobject)
7086           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7087           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
7088           << /*IsObjCPtr*/false;
7089       S.NoteDeletedFunction(BaseCtor);
7090     }
7091     return BaseCtor->isDeleted();
7092   }
7093   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7094 }
7095 
7096 /// Check whether we should delete a special member function due to the class
7097 /// having a particular non-static data member.
7098 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7099   QualType FieldType = S.Context.getBaseElementType(FD->getType());
7100   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7101 
7102   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
7103     return true;
7104 
7105   if (CSM == Sema::CXXDefaultConstructor) {
7106     // For a default constructor, all references must be initialized in-class
7107     // and, if a union, it must have a non-const member.
7108     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7109       if (Diagnose)
7110         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7111           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7112       return true;
7113     }
7114     // C++11 [class.ctor]p5: any non-variant non-static data member of
7115     // const-qualified type (or array thereof) with no
7116     // brace-or-equal-initializer does not have a user-provided default
7117     // constructor.
7118     if (!inUnion() && FieldType.isConstQualified() &&
7119         !FD->hasInClassInitializer() &&
7120         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7121       if (Diagnose)
7122         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7123           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7124       return true;
7125     }
7126 
7127     if (inUnion() && !FieldType.isConstQualified())
7128       AllFieldsAreConst = false;
7129   } else if (CSM == Sema::CXXCopyConstructor) {
7130     // For a copy constructor, data members must not be of rvalue reference
7131     // type.
7132     if (FieldType->isRValueReferenceType()) {
7133       if (Diagnose)
7134         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7135           << MD->getParent() << FD << FieldType;
7136       return true;
7137     }
7138   } else if (IsAssignment) {
7139     // For an assignment operator, data members must not be of reference type.
7140     if (FieldType->isReferenceType()) {
7141       if (Diagnose)
7142         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7143           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7144       return true;
7145     }
7146     if (!FieldRecord && FieldType.isConstQualified()) {
7147       // C++11 [class.copy]p23:
7148       // -- a non-static data member of const non-class type (or array thereof)
7149       if (Diagnose)
7150         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7151           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7152       return true;
7153     }
7154   }
7155 
7156   if (FieldRecord) {
7157     // Some additional restrictions exist on the variant members.
7158     if (!inUnion() && FieldRecord->isUnion() &&
7159         FieldRecord->isAnonymousStructOrUnion()) {
7160       bool AllVariantFieldsAreConst = true;
7161 
7162       // FIXME: Handle anonymous unions declared within anonymous unions.
7163       for (auto *UI : FieldRecord->fields()) {
7164         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7165 
7166         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
7167           return true;
7168 
7169         if (!UnionFieldType.isConstQualified())
7170           AllVariantFieldsAreConst = false;
7171 
7172         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7173         if (UnionFieldRecord &&
7174             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7175                                           UnionFieldType.getCVRQualifiers()))
7176           return true;
7177       }
7178 
7179       // At least one member in each anonymous union must be non-const
7180       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7181           !FieldRecord->field_empty()) {
7182         if (Diagnose)
7183           S.Diag(FieldRecord->getLocation(),
7184                  diag::note_deleted_default_ctor_all_const)
7185             << !!ICI << MD->getParent() << /*anonymous union*/1;
7186         return true;
7187       }
7188 
7189       // Don't check the implicit member of the anonymous union type.
7190       // This is technically non-conformant, but sanity demands it.
7191       return false;
7192     }
7193 
7194     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7195                                       FieldType.getCVRQualifiers()))
7196       return true;
7197   }
7198 
7199   return false;
7200 }
7201 
7202 /// C++11 [class.ctor] p5:
7203 ///   A defaulted default constructor for a class X is defined as deleted if
7204 /// X is a union and all of its variant members are of const-qualified type.
7205 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7206   // This is a silly definition, because it gives an empty union a deleted
7207   // default constructor. Don't do that.
7208   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7209     bool AnyFields = false;
7210     for (auto *F : MD->getParent()->fields())
7211       if ((AnyFields = !F->isUnnamedBitfield()))
7212         break;
7213     if (!AnyFields)
7214       return false;
7215     if (Diagnose)
7216       S.Diag(MD->getParent()->getLocation(),
7217              diag::note_deleted_default_ctor_all_const)
7218         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7219     return true;
7220   }
7221   return false;
7222 }
7223 
7224 /// Determine whether a defaulted special member function should be defined as
7225 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7226 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7227 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7228                                      InheritedConstructorInfo *ICI,
7229                                      bool Diagnose) {
7230   if (MD->isInvalidDecl())
7231     return false;
7232   CXXRecordDecl *RD = MD->getParent();
7233   assert(!RD->isDependentType() && "do deletion after instantiation");
7234   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7235     return false;
7236 
7237   // C++11 [expr.lambda.prim]p19:
7238   //   The closure type associated with a lambda-expression has a
7239   //   deleted (8.4.3) default constructor and a deleted copy
7240   //   assignment operator.
7241   // C++2a adds back these operators if the lambda has no lambda-capture.
7242   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7243       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7244     if (Diagnose)
7245       Diag(RD->getLocation(), diag::note_lambda_decl);
7246     return true;
7247   }
7248 
7249   // For an anonymous struct or union, the copy and assignment special members
7250   // will never be used, so skip the check. For an anonymous union declared at
7251   // namespace scope, the constructor and destructor are used.
7252   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7253       RD->isAnonymousStructOrUnion())
7254     return false;
7255 
7256   // C++11 [class.copy]p7, p18:
7257   //   If the class definition declares a move constructor or move assignment
7258   //   operator, an implicitly declared copy constructor or copy assignment
7259   //   operator is defined as deleted.
7260   if (MD->isImplicit() &&
7261       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7262     CXXMethodDecl *UserDeclaredMove = nullptr;
7263 
7264     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7265     // deletion of the corresponding copy operation, not both copy operations.
7266     // MSVC 2015 has adopted the standards conforming behavior.
7267     bool DeletesOnlyMatchingCopy =
7268         getLangOpts().MSVCCompat &&
7269         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7270 
7271     if (RD->hasUserDeclaredMoveConstructor() &&
7272         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7273       if (!Diagnose) return true;
7274 
7275       // Find any user-declared move constructor.
7276       for (auto *I : RD->ctors()) {
7277         if (I->isMoveConstructor()) {
7278           UserDeclaredMove = I;
7279           break;
7280         }
7281       }
7282       assert(UserDeclaredMove);
7283     } else if (RD->hasUserDeclaredMoveAssignment() &&
7284                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7285       if (!Diagnose) return true;
7286 
7287       // Find any user-declared move assignment operator.
7288       for (auto *I : RD->methods()) {
7289         if (I->isMoveAssignmentOperator()) {
7290           UserDeclaredMove = I;
7291           break;
7292         }
7293       }
7294       assert(UserDeclaredMove);
7295     }
7296 
7297     if (UserDeclaredMove) {
7298       Diag(UserDeclaredMove->getLocation(),
7299            diag::note_deleted_copy_user_declared_move)
7300         << (CSM == CXXCopyAssignment) << RD
7301         << UserDeclaredMove->isMoveAssignmentOperator();
7302       return true;
7303     }
7304   }
7305 
7306   // Do access control from the special member function
7307   ContextRAII MethodContext(*this, MD);
7308 
7309   // C++11 [class.dtor]p5:
7310   // -- for a virtual destructor, lookup of the non-array deallocation function
7311   //    results in an ambiguity or in a function that is deleted or inaccessible
7312   if (CSM == CXXDestructor && MD->isVirtual()) {
7313     FunctionDecl *OperatorDelete = nullptr;
7314     DeclarationName Name =
7315       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7316     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7317                                  OperatorDelete, /*Diagnose*/false)) {
7318       if (Diagnose)
7319         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7320       return true;
7321     }
7322   }
7323 
7324   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7325 
7326   // Per DR1611, do not consider virtual bases of constructors of abstract
7327   // classes, since we are not going to construct them.
7328   // Per DR1658, do not consider virtual bases of destructors of abstract
7329   // classes either.
7330   // Per DR2180, for assignment operators we only assign (and thus only
7331   // consider) direct bases.
7332   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7333                                  : SMI.VisitPotentiallyConstructedBases))
7334     return true;
7335 
7336   if (SMI.shouldDeleteForAllConstMembers())
7337     return true;
7338 
7339   if (getLangOpts().CUDA) {
7340     // We should delete the special member in CUDA mode if target inference
7341     // failed.
7342     // For inherited constructors (non-null ICI), CSM may be passed so that MD
7343     // is treated as certain special member, which may not reflect what special
7344     // member MD really is. However inferCUDATargetForImplicitSpecialMember
7345     // expects CSM to match MD, therefore recalculate CSM.
7346     assert(ICI || CSM == getSpecialMember(MD));
7347     auto RealCSM = CSM;
7348     if (ICI)
7349       RealCSM = getSpecialMember(MD);
7350 
7351     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7352                                                    SMI.ConstArg, Diagnose);
7353   }
7354 
7355   return false;
7356 }
7357 
7358 /// Perform lookup for a special member of the specified kind, and determine
7359 /// whether it is trivial. If the triviality can be determined without the
7360 /// lookup, skip it. This is intended for use when determining whether a
7361 /// special member of a containing object is trivial, and thus does not ever
7362 /// perform overload resolution for default constructors.
7363 ///
7364 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7365 /// member that was most likely to be intended to be trivial, if any.
7366 ///
7367 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7368 /// determine whether the special member is trivial.
7369 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7370                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7371                                      bool ConstRHS,
7372                                      Sema::TrivialABIHandling TAH,
7373                                      CXXMethodDecl **Selected) {
7374   if (Selected)
7375     *Selected = nullptr;
7376 
7377   switch (CSM) {
7378   case Sema::CXXInvalid:
7379     llvm_unreachable("not a special member");
7380 
7381   case Sema::CXXDefaultConstructor:
7382     // C++11 [class.ctor]p5:
7383     //   A default constructor is trivial if:
7384     //    - all the [direct subobjects] have trivial default constructors
7385     //
7386     // Note, no overload resolution is performed in this case.
7387     if (RD->hasTrivialDefaultConstructor())
7388       return true;
7389 
7390     if (Selected) {
7391       // If there's a default constructor which could have been trivial, dig it
7392       // out. Otherwise, if there's any user-provided default constructor, point
7393       // to that as an example of why there's not a trivial one.
7394       CXXConstructorDecl *DefCtor = nullptr;
7395       if (RD->needsImplicitDefaultConstructor())
7396         S.DeclareImplicitDefaultConstructor(RD);
7397       for (auto *CI : RD->ctors()) {
7398         if (!CI->isDefaultConstructor())
7399           continue;
7400         DefCtor = CI;
7401         if (!DefCtor->isUserProvided())
7402           break;
7403       }
7404 
7405       *Selected = DefCtor;
7406     }
7407 
7408     return false;
7409 
7410   case Sema::CXXDestructor:
7411     // C++11 [class.dtor]p5:
7412     //   A destructor is trivial if:
7413     //    - all the direct [subobjects] have trivial destructors
7414     if (RD->hasTrivialDestructor() ||
7415         (TAH == Sema::TAH_ConsiderTrivialABI &&
7416          RD->hasTrivialDestructorForCall()))
7417       return true;
7418 
7419     if (Selected) {
7420       if (RD->needsImplicitDestructor())
7421         S.DeclareImplicitDestructor(RD);
7422       *Selected = RD->getDestructor();
7423     }
7424 
7425     return false;
7426 
7427   case Sema::CXXCopyConstructor:
7428     // C++11 [class.copy]p12:
7429     //   A copy constructor is trivial if:
7430     //    - the constructor selected to copy each direct [subobject] is trivial
7431     if (RD->hasTrivialCopyConstructor() ||
7432         (TAH == Sema::TAH_ConsiderTrivialABI &&
7433          RD->hasTrivialCopyConstructorForCall())) {
7434       if (Quals == Qualifiers::Const)
7435         // We must either select the trivial copy constructor or reach an
7436         // ambiguity; no need to actually perform overload resolution.
7437         return true;
7438     } else if (!Selected) {
7439       return false;
7440     }
7441     // In C++98, we are not supposed to perform overload resolution here, but we
7442     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7443     // cases like B as having a non-trivial copy constructor:
7444     //   struct A { template<typename T> A(T&); };
7445     //   struct B { mutable A a; };
7446     goto NeedOverloadResolution;
7447 
7448   case Sema::CXXCopyAssignment:
7449     // C++11 [class.copy]p25:
7450     //   A copy assignment operator is trivial if:
7451     //    - the assignment operator selected to copy each direct [subobject] is
7452     //      trivial
7453     if (RD->hasTrivialCopyAssignment()) {
7454       if (Quals == Qualifiers::Const)
7455         return true;
7456     } else if (!Selected) {
7457       return false;
7458     }
7459     // In C++98, we are not supposed to perform overload resolution here, but we
7460     // treat that as a language defect.
7461     goto NeedOverloadResolution;
7462 
7463   case Sema::CXXMoveConstructor:
7464   case Sema::CXXMoveAssignment:
7465   NeedOverloadResolution:
7466     Sema::SpecialMemberOverloadResult SMOR =
7467         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7468 
7469     // The standard doesn't describe how to behave if the lookup is ambiguous.
7470     // We treat it as not making the member non-trivial, just like the standard
7471     // mandates for the default constructor. This should rarely matter, because
7472     // the member will also be deleted.
7473     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7474       return true;
7475 
7476     if (!SMOR.getMethod()) {
7477       assert(SMOR.getKind() ==
7478              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7479       return false;
7480     }
7481 
7482     // We deliberately don't check if we found a deleted special member. We're
7483     // not supposed to!
7484     if (Selected)
7485       *Selected = SMOR.getMethod();
7486 
7487     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7488         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7489       return SMOR.getMethod()->isTrivialForCall();
7490     return SMOR.getMethod()->isTrivial();
7491   }
7492 
7493   llvm_unreachable("unknown special method kind");
7494 }
7495 
7496 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7497   for (auto *CI : RD->ctors())
7498     if (!CI->isImplicit())
7499       return CI;
7500 
7501   // Look for constructor templates.
7502   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7503   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7504     if (CXXConstructorDecl *CD =
7505           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7506       return CD;
7507   }
7508 
7509   return nullptr;
7510 }
7511 
7512 /// The kind of subobject we are checking for triviality. The values of this
7513 /// enumeration are used in diagnostics.
7514 enum TrivialSubobjectKind {
7515   /// The subobject is a base class.
7516   TSK_BaseClass,
7517   /// The subobject is a non-static data member.
7518   TSK_Field,
7519   /// The object is actually the complete object.
7520   TSK_CompleteObject
7521 };
7522 
7523 /// Check whether the special member selected for a given type would be trivial.
7524 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7525                                       QualType SubType, bool ConstRHS,
7526                                       Sema::CXXSpecialMember CSM,
7527                                       TrivialSubobjectKind Kind,
7528                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7529   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7530   if (!SubRD)
7531     return true;
7532 
7533   CXXMethodDecl *Selected;
7534   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7535                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7536     return true;
7537 
7538   if (Diagnose) {
7539     if (ConstRHS)
7540       SubType.addConst();
7541 
7542     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7543       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7544         << Kind << SubType.getUnqualifiedType();
7545       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7546         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7547     } else if (!Selected)
7548       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7549         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7550     else if (Selected->isUserProvided()) {
7551       if (Kind == TSK_CompleteObject)
7552         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7553           << Kind << SubType.getUnqualifiedType() << CSM;
7554       else {
7555         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7556           << Kind << SubType.getUnqualifiedType() << CSM;
7557         S.Diag(Selected->getLocation(), diag::note_declared_at);
7558       }
7559     } else {
7560       if (Kind != TSK_CompleteObject)
7561         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7562           << Kind << SubType.getUnqualifiedType() << CSM;
7563 
7564       // Explain why the defaulted or deleted special member isn't trivial.
7565       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7566                                Diagnose);
7567     }
7568   }
7569 
7570   return false;
7571 }
7572 
7573 /// Check whether the members of a class type allow a special member to be
7574 /// trivial.
7575 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7576                                      Sema::CXXSpecialMember CSM,
7577                                      bool ConstArg,
7578                                      Sema::TrivialABIHandling TAH,
7579                                      bool Diagnose) {
7580   for (const auto *FI : RD->fields()) {
7581     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7582       continue;
7583 
7584     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7585 
7586     // Pretend anonymous struct or union members are members of this class.
7587     if (FI->isAnonymousStructOrUnion()) {
7588       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7589                                     CSM, ConstArg, TAH, Diagnose))
7590         return false;
7591       continue;
7592     }
7593 
7594     // C++11 [class.ctor]p5:
7595     //   A default constructor is trivial if [...]
7596     //    -- no non-static data member of its class has a
7597     //       brace-or-equal-initializer
7598     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7599       if (Diagnose)
7600         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7601       return false;
7602     }
7603 
7604     // Objective C ARC 4.3.5:
7605     //   [...] nontrivally ownership-qualified types are [...] not trivially
7606     //   default constructible, copy constructible, move constructible, copy
7607     //   assignable, move assignable, or destructible [...]
7608     if (FieldType.hasNonTrivialObjCLifetime()) {
7609       if (Diagnose)
7610         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7611           << RD << FieldType.getObjCLifetime();
7612       return false;
7613     }
7614 
7615     bool ConstRHS = ConstArg && !FI->isMutable();
7616     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7617                                    CSM, TSK_Field, TAH, Diagnose))
7618       return false;
7619   }
7620 
7621   return true;
7622 }
7623 
7624 /// Diagnose why the specified class does not have a trivial special member of
7625 /// the given kind.
7626 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7627   QualType Ty = Context.getRecordType(RD);
7628 
7629   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7630   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7631                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7632                             /*Diagnose*/true);
7633 }
7634 
7635 /// Determine whether a defaulted or deleted special member function is trivial,
7636 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7637 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7638 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7639                                   TrivialABIHandling TAH, bool Diagnose) {
7640   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7641 
7642   CXXRecordDecl *RD = MD->getParent();
7643 
7644   bool ConstArg = false;
7645 
7646   // C++11 [class.copy]p12, p25: [DR1593]
7647   //   A [special member] is trivial if [...] its parameter-type-list is
7648   //   equivalent to the parameter-type-list of an implicit declaration [...]
7649   switch (CSM) {
7650   case CXXDefaultConstructor:
7651   case CXXDestructor:
7652     // Trivial default constructors and destructors cannot have parameters.
7653     break;
7654 
7655   case CXXCopyConstructor:
7656   case CXXCopyAssignment: {
7657     // Trivial copy operations always have const, non-volatile parameter types.
7658     ConstArg = true;
7659     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7660     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7661     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7662       if (Diagnose)
7663         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7664           << Param0->getSourceRange() << Param0->getType()
7665           << Context.getLValueReferenceType(
7666                Context.getRecordType(RD).withConst());
7667       return false;
7668     }
7669     break;
7670   }
7671 
7672   case CXXMoveConstructor:
7673   case CXXMoveAssignment: {
7674     // Trivial move operations always have non-cv-qualified parameters.
7675     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7676     const RValueReferenceType *RT =
7677       Param0->getType()->getAs<RValueReferenceType>();
7678     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7679       if (Diagnose)
7680         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7681           << Param0->getSourceRange() << Param0->getType()
7682           << Context.getRValueReferenceType(Context.getRecordType(RD));
7683       return false;
7684     }
7685     break;
7686   }
7687 
7688   case CXXInvalid:
7689     llvm_unreachable("not a special member");
7690   }
7691 
7692   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7693     if (Diagnose)
7694       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7695            diag::note_nontrivial_default_arg)
7696         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7697     return false;
7698   }
7699   if (MD->isVariadic()) {
7700     if (Diagnose)
7701       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7702     return false;
7703   }
7704 
7705   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7706   //   A copy/move [constructor or assignment operator] is trivial if
7707   //    -- the [member] selected to copy/move each direct base class subobject
7708   //       is trivial
7709   //
7710   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7711   //   A [default constructor or destructor] is trivial if
7712   //    -- all the direct base classes have trivial [default constructors or
7713   //       destructors]
7714   for (const auto &BI : RD->bases())
7715     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7716                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7717       return false;
7718 
7719   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7720   //   A copy/move [constructor or assignment operator] for a class X is
7721   //   trivial if
7722   //    -- for each non-static data member of X that is of class type (or array
7723   //       thereof), the constructor selected to copy/move that member is
7724   //       trivial
7725   //
7726   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7727   //   A [default constructor or destructor] is trivial if
7728   //    -- for all of the non-static data members of its class that are of class
7729   //       type (or array thereof), each such class has a trivial [default
7730   //       constructor or destructor]
7731   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7732     return false;
7733 
7734   // C++11 [class.dtor]p5:
7735   //   A destructor is trivial if [...]
7736   //    -- the destructor is not virtual
7737   if (CSM == CXXDestructor && MD->isVirtual()) {
7738     if (Diagnose)
7739       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7740     return false;
7741   }
7742 
7743   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7744   //   A [special member] for class X is trivial if [...]
7745   //    -- class X has no virtual functions and no virtual base classes
7746   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7747     if (!Diagnose)
7748       return false;
7749 
7750     if (RD->getNumVBases()) {
7751       // Check for virtual bases. We already know that the corresponding
7752       // member in all bases is trivial, so vbases must all be direct.
7753       CXXBaseSpecifier &BS = *RD->vbases_begin();
7754       assert(BS.isVirtual());
7755       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7756       return false;
7757     }
7758 
7759     // Must have a virtual method.
7760     for (const auto *MI : RD->methods()) {
7761       if (MI->isVirtual()) {
7762         SourceLocation MLoc = MI->getBeginLoc();
7763         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7764         return false;
7765       }
7766     }
7767 
7768     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7769   }
7770 
7771   // Looks like it's trivial!
7772   return true;
7773 }
7774 
7775 namespace {
7776 struct FindHiddenVirtualMethod {
7777   Sema *S;
7778   CXXMethodDecl *Method;
7779   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7780   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7781 
7782 private:
7783   /// Check whether any most overridden method from MD in Methods
7784   static bool CheckMostOverridenMethods(
7785       const CXXMethodDecl *MD,
7786       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7787     if (MD->size_overridden_methods() == 0)
7788       return Methods.count(MD->getCanonicalDecl());
7789     for (const CXXMethodDecl *O : MD->overridden_methods())
7790       if (CheckMostOverridenMethods(O, Methods))
7791         return true;
7792     return false;
7793   }
7794 
7795 public:
7796   /// Member lookup function that determines whether a given C++
7797   /// method overloads virtual methods in a base class without overriding any,
7798   /// to be used with CXXRecordDecl::lookupInBases().
7799   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7800     RecordDecl *BaseRecord =
7801         Specifier->getType()->getAs<RecordType>()->getDecl();
7802 
7803     DeclarationName Name = Method->getDeclName();
7804     assert(Name.getNameKind() == DeclarationName::Identifier);
7805 
7806     bool foundSameNameMethod = false;
7807     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7808     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7809          Path.Decls = Path.Decls.slice(1)) {
7810       NamedDecl *D = Path.Decls.front();
7811       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7812         MD = MD->getCanonicalDecl();
7813         foundSameNameMethod = true;
7814         // Interested only in hidden virtual methods.
7815         if (!MD->isVirtual())
7816           continue;
7817         // If the method we are checking overrides a method from its base
7818         // don't warn about the other overloaded methods. Clang deviates from
7819         // GCC by only diagnosing overloads of inherited virtual functions that
7820         // do not override any other virtual functions in the base. GCC's
7821         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7822         // function from a base class. These cases may be better served by a
7823         // warning (not specific to virtual functions) on call sites when the
7824         // call would select a different function from the base class, were it
7825         // visible.
7826         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7827         if (!S->IsOverload(Method, MD, false))
7828           return true;
7829         // Collect the overload only if its hidden.
7830         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7831           overloadedMethods.push_back(MD);
7832       }
7833     }
7834 
7835     if (foundSameNameMethod)
7836       OverloadedMethods.append(overloadedMethods.begin(),
7837                                overloadedMethods.end());
7838     return foundSameNameMethod;
7839   }
7840 };
7841 } // end anonymous namespace
7842 
7843 /// Add the most overriden methods from MD to Methods
7844 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7845                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7846   if (MD->size_overridden_methods() == 0)
7847     Methods.insert(MD->getCanonicalDecl());
7848   else
7849     for (const CXXMethodDecl *O : MD->overridden_methods())
7850       AddMostOverridenMethods(O, Methods);
7851 }
7852 
7853 /// Check if a method overloads virtual methods in a base class without
7854 /// overriding any.
7855 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7856                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7857   if (!MD->getDeclName().isIdentifier())
7858     return;
7859 
7860   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7861                      /*bool RecordPaths=*/false,
7862                      /*bool DetectVirtual=*/false);
7863   FindHiddenVirtualMethod FHVM;
7864   FHVM.Method = MD;
7865   FHVM.S = this;
7866 
7867   // Keep the base methods that were overridden or introduced in the subclass
7868   // by 'using' in a set. A base method not in this set is hidden.
7869   CXXRecordDecl *DC = MD->getParent();
7870   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7871   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7872     NamedDecl *ND = *I;
7873     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7874       ND = shad->getTargetDecl();
7875     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7876       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7877   }
7878 
7879   if (DC->lookupInBases(FHVM, Paths))
7880     OverloadedMethods = FHVM.OverloadedMethods;
7881 }
7882 
7883 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7884                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7885   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7886     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7887     PartialDiagnostic PD = PDiag(
7888          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7889     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7890     Diag(overloadedMD->getLocation(), PD);
7891   }
7892 }
7893 
7894 /// Diagnose methods which overload virtual methods in a base class
7895 /// without overriding any.
7896 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7897   if (MD->isInvalidDecl())
7898     return;
7899 
7900   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7901     return;
7902 
7903   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7904   FindHiddenVirtualMethods(MD, OverloadedMethods);
7905   if (!OverloadedMethods.empty()) {
7906     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7907       << MD << (OverloadedMethods.size() > 1);
7908 
7909     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7910   }
7911 }
7912 
7913 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7914   auto PrintDiagAndRemoveAttr = [&]() {
7915     // No diagnostics if this is a template instantiation.
7916     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7917       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7918            diag::ext_cannot_use_trivial_abi) << &RD;
7919     RD.dropAttr<TrivialABIAttr>();
7920   };
7921 
7922   // Ill-formed if the struct has virtual functions.
7923   if (RD.isPolymorphic()) {
7924     PrintDiagAndRemoveAttr();
7925     return;
7926   }
7927 
7928   for (const auto &B : RD.bases()) {
7929     // Ill-formed if the base class is non-trivial for the purpose of calls or a
7930     // virtual base.
7931     if ((!B.getType()->isDependentType() &&
7932          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7933         B.isVirtual()) {
7934       PrintDiagAndRemoveAttr();
7935       return;
7936     }
7937   }
7938 
7939   for (const auto *FD : RD.fields()) {
7940     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7941     // non-trivial for the purpose of calls.
7942     QualType FT = FD->getType();
7943     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7944       PrintDiagAndRemoveAttr();
7945       return;
7946     }
7947 
7948     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7949       if (!RT->isDependentType() &&
7950           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7951         PrintDiagAndRemoveAttr();
7952         return;
7953       }
7954   }
7955 }
7956 
7957 void Sema::ActOnFinishCXXMemberSpecification(
7958     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
7959     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
7960   if (!TagDecl)
7961     return;
7962 
7963   AdjustDeclIfTemplate(TagDecl);
7964 
7965   for (const ParsedAttr &AL : AttrList) {
7966     if (AL.getKind() != ParsedAttr::AT_Visibility)
7967       continue;
7968     AL.setInvalid();
7969     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
7970         << AL.getName();
7971   }
7972 
7973   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7974               // strict aliasing violation!
7975               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7976               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7977 
7978   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7979 }
7980 
7981 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7982 /// special functions, such as the default constructor, copy
7983 /// constructor, or destructor, to the given C++ class (C++
7984 /// [special]p1).  This routine can only be executed just before the
7985 /// definition of the class is complete.
7986 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7987   if (ClassDecl->needsImplicitDefaultConstructor()) {
7988     ++getASTContext().NumImplicitDefaultConstructors;
7989 
7990     if (ClassDecl->hasInheritedConstructor())
7991       DeclareImplicitDefaultConstructor(ClassDecl);
7992   }
7993 
7994   if (ClassDecl->needsImplicitCopyConstructor()) {
7995     ++getASTContext().NumImplicitCopyConstructors;
7996 
7997     // If the properties or semantics of the copy constructor couldn't be
7998     // determined while the class was being declared, force a declaration
7999     // of it now.
8000     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
8001         ClassDecl->hasInheritedConstructor())
8002       DeclareImplicitCopyConstructor(ClassDecl);
8003     // For the MS ABI we need to know whether the copy ctor is deleted. A
8004     // prerequisite for deleting the implicit copy ctor is that the class has a
8005     // move ctor or move assignment that is either user-declared or whose
8006     // semantics are inherited from a subobject. FIXME: We should provide a more
8007     // direct way for CodeGen to ask whether the constructor was deleted.
8008     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8009              (ClassDecl->hasUserDeclaredMoveConstructor() ||
8010               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8011               ClassDecl->hasUserDeclaredMoveAssignment() ||
8012               ClassDecl->needsOverloadResolutionForMoveAssignment()))
8013       DeclareImplicitCopyConstructor(ClassDecl);
8014   }
8015 
8016   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
8017     ++getASTContext().NumImplicitMoveConstructors;
8018 
8019     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8020         ClassDecl->hasInheritedConstructor())
8021       DeclareImplicitMoveConstructor(ClassDecl);
8022   }
8023 
8024   if (ClassDecl->needsImplicitCopyAssignment()) {
8025     ++getASTContext().NumImplicitCopyAssignmentOperators;
8026 
8027     // If we have a dynamic class, then the copy assignment operator may be
8028     // virtual, so we have to declare it immediately. This ensures that, e.g.,
8029     // it shows up in the right place in the vtable and that we diagnose
8030     // problems with the implicit exception specification.
8031     if (ClassDecl->isDynamicClass() ||
8032         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
8033         ClassDecl->hasInheritedAssignment())
8034       DeclareImplicitCopyAssignment(ClassDecl);
8035   }
8036 
8037   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
8038     ++getASTContext().NumImplicitMoveAssignmentOperators;
8039 
8040     // Likewise for the move assignment operator.
8041     if (ClassDecl->isDynamicClass() ||
8042         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
8043         ClassDecl->hasInheritedAssignment())
8044       DeclareImplicitMoveAssignment(ClassDecl);
8045   }
8046 
8047   if (ClassDecl->needsImplicitDestructor()) {
8048     ++getASTContext().NumImplicitDestructors;
8049 
8050     // If we have a dynamic class, then the destructor may be virtual, so we
8051     // have to declare the destructor immediately. This ensures that, e.g., it
8052     // shows up in the right place in the vtable and that we diagnose problems
8053     // with the implicit exception specification.
8054     if (ClassDecl->isDynamicClass() ||
8055         ClassDecl->needsOverloadResolutionForDestructor())
8056       DeclareImplicitDestructor(ClassDecl);
8057   }
8058 }
8059 
8060 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
8061   if (!D)
8062     return 0;
8063 
8064   // The order of template parameters is not important here. All names
8065   // get added to the same scope.
8066   SmallVector<TemplateParameterList *, 4> ParameterLists;
8067 
8068   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8069     D = TD->getTemplatedDecl();
8070 
8071   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
8072     ParameterLists.push_back(PSD->getTemplateParameters());
8073 
8074   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
8075     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
8076       ParameterLists.push_back(DD->getTemplateParameterList(i));
8077 
8078     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8079       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
8080         ParameterLists.push_back(FTD->getTemplateParameters());
8081     }
8082   }
8083 
8084   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8085     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
8086       ParameterLists.push_back(TD->getTemplateParameterList(i));
8087 
8088     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
8089       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
8090         ParameterLists.push_back(CTD->getTemplateParameters());
8091     }
8092   }
8093 
8094   unsigned Count = 0;
8095   for (TemplateParameterList *Params : ParameterLists) {
8096     if (Params->size() > 0)
8097       // Ignore explicit specializations; they don't contribute to the template
8098       // depth.
8099       ++Count;
8100     for (NamedDecl *Param : *Params) {
8101       if (Param->getDeclName()) {
8102         S->AddDecl(Param);
8103         IdResolver.AddDecl(Param);
8104       }
8105     }
8106   }
8107 
8108   return Count;
8109 }
8110 
8111 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8112   if (!RecordD) return;
8113   AdjustDeclIfTemplate(RecordD);
8114   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8115   PushDeclContext(S, Record);
8116 }
8117 
8118 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8119   if (!RecordD) return;
8120   PopDeclContext();
8121 }
8122 
8123 /// This is used to implement the constant expression evaluation part of the
8124 /// attribute enable_if extension. There is nothing in standard C++ which would
8125 /// require reentering parameters.
8126 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8127   if (!Param)
8128     return;
8129 
8130   S->AddDecl(Param);
8131   if (Param->getDeclName())
8132     IdResolver.AddDecl(Param);
8133 }
8134 
8135 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
8136 /// parsing a top-level (non-nested) C++ class, and we are now
8137 /// parsing those parts of the given Method declaration that could
8138 /// not be parsed earlier (C++ [class.mem]p2), such as default
8139 /// arguments. This action should enter the scope of the given
8140 /// Method declaration as if we had just parsed the qualified method
8141 /// name. However, it should not bring the parameters into scope;
8142 /// that will be performed by ActOnDelayedCXXMethodParameter.
8143 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8144 }
8145 
8146 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8147 /// C++ method declaration. We're (re-)introducing the given
8148 /// function parameter into scope for use in parsing later parts of
8149 /// the method declaration. For example, we could see an
8150 /// ActOnParamDefaultArgument event for this parameter.
8151 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8152   if (!ParamD)
8153     return;
8154 
8155   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8156 
8157   // If this parameter has an unparsed default argument, clear it out
8158   // to make way for the parsed default argument.
8159   if (Param->hasUnparsedDefaultArg())
8160     Param->setDefaultArg(nullptr);
8161 
8162   S->AddDecl(Param);
8163   if (Param->getDeclName())
8164     IdResolver.AddDecl(Param);
8165 }
8166 
8167 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8168 /// processing the delayed method declaration for Method. The method
8169 /// declaration is now considered finished. There may be a separate
8170 /// ActOnStartOfFunctionDef action later (not necessarily
8171 /// immediately!) for this method, if it was also defined inside the
8172 /// class body.
8173 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8174   if (!MethodD)
8175     return;
8176 
8177   AdjustDeclIfTemplate(MethodD);
8178 
8179   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8180 
8181   // Now that we have our default arguments, check the constructor
8182   // again. It could produce additional diagnostics or affect whether
8183   // the class has implicitly-declared destructors, among other
8184   // things.
8185   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8186     CheckConstructor(Constructor);
8187 
8188   // Check the default arguments, which we may have added.
8189   if (!Method->isInvalidDecl())
8190     CheckCXXDefaultArguments(Method);
8191 }
8192 
8193 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8194 /// the well-formedness of the constructor declarator @p D with type @p
8195 /// R. If there are any errors in the declarator, this routine will
8196 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8197 /// will be updated to reflect a well-formed type for the constructor and
8198 /// returned.
8199 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8200                                           StorageClass &SC) {
8201   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8202 
8203   // C++ [class.ctor]p3:
8204   //   A constructor shall not be virtual (10.3) or static (9.4). A
8205   //   constructor can be invoked for a const, volatile or const
8206   //   volatile object. A constructor shall not be declared const,
8207   //   volatile, or const volatile (9.3.2).
8208   if (isVirtual) {
8209     if (!D.isInvalidType())
8210       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8211         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8212         << SourceRange(D.getIdentifierLoc());
8213     D.setInvalidType();
8214   }
8215   if (SC == SC_Static) {
8216     if (!D.isInvalidType())
8217       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8218         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8219         << SourceRange(D.getIdentifierLoc());
8220     D.setInvalidType();
8221     SC = SC_None;
8222   }
8223 
8224   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8225     diagnoseIgnoredQualifiers(
8226         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8227         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8228         D.getDeclSpec().getRestrictSpecLoc(),
8229         D.getDeclSpec().getAtomicSpecLoc());
8230     D.setInvalidType();
8231   }
8232 
8233   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8234   if (FTI.hasMethodTypeQualifiers()) {
8235     bool DiagOccured = false;
8236     FTI.MethodQualifiers->forEachQualifier(
8237         [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
8238           // This diagnostic should be emitted on any qualifier except an addr
8239           // space qualifier. However, forEachQualifier currently doesn't visit
8240           // addr space qualifiers, so there's no way to write this condition
8241           // right now; we just diagnose on everything.
8242           Diag(SL, diag::err_invalid_qualified_constructor)
8243               << QualName << SourceRange(SL);
8244           DiagOccured = true;
8245         });
8246     if (DiagOccured)
8247       D.setInvalidType();
8248   }
8249 
8250   // C++0x [class.ctor]p4:
8251   //   A constructor shall not be declared with a ref-qualifier.
8252   if (FTI.hasRefQualifier()) {
8253     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8254       << FTI.RefQualifierIsLValueRef
8255       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8256     D.setInvalidType();
8257   }
8258 
8259   // Rebuild the function type "R" without any type qualifiers (in
8260   // case any of the errors above fired) and with "void" as the
8261   // return type, since constructors don't have return types.
8262   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8263   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8264     return R;
8265 
8266   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8267   EPI.TypeQuals = Qualifiers();
8268   EPI.RefQualifier = RQ_None;
8269 
8270   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8271 }
8272 
8273 /// CheckConstructor - Checks a fully-formed constructor for
8274 /// well-formedness, issuing any diagnostics required. Returns true if
8275 /// the constructor declarator is invalid.
8276 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8277   CXXRecordDecl *ClassDecl
8278     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8279   if (!ClassDecl)
8280     return Constructor->setInvalidDecl();
8281 
8282   // C++ [class.copy]p3:
8283   //   A declaration of a constructor for a class X is ill-formed if
8284   //   its first parameter is of type (optionally cv-qualified) X and
8285   //   either there are no other parameters or else all other
8286   //   parameters have default arguments.
8287   if (!Constructor->isInvalidDecl() &&
8288       ((Constructor->getNumParams() == 1) ||
8289        (Constructor->getNumParams() > 1 &&
8290         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8291       Constructor->getTemplateSpecializationKind()
8292                                               != TSK_ImplicitInstantiation) {
8293     QualType ParamType = Constructor->getParamDecl(0)->getType();
8294     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8295     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8296       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8297       const char *ConstRef
8298         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8299                                                         : " const &";
8300       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8301         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8302 
8303       // FIXME: Rather that making the constructor invalid, we should endeavor
8304       // to fix the type.
8305       Constructor->setInvalidDecl();
8306     }
8307   }
8308 }
8309 
8310 /// CheckDestructor - Checks a fully-formed destructor definition for
8311 /// well-formedness, issuing any diagnostics required.  Returns true
8312 /// on error.
8313 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8314   CXXRecordDecl *RD = Destructor->getParent();
8315 
8316   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8317     SourceLocation Loc;
8318 
8319     if (!Destructor->isImplicit())
8320       Loc = Destructor->getLocation();
8321     else
8322       Loc = RD->getLocation();
8323 
8324     // If we have a virtual destructor, look up the deallocation function
8325     if (FunctionDecl *OperatorDelete =
8326             FindDeallocationFunctionForDestructor(Loc, RD)) {
8327       Expr *ThisArg = nullptr;
8328 
8329       // If the notional 'delete this' expression requires a non-trivial
8330       // conversion from 'this' to the type of a destroying operator delete's
8331       // first parameter, perform that conversion now.
8332       if (OperatorDelete->isDestroyingOperatorDelete()) {
8333         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8334         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8335           // C++ [class.dtor]p13:
8336           //   ... as if for the expression 'delete this' appearing in a
8337           //   non-virtual destructor of the destructor's class.
8338           ContextRAII SwitchContext(*this, Destructor);
8339           ExprResult This =
8340               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8341           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8342           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8343           if (This.isInvalid()) {
8344             // FIXME: Register this as a context note so that it comes out
8345             // in the right order.
8346             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8347             return true;
8348           }
8349           ThisArg = This.get();
8350         }
8351       }
8352 
8353       DiagnoseUseOfDecl(OperatorDelete, Loc);
8354       MarkFunctionReferenced(Loc, OperatorDelete);
8355       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8356     }
8357   }
8358 
8359   return false;
8360 }
8361 
8362 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8363 /// the well-formednes of the destructor declarator @p D with type @p
8364 /// R. If there are any errors in the declarator, this routine will
8365 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8366 /// will be updated to reflect a well-formed type for the destructor and
8367 /// returned.
8368 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8369                                          StorageClass& SC) {
8370   // C++ [class.dtor]p1:
8371   //   [...] A typedef-name that names a class is a class-name
8372   //   (7.1.3); however, a typedef-name that names a class shall not
8373   //   be used as the identifier in the declarator for a destructor
8374   //   declaration.
8375   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8376   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8377     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8378       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8379   else if (const TemplateSpecializationType *TST =
8380              DeclaratorType->getAs<TemplateSpecializationType>())
8381     if (TST->isTypeAlias())
8382       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8383         << DeclaratorType << 1;
8384 
8385   // C++ [class.dtor]p2:
8386   //   A destructor is used to destroy objects of its class type. A
8387   //   destructor takes no parameters, and no return type can be
8388   //   specified for it (not even void). The address of a destructor
8389   //   shall not be taken. A destructor shall not be static. A
8390   //   destructor can be invoked for a const, volatile or const
8391   //   volatile object. A destructor shall not be declared const,
8392   //   volatile or const volatile (9.3.2).
8393   if (SC == SC_Static) {
8394     if (!D.isInvalidType())
8395       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8396         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8397         << SourceRange(D.getIdentifierLoc())
8398         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8399 
8400     SC = SC_None;
8401   }
8402   if (!D.isInvalidType()) {
8403     // Destructors don't have return types, but the parser will
8404     // happily parse something like:
8405     //
8406     //   class X {
8407     //     float ~X();
8408     //   };
8409     //
8410     // The return type will be eliminated later.
8411     if (D.getDeclSpec().hasTypeSpecifier())
8412       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8413         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8414         << SourceRange(D.getIdentifierLoc());
8415     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8416       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8417                                 SourceLocation(),
8418                                 D.getDeclSpec().getConstSpecLoc(),
8419                                 D.getDeclSpec().getVolatileSpecLoc(),
8420                                 D.getDeclSpec().getRestrictSpecLoc(),
8421                                 D.getDeclSpec().getAtomicSpecLoc());
8422       D.setInvalidType();
8423     }
8424   }
8425 
8426   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8427   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
8428     FTI.MethodQualifiers->forEachQualifier(
8429         [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
8430           Diag(SL, diag::err_invalid_qualified_destructor)
8431               << QualName << SourceRange(SL);
8432         });
8433     D.setInvalidType();
8434   }
8435 
8436   // C++0x [class.dtor]p2:
8437   //   A destructor shall not be declared with a ref-qualifier.
8438   if (FTI.hasRefQualifier()) {
8439     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8440       << FTI.RefQualifierIsLValueRef
8441       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8442     D.setInvalidType();
8443   }
8444 
8445   // Make sure we don't have any parameters.
8446   if (FTIHasNonVoidParameters(FTI)) {
8447     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8448 
8449     // Delete the parameters.
8450     FTI.freeParams();
8451     D.setInvalidType();
8452   }
8453 
8454   // Make sure the destructor isn't variadic.
8455   if (FTI.isVariadic) {
8456     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8457     D.setInvalidType();
8458   }
8459 
8460   // Rebuild the function type "R" without any type qualifiers or
8461   // parameters (in case any of the errors above fired) and with
8462   // "void" as the return type, since destructors don't have return
8463   // types.
8464   if (!D.isInvalidType())
8465     return R;
8466 
8467   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8468   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8469   EPI.Variadic = false;
8470   EPI.TypeQuals = Qualifiers();
8471   EPI.RefQualifier = RQ_None;
8472   return Context.getFunctionType(Context.VoidTy, None, EPI);
8473 }
8474 
8475 static void extendLeft(SourceRange &R, SourceRange Before) {
8476   if (Before.isInvalid())
8477     return;
8478   R.setBegin(Before.getBegin());
8479   if (R.getEnd().isInvalid())
8480     R.setEnd(Before.getEnd());
8481 }
8482 
8483 static void extendRight(SourceRange &R, SourceRange After) {
8484   if (After.isInvalid())
8485     return;
8486   if (R.getBegin().isInvalid())
8487     R.setBegin(After.getBegin());
8488   R.setEnd(After.getEnd());
8489 }
8490 
8491 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8492 /// well-formednes of the conversion function declarator @p D with
8493 /// type @p R. If there are any errors in the declarator, this routine
8494 /// will emit diagnostics and return true. Otherwise, it will return
8495 /// false. Either way, the type @p R will be updated to reflect a
8496 /// well-formed type for the conversion operator.
8497 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8498                                      StorageClass& SC) {
8499   // C++ [class.conv.fct]p1:
8500   //   Neither parameter types nor return type can be specified. The
8501   //   type of a conversion function (8.3.5) is "function taking no
8502   //   parameter returning conversion-type-id."
8503   if (SC == SC_Static) {
8504     if (!D.isInvalidType())
8505       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8506         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8507         << D.getName().getSourceRange();
8508     D.setInvalidType();
8509     SC = SC_None;
8510   }
8511 
8512   TypeSourceInfo *ConvTSI = nullptr;
8513   QualType ConvType =
8514       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8515 
8516   const DeclSpec &DS = D.getDeclSpec();
8517   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8518     // Conversion functions don't have return types, but the parser will
8519     // happily parse something like:
8520     //
8521     //   class X {
8522     //     float operator bool();
8523     //   };
8524     //
8525     // The return type will be changed later anyway.
8526     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8527       << SourceRange(DS.getTypeSpecTypeLoc())
8528       << SourceRange(D.getIdentifierLoc());
8529     D.setInvalidType();
8530   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8531     // It's also plausible that the user writes type qualifiers in the wrong
8532     // place, such as:
8533     //   struct S { const operator int(); };
8534     // FIXME: we could provide a fixit to move the qualifiers onto the
8535     // conversion type.
8536     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8537         << SourceRange(D.getIdentifierLoc()) << 0;
8538     D.setInvalidType();
8539   }
8540 
8541   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8542 
8543   // Make sure we don't have any parameters.
8544   if (Proto->getNumParams() > 0) {
8545     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8546 
8547     // Delete the parameters.
8548     D.getFunctionTypeInfo().freeParams();
8549     D.setInvalidType();
8550   } else if (Proto->isVariadic()) {
8551     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8552     D.setInvalidType();
8553   }
8554 
8555   // Diagnose "&operator bool()" and other such nonsense.  This
8556   // is actually a gcc extension which we don't support.
8557   if (Proto->getReturnType() != ConvType) {
8558     bool NeedsTypedef = false;
8559     SourceRange Before, After;
8560 
8561     // Walk the chunks and extract information on them for our diagnostic.
8562     bool PastFunctionChunk = false;
8563     for (auto &Chunk : D.type_objects()) {
8564       switch (Chunk.Kind) {
8565       case DeclaratorChunk::Function:
8566         if (!PastFunctionChunk) {
8567           if (Chunk.Fun.HasTrailingReturnType) {
8568             TypeSourceInfo *TRT = nullptr;
8569             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8570             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8571           }
8572           PastFunctionChunk = true;
8573           break;
8574         }
8575         LLVM_FALLTHROUGH;
8576       case DeclaratorChunk::Array:
8577         NeedsTypedef = true;
8578         extendRight(After, Chunk.getSourceRange());
8579         break;
8580 
8581       case DeclaratorChunk::Pointer:
8582       case DeclaratorChunk::BlockPointer:
8583       case DeclaratorChunk::Reference:
8584       case DeclaratorChunk::MemberPointer:
8585       case DeclaratorChunk::Pipe:
8586         extendLeft(Before, Chunk.getSourceRange());
8587         break;
8588 
8589       case DeclaratorChunk::Paren:
8590         extendLeft(Before, Chunk.Loc);
8591         extendRight(After, Chunk.EndLoc);
8592         break;
8593       }
8594     }
8595 
8596     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8597                          After.isValid()  ? After.getBegin() :
8598                                             D.getIdentifierLoc();
8599     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8600     DB << Before << After;
8601 
8602     if (!NeedsTypedef) {
8603       DB << /*don't need a typedef*/0;
8604 
8605       // If we can provide a correct fix-it hint, do so.
8606       if (After.isInvalid() && ConvTSI) {
8607         SourceLocation InsertLoc =
8608             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8609         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8610            << FixItHint::CreateInsertionFromRange(
8611                   InsertLoc, CharSourceRange::getTokenRange(Before))
8612            << FixItHint::CreateRemoval(Before);
8613       }
8614     } else if (!Proto->getReturnType()->isDependentType()) {
8615       DB << /*typedef*/1 << Proto->getReturnType();
8616     } else if (getLangOpts().CPlusPlus11) {
8617       DB << /*alias template*/2 << Proto->getReturnType();
8618     } else {
8619       DB << /*might not be fixable*/3;
8620     }
8621 
8622     // Recover by incorporating the other type chunks into the result type.
8623     // Note, this does *not* change the name of the function. This is compatible
8624     // with the GCC extension:
8625     //   struct S { &operator int(); } s;
8626     //   int &r = s.operator int(); // ok in GCC
8627     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8628     ConvType = Proto->getReturnType();
8629   }
8630 
8631   // C++ [class.conv.fct]p4:
8632   //   The conversion-type-id shall not represent a function type nor
8633   //   an array type.
8634   if (ConvType->isArrayType()) {
8635     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8636     ConvType = Context.getPointerType(ConvType);
8637     D.setInvalidType();
8638   } else if (ConvType->isFunctionType()) {
8639     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8640     ConvType = Context.getPointerType(ConvType);
8641     D.setInvalidType();
8642   }
8643 
8644   // Rebuild the function type "R" without any parameters (in case any
8645   // of the errors above fired) and with the conversion type as the
8646   // return type.
8647   if (D.isInvalidType())
8648     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8649 
8650   // C++0x explicit conversion operators.
8651   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a)
8652     Diag(DS.getExplicitSpecLoc(),
8653          getLangOpts().CPlusPlus11
8654              ? diag::warn_cxx98_compat_explicit_conversion_functions
8655              : diag::ext_explicit_conversion_functions)
8656         << SourceRange(DS.getExplicitSpecRange());
8657 }
8658 
8659 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8660 /// the declaration of the given C++ conversion function. This routine
8661 /// is responsible for recording the conversion function in the C++
8662 /// class, if possible.
8663 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8664   assert(Conversion && "Expected to receive a conversion function declaration");
8665 
8666   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8667 
8668   // Make sure we aren't redeclaring the conversion function.
8669   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8670 
8671   // C++ [class.conv.fct]p1:
8672   //   [...] A conversion function is never used to convert a
8673   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8674   //   same object type (or a reference to it), to a (possibly
8675   //   cv-qualified) base class of that type (or a reference to it),
8676   //   or to (possibly cv-qualified) void.
8677   // FIXME: Suppress this warning if the conversion function ends up being a
8678   // virtual function that overrides a virtual function in a base class.
8679   QualType ClassType
8680     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8681   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8682     ConvType = ConvTypeRef->getPointeeType();
8683   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8684       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8685     /* Suppress diagnostics for instantiations. */;
8686   else if (ConvType->isRecordType()) {
8687     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8688     if (ConvType == ClassType)
8689       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8690         << ClassType;
8691     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8692       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8693         <<  ClassType << ConvType;
8694   } else if (ConvType->isVoidType()) {
8695     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8696       << ClassType << ConvType;
8697   }
8698 
8699   if (FunctionTemplateDecl *ConversionTemplate
8700                                 = Conversion->getDescribedFunctionTemplate())
8701     return ConversionTemplate;
8702 
8703   return Conversion;
8704 }
8705 
8706 namespace {
8707 /// Utility class to accumulate and print a diagnostic listing the invalid
8708 /// specifier(s) on a declaration.
8709 struct BadSpecifierDiagnoser {
8710   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8711       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8712   ~BadSpecifierDiagnoser() {
8713     Diagnostic << Specifiers;
8714   }
8715 
8716   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8717     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8718   }
8719   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8720     return check(SpecLoc,
8721                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8722   }
8723   void check(SourceLocation SpecLoc, const char *Spec) {
8724     if (SpecLoc.isInvalid()) return;
8725     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8726     if (!Specifiers.empty()) Specifiers += " ";
8727     Specifiers += Spec;
8728   }
8729 
8730   Sema &S;
8731   Sema::SemaDiagnosticBuilder Diagnostic;
8732   std::string Specifiers;
8733 };
8734 }
8735 
8736 /// Check the validity of a declarator that we parsed for a deduction-guide.
8737 /// These aren't actually declarators in the grammar, so we need to check that
8738 /// the user didn't specify any pieces that are not part of the deduction-guide
8739 /// grammar.
8740 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8741                                          StorageClass &SC) {
8742   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8743   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8744   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8745 
8746   // C++ [temp.deduct.guide]p3:
8747   //   A deduction-gide shall be declared in the same scope as the
8748   //   corresponding class template.
8749   if (!CurContext->getRedeclContext()->Equals(
8750           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8751     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8752       << GuidedTemplateDecl;
8753     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8754   }
8755 
8756   auto &DS = D.getMutableDeclSpec();
8757   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8758   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8759       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8760       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
8761     BadSpecifierDiagnoser Diagnoser(
8762         *this, D.getIdentifierLoc(),
8763         diag::err_deduction_guide_invalid_specifier);
8764 
8765     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8766     DS.ClearStorageClassSpecs();
8767     SC = SC_None;
8768 
8769     // 'explicit' is permitted.
8770     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8771     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8772     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8773     DS.ClearConstexprSpec();
8774 
8775     Diagnoser.check(DS.getConstSpecLoc(), "const");
8776     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8777     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8778     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8779     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8780     DS.ClearTypeQualifiers();
8781 
8782     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8783     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8784     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8785     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8786     DS.ClearTypeSpecType();
8787   }
8788 
8789   if (D.isInvalidType())
8790     return;
8791 
8792   // Check the declarator is simple enough.
8793   bool FoundFunction = false;
8794   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8795     if (Chunk.Kind == DeclaratorChunk::Paren)
8796       continue;
8797     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8798       Diag(D.getDeclSpec().getBeginLoc(),
8799            diag::err_deduction_guide_with_complex_decl)
8800           << D.getSourceRange();
8801       break;
8802     }
8803     if (!Chunk.Fun.hasTrailingReturnType()) {
8804       Diag(D.getName().getBeginLoc(),
8805            diag::err_deduction_guide_no_trailing_return_type);
8806       break;
8807     }
8808 
8809     // Check that the return type is written as a specialization of
8810     // the template specified as the deduction-guide's name.
8811     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8812     TypeSourceInfo *TSI = nullptr;
8813     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8814     assert(TSI && "deduction guide has valid type but invalid return type?");
8815     bool AcceptableReturnType = false;
8816     bool MightInstantiateToSpecialization = false;
8817     if (auto RetTST =
8818             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8819       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8820       bool TemplateMatches =
8821           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8822       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8823         AcceptableReturnType = true;
8824       else {
8825         // This could still instantiate to the right type, unless we know it
8826         // names the wrong class template.
8827         auto *TD = SpecifiedName.getAsTemplateDecl();
8828         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8829                                              !TemplateMatches);
8830       }
8831     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8832       MightInstantiateToSpecialization = true;
8833     }
8834 
8835     if (!AcceptableReturnType) {
8836       Diag(TSI->getTypeLoc().getBeginLoc(),
8837            diag::err_deduction_guide_bad_trailing_return_type)
8838           << GuidedTemplate << TSI->getType()
8839           << MightInstantiateToSpecialization
8840           << TSI->getTypeLoc().getSourceRange();
8841     }
8842 
8843     // Keep going to check that we don't have any inner declarator pieces (we
8844     // could still have a function returning a pointer to a function).
8845     FoundFunction = true;
8846   }
8847 
8848   if (D.isFunctionDefinition())
8849     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8850 }
8851 
8852 //===----------------------------------------------------------------------===//
8853 // Namespace Handling
8854 //===----------------------------------------------------------------------===//
8855 
8856 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8857 /// reopened.
8858 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8859                                             SourceLocation Loc,
8860                                             IdentifierInfo *II, bool *IsInline,
8861                                             NamespaceDecl *PrevNS) {
8862   assert(*IsInline != PrevNS->isInline());
8863 
8864   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8865   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8866   // inline namespaces, with the intention of bringing names into namespace std.
8867   //
8868   // We support this just well enough to get that case working; this is not
8869   // sufficient to support reopening namespaces as inline in general.
8870   if (*IsInline && II && II->getName().startswith("__atomic") &&
8871       S.getSourceManager().isInSystemHeader(Loc)) {
8872     // Mark all prior declarations of the namespace as inline.
8873     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8874          NS = NS->getPreviousDecl())
8875       NS->setInline(*IsInline);
8876     // Patch up the lookup table for the containing namespace. This isn't really
8877     // correct, but it's good enough for this particular case.
8878     for (auto *I : PrevNS->decls())
8879       if (auto *ND = dyn_cast<NamedDecl>(I))
8880         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8881     return;
8882   }
8883 
8884   if (PrevNS->isInline())
8885     // The user probably just forgot the 'inline', so suggest that it
8886     // be added back.
8887     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8888       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8889   else
8890     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8891 
8892   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8893   *IsInline = PrevNS->isInline();
8894 }
8895 
8896 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8897 /// definition.
8898 Decl *Sema::ActOnStartNamespaceDef(
8899     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
8900     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
8901     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
8902   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8903   // For anonymous namespace, take the location of the left brace.
8904   SourceLocation Loc = II ? IdentLoc : LBrace;
8905   bool IsInline = InlineLoc.isValid();
8906   bool IsInvalid = false;
8907   bool IsStd = false;
8908   bool AddToKnown = false;
8909   Scope *DeclRegionScope = NamespcScope->getParent();
8910 
8911   NamespaceDecl *PrevNS = nullptr;
8912   if (II) {
8913     // C++ [namespace.def]p2:
8914     //   The identifier in an original-namespace-definition shall not
8915     //   have been previously defined in the declarative region in
8916     //   which the original-namespace-definition appears. The
8917     //   identifier in an original-namespace-definition is the name of
8918     //   the namespace. Subsequently in that declarative region, it is
8919     //   treated as an original-namespace-name.
8920     //
8921     // Since namespace names are unique in their scope, and we don't
8922     // look through using directives, just look for any ordinary names
8923     // as if by qualified name lookup.
8924     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8925                    ForExternalRedeclaration);
8926     LookupQualifiedName(R, CurContext->getRedeclContext());
8927     NamedDecl *PrevDecl =
8928         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8929     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8930 
8931     if (PrevNS) {
8932       // This is an extended namespace definition.
8933       if (IsInline != PrevNS->isInline())
8934         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8935                                         &IsInline, PrevNS);
8936     } else if (PrevDecl) {
8937       // This is an invalid name redefinition.
8938       Diag(Loc, diag::err_redefinition_different_kind)
8939         << II;
8940       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8941       IsInvalid = true;
8942       // Continue on to push Namespc as current DeclContext and return it.
8943     } else if (II->isStr("std") &&
8944                CurContext->getRedeclContext()->isTranslationUnit()) {
8945       // This is the first "real" definition of the namespace "std", so update
8946       // our cache of the "std" namespace to point at this definition.
8947       PrevNS = getStdNamespace();
8948       IsStd = true;
8949       AddToKnown = !IsInline;
8950     } else {
8951       // We've seen this namespace for the first time.
8952       AddToKnown = !IsInline;
8953     }
8954   } else {
8955     // Anonymous namespaces.
8956 
8957     // Determine whether the parent already has an anonymous namespace.
8958     DeclContext *Parent = CurContext->getRedeclContext();
8959     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8960       PrevNS = TU->getAnonymousNamespace();
8961     } else {
8962       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8963       PrevNS = ND->getAnonymousNamespace();
8964     }
8965 
8966     if (PrevNS && IsInline != PrevNS->isInline())
8967       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8968                                       &IsInline, PrevNS);
8969   }
8970 
8971   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8972                                                  StartLoc, Loc, II, PrevNS);
8973   if (IsInvalid)
8974     Namespc->setInvalidDecl();
8975 
8976   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8977   AddPragmaAttributes(DeclRegionScope, Namespc);
8978 
8979   // FIXME: Should we be merging attributes?
8980   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8981     PushNamespaceVisibilityAttr(Attr, Loc);
8982 
8983   if (IsStd)
8984     StdNamespace = Namespc;
8985   if (AddToKnown)
8986     KnownNamespaces[Namespc] = false;
8987 
8988   if (II) {
8989     PushOnScopeChains(Namespc, DeclRegionScope);
8990   } else {
8991     // Link the anonymous namespace into its parent.
8992     DeclContext *Parent = CurContext->getRedeclContext();
8993     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8994       TU->setAnonymousNamespace(Namespc);
8995     } else {
8996       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8997     }
8998 
8999     CurContext->addDecl(Namespc);
9000 
9001     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
9002     //   behaves as if it were replaced by
9003     //     namespace unique { /* empty body */ }
9004     //     using namespace unique;
9005     //     namespace unique { namespace-body }
9006     //   where all occurrences of 'unique' in a translation unit are
9007     //   replaced by the same identifier and this identifier differs
9008     //   from all other identifiers in the entire program.
9009 
9010     // We just create the namespace with an empty name and then add an
9011     // implicit using declaration, just like the standard suggests.
9012     //
9013     // CodeGen enforces the "universally unique" aspect by giving all
9014     // declarations semantically contained within an anonymous
9015     // namespace internal linkage.
9016 
9017     if (!PrevNS) {
9018       UD = UsingDirectiveDecl::Create(Context, Parent,
9019                                       /* 'using' */ LBrace,
9020                                       /* 'namespace' */ SourceLocation(),
9021                                       /* qualifier */ NestedNameSpecifierLoc(),
9022                                       /* identifier */ SourceLocation(),
9023                                       Namespc,
9024                                       /* Ancestor */ Parent);
9025       UD->setImplicit();
9026       Parent->addDecl(UD);
9027     }
9028   }
9029 
9030   ActOnDocumentableDecl(Namespc);
9031 
9032   // Although we could have an invalid decl (i.e. the namespace name is a
9033   // redefinition), push it as current DeclContext and try to continue parsing.
9034   // FIXME: We should be able to push Namespc here, so that the each DeclContext
9035   // for the namespace has the declarations that showed up in that particular
9036   // namespace definition.
9037   PushDeclContext(NamespcScope, Namespc);
9038   return Namespc;
9039 }
9040 
9041 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
9042 /// is a namespace alias, returns the namespace it points to.
9043 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
9044   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
9045     return AD->getNamespace();
9046   return dyn_cast_or_null<NamespaceDecl>(D);
9047 }
9048 
9049 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
9050 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
9051 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
9052   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
9053   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
9054   Namespc->setRBraceLoc(RBrace);
9055   PopDeclContext();
9056   if (Namespc->hasAttr<VisibilityAttr>())
9057     PopPragmaVisibility(true, RBrace);
9058   // If this namespace contains an export-declaration, export it now.
9059   if (DeferredExportedNamespaces.erase(Namespc))
9060     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
9061 }
9062 
9063 CXXRecordDecl *Sema::getStdBadAlloc() const {
9064   return cast_or_null<CXXRecordDecl>(
9065                                   StdBadAlloc.get(Context.getExternalSource()));
9066 }
9067 
9068 EnumDecl *Sema::getStdAlignValT() const {
9069   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9070 }
9071 
9072 NamespaceDecl *Sema::getStdNamespace() const {
9073   return cast_or_null<NamespaceDecl>(
9074                                  StdNamespace.get(Context.getExternalSource()));
9075 }
9076 
9077 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
9078   if (!StdExperimentalNamespaceCache) {
9079     if (auto Std = getStdNamespace()) {
9080       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9081                           SourceLocation(), LookupNamespaceName);
9082       if (!LookupQualifiedName(Result, Std) ||
9083           !(StdExperimentalNamespaceCache =
9084                 Result.getAsSingle<NamespaceDecl>()))
9085         Result.suppressDiagnostics();
9086     }
9087   }
9088   return StdExperimentalNamespaceCache;
9089 }
9090 
9091 namespace {
9092 
9093 enum UnsupportedSTLSelect {
9094   USS_InvalidMember,
9095   USS_MissingMember,
9096   USS_NonTrivial,
9097   USS_Other
9098 };
9099 
9100 struct InvalidSTLDiagnoser {
9101   Sema &S;
9102   SourceLocation Loc;
9103   QualType TyForDiags;
9104 
9105   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9106                       const VarDecl *VD = nullptr) {
9107     {
9108       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9109                << TyForDiags << ((int)Sel);
9110       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9111         assert(!Name.empty());
9112         D << Name;
9113       }
9114     }
9115     if (Sel == USS_InvalidMember) {
9116       S.Diag(VD->getLocation(), diag::note_var_declared_here)
9117           << VD << VD->getSourceRange();
9118     }
9119     return QualType();
9120   }
9121 };
9122 } // namespace
9123 
9124 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9125                                            SourceLocation Loc) {
9126   assert(getLangOpts().CPlusPlus &&
9127          "Looking for comparison category type outside of C++.");
9128 
9129   // Check if we've already successfully checked the comparison category type
9130   // before. If so, skip checking it again.
9131   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9132   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9133     return Info->getType();
9134 
9135   // If lookup failed
9136   if (!Info) {
9137     std::string NameForDiags = "std::";
9138     NameForDiags += ComparisonCategories::getCategoryString(Kind);
9139     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9140         << NameForDiags;
9141     return QualType();
9142   }
9143 
9144   assert(Info->Kind == Kind);
9145   assert(Info->Record);
9146 
9147   // Update the Record decl in case we encountered a forward declaration on our
9148   // first pass. FIXME: This is a bit of a hack.
9149   if (Info->Record->hasDefinition())
9150     Info->Record = Info->Record->getDefinition();
9151 
9152   // Use an elaborated type for diagnostics which has a name containing the
9153   // prepended 'std' namespace but not any inline namespace names.
9154   QualType TyForDiags = [&]() {
9155     auto *NNS =
9156         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9157     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9158   }();
9159 
9160   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9161     return QualType();
9162 
9163   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9164 
9165   if (!Info->Record->isTriviallyCopyable())
9166     return UnsupportedSTLError(USS_NonTrivial);
9167 
9168   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9169     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9170     // Tolerate empty base classes.
9171     if (Base->isEmpty())
9172       continue;
9173     // Reject STL implementations which have at least one non-empty base.
9174     return UnsupportedSTLError();
9175   }
9176 
9177   // Check that the STL has implemented the types using a single integer field.
9178   // This expectation allows better codegen for builtin operators. We require:
9179   //   (1) The class has exactly one field.
9180   //   (2) The field is an integral or enumeration type.
9181   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9182   if (std::distance(FIt, FEnd) != 1 ||
9183       !FIt->getType()->isIntegralOrEnumerationType()) {
9184     return UnsupportedSTLError();
9185   }
9186 
9187   // Build each of the require values and store them in Info.
9188   for (ComparisonCategoryResult CCR :
9189        ComparisonCategories::getPossibleResultsForType(Kind)) {
9190     StringRef MemName = ComparisonCategories::getResultString(CCR);
9191     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9192 
9193     if (!ValInfo)
9194       return UnsupportedSTLError(USS_MissingMember, MemName);
9195 
9196     VarDecl *VD = ValInfo->VD;
9197     assert(VD && "should not be null!");
9198 
9199     // Attempt to diagnose reasons why the STL definition of this type
9200     // might be foobar, including it failing to be a constant expression.
9201     // TODO Handle more ways the lookup or result can be invalid.
9202     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9203         !VD->checkInitIsICE())
9204       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9205 
9206     // Attempt to evaluate the var decl as a constant expression and extract
9207     // the value of its first field as a ICE. If this fails, the STL
9208     // implementation is not supported.
9209     if (!ValInfo->hasValidIntValue())
9210       return UnsupportedSTLError();
9211 
9212     MarkVariableReferenced(Loc, VD);
9213   }
9214 
9215   // We've successfully built the required types and expressions. Update
9216   // the cache and return the newly cached value.
9217   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9218   return Info->getType();
9219 }
9220 
9221 /// Retrieve the special "std" namespace, which may require us to
9222 /// implicitly define the namespace.
9223 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9224   if (!StdNamespace) {
9225     // The "std" namespace has not yet been defined, so build one implicitly.
9226     StdNamespace = NamespaceDecl::Create(Context,
9227                                          Context.getTranslationUnitDecl(),
9228                                          /*Inline=*/false,
9229                                          SourceLocation(), SourceLocation(),
9230                                          &PP.getIdentifierTable().get("std"),
9231                                          /*PrevDecl=*/nullptr);
9232     getStdNamespace()->setImplicit(true);
9233   }
9234 
9235   return getStdNamespace();
9236 }
9237 
9238 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9239   assert(getLangOpts().CPlusPlus &&
9240          "Looking for std::initializer_list outside of C++.");
9241 
9242   // We're looking for implicit instantiations of
9243   // template <typename E> class std::initializer_list.
9244 
9245   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9246     return false;
9247 
9248   ClassTemplateDecl *Template = nullptr;
9249   const TemplateArgument *Arguments = nullptr;
9250 
9251   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9252 
9253     ClassTemplateSpecializationDecl *Specialization =
9254         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9255     if (!Specialization)
9256       return false;
9257 
9258     Template = Specialization->getSpecializedTemplate();
9259     Arguments = Specialization->getTemplateArgs().data();
9260   } else if (const TemplateSpecializationType *TST =
9261                  Ty->getAs<TemplateSpecializationType>()) {
9262     Template = dyn_cast_or_null<ClassTemplateDecl>(
9263         TST->getTemplateName().getAsTemplateDecl());
9264     Arguments = TST->getArgs();
9265   }
9266   if (!Template)
9267     return false;
9268 
9269   if (!StdInitializerList) {
9270     // Haven't recognized std::initializer_list yet, maybe this is it.
9271     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9272     if (TemplateClass->getIdentifier() !=
9273             &PP.getIdentifierTable().get("initializer_list") ||
9274         !getStdNamespace()->InEnclosingNamespaceSetOf(
9275             TemplateClass->getDeclContext()))
9276       return false;
9277     // This is a template called std::initializer_list, but is it the right
9278     // template?
9279     TemplateParameterList *Params = Template->getTemplateParameters();
9280     if (Params->getMinRequiredArguments() != 1)
9281       return false;
9282     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9283       return false;
9284 
9285     // It's the right template.
9286     StdInitializerList = Template;
9287   }
9288 
9289   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9290     return false;
9291 
9292   // This is an instance of std::initializer_list. Find the argument type.
9293   if (Element)
9294     *Element = Arguments[0].getAsType();
9295   return true;
9296 }
9297 
9298 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9299   NamespaceDecl *Std = S.getStdNamespace();
9300   if (!Std) {
9301     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9302     return nullptr;
9303   }
9304 
9305   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9306                       Loc, Sema::LookupOrdinaryName);
9307   if (!S.LookupQualifiedName(Result, Std)) {
9308     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9309     return nullptr;
9310   }
9311   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9312   if (!Template) {
9313     Result.suppressDiagnostics();
9314     // We found something weird. Complain about the first thing we found.
9315     NamedDecl *Found = *Result.begin();
9316     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9317     return nullptr;
9318   }
9319 
9320   // We found some template called std::initializer_list. Now verify that it's
9321   // correct.
9322   TemplateParameterList *Params = Template->getTemplateParameters();
9323   if (Params->getMinRequiredArguments() != 1 ||
9324       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9325     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9326     return nullptr;
9327   }
9328 
9329   return Template;
9330 }
9331 
9332 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9333   if (!StdInitializerList) {
9334     StdInitializerList = LookupStdInitializerList(*this, Loc);
9335     if (!StdInitializerList)
9336       return QualType();
9337   }
9338 
9339   TemplateArgumentListInfo Args(Loc, Loc);
9340   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9341                                        Context.getTrivialTypeSourceInfo(Element,
9342                                                                         Loc)));
9343   return Context.getCanonicalType(
9344       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9345 }
9346 
9347 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9348   // C++ [dcl.init.list]p2:
9349   //   A constructor is an initializer-list constructor if its first parameter
9350   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9351   //   std::initializer_list<E> for some type E, and either there are no other
9352   //   parameters or else all other parameters have default arguments.
9353   if (Ctor->getNumParams() < 1 ||
9354       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9355     return false;
9356 
9357   QualType ArgType = Ctor->getParamDecl(0)->getType();
9358   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9359     ArgType = RT->getPointeeType().getUnqualifiedType();
9360 
9361   return isStdInitializerList(ArgType, nullptr);
9362 }
9363 
9364 /// Determine whether a using statement is in a context where it will be
9365 /// apply in all contexts.
9366 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9367   switch (CurContext->getDeclKind()) {
9368     case Decl::TranslationUnit:
9369       return true;
9370     case Decl::LinkageSpec:
9371       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9372     default:
9373       return false;
9374   }
9375 }
9376 
9377 namespace {
9378 
9379 // Callback to only accept typo corrections that are namespaces.
9380 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
9381 public:
9382   bool ValidateCandidate(const TypoCorrection &candidate) override {
9383     if (NamedDecl *ND = candidate.getCorrectionDecl())
9384       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9385     return false;
9386   }
9387 
9388   std::unique_ptr<CorrectionCandidateCallback> clone() override {
9389     return llvm::make_unique<NamespaceValidatorCCC>(*this);
9390   }
9391 };
9392 
9393 }
9394 
9395 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9396                                        CXXScopeSpec &SS,
9397                                        SourceLocation IdentLoc,
9398                                        IdentifierInfo *Ident) {
9399   R.clear();
9400   NamespaceValidatorCCC CCC{};
9401   if (TypoCorrection Corrected =
9402           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
9403                         Sema::CTK_ErrorRecovery)) {
9404     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9405       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9406       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9407                               Ident->getName().equals(CorrectedStr);
9408       S.diagnoseTypo(Corrected,
9409                      S.PDiag(diag::err_using_directive_member_suggest)
9410                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9411                      S.PDiag(diag::note_namespace_defined_here));
9412     } else {
9413       S.diagnoseTypo(Corrected,
9414                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9415                      S.PDiag(diag::note_namespace_defined_here));
9416     }
9417     R.addDecl(Corrected.getFoundDecl());
9418     return true;
9419   }
9420   return false;
9421 }
9422 
9423 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9424                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9425                                 SourceLocation IdentLoc,
9426                                 IdentifierInfo *NamespcName,
9427                                 const ParsedAttributesView &AttrList) {
9428   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9429   assert(NamespcName && "Invalid NamespcName.");
9430   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9431 
9432   // This can only happen along a recovery path.
9433   while (S->isTemplateParamScope())
9434     S = S->getParent();
9435   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9436 
9437   UsingDirectiveDecl *UDir = nullptr;
9438   NestedNameSpecifier *Qualifier = nullptr;
9439   if (SS.isSet())
9440     Qualifier = SS.getScopeRep();
9441 
9442   // Lookup namespace name.
9443   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9444   LookupParsedName(R, S, &SS);
9445   if (R.isAmbiguous())
9446     return nullptr;
9447 
9448   if (R.empty()) {
9449     R.clear();
9450     // Allow "using namespace std;" or "using namespace ::std;" even if
9451     // "std" hasn't been defined yet, for GCC compatibility.
9452     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9453         NamespcName->isStr("std")) {
9454       Diag(IdentLoc, diag::ext_using_undefined_std);
9455       R.addDecl(getOrCreateStdNamespace());
9456       R.resolveKind();
9457     }
9458     // Otherwise, attempt typo correction.
9459     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9460   }
9461 
9462   if (!R.empty()) {
9463     NamedDecl *Named = R.getRepresentativeDecl();
9464     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9465     assert(NS && "expected namespace decl");
9466 
9467     // The use of a nested name specifier may trigger deprecation warnings.
9468     DiagnoseUseOfDecl(Named, IdentLoc);
9469 
9470     // C++ [namespace.udir]p1:
9471     //   A using-directive specifies that the names in the nominated
9472     //   namespace can be used in the scope in which the
9473     //   using-directive appears after the using-directive. During
9474     //   unqualified name lookup (3.4.1), the names appear as if they
9475     //   were declared in the nearest enclosing namespace which
9476     //   contains both the using-directive and the nominated
9477     //   namespace. [Note: in this context, "contains" means "contains
9478     //   directly or indirectly". ]
9479 
9480     // Find enclosing context containing both using-directive and
9481     // nominated namespace.
9482     DeclContext *CommonAncestor = NS;
9483     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9484       CommonAncestor = CommonAncestor->getParent();
9485 
9486     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9487                                       SS.getWithLocInContext(Context),
9488                                       IdentLoc, Named, CommonAncestor);
9489 
9490     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9491         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9492       Diag(IdentLoc, diag::warn_using_directive_in_header);
9493     }
9494 
9495     PushUsingDirective(S, UDir);
9496   } else {
9497     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9498   }
9499 
9500   if (UDir)
9501     ProcessDeclAttributeList(S, UDir, AttrList);
9502 
9503   return UDir;
9504 }
9505 
9506 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9507   // If the scope has an associated entity and the using directive is at
9508   // namespace or translation unit scope, add the UsingDirectiveDecl into
9509   // its lookup structure so qualified name lookup can find it.
9510   DeclContext *Ctx = S->getEntity();
9511   if (Ctx && !Ctx->isFunctionOrMethod())
9512     Ctx->addDecl(UDir);
9513   else
9514     // Otherwise, it is at block scope. The using-directives will affect lookup
9515     // only to the end of the scope.
9516     S->PushUsingDirective(UDir);
9517 }
9518 
9519 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9520                                   SourceLocation UsingLoc,
9521                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
9522                                   UnqualifiedId &Name,
9523                                   SourceLocation EllipsisLoc,
9524                                   const ParsedAttributesView &AttrList) {
9525   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9526 
9527   if (SS.isEmpty()) {
9528     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9529     return nullptr;
9530   }
9531 
9532   switch (Name.getKind()) {
9533   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9534   case UnqualifiedIdKind::IK_Identifier:
9535   case UnqualifiedIdKind::IK_OperatorFunctionId:
9536   case UnqualifiedIdKind::IK_LiteralOperatorId:
9537   case UnqualifiedIdKind::IK_ConversionFunctionId:
9538     break;
9539 
9540   case UnqualifiedIdKind::IK_ConstructorName:
9541   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9542     // C++11 inheriting constructors.
9543     Diag(Name.getBeginLoc(),
9544          getLangOpts().CPlusPlus11
9545              ? diag::warn_cxx98_compat_using_decl_constructor
9546              : diag::err_using_decl_constructor)
9547         << SS.getRange();
9548 
9549     if (getLangOpts().CPlusPlus11) break;
9550 
9551     return nullptr;
9552 
9553   case UnqualifiedIdKind::IK_DestructorName:
9554     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9555     return nullptr;
9556 
9557   case UnqualifiedIdKind::IK_TemplateId:
9558     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9559         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9560     return nullptr;
9561 
9562   case UnqualifiedIdKind::IK_DeductionGuideName:
9563     llvm_unreachable("cannot parse qualified deduction guide name");
9564   }
9565 
9566   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9567   DeclarationName TargetName = TargetNameInfo.getName();
9568   if (!TargetName)
9569     return nullptr;
9570 
9571   // Warn about access declarations.
9572   if (UsingLoc.isInvalid()) {
9573     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9574                                  ? diag::err_access_decl
9575                                  : diag::warn_access_decl_deprecated)
9576         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9577   }
9578 
9579   if (EllipsisLoc.isInvalid()) {
9580     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9581         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9582       return nullptr;
9583   } else {
9584     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9585         !TargetNameInfo.containsUnexpandedParameterPack()) {
9586       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9587         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9588       EllipsisLoc = SourceLocation();
9589     }
9590   }
9591 
9592   NamedDecl *UD =
9593       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9594                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9595                             /*IsInstantiation*/false);
9596   if (UD)
9597     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9598 
9599   return UD;
9600 }
9601 
9602 /// Determine whether a using declaration considers the given
9603 /// declarations as "equivalent", e.g., if they are redeclarations of
9604 /// the same entity or are both typedefs of the same type.
9605 static bool
9606 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9607   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9608     return true;
9609 
9610   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9611     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9612       return Context.hasSameType(TD1->getUnderlyingType(),
9613                                  TD2->getUnderlyingType());
9614 
9615   return false;
9616 }
9617 
9618 
9619 /// Determines whether to create a using shadow decl for a particular
9620 /// decl, given the set of decls existing prior to this using lookup.
9621 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9622                                 const LookupResult &Previous,
9623                                 UsingShadowDecl *&PrevShadow) {
9624   // Diagnose finding a decl which is not from a base class of the
9625   // current class.  We do this now because there are cases where this
9626   // function will silently decide not to build a shadow decl, which
9627   // will pre-empt further diagnostics.
9628   //
9629   // We don't need to do this in C++11 because we do the check once on
9630   // the qualifier.
9631   //
9632   // FIXME: diagnose the following if we care enough:
9633   //   struct A { int foo; };
9634   //   struct B : A { using A::foo; };
9635   //   template <class T> struct C : A {};
9636   //   template <class T> struct D : C<T> { using B::foo; } // <---
9637   // This is invalid (during instantiation) in C++03 because B::foo
9638   // resolves to the using decl in B, which is not a base class of D<T>.
9639   // We can't diagnose it immediately because C<T> is an unknown
9640   // specialization.  The UsingShadowDecl in D<T> then points directly
9641   // to A::foo, which will look well-formed when we instantiate.
9642   // The right solution is to not collapse the shadow-decl chain.
9643   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9644     DeclContext *OrigDC = Orig->getDeclContext();
9645 
9646     // Handle enums and anonymous structs.
9647     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9648     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9649     while (OrigRec->isAnonymousStructOrUnion())
9650       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9651 
9652     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9653       if (OrigDC == CurContext) {
9654         Diag(Using->getLocation(),
9655              diag::err_using_decl_nested_name_specifier_is_current_class)
9656           << Using->getQualifierLoc().getSourceRange();
9657         Diag(Orig->getLocation(), diag::note_using_decl_target);
9658         Using->setInvalidDecl();
9659         return true;
9660       }
9661 
9662       Diag(Using->getQualifierLoc().getBeginLoc(),
9663            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9664         << Using->getQualifier()
9665         << cast<CXXRecordDecl>(CurContext)
9666         << Using->getQualifierLoc().getSourceRange();
9667       Diag(Orig->getLocation(), diag::note_using_decl_target);
9668       Using->setInvalidDecl();
9669       return true;
9670     }
9671   }
9672 
9673   if (Previous.empty()) return false;
9674 
9675   NamedDecl *Target = Orig;
9676   if (isa<UsingShadowDecl>(Target))
9677     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9678 
9679   // If the target happens to be one of the previous declarations, we
9680   // don't have a conflict.
9681   //
9682   // FIXME: but we might be increasing its access, in which case we
9683   // should redeclare it.
9684   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9685   bool FoundEquivalentDecl = false;
9686   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9687          I != E; ++I) {
9688     NamedDecl *D = (*I)->getUnderlyingDecl();
9689     // We can have UsingDecls in our Previous results because we use the same
9690     // LookupResult for checking whether the UsingDecl itself is a valid
9691     // redeclaration.
9692     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9693       continue;
9694 
9695     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9696       // C++ [class.mem]p19:
9697       //   If T is the name of a class, then [every named member other than
9698       //   a non-static data member] shall have a name different from T
9699       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9700           !isa<IndirectFieldDecl>(Target) &&
9701           !isa<UnresolvedUsingValueDecl>(Target) &&
9702           DiagnoseClassNameShadow(
9703               CurContext,
9704               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9705         return true;
9706     }
9707 
9708     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9709       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9710         PrevShadow = Shadow;
9711       FoundEquivalentDecl = true;
9712     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9713       // We don't conflict with an existing using shadow decl of an equivalent
9714       // declaration, but we're not a redeclaration of it.
9715       FoundEquivalentDecl = true;
9716     }
9717 
9718     if (isVisible(D))
9719       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9720   }
9721 
9722   if (FoundEquivalentDecl)
9723     return false;
9724 
9725   if (FunctionDecl *FD = Target->getAsFunction()) {
9726     NamedDecl *OldDecl = nullptr;
9727     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9728                           /*IsForUsingDecl*/ true)) {
9729     case Ovl_Overload:
9730       return false;
9731 
9732     case Ovl_NonFunction:
9733       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9734       break;
9735 
9736     // We found a decl with the exact signature.
9737     case Ovl_Match:
9738       // If we're in a record, we want to hide the target, so we
9739       // return true (without a diagnostic) to tell the caller not to
9740       // build a shadow decl.
9741       if (CurContext->isRecord())
9742         return true;
9743 
9744       // If we're not in a record, this is an error.
9745       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9746       break;
9747     }
9748 
9749     Diag(Target->getLocation(), diag::note_using_decl_target);
9750     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9751     Using->setInvalidDecl();
9752     return true;
9753   }
9754 
9755   // Target is not a function.
9756 
9757   if (isa<TagDecl>(Target)) {
9758     // No conflict between a tag and a non-tag.
9759     if (!Tag) return false;
9760 
9761     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9762     Diag(Target->getLocation(), diag::note_using_decl_target);
9763     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9764     Using->setInvalidDecl();
9765     return true;
9766   }
9767 
9768   // No conflict between a tag and a non-tag.
9769   if (!NonTag) return false;
9770 
9771   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9772   Diag(Target->getLocation(), diag::note_using_decl_target);
9773   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9774   Using->setInvalidDecl();
9775   return true;
9776 }
9777 
9778 /// Determine whether a direct base class is a virtual base class.
9779 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9780   if (!Derived->getNumVBases())
9781     return false;
9782   for (auto &B : Derived->bases())
9783     if (B.getType()->getAsCXXRecordDecl() == Base)
9784       return B.isVirtual();
9785   llvm_unreachable("not a direct base class");
9786 }
9787 
9788 /// Builds a shadow declaration corresponding to a 'using' declaration.
9789 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9790                                             UsingDecl *UD,
9791                                             NamedDecl *Orig,
9792                                             UsingShadowDecl *PrevDecl) {
9793   // If we resolved to another shadow declaration, just coalesce them.
9794   NamedDecl *Target = Orig;
9795   if (isa<UsingShadowDecl>(Target)) {
9796     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9797     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9798   }
9799 
9800   NamedDecl *NonTemplateTarget = Target;
9801   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9802     NonTemplateTarget = TargetTD->getTemplatedDecl();
9803 
9804   UsingShadowDecl *Shadow;
9805   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9806     bool IsVirtualBase =
9807         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9808                             UD->getQualifier()->getAsRecordDecl());
9809     Shadow = ConstructorUsingShadowDecl::Create(
9810         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9811   } else {
9812     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9813                                      Target);
9814   }
9815   UD->addShadowDecl(Shadow);
9816 
9817   Shadow->setAccess(UD->getAccess());
9818   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9819     Shadow->setInvalidDecl();
9820 
9821   Shadow->setPreviousDecl(PrevDecl);
9822 
9823   if (S)
9824     PushOnScopeChains(Shadow, S);
9825   else
9826     CurContext->addDecl(Shadow);
9827 
9828 
9829   return Shadow;
9830 }
9831 
9832 /// Hides a using shadow declaration.  This is required by the current
9833 /// using-decl implementation when a resolvable using declaration in a
9834 /// class is followed by a declaration which would hide or override
9835 /// one or more of the using decl's targets; for example:
9836 ///
9837 ///   struct Base { void foo(int); };
9838 ///   struct Derived : Base {
9839 ///     using Base::foo;
9840 ///     void foo(int);
9841 ///   };
9842 ///
9843 /// The governing language is C++03 [namespace.udecl]p12:
9844 ///
9845 ///   When a using-declaration brings names from a base class into a
9846 ///   derived class scope, member functions in the derived class
9847 ///   override and/or hide member functions with the same name and
9848 ///   parameter types in a base class (rather than conflicting).
9849 ///
9850 /// There are two ways to implement this:
9851 ///   (1) optimistically create shadow decls when they're not hidden
9852 ///       by existing declarations, or
9853 ///   (2) don't create any shadow decls (or at least don't make them
9854 ///       visible) until we've fully parsed/instantiated the class.
9855 /// The problem with (1) is that we might have to retroactively remove
9856 /// a shadow decl, which requires several O(n) operations because the
9857 /// decl structures are (very reasonably) not designed for removal.
9858 /// (2) avoids this but is very fiddly and phase-dependent.
9859 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9860   if (Shadow->getDeclName().getNameKind() ==
9861         DeclarationName::CXXConversionFunctionName)
9862     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9863 
9864   // Remove it from the DeclContext...
9865   Shadow->getDeclContext()->removeDecl(Shadow);
9866 
9867   // ...and the scope, if applicable...
9868   if (S) {
9869     S->RemoveDecl(Shadow);
9870     IdResolver.RemoveDecl(Shadow);
9871   }
9872 
9873   // ...and the using decl.
9874   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9875 
9876   // TODO: complain somehow if Shadow was used.  It shouldn't
9877   // be possible for this to happen, because...?
9878 }
9879 
9880 /// Find the base specifier for a base class with the given type.
9881 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9882                                                 QualType DesiredBase,
9883                                                 bool &AnyDependentBases) {
9884   // Check whether the named type is a direct base class.
9885   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9886   for (auto &Base : Derived->bases()) {
9887     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9888     if (CanonicalDesiredBase == BaseType)
9889       return &Base;
9890     if (BaseType->isDependentType())
9891       AnyDependentBases = true;
9892   }
9893   return nullptr;
9894 }
9895 
9896 namespace {
9897 class UsingValidatorCCC final : public CorrectionCandidateCallback {
9898 public:
9899   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9900                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9901       : HasTypenameKeyword(HasTypenameKeyword),
9902         IsInstantiation(IsInstantiation), OldNNS(NNS),
9903         RequireMemberOf(RequireMemberOf) {}
9904 
9905   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9906     NamedDecl *ND = Candidate.getCorrectionDecl();
9907 
9908     // Keywords are not valid here.
9909     if (!ND || isa<NamespaceDecl>(ND))
9910       return false;
9911 
9912     // Completely unqualified names are invalid for a 'using' declaration.
9913     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9914       return false;
9915 
9916     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9917     // reject.
9918 
9919     if (RequireMemberOf) {
9920       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9921       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9922         // No-one ever wants a using-declaration to name an injected-class-name
9923         // of a base class, unless they're declaring an inheriting constructor.
9924         ASTContext &Ctx = ND->getASTContext();
9925         if (!Ctx.getLangOpts().CPlusPlus11)
9926           return false;
9927         QualType FoundType = Ctx.getRecordType(FoundRecord);
9928 
9929         // Check that the injected-class-name is named as a member of its own
9930         // type; we don't want to suggest 'using Derived::Base;', since that
9931         // means something else.
9932         NestedNameSpecifier *Specifier =
9933             Candidate.WillReplaceSpecifier()
9934                 ? Candidate.getCorrectionSpecifier()
9935                 : OldNNS;
9936         if (!Specifier->getAsType() ||
9937             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9938           return false;
9939 
9940         // Check that this inheriting constructor declaration actually names a
9941         // direct base class of the current class.
9942         bool AnyDependentBases = false;
9943         if (!findDirectBaseWithType(RequireMemberOf,
9944                                     Ctx.getRecordType(FoundRecord),
9945                                     AnyDependentBases) &&
9946             !AnyDependentBases)
9947           return false;
9948       } else {
9949         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9950         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9951           return false;
9952 
9953         // FIXME: Check that the base class member is accessible?
9954       }
9955     } else {
9956       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9957       if (FoundRecord && FoundRecord->isInjectedClassName())
9958         return false;
9959     }
9960 
9961     if (isa<TypeDecl>(ND))
9962       return HasTypenameKeyword || !IsInstantiation;
9963 
9964     return !HasTypenameKeyword;
9965   }
9966 
9967   std::unique_ptr<CorrectionCandidateCallback> clone() override {
9968     return llvm::make_unique<UsingValidatorCCC>(*this);
9969   }
9970 
9971 private:
9972   bool HasTypenameKeyword;
9973   bool IsInstantiation;
9974   NestedNameSpecifier *OldNNS;
9975   CXXRecordDecl *RequireMemberOf;
9976 };
9977 } // end anonymous namespace
9978 
9979 /// Builds a using declaration.
9980 ///
9981 /// \param IsInstantiation - Whether this call arises from an
9982 ///   instantiation of an unresolved using declaration.  We treat
9983 ///   the lookup differently for these declarations.
9984 NamedDecl *Sema::BuildUsingDeclaration(
9985     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9986     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9987     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9988     const ParsedAttributesView &AttrList, bool IsInstantiation) {
9989   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9990   SourceLocation IdentLoc = NameInfo.getLoc();
9991   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9992 
9993   // FIXME: We ignore attributes for now.
9994 
9995   // For an inheriting constructor declaration, the name of the using
9996   // declaration is the name of a constructor in this class, not in the
9997   // base class.
9998   DeclarationNameInfo UsingName = NameInfo;
9999   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
10000     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
10001       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10002           Context.getCanonicalType(Context.getRecordType(RD))));
10003 
10004   // Do the redeclaration lookup in the current scope.
10005   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
10006                         ForVisibleRedeclaration);
10007   Previous.setHideTags(false);
10008   if (S) {
10009     LookupName(Previous, S);
10010 
10011     // It is really dumb that we have to do this.
10012     LookupResult::Filter F = Previous.makeFilter();
10013     while (F.hasNext()) {
10014       NamedDecl *D = F.next();
10015       if (!isDeclInScope(D, CurContext, S))
10016         F.erase();
10017       // If we found a local extern declaration that's not ordinarily visible,
10018       // and this declaration is being added to a non-block scope, ignore it.
10019       // We're only checking for scope conflicts here, not also for violations
10020       // of the linkage rules.
10021       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
10022                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
10023         F.erase();
10024     }
10025     F.done();
10026   } else {
10027     assert(IsInstantiation && "no scope in non-instantiation");
10028     if (CurContext->isRecord())
10029       LookupQualifiedName(Previous, CurContext);
10030     else {
10031       // No redeclaration check is needed here; in non-member contexts we
10032       // diagnosed all possible conflicts with other using-declarations when
10033       // building the template:
10034       //
10035       // For a dependent non-type using declaration, the only valid case is
10036       // if we instantiate to a single enumerator. We check for conflicts
10037       // between shadow declarations we introduce, and we check in the template
10038       // definition for conflicts between a non-type using declaration and any
10039       // other declaration, which together covers all cases.
10040       //
10041       // A dependent typename using declaration will never successfully
10042       // instantiate, since it will always name a class member, so we reject
10043       // that in the template definition.
10044     }
10045   }
10046 
10047   // Check for invalid redeclarations.
10048   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
10049                                   SS, IdentLoc, Previous))
10050     return nullptr;
10051 
10052   // Check for bad qualifiers.
10053   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
10054                               IdentLoc))
10055     return nullptr;
10056 
10057   DeclContext *LookupContext = computeDeclContext(SS);
10058   NamedDecl *D;
10059   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10060   if (!LookupContext || EllipsisLoc.isValid()) {
10061     if (HasTypenameKeyword) {
10062       // FIXME: not all declaration name kinds are legal here
10063       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
10064                                               UsingLoc, TypenameLoc,
10065                                               QualifierLoc,
10066                                               IdentLoc, NameInfo.getName(),
10067                                               EllipsisLoc);
10068     } else {
10069       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
10070                                            QualifierLoc, NameInfo, EllipsisLoc);
10071     }
10072     D->setAccess(AS);
10073     CurContext->addDecl(D);
10074     return D;
10075   }
10076 
10077   auto Build = [&](bool Invalid) {
10078     UsingDecl *UD =
10079         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10080                           UsingName, HasTypenameKeyword);
10081     UD->setAccess(AS);
10082     CurContext->addDecl(UD);
10083     UD->setInvalidDecl(Invalid);
10084     return UD;
10085   };
10086   auto BuildInvalid = [&]{ return Build(true); };
10087   auto BuildValid = [&]{ return Build(false); };
10088 
10089   if (RequireCompleteDeclContext(SS, LookupContext))
10090     return BuildInvalid();
10091 
10092   // Look up the target name.
10093   LookupResult R(*this, NameInfo, LookupOrdinaryName);
10094 
10095   // Unlike most lookups, we don't always want to hide tag
10096   // declarations: tag names are visible through the using declaration
10097   // even if hidden by ordinary names, *except* in a dependent context
10098   // where it's important for the sanity of two-phase lookup.
10099   if (!IsInstantiation)
10100     R.setHideTags(false);
10101 
10102   // For the purposes of this lookup, we have a base object type
10103   // equal to that of the current context.
10104   if (CurContext->isRecord()) {
10105     R.setBaseObjectType(
10106                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10107   }
10108 
10109   LookupQualifiedName(R, LookupContext);
10110 
10111   // Try to correct typos if possible. If constructor name lookup finds no
10112   // results, that means the named class has no explicit constructors, and we
10113   // suppressed declaring implicit ones (probably because it's dependent or
10114   // invalid).
10115   if (R.empty() &&
10116       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10117     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10118     // it will believe that glibc provides a ::gets in cases where it does not,
10119     // and will try to pull it into namespace std with a using-declaration.
10120     // Just ignore the using-declaration in that case.
10121     auto *II = NameInfo.getName().getAsIdentifierInfo();
10122     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10123         CurContext->isStdNamespace() &&
10124         isa<TranslationUnitDecl>(LookupContext) &&
10125         getSourceManager().isInSystemHeader(UsingLoc))
10126       return nullptr;
10127     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10128                           dyn_cast<CXXRecordDecl>(CurContext));
10129     if (TypoCorrection Corrected =
10130             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
10131                         CTK_ErrorRecovery)) {
10132       // We reject candidates where DroppedSpecifier == true, hence the
10133       // literal '0' below.
10134       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10135                                 << NameInfo.getName() << LookupContext << 0
10136                                 << SS.getRange());
10137 
10138       // If we picked a correction with no attached Decl we can't do anything
10139       // useful with it, bail out.
10140       NamedDecl *ND = Corrected.getCorrectionDecl();
10141       if (!ND)
10142         return BuildInvalid();
10143 
10144       // If we corrected to an inheriting constructor, handle it as one.
10145       auto *RD = dyn_cast<CXXRecordDecl>(ND);
10146       if (RD && RD->isInjectedClassName()) {
10147         // The parent of the injected class name is the class itself.
10148         RD = cast<CXXRecordDecl>(RD->getParent());
10149 
10150         // Fix up the information we'll use to build the using declaration.
10151         if (Corrected.WillReplaceSpecifier()) {
10152           NestedNameSpecifierLocBuilder Builder;
10153           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10154                               QualifierLoc.getSourceRange());
10155           QualifierLoc = Builder.getWithLocInContext(Context);
10156         }
10157 
10158         // In this case, the name we introduce is the name of a derived class
10159         // constructor.
10160         auto *CurClass = cast<CXXRecordDecl>(CurContext);
10161         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10162             Context.getCanonicalType(Context.getRecordType(CurClass))));
10163         UsingName.setNamedTypeInfo(nullptr);
10164         for (auto *Ctor : LookupConstructors(RD))
10165           R.addDecl(Ctor);
10166         R.resolveKind();
10167       } else {
10168         // FIXME: Pick up all the declarations if we found an overloaded
10169         // function.
10170         UsingName.setName(ND->getDeclName());
10171         R.addDecl(ND);
10172       }
10173     } else {
10174       Diag(IdentLoc, diag::err_no_member)
10175         << NameInfo.getName() << LookupContext << SS.getRange();
10176       return BuildInvalid();
10177     }
10178   }
10179 
10180   if (R.isAmbiguous())
10181     return BuildInvalid();
10182 
10183   if (HasTypenameKeyword) {
10184     // If we asked for a typename and got a non-type decl, error out.
10185     if (!R.getAsSingle<TypeDecl>()) {
10186       Diag(IdentLoc, diag::err_using_typename_non_type);
10187       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10188         Diag((*I)->getUnderlyingDecl()->getLocation(),
10189              diag::note_using_decl_target);
10190       return BuildInvalid();
10191     }
10192   } else {
10193     // If we asked for a non-typename and we got a type, error out,
10194     // but only if this is an instantiation of an unresolved using
10195     // decl.  Otherwise just silently find the type name.
10196     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10197       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10198       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10199       return BuildInvalid();
10200     }
10201   }
10202 
10203   // C++14 [namespace.udecl]p6:
10204   // A using-declaration shall not name a namespace.
10205   if (R.getAsSingle<NamespaceDecl>()) {
10206     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10207       << SS.getRange();
10208     return BuildInvalid();
10209   }
10210 
10211   // C++14 [namespace.udecl]p7:
10212   // A using-declaration shall not name a scoped enumerator.
10213   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10214     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10215       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10216         << SS.getRange();
10217       return BuildInvalid();
10218     }
10219   }
10220 
10221   UsingDecl *UD = BuildValid();
10222 
10223   // Some additional rules apply to inheriting constructors.
10224   if (UsingName.getName().getNameKind() ==
10225         DeclarationName::CXXConstructorName) {
10226     // Suppress access diagnostics; the access check is instead performed at the
10227     // point of use for an inheriting constructor.
10228     R.suppressDiagnostics();
10229     if (CheckInheritingConstructorUsingDecl(UD))
10230       return UD;
10231   }
10232 
10233   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10234     UsingShadowDecl *PrevDecl = nullptr;
10235     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10236       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10237   }
10238 
10239   return UD;
10240 }
10241 
10242 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10243                                     ArrayRef<NamedDecl *> Expansions) {
10244   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10245          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10246          isa<UsingPackDecl>(InstantiatedFrom));
10247 
10248   auto *UPD =
10249       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10250   UPD->setAccess(InstantiatedFrom->getAccess());
10251   CurContext->addDecl(UPD);
10252   return UPD;
10253 }
10254 
10255 /// Additional checks for a using declaration referring to a constructor name.
10256 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10257   assert(!UD->hasTypename() && "expecting a constructor name");
10258 
10259   const Type *SourceType = UD->getQualifier()->getAsType();
10260   assert(SourceType &&
10261          "Using decl naming constructor doesn't have type in scope spec.");
10262   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10263 
10264   // Check whether the named type is a direct base class.
10265   bool AnyDependentBases = false;
10266   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10267                                       AnyDependentBases);
10268   if (!Base && !AnyDependentBases) {
10269     Diag(UD->getUsingLoc(),
10270          diag::err_using_decl_constructor_not_in_direct_base)
10271       << UD->getNameInfo().getSourceRange()
10272       << QualType(SourceType, 0) << TargetClass;
10273     UD->setInvalidDecl();
10274     return true;
10275   }
10276 
10277   if (Base)
10278     Base->setInheritConstructors();
10279 
10280   return false;
10281 }
10282 
10283 /// Checks that the given using declaration is not an invalid
10284 /// redeclaration.  Note that this is checking only for the using decl
10285 /// itself, not for any ill-formedness among the UsingShadowDecls.
10286 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10287                                        bool HasTypenameKeyword,
10288                                        const CXXScopeSpec &SS,
10289                                        SourceLocation NameLoc,
10290                                        const LookupResult &Prev) {
10291   NestedNameSpecifier *Qual = SS.getScopeRep();
10292 
10293   // C++03 [namespace.udecl]p8:
10294   // C++0x [namespace.udecl]p10:
10295   //   A using-declaration is a declaration and can therefore be used
10296   //   repeatedly where (and only where) multiple declarations are
10297   //   allowed.
10298   //
10299   // That's in non-member contexts.
10300   if (!CurContext->getRedeclContext()->isRecord()) {
10301     // A dependent qualifier outside a class can only ever resolve to an
10302     // enumeration type. Therefore it conflicts with any other non-type
10303     // declaration in the same scope.
10304     // FIXME: How should we check for dependent type-type conflicts at block
10305     // scope?
10306     if (Qual->isDependent() && !HasTypenameKeyword) {
10307       for (auto *D : Prev) {
10308         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10309           bool OldCouldBeEnumerator =
10310               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10311           Diag(NameLoc,
10312                OldCouldBeEnumerator ? diag::err_redefinition
10313                                     : diag::err_redefinition_different_kind)
10314               << Prev.getLookupName();
10315           Diag(D->getLocation(), diag::note_previous_definition);
10316           return true;
10317         }
10318       }
10319     }
10320     return false;
10321   }
10322 
10323   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10324     NamedDecl *D = *I;
10325 
10326     bool DTypename;
10327     NestedNameSpecifier *DQual;
10328     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10329       DTypename = UD->hasTypename();
10330       DQual = UD->getQualifier();
10331     } else if (UnresolvedUsingValueDecl *UD
10332                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10333       DTypename = false;
10334       DQual = UD->getQualifier();
10335     } else if (UnresolvedUsingTypenameDecl *UD
10336                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10337       DTypename = true;
10338       DQual = UD->getQualifier();
10339     } else continue;
10340 
10341     // using decls differ if one says 'typename' and the other doesn't.
10342     // FIXME: non-dependent using decls?
10343     if (HasTypenameKeyword != DTypename) continue;
10344 
10345     // using decls differ if they name different scopes (but note that
10346     // template instantiation can cause this check to trigger when it
10347     // didn't before instantiation).
10348     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10349         Context.getCanonicalNestedNameSpecifier(DQual))
10350       continue;
10351 
10352     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10353     Diag(D->getLocation(), diag::note_using_decl) << 1;
10354     return true;
10355   }
10356 
10357   return false;
10358 }
10359 
10360 
10361 /// Checks that the given nested-name qualifier used in a using decl
10362 /// in the current context is appropriately related to the current
10363 /// scope.  If an error is found, diagnoses it and returns true.
10364 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10365                                    bool HasTypename,
10366                                    const CXXScopeSpec &SS,
10367                                    const DeclarationNameInfo &NameInfo,
10368                                    SourceLocation NameLoc) {
10369   DeclContext *NamedContext = computeDeclContext(SS);
10370 
10371   if (!CurContext->isRecord()) {
10372     // C++03 [namespace.udecl]p3:
10373     // C++0x [namespace.udecl]p8:
10374     //   A using-declaration for a class member shall be a member-declaration.
10375 
10376     // If we weren't able to compute a valid scope, it might validly be a
10377     // dependent class scope or a dependent enumeration unscoped scope. If
10378     // we have a 'typename' keyword, the scope must resolve to a class type.
10379     if ((HasTypename && !NamedContext) ||
10380         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10381       auto *RD = NamedContext
10382                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10383                      : nullptr;
10384       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10385         RD = nullptr;
10386 
10387       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10388         << SS.getRange();
10389 
10390       // If we have a complete, non-dependent source type, try to suggest a
10391       // way to get the same effect.
10392       if (!RD)
10393         return true;
10394 
10395       // Find what this using-declaration was referring to.
10396       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10397       R.setHideTags(false);
10398       R.suppressDiagnostics();
10399       LookupQualifiedName(R, RD);
10400 
10401       if (R.getAsSingle<TypeDecl>()) {
10402         if (getLangOpts().CPlusPlus11) {
10403           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10404           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10405             << 0 // alias declaration
10406             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10407                                           NameInfo.getName().getAsString() +
10408                                               " = ");
10409         } else {
10410           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10411           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10412           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10413             << 1 // typedef declaration
10414             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10415             << FixItHint::CreateInsertion(
10416                    InsertLoc, " " + NameInfo.getName().getAsString());
10417         }
10418       } else if (R.getAsSingle<VarDecl>()) {
10419         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10420         // repeating the type of the static data member here.
10421         FixItHint FixIt;
10422         if (getLangOpts().CPlusPlus11) {
10423           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10424           FixIt = FixItHint::CreateReplacement(
10425               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10426         }
10427 
10428         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10429           << 2 // reference declaration
10430           << FixIt;
10431       } else if (R.getAsSingle<EnumConstantDecl>()) {
10432         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10433         // repeating the type of the enumeration here, and we can't do so if
10434         // the type is anonymous.
10435         FixItHint FixIt;
10436         if (getLangOpts().CPlusPlus11) {
10437           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10438           FixIt = FixItHint::CreateReplacement(
10439               UsingLoc,
10440               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10441         }
10442 
10443         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10444           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10445           << FixIt;
10446       }
10447       return true;
10448     }
10449 
10450     // Otherwise, this might be valid.
10451     return false;
10452   }
10453 
10454   // The current scope is a record.
10455 
10456   // If the named context is dependent, we can't decide much.
10457   if (!NamedContext) {
10458     // FIXME: in C++0x, we can diagnose if we can prove that the
10459     // nested-name-specifier does not refer to a base class, which is
10460     // still possible in some cases.
10461 
10462     // Otherwise we have to conservatively report that things might be
10463     // okay.
10464     return false;
10465   }
10466 
10467   if (!NamedContext->isRecord()) {
10468     // Ideally this would point at the last name in the specifier,
10469     // but we don't have that level of source info.
10470     Diag(SS.getRange().getBegin(),
10471          diag::err_using_decl_nested_name_specifier_is_not_class)
10472       << SS.getScopeRep() << SS.getRange();
10473     return true;
10474   }
10475 
10476   if (!NamedContext->isDependentContext() &&
10477       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10478     return true;
10479 
10480   if (getLangOpts().CPlusPlus11) {
10481     // C++11 [namespace.udecl]p3:
10482     //   In a using-declaration used as a member-declaration, the
10483     //   nested-name-specifier shall name a base class of the class
10484     //   being defined.
10485 
10486     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10487                                  cast<CXXRecordDecl>(NamedContext))) {
10488       if (CurContext == NamedContext) {
10489         Diag(NameLoc,
10490              diag::err_using_decl_nested_name_specifier_is_current_class)
10491           << SS.getRange();
10492         return true;
10493       }
10494 
10495       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10496         Diag(SS.getRange().getBegin(),
10497              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10498           << SS.getScopeRep()
10499           << cast<CXXRecordDecl>(CurContext)
10500           << SS.getRange();
10501       }
10502       return true;
10503     }
10504 
10505     return false;
10506   }
10507 
10508   // C++03 [namespace.udecl]p4:
10509   //   A using-declaration used as a member-declaration shall refer
10510   //   to a member of a base class of the class being defined [etc.].
10511 
10512   // Salient point: SS doesn't have to name a base class as long as
10513   // lookup only finds members from base classes.  Therefore we can
10514   // diagnose here only if we can prove that that can't happen,
10515   // i.e. if the class hierarchies provably don't intersect.
10516 
10517   // TODO: it would be nice if "definitely valid" results were cached
10518   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10519   // need to be repeated.
10520 
10521   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10522   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10523     Bases.insert(Base);
10524     return true;
10525   };
10526 
10527   // Collect all bases. Return false if we find a dependent base.
10528   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10529     return false;
10530 
10531   // Returns true if the base is dependent or is one of the accumulated base
10532   // classes.
10533   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10534     return !Bases.count(Base);
10535   };
10536 
10537   // Return false if the class has a dependent base or if it or one
10538   // of its bases is present in the base set of the current context.
10539   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10540       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10541     return false;
10542 
10543   Diag(SS.getRange().getBegin(),
10544        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10545     << SS.getScopeRep()
10546     << cast<CXXRecordDecl>(CurContext)
10547     << SS.getRange();
10548 
10549   return true;
10550 }
10551 
10552 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10553                                   MultiTemplateParamsArg TemplateParamLists,
10554                                   SourceLocation UsingLoc, UnqualifiedId &Name,
10555                                   const ParsedAttributesView &AttrList,
10556                                   TypeResult Type, Decl *DeclFromDeclSpec) {
10557   // Skip up to the relevant declaration scope.
10558   while (S->isTemplateParamScope())
10559     S = S->getParent();
10560   assert((S->getFlags() & Scope::DeclScope) &&
10561          "got alias-declaration outside of declaration scope");
10562 
10563   if (Type.isInvalid())
10564     return nullptr;
10565 
10566   bool Invalid = false;
10567   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10568   TypeSourceInfo *TInfo = nullptr;
10569   GetTypeFromParser(Type.get(), &TInfo);
10570 
10571   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10572     return nullptr;
10573 
10574   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10575                                       UPPC_DeclarationType)) {
10576     Invalid = true;
10577     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10578                                              TInfo->getTypeLoc().getBeginLoc());
10579   }
10580 
10581   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10582                         TemplateParamLists.size()
10583                             ? forRedeclarationInCurContext()
10584                             : ForVisibleRedeclaration);
10585   LookupName(Previous, S);
10586 
10587   // Warn about shadowing the name of a template parameter.
10588   if (Previous.isSingleResult() &&
10589       Previous.getFoundDecl()->isTemplateParameter()) {
10590     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10591     Previous.clear();
10592   }
10593 
10594   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10595          "name in alias declaration must be an identifier");
10596   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10597                                                Name.StartLocation,
10598                                                Name.Identifier, TInfo);
10599 
10600   NewTD->setAccess(AS);
10601 
10602   if (Invalid)
10603     NewTD->setInvalidDecl();
10604 
10605   ProcessDeclAttributeList(S, NewTD, AttrList);
10606   AddPragmaAttributes(S, NewTD);
10607 
10608   CheckTypedefForVariablyModifiedType(S, NewTD);
10609   Invalid |= NewTD->isInvalidDecl();
10610 
10611   bool Redeclaration = false;
10612 
10613   NamedDecl *NewND;
10614   if (TemplateParamLists.size()) {
10615     TypeAliasTemplateDecl *OldDecl = nullptr;
10616     TemplateParameterList *OldTemplateParams = nullptr;
10617 
10618     if (TemplateParamLists.size() != 1) {
10619       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10620         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10621          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10622     }
10623     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10624 
10625     // Check that we can declare a template here.
10626     if (CheckTemplateDeclScope(S, TemplateParams))
10627       return nullptr;
10628 
10629     // Only consider previous declarations in the same scope.
10630     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10631                          /*ExplicitInstantiationOrSpecialization*/false);
10632     if (!Previous.empty()) {
10633       Redeclaration = true;
10634 
10635       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10636       if (!OldDecl && !Invalid) {
10637         Diag(UsingLoc, diag::err_redefinition_different_kind)
10638           << Name.Identifier;
10639 
10640         NamedDecl *OldD = Previous.getRepresentativeDecl();
10641         if (OldD->getLocation().isValid())
10642           Diag(OldD->getLocation(), diag::note_previous_definition);
10643 
10644         Invalid = true;
10645       }
10646 
10647       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10648         if (TemplateParameterListsAreEqual(TemplateParams,
10649                                            OldDecl->getTemplateParameters(),
10650                                            /*Complain=*/true,
10651                                            TPL_TemplateMatch))
10652           OldTemplateParams =
10653               OldDecl->getMostRecentDecl()->getTemplateParameters();
10654         else
10655           Invalid = true;
10656 
10657         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10658         if (!Invalid &&
10659             !Context.hasSameType(OldTD->getUnderlyingType(),
10660                                  NewTD->getUnderlyingType())) {
10661           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10662           // but we can't reasonably accept it.
10663           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10664             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10665           if (OldTD->getLocation().isValid())
10666             Diag(OldTD->getLocation(), diag::note_previous_definition);
10667           Invalid = true;
10668         }
10669       }
10670     }
10671 
10672     // Merge any previous default template arguments into our parameters,
10673     // and check the parameter list.
10674     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10675                                    TPC_TypeAliasTemplate))
10676       return nullptr;
10677 
10678     TypeAliasTemplateDecl *NewDecl =
10679       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10680                                     Name.Identifier, TemplateParams,
10681                                     NewTD);
10682     NewTD->setDescribedAliasTemplate(NewDecl);
10683 
10684     NewDecl->setAccess(AS);
10685 
10686     if (Invalid)
10687       NewDecl->setInvalidDecl();
10688     else if (OldDecl) {
10689       NewDecl->setPreviousDecl(OldDecl);
10690       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10691     }
10692 
10693     NewND = NewDecl;
10694   } else {
10695     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10696       setTagNameForLinkagePurposes(TD, NewTD);
10697       handleTagNumbering(TD, S);
10698     }
10699     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10700     NewND = NewTD;
10701   }
10702 
10703   PushOnScopeChains(NewND, S);
10704   ActOnDocumentableDecl(NewND);
10705   return NewND;
10706 }
10707 
10708 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10709                                    SourceLocation AliasLoc,
10710                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10711                                    SourceLocation IdentLoc,
10712                                    IdentifierInfo *Ident) {
10713 
10714   // Lookup the namespace name.
10715   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10716   LookupParsedName(R, S, &SS);
10717 
10718   if (R.isAmbiguous())
10719     return nullptr;
10720 
10721   if (R.empty()) {
10722     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10723       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10724       return nullptr;
10725     }
10726   }
10727   assert(!R.isAmbiguous() && !R.empty());
10728   NamedDecl *ND = R.getRepresentativeDecl();
10729 
10730   // Check if we have a previous declaration with the same name.
10731   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10732                      ForVisibleRedeclaration);
10733   LookupName(PrevR, S);
10734 
10735   // Check we're not shadowing a template parameter.
10736   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10737     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10738     PrevR.clear();
10739   }
10740 
10741   // Filter out any other lookup result from an enclosing scope.
10742   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10743                        /*AllowInlineNamespace*/false);
10744 
10745   // Find the previous declaration and check that we can redeclare it.
10746   NamespaceAliasDecl *Prev = nullptr;
10747   if (PrevR.isSingleResult()) {
10748     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10749     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10750       // We already have an alias with the same name that points to the same
10751       // namespace; check that it matches.
10752       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10753         Prev = AD;
10754       } else if (isVisible(PrevDecl)) {
10755         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10756           << Alias;
10757         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10758           << AD->getNamespace();
10759         return nullptr;
10760       }
10761     } else if (isVisible(PrevDecl)) {
10762       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10763                             ? diag::err_redefinition
10764                             : diag::err_redefinition_different_kind;
10765       Diag(AliasLoc, DiagID) << Alias;
10766       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10767       return nullptr;
10768     }
10769   }
10770 
10771   // The use of a nested name specifier may trigger deprecation warnings.
10772   DiagnoseUseOfDecl(ND, IdentLoc);
10773 
10774   NamespaceAliasDecl *AliasDecl =
10775     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10776                                Alias, SS.getWithLocInContext(Context),
10777                                IdentLoc, ND);
10778   if (Prev)
10779     AliasDecl->setPreviousDecl(Prev);
10780 
10781   PushOnScopeChains(AliasDecl, S);
10782   return AliasDecl;
10783 }
10784 
10785 namespace {
10786 struct SpecialMemberExceptionSpecInfo
10787     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10788   SourceLocation Loc;
10789   Sema::ImplicitExceptionSpecification ExceptSpec;
10790 
10791   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10792                                  Sema::CXXSpecialMember CSM,
10793                                  Sema::InheritedConstructorInfo *ICI,
10794                                  SourceLocation Loc)
10795       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10796 
10797   bool visitBase(CXXBaseSpecifier *Base);
10798   bool visitField(FieldDecl *FD);
10799 
10800   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10801                            unsigned Quals);
10802 
10803   void visitSubobjectCall(Subobject Subobj,
10804                           Sema::SpecialMemberOverloadResult SMOR);
10805 };
10806 }
10807 
10808 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10809   auto *RT = Base->getType()->getAs<RecordType>();
10810   if (!RT)
10811     return false;
10812 
10813   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10814   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10815   if (auto *BaseCtor = SMOR.getMethod()) {
10816     visitSubobjectCall(Base, BaseCtor);
10817     return false;
10818   }
10819 
10820   visitClassSubobject(BaseClass, Base, 0);
10821   return false;
10822 }
10823 
10824 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10825   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10826     Expr *E = FD->getInClassInitializer();
10827     if (!E)
10828       // FIXME: It's a little wasteful to build and throw away a
10829       // CXXDefaultInitExpr here.
10830       // FIXME: We should have a single context note pointing at Loc, and
10831       // this location should be MD->getLocation() instead, since that's
10832       // the location where we actually use the default init expression.
10833       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10834     if (E)
10835       ExceptSpec.CalledExpr(E);
10836   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10837                             ->getAs<RecordType>()) {
10838     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10839                         FD->getType().getCVRQualifiers());
10840   }
10841   return false;
10842 }
10843 
10844 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10845                                                          Subobject Subobj,
10846                                                          unsigned Quals) {
10847   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10848   bool IsMutable = Field && Field->isMutable();
10849   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10850 }
10851 
10852 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10853     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10854   // Note, if lookup fails, it doesn't matter what exception specification we
10855   // choose because the special member will be deleted.
10856   if (CXXMethodDecl *MD = SMOR.getMethod())
10857     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10858 }
10859 
10860 namespace {
10861 /// RAII object to register a special member as being currently declared.
10862 struct ComputingExceptionSpec {
10863   Sema &S;
10864 
10865   ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
10866       : S(S) {
10867     Sema::CodeSynthesisContext Ctx;
10868     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
10869     Ctx.PointOfInstantiation = Loc;
10870     Ctx.Entity = MD;
10871     S.pushCodeSynthesisContext(Ctx);
10872   }
10873   ~ComputingExceptionSpec() {
10874     S.popCodeSynthesisContext();
10875   }
10876 };
10877 }
10878 
10879 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
10880   llvm::APSInt Result;
10881   ExprResult Converted = CheckConvertedConstantExpression(
10882       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
10883   ExplicitSpec.setExpr(Converted.get());
10884   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
10885     ExplicitSpec.setKind(Result.getBoolValue()
10886                              ? ExplicitSpecKind::ResolvedTrue
10887                              : ExplicitSpecKind::ResolvedFalse);
10888     return true;
10889   }
10890   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
10891   return false;
10892 }
10893 
10894 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
10895   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
10896   if (!ExplicitExpr->isTypeDependent())
10897     tryResolveExplicitSpecifier(ES);
10898   return ES;
10899 }
10900 
10901 static Sema::ImplicitExceptionSpecification
10902 ComputeDefaultedSpecialMemberExceptionSpec(
10903     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10904     Sema::InheritedConstructorInfo *ICI) {
10905   ComputingExceptionSpec CES(S, MD, Loc);
10906 
10907   CXXRecordDecl *ClassDecl = MD->getParent();
10908 
10909   // C++ [except.spec]p14:
10910   //   An implicitly declared special member function (Clause 12) shall have an
10911   //   exception-specification. [...]
10912   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
10913   if (ClassDecl->isInvalidDecl())
10914     return Info.ExceptSpec;
10915 
10916   // FIXME: If this diagnostic fires, we're probably missing a check for
10917   // attempting to resolve an exception specification before it's known
10918   // at a higher level.
10919   if (S.RequireCompleteType(MD->getLocation(),
10920                             S.Context.getRecordType(ClassDecl),
10921                             diag::err_exception_spec_incomplete_type))
10922     return Info.ExceptSpec;
10923 
10924   // C++1z [except.spec]p7:
10925   //   [Look for exceptions thrown by] a constructor selected [...] to
10926   //   initialize a potentially constructed subobject,
10927   // C++1z [except.spec]p8:
10928   //   The exception specification for an implicitly-declared destructor, or a
10929   //   destructor without a noexcept-specifier, is potentially-throwing if and
10930   //   only if any of the destructors for any of its potentially constructed
10931   //   subojects is potentially throwing.
10932   // FIXME: We respect the first rule but ignore the "potentially constructed"
10933   // in the second rule to resolve a core issue (no number yet) that would have
10934   // us reject:
10935   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10936   //   struct B : A {};
10937   //   struct C : B { void f(); };
10938   // ... due to giving B::~B() a non-throwing exception specification.
10939   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10940                                 : Info.VisitAllBases);
10941 
10942   return Info.ExceptSpec;
10943 }
10944 
10945 namespace {
10946 /// RAII object to register a special member as being currently declared.
10947 struct DeclaringSpecialMember {
10948   Sema &S;
10949   Sema::SpecialMemberDecl D;
10950   Sema::ContextRAII SavedContext;
10951   bool WasAlreadyBeingDeclared;
10952 
10953   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10954       : S(S), D(RD, CSM), SavedContext(S, RD) {
10955     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10956     if (WasAlreadyBeingDeclared)
10957       // This almost never happens, but if it does, ensure that our cache
10958       // doesn't contain a stale result.
10959       S.SpecialMemberCache.clear();
10960     else {
10961       // Register a note to be produced if we encounter an error while
10962       // declaring the special member.
10963       Sema::CodeSynthesisContext Ctx;
10964       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10965       // FIXME: We don't have a location to use here. Using the class's
10966       // location maintains the fiction that we declare all special members
10967       // with the class, but (1) it's not clear that lying about that helps our
10968       // users understand what's going on, and (2) there may be outer contexts
10969       // on the stack (some of which are relevant) and printing them exposes
10970       // our lies.
10971       Ctx.PointOfInstantiation = RD->getLocation();
10972       Ctx.Entity = RD;
10973       Ctx.SpecialMember = CSM;
10974       S.pushCodeSynthesisContext(Ctx);
10975     }
10976   }
10977   ~DeclaringSpecialMember() {
10978     if (!WasAlreadyBeingDeclared) {
10979       S.SpecialMembersBeingDeclared.erase(D);
10980       S.popCodeSynthesisContext();
10981     }
10982   }
10983 
10984   /// Are we already trying to declare this special member?
10985   bool isAlreadyBeingDeclared() const {
10986     return WasAlreadyBeingDeclared;
10987   }
10988 };
10989 }
10990 
10991 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10992   // Look up any existing declarations, but don't trigger declaration of all
10993   // implicit special members with this name.
10994   DeclarationName Name = FD->getDeclName();
10995   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10996                  ForExternalRedeclaration);
10997   for (auto *D : FD->getParent()->lookup(Name))
10998     if (auto *Acceptable = R.getAcceptableDecl(D))
10999       R.addDecl(Acceptable);
11000   R.resolveKind();
11001   R.suppressDiagnostics();
11002 
11003   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
11004 }
11005 
11006 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
11007                                           QualType ResultTy,
11008                                           ArrayRef<QualType> Args) {
11009   // Build an exception specification pointing back at this constructor.
11010   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
11011 
11012   if (getLangOpts().OpenCLCPlusPlus) {
11013     // OpenCL: Implicitly defaulted special member are of the generic address
11014     // space.
11015     EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
11016   }
11017 
11018   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
11019   SpecialMem->setType(QT);
11020 }
11021 
11022 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
11023                                                      CXXRecordDecl *ClassDecl) {
11024   // C++ [class.ctor]p5:
11025   //   A default constructor for a class X is a constructor of class X
11026   //   that can be called without an argument. If there is no
11027   //   user-declared constructor for class X, a default constructor is
11028   //   implicitly declared. An implicitly-declared default constructor
11029   //   is an inline public member of its class.
11030   assert(ClassDecl->needsImplicitDefaultConstructor() &&
11031          "Should not build implicit default constructor!");
11032 
11033   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
11034   if (DSM.isAlreadyBeingDeclared())
11035     return nullptr;
11036 
11037   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11038                                                      CXXDefaultConstructor,
11039                                                      false);
11040 
11041   // Create the actual constructor declaration.
11042   CanQualType ClassType
11043     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11044   SourceLocation ClassLoc = ClassDecl->getLocation();
11045   DeclarationName Name
11046     = Context.DeclarationNames.getCXXConstructorName(ClassType);
11047   DeclarationNameInfo NameInfo(Name, ClassLoc);
11048   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
11049       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
11050       /*TInfo=*/nullptr, ExplicitSpecifier(),
11051       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11052       Constexpr ? CSK_constexpr : CSK_unspecified);
11053   DefaultCon->setAccess(AS_public);
11054   DefaultCon->setDefaulted();
11055 
11056   if (getLangOpts().CUDA) {
11057     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
11058                                             DefaultCon,
11059                                             /* ConstRHS */ false,
11060                                             /* Diagnose */ false);
11061   }
11062 
11063   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
11064 
11065   // We don't need to use SpecialMemberIsTrivial here; triviality for default
11066   // constructors is easy to compute.
11067   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
11068 
11069   // Note that we have declared this constructor.
11070   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
11071 
11072   Scope *S = getScopeForContext(ClassDecl);
11073   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
11074 
11075   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
11076     SetDeclDeleted(DefaultCon, ClassLoc);
11077 
11078   if (S)
11079     PushOnScopeChains(DefaultCon, S, false);
11080   ClassDecl->addDecl(DefaultCon);
11081 
11082   return DefaultCon;
11083 }
11084 
11085 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
11086                                             CXXConstructorDecl *Constructor) {
11087   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
11088           !Constructor->doesThisDeclarationHaveABody() &&
11089           !Constructor->isDeleted()) &&
11090     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
11091   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11092     return;
11093 
11094   CXXRecordDecl *ClassDecl = Constructor->getParent();
11095   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
11096 
11097   SynthesizedFunctionScope Scope(*this, Constructor);
11098 
11099   // The exception specification is needed because we are defining the
11100   // function.
11101   ResolveExceptionSpec(CurrentLocation,
11102                        Constructor->getType()->castAs<FunctionProtoType>());
11103   MarkVTableUsed(CurrentLocation, ClassDecl);
11104 
11105   // Add a context note for diagnostics produced after this point.
11106   Scope.addContextNote(CurrentLocation);
11107 
11108   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11109     Constructor->setInvalidDecl();
11110     return;
11111   }
11112 
11113   SourceLocation Loc = Constructor->getEndLoc().isValid()
11114                            ? Constructor->getEndLoc()
11115                            : Constructor->getLocation();
11116   Constructor->setBody(new (Context) CompoundStmt(Loc));
11117   Constructor->markUsed(Context);
11118 
11119   if (ASTMutationListener *L = getASTMutationListener()) {
11120     L->CompletedImplicitDefinition(Constructor);
11121   }
11122 
11123   DiagnoseUninitializedFields(*this, Constructor);
11124 }
11125 
11126 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
11127   // Perform any delayed checks on exception specifications.
11128   CheckDelayedMemberExceptionSpecs();
11129 }
11130 
11131 /// Find or create the fake constructor we synthesize to model constructing an
11132 /// object of a derived class via a constructor of a base class.
11133 CXXConstructorDecl *
11134 Sema::findInheritingConstructor(SourceLocation Loc,
11135                                 CXXConstructorDecl *BaseCtor,
11136                                 ConstructorUsingShadowDecl *Shadow) {
11137   CXXRecordDecl *Derived = Shadow->getParent();
11138   SourceLocation UsingLoc = Shadow->getLocation();
11139 
11140   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11141   // For now we use the name of the base class constructor as a member of the
11142   // derived class to indicate a (fake) inherited constructor name.
11143   DeclarationName Name = BaseCtor->getDeclName();
11144 
11145   // Check to see if we already have a fake constructor for this inherited
11146   // constructor call.
11147   for (NamedDecl *Ctor : Derived->lookup(Name))
11148     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11149                                ->getInheritedConstructor()
11150                                .getConstructor(),
11151                            BaseCtor))
11152       return cast<CXXConstructorDecl>(Ctor);
11153 
11154   DeclarationNameInfo NameInfo(Name, UsingLoc);
11155   TypeSourceInfo *TInfo =
11156       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11157   FunctionProtoTypeLoc ProtoLoc =
11158       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11159 
11160   // Check the inherited constructor is valid and find the list of base classes
11161   // from which it was inherited.
11162   InheritedConstructorInfo ICI(*this, Loc, Shadow);
11163 
11164   bool Constexpr =
11165       BaseCtor->isConstexpr() &&
11166       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11167                                         false, BaseCtor, &ICI);
11168 
11169   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11170       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11171       BaseCtor->getExplicitSpecifier(), /*Inline=*/true,
11172       /*ImplicitlyDeclared=*/true,
11173       Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
11174       InheritedConstructor(Shadow, BaseCtor));
11175   if (Shadow->isInvalidDecl())
11176     DerivedCtor->setInvalidDecl();
11177 
11178   // Build an unevaluated exception specification for this fake constructor.
11179   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11180   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11181   EPI.ExceptionSpec.Type = EST_Unevaluated;
11182   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11183   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11184                                                FPT->getParamTypes(), EPI));
11185 
11186   // Build the parameter declarations.
11187   SmallVector<ParmVarDecl *, 16> ParamDecls;
11188   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11189     TypeSourceInfo *TInfo =
11190         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11191     ParmVarDecl *PD = ParmVarDecl::Create(
11192         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11193         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
11194     PD->setScopeInfo(0, I);
11195     PD->setImplicit();
11196     // Ensure attributes are propagated onto parameters (this matters for
11197     // format, pass_object_size, ...).
11198     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11199     ParamDecls.push_back(PD);
11200     ProtoLoc.setParam(I, PD);
11201   }
11202 
11203   // Set up the new constructor.
11204   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11205   DerivedCtor->setAccess(BaseCtor->getAccess());
11206   DerivedCtor->setParams(ParamDecls);
11207   Derived->addDecl(DerivedCtor);
11208 
11209   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11210     SetDeclDeleted(DerivedCtor, UsingLoc);
11211 
11212   return DerivedCtor;
11213 }
11214 
11215 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11216   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11217                                Ctor->getInheritedConstructor().getShadowDecl());
11218   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11219                             /*Diagnose*/true);
11220 }
11221 
11222 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11223                                        CXXConstructorDecl *Constructor) {
11224   CXXRecordDecl *ClassDecl = Constructor->getParent();
11225   assert(Constructor->getInheritedConstructor() &&
11226          !Constructor->doesThisDeclarationHaveABody() &&
11227          !Constructor->isDeleted());
11228   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11229     return;
11230 
11231   // Initializations are performed "as if by a defaulted default constructor",
11232   // so enter the appropriate scope.
11233   SynthesizedFunctionScope Scope(*this, Constructor);
11234 
11235   // The exception specification is needed because we are defining the
11236   // function.
11237   ResolveExceptionSpec(CurrentLocation,
11238                        Constructor->getType()->castAs<FunctionProtoType>());
11239   MarkVTableUsed(CurrentLocation, ClassDecl);
11240 
11241   // Add a context note for diagnostics produced after this point.
11242   Scope.addContextNote(CurrentLocation);
11243 
11244   ConstructorUsingShadowDecl *Shadow =
11245       Constructor->getInheritedConstructor().getShadowDecl();
11246   CXXConstructorDecl *InheritedCtor =
11247       Constructor->getInheritedConstructor().getConstructor();
11248 
11249   // [class.inhctor.init]p1:
11250   //   initialization proceeds as if a defaulted default constructor is used to
11251   //   initialize the D object and each base class subobject from which the
11252   //   constructor was inherited
11253 
11254   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11255   CXXRecordDecl *RD = Shadow->getParent();
11256   SourceLocation InitLoc = Shadow->getLocation();
11257 
11258   // Build explicit initializers for all base classes from which the
11259   // constructor was inherited.
11260   SmallVector<CXXCtorInitializer*, 8> Inits;
11261   for (bool VBase : {false, true}) {
11262     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11263       if (B.isVirtual() != VBase)
11264         continue;
11265 
11266       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11267       if (!BaseRD)
11268         continue;
11269 
11270       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11271       if (!BaseCtor.first)
11272         continue;
11273 
11274       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11275       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11276           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11277 
11278       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11279       Inits.push_back(new (Context) CXXCtorInitializer(
11280           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11281           SourceLocation()));
11282     }
11283   }
11284 
11285   // We now proceed as if for a defaulted default constructor, with the relevant
11286   // initializers replaced.
11287 
11288   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11289     Constructor->setInvalidDecl();
11290     return;
11291   }
11292 
11293   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11294   Constructor->markUsed(Context);
11295 
11296   if (ASTMutationListener *L = getASTMutationListener()) {
11297     L->CompletedImplicitDefinition(Constructor);
11298   }
11299 
11300   DiagnoseUninitializedFields(*this, Constructor);
11301 }
11302 
11303 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11304   // C++ [class.dtor]p2:
11305   //   If a class has no user-declared destructor, a destructor is
11306   //   declared implicitly. An implicitly-declared destructor is an
11307   //   inline public member of its class.
11308   assert(ClassDecl->needsImplicitDestructor());
11309 
11310   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11311   if (DSM.isAlreadyBeingDeclared())
11312     return nullptr;
11313 
11314   // Create the actual destructor declaration.
11315   CanQualType ClassType
11316     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11317   SourceLocation ClassLoc = ClassDecl->getLocation();
11318   DeclarationName Name
11319     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11320   DeclarationNameInfo NameInfo(Name, ClassLoc);
11321   CXXDestructorDecl *Destructor
11322       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11323                                   QualType(), nullptr, /*isInline=*/true,
11324                                   /*isImplicitlyDeclared=*/true);
11325   Destructor->setAccess(AS_public);
11326   Destructor->setDefaulted();
11327 
11328   if (getLangOpts().CUDA) {
11329     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11330                                             Destructor,
11331                                             /* ConstRHS */ false,
11332                                             /* Diagnose */ false);
11333   }
11334 
11335   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
11336 
11337   // We don't need to use SpecialMemberIsTrivial here; triviality for
11338   // destructors is easy to compute.
11339   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11340   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11341                                 ClassDecl->hasTrivialDestructorForCall());
11342 
11343   // Note that we have declared this destructor.
11344   ++getASTContext().NumImplicitDestructorsDeclared;
11345 
11346   Scope *S = getScopeForContext(ClassDecl);
11347   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11348 
11349   // We can't check whether an implicit destructor is deleted before we complete
11350   // the definition of the class, because its validity depends on the alignment
11351   // of the class. We'll check this from ActOnFields once the class is complete.
11352   if (ClassDecl->isCompleteDefinition() &&
11353       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11354     SetDeclDeleted(Destructor, ClassLoc);
11355 
11356   // Introduce this destructor into its scope.
11357   if (S)
11358     PushOnScopeChains(Destructor, S, false);
11359   ClassDecl->addDecl(Destructor);
11360 
11361   return Destructor;
11362 }
11363 
11364 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11365                                     CXXDestructorDecl *Destructor) {
11366   assert((Destructor->isDefaulted() &&
11367           !Destructor->doesThisDeclarationHaveABody() &&
11368           !Destructor->isDeleted()) &&
11369          "DefineImplicitDestructor - call it for implicit default dtor");
11370   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11371     return;
11372 
11373   CXXRecordDecl *ClassDecl = Destructor->getParent();
11374   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11375 
11376   SynthesizedFunctionScope Scope(*this, Destructor);
11377 
11378   // The exception specification is needed because we are defining the
11379   // function.
11380   ResolveExceptionSpec(CurrentLocation,
11381                        Destructor->getType()->castAs<FunctionProtoType>());
11382   MarkVTableUsed(CurrentLocation, ClassDecl);
11383 
11384   // Add a context note for diagnostics produced after this point.
11385   Scope.addContextNote(CurrentLocation);
11386 
11387   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11388                                          Destructor->getParent());
11389 
11390   if (CheckDestructor(Destructor)) {
11391     Destructor->setInvalidDecl();
11392     return;
11393   }
11394 
11395   SourceLocation Loc = Destructor->getEndLoc().isValid()
11396                            ? Destructor->getEndLoc()
11397                            : Destructor->getLocation();
11398   Destructor->setBody(new (Context) CompoundStmt(Loc));
11399   Destructor->markUsed(Context);
11400 
11401   if (ASTMutationListener *L = getASTMutationListener()) {
11402     L->CompletedImplicitDefinition(Destructor);
11403   }
11404 }
11405 
11406 /// Perform any semantic analysis which needs to be delayed until all
11407 /// pending class member declarations have been parsed.
11408 void Sema::ActOnFinishCXXMemberDecls() {
11409   // If the context is an invalid C++ class, just suppress these checks.
11410   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11411     if (Record->isInvalidDecl()) {
11412       DelayedOverridingExceptionSpecChecks.clear();
11413       DelayedEquivalentExceptionSpecChecks.clear();
11414       return;
11415     }
11416     checkForMultipleExportedDefaultConstructors(*this, Record);
11417   }
11418 }
11419 
11420 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11421   referenceDLLExportedClassMethods();
11422 }
11423 
11424 void Sema::referenceDLLExportedClassMethods() {
11425   if (!DelayedDllExportClasses.empty()) {
11426     // Calling ReferenceDllExportedMembers might cause the current function to
11427     // be called again, so use a local copy of DelayedDllExportClasses.
11428     SmallVector<CXXRecordDecl *, 4> WorkList;
11429     std::swap(DelayedDllExportClasses, WorkList);
11430     for (CXXRecordDecl *Class : WorkList)
11431       ReferenceDllExportedMembers(*this, Class);
11432   }
11433 }
11434 
11435 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11436   assert(getLangOpts().CPlusPlus11 &&
11437          "adjusting dtor exception specs was introduced in c++11");
11438 
11439   if (Destructor->isDependentContext())
11440     return;
11441 
11442   // C++11 [class.dtor]p3:
11443   //   A declaration of a destructor that does not have an exception-
11444   //   specification is implicitly considered to have the same exception-
11445   //   specification as an implicit declaration.
11446   const FunctionProtoType *DtorType = Destructor->getType()->
11447                                         getAs<FunctionProtoType>();
11448   if (DtorType->hasExceptionSpec())
11449     return;
11450 
11451   // Replace the destructor's type, building off the existing one. Fortunately,
11452   // the only thing of interest in the destructor type is its extended info.
11453   // The return and arguments are fixed.
11454   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11455   EPI.ExceptionSpec.Type = EST_Unevaluated;
11456   EPI.ExceptionSpec.SourceDecl = Destructor;
11457   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11458 
11459   // FIXME: If the destructor has a body that could throw, and the newly created
11460   // spec doesn't allow exceptions, we should emit a warning, because this
11461   // change in behavior can break conforming C++03 programs at runtime.
11462   // However, we don't have a body or an exception specification yet, so it
11463   // needs to be done somewhere else.
11464 }
11465 
11466 namespace {
11467 /// An abstract base class for all helper classes used in building the
11468 //  copy/move operators. These classes serve as factory functions and help us
11469 //  avoid using the same Expr* in the AST twice.
11470 class ExprBuilder {
11471   ExprBuilder(const ExprBuilder&) = delete;
11472   ExprBuilder &operator=(const ExprBuilder&) = delete;
11473 
11474 protected:
11475   static Expr *assertNotNull(Expr *E) {
11476     assert(E && "Expression construction must not fail.");
11477     return E;
11478   }
11479 
11480 public:
11481   ExprBuilder() {}
11482   virtual ~ExprBuilder() {}
11483 
11484   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11485 };
11486 
11487 class RefBuilder: public ExprBuilder {
11488   VarDecl *Var;
11489   QualType VarType;
11490 
11491 public:
11492   Expr *build(Sema &S, SourceLocation Loc) const override {
11493     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
11494   }
11495 
11496   RefBuilder(VarDecl *Var, QualType VarType)
11497       : Var(Var), VarType(VarType) {}
11498 };
11499 
11500 class ThisBuilder: public ExprBuilder {
11501 public:
11502   Expr *build(Sema &S, SourceLocation Loc) const override {
11503     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11504   }
11505 };
11506 
11507 class CastBuilder: public ExprBuilder {
11508   const ExprBuilder &Builder;
11509   QualType Type;
11510   ExprValueKind Kind;
11511   const CXXCastPath &Path;
11512 
11513 public:
11514   Expr *build(Sema &S, SourceLocation Loc) const override {
11515     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11516                                              CK_UncheckedDerivedToBase, Kind,
11517                                              &Path).get());
11518   }
11519 
11520   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11521               const CXXCastPath &Path)
11522       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11523 };
11524 
11525 class DerefBuilder: public ExprBuilder {
11526   const ExprBuilder &Builder;
11527 
11528 public:
11529   Expr *build(Sema &S, SourceLocation Loc) const override {
11530     return assertNotNull(
11531         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11532   }
11533 
11534   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11535 };
11536 
11537 class MemberBuilder: public ExprBuilder {
11538   const ExprBuilder &Builder;
11539   QualType Type;
11540   CXXScopeSpec SS;
11541   bool IsArrow;
11542   LookupResult &MemberLookup;
11543 
11544 public:
11545   Expr *build(Sema &S, SourceLocation Loc) const override {
11546     return assertNotNull(S.BuildMemberReferenceExpr(
11547         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11548         nullptr, MemberLookup, nullptr, nullptr).get());
11549   }
11550 
11551   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11552                 LookupResult &MemberLookup)
11553       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11554         MemberLookup(MemberLookup) {}
11555 };
11556 
11557 class MoveCastBuilder: public ExprBuilder {
11558   const ExprBuilder &Builder;
11559 
11560 public:
11561   Expr *build(Sema &S, SourceLocation Loc) const override {
11562     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11563   }
11564 
11565   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11566 };
11567 
11568 class LvalueConvBuilder: public ExprBuilder {
11569   const ExprBuilder &Builder;
11570 
11571 public:
11572   Expr *build(Sema &S, SourceLocation Loc) const override {
11573     return assertNotNull(
11574         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11575   }
11576 
11577   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11578 };
11579 
11580 class SubscriptBuilder: public ExprBuilder {
11581   const ExprBuilder &Base;
11582   const ExprBuilder &Index;
11583 
11584 public:
11585   Expr *build(Sema &S, SourceLocation Loc) const override {
11586     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11587         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11588   }
11589 
11590   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11591       : Base(Base), Index(Index) {}
11592 };
11593 
11594 } // end anonymous namespace
11595 
11596 /// When generating a defaulted copy or move assignment operator, if a field
11597 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11598 /// do so. This optimization only applies for arrays of scalars, and for arrays
11599 /// of class type where the selected copy/move-assignment operator is trivial.
11600 static StmtResult
11601 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11602                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11603   // Compute the size of the memory buffer to be copied.
11604   QualType SizeType = S.Context.getSizeType();
11605   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11606                    S.Context.getTypeSizeInChars(T).getQuantity());
11607 
11608   // Take the address of the field references for "from" and "to". We
11609   // directly construct UnaryOperators here because semantic analysis
11610   // does not permit us to take the address of an xvalue.
11611   Expr *From = FromB.build(S, Loc);
11612   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11613                          S.Context.getPointerType(From->getType()),
11614                          VK_RValue, OK_Ordinary, Loc, false);
11615   Expr *To = ToB.build(S, Loc);
11616   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11617                        S.Context.getPointerType(To->getType()),
11618                        VK_RValue, OK_Ordinary, Loc, false);
11619 
11620   const Type *E = T->getBaseElementTypeUnsafe();
11621   bool NeedsCollectableMemCpy =
11622     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11623 
11624   // Create a reference to the __builtin_objc_memmove_collectable function
11625   StringRef MemCpyName = NeedsCollectableMemCpy ?
11626     "__builtin_objc_memmove_collectable" :
11627     "__builtin_memcpy";
11628   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11629                  Sema::LookupOrdinaryName);
11630   S.LookupName(R, S.TUScope, true);
11631 
11632   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11633   if (!MemCpy)
11634     // Something went horribly wrong earlier, and we will have complained
11635     // about it.
11636     return StmtError();
11637 
11638   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11639                                             VK_RValue, Loc, nullptr);
11640   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11641 
11642   Expr *CallArgs[] = {
11643     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11644   };
11645   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11646                                     Loc, CallArgs, Loc);
11647 
11648   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11649   return Call.getAs<Stmt>();
11650 }
11651 
11652 /// Builds a statement that copies/moves the given entity from \p From to
11653 /// \c To.
11654 ///
11655 /// This routine is used to copy/move the members of a class with an
11656 /// implicitly-declared copy/move assignment operator. When the entities being
11657 /// copied are arrays, this routine builds for loops to copy them.
11658 ///
11659 /// \param S The Sema object used for type-checking.
11660 ///
11661 /// \param Loc The location where the implicit copy/move is being generated.
11662 ///
11663 /// \param T The type of the expressions being copied/moved. Both expressions
11664 /// must have this type.
11665 ///
11666 /// \param To The expression we are copying/moving to.
11667 ///
11668 /// \param From The expression we are copying/moving from.
11669 ///
11670 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11671 /// Otherwise, it's a non-static member subobject.
11672 ///
11673 /// \param Copying Whether we're copying or moving.
11674 ///
11675 /// \param Depth Internal parameter recording the depth of the recursion.
11676 ///
11677 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11678 /// if a memcpy should be used instead.
11679 static StmtResult
11680 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11681                                  const ExprBuilder &To, const ExprBuilder &From,
11682                                  bool CopyingBaseSubobject, bool Copying,
11683                                  unsigned Depth = 0) {
11684   // C++11 [class.copy]p28:
11685   //   Each subobject is assigned in the manner appropriate to its type:
11686   //
11687   //     - if the subobject is of class type, as if by a call to operator= with
11688   //       the subobject as the object expression and the corresponding
11689   //       subobject of x as a single function argument (as if by explicit
11690   //       qualification; that is, ignoring any possible virtual overriding
11691   //       functions in more derived classes);
11692   //
11693   // C++03 [class.copy]p13:
11694   //     - if the subobject is of class type, the copy assignment operator for
11695   //       the class is used (as if by explicit qualification; that is,
11696   //       ignoring any possible virtual overriding functions in more derived
11697   //       classes);
11698   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11699     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11700 
11701     // Look for operator=.
11702     DeclarationName Name
11703       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11704     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11705     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11706 
11707     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11708     // operator.
11709     if (!S.getLangOpts().CPlusPlus11) {
11710       LookupResult::Filter F = OpLookup.makeFilter();
11711       while (F.hasNext()) {
11712         NamedDecl *D = F.next();
11713         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11714           if (Method->isCopyAssignmentOperator() ||
11715               (!Copying && Method->isMoveAssignmentOperator()))
11716             continue;
11717 
11718         F.erase();
11719       }
11720       F.done();
11721     }
11722 
11723     // Suppress the protected check (C++ [class.protected]) for each of the
11724     // assignment operators we found. This strange dance is required when
11725     // we're assigning via a base classes's copy-assignment operator. To
11726     // ensure that we're getting the right base class subobject (without
11727     // ambiguities), we need to cast "this" to that subobject type; to
11728     // ensure that we don't go through the virtual call mechanism, we need
11729     // to qualify the operator= name with the base class (see below). However,
11730     // this means that if the base class has a protected copy assignment
11731     // operator, the protected member access check will fail. So, we
11732     // rewrite "protected" access to "public" access in this case, since we
11733     // know by construction that we're calling from a derived class.
11734     if (CopyingBaseSubobject) {
11735       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11736            L != LEnd; ++L) {
11737         if (L.getAccess() == AS_protected)
11738           L.setAccess(AS_public);
11739       }
11740     }
11741 
11742     // Create the nested-name-specifier that will be used to qualify the
11743     // reference to operator=; this is required to suppress the virtual
11744     // call mechanism.
11745     CXXScopeSpec SS;
11746     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11747     SS.MakeTrivial(S.Context,
11748                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11749                                                CanonicalT),
11750                    Loc);
11751 
11752     // Create the reference to operator=.
11753     ExprResult OpEqualRef
11754       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11755                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11756                                    /*FirstQualifierInScope=*/nullptr,
11757                                    OpLookup,
11758                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11759                                    /*SuppressQualifierCheck=*/true);
11760     if (OpEqualRef.isInvalid())
11761       return StmtError();
11762 
11763     // Build the call to the assignment operator.
11764 
11765     Expr *FromInst = From.build(S, Loc);
11766     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11767                                                   OpEqualRef.getAs<Expr>(),
11768                                                   Loc, FromInst, Loc);
11769     if (Call.isInvalid())
11770       return StmtError();
11771 
11772     // If we built a call to a trivial 'operator=' while copying an array,
11773     // bail out. We'll replace the whole shebang with a memcpy.
11774     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11775     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11776       return StmtResult((Stmt*)nullptr);
11777 
11778     // Convert to an expression-statement, and clean up any produced
11779     // temporaries.
11780     return S.ActOnExprStmt(Call);
11781   }
11782 
11783   //     - if the subobject is of scalar type, the built-in assignment
11784   //       operator is used.
11785   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11786   if (!ArrayTy) {
11787     ExprResult Assignment = S.CreateBuiltinBinOp(
11788         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11789     if (Assignment.isInvalid())
11790       return StmtError();
11791     return S.ActOnExprStmt(Assignment);
11792   }
11793 
11794   //     - if the subobject is an array, each element is assigned, in the
11795   //       manner appropriate to the element type;
11796 
11797   // Construct a loop over the array bounds, e.g.,
11798   //
11799   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11800   //
11801   // that will copy each of the array elements.
11802   QualType SizeType = S.Context.getSizeType();
11803 
11804   // Create the iteration variable.
11805   IdentifierInfo *IterationVarName = nullptr;
11806   {
11807     SmallString<8> Str;
11808     llvm::raw_svector_ostream OS(Str);
11809     OS << "__i" << Depth;
11810     IterationVarName = &S.Context.Idents.get(OS.str());
11811   }
11812   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11813                                           IterationVarName, SizeType,
11814                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11815                                           SC_None);
11816 
11817   // Initialize the iteration variable to zero.
11818   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11819   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11820 
11821   // Creates a reference to the iteration variable.
11822   RefBuilder IterationVarRef(IterationVar, SizeType);
11823   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11824 
11825   // Create the DeclStmt that holds the iteration variable.
11826   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11827 
11828   // Subscript the "from" and "to" expressions with the iteration variable.
11829   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11830   MoveCastBuilder FromIndexMove(FromIndexCopy);
11831   const ExprBuilder *FromIndex;
11832   if (Copying)
11833     FromIndex = &FromIndexCopy;
11834   else
11835     FromIndex = &FromIndexMove;
11836 
11837   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11838 
11839   // Build the copy/move for an individual element of the array.
11840   StmtResult Copy =
11841     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11842                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11843                                      Copying, Depth + 1);
11844   // Bail out if copying fails or if we determined that we should use memcpy.
11845   if (Copy.isInvalid() || !Copy.get())
11846     return Copy;
11847 
11848   // Create the comparison against the array bound.
11849   llvm::APInt Upper
11850     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11851   Expr *Comparison
11852     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11853                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11854                                      BO_NE, S.Context.BoolTy,
11855                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11856 
11857   // Create the pre-increment of the iteration variable. We can determine
11858   // whether the increment will overflow based on the value of the array
11859   // bound.
11860   Expr *Increment = new (S.Context)
11861       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11862                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11863 
11864   // Construct the loop that copies all elements of this array.
11865   return S.ActOnForStmt(
11866       Loc, Loc, InitStmt,
11867       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11868       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11869 }
11870 
11871 static StmtResult
11872 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11873                       const ExprBuilder &To, const ExprBuilder &From,
11874                       bool CopyingBaseSubobject, bool Copying) {
11875   // Maybe we should use a memcpy?
11876   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11877       T.isTriviallyCopyableType(S.Context))
11878     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11879 
11880   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11881                                                      CopyingBaseSubobject,
11882                                                      Copying, 0));
11883 
11884   // If we ended up picking a trivial assignment operator for an array of a
11885   // non-trivially-copyable class type, just emit a memcpy.
11886   if (!Result.isInvalid() && !Result.get())
11887     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11888 
11889   return Result;
11890 }
11891 
11892 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11893   // Note: The following rules are largely analoguous to the copy
11894   // constructor rules. Note that virtual bases are not taken into account
11895   // for determining the argument type of the operator. Note also that
11896   // operators taking an object instead of a reference are allowed.
11897   assert(ClassDecl->needsImplicitCopyAssignment());
11898 
11899   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11900   if (DSM.isAlreadyBeingDeclared())
11901     return nullptr;
11902 
11903   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11904   if (Context.getLangOpts().OpenCLCPlusPlus)
11905     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
11906   QualType RetType = Context.getLValueReferenceType(ArgType);
11907   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11908   if (Const)
11909     ArgType = ArgType.withConst();
11910 
11911   ArgType = Context.getLValueReferenceType(ArgType);
11912 
11913   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11914                                                      CXXCopyAssignment,
11915                                                      Const);
11916 
11917   //   An implicitly-declared copy assignment operator is an inline public
11918   //   member of its class.
11919   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11920   SourceLocation ClassLoc = ClassDecl->getLocation();
11921   DeclarationNameInfo NameInfo(Name, ClassLoc);
11922   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
11923       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11924       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11925       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
11926       SourceLocation());
11927   CopyAssignment->setAccess(AS_public);
11928   CopyAssignment->setDefaulted();
11929   CopyAssignment->setImplicit();
11930 
11931   if (getLangOpts().CUDA) {
11932     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11933                                             CopyAssignment,
11934                                             /* ConstRHS */ Const,
11935                                             /* Diagnose */ false);
11936   }
11937 
11938   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
11939 
11940   // Add the parameter to the operator.
11941   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11942                                                ClassLoc, ClassLoc,
11943                                                /*Id=*/nullptr, ArgType,
11944                                                /*TInfo=*/nullptr, SC_None,
11945                                                nullptr);
11946   CopyAssignment->setParams(FromParam);
11947 
11948   CopyAssignment->setTrivial(
11949     ClassDecl->needsOverloadResolutionForCopyAssignment()
11950       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11951       : ClassDecl->hasTrivialCopyAssignment());
11952 
11953   // Note that we have added this copy-assignment operator.
11954   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
11955 
11956   Scope *S = getScopeForContext(ClassDecl);
11957   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11958 
11959   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11960     SetDeclDeleted(CopyAssignment, ClassLoc);
11961 
11962   if (S)
11963     PushOnScopeChains(CopyAssignment, S, false);
11964   ClassDecl->addDecl(CopyAssignment);
11965 
11966   return CopyAssignment;
11967 }
11968 
11969 /// Diagnose an implicit copy operation for a class which is odr-used, but
11970 /// which is deprecated because the class has a user-declared copy constructor,
11971 /// copy assignment operator, or destructor.
11972 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11973   assert(CopyOp->isImplicit());
11974 
11975   CXXRecordDecl *RD = CopyOp->getParent();
11976   CXXMethodDecl *UserDeclaredOperation = nullptr;
11977 
11978   // In Microsoft mode, assignment operations don't affect constructors and
11979   // vice versa.
11980   if (RD->hasUserDeclaredDestructor()) {
11981     UserDeclaredOperation = RD->getDestructor();
11982   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11983              RD->hasUserDeclaredCopyConstructor() &&
11984              !S.getLangOpts().MSVCCompat) {
11985     // Find any user-declared copy constructor.
11986     for (auto *I : RD->ctors()) {
11987       if (I->isCopyConstructor()) {
11988         UserDeclaredOperation = I;
11989         break;
11990       }
11991     }
11992     assert(UserDeclaredOperation);
11993   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11994              RD->hasUserDeclaredCopyAssignment() &&
11995              !S.getLangOpts().MSVCCompat) {
11996     // Find any user-declared move assignment operator.
11997     for (auto *I : RD->methods()) {
11998       if (I->isCopyAssignmentOperator()) {
11999         UserDeclaredOperation = I;
12000         break;
12001       }
12002     }
12003     assert(UserDeclaredOperation);
12004   }
12005 
12006   if (UserDeclaredOperation) {
12007     S.Diag(UserDeclaredOperation->getLocation(),
12008          diag::warn_deprecated_copy_operation)
12009       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
12010       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
12011   }
12012 }
12013 
12014 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
12015                                         CXXMethodDecl *CopyAssignOperator) {
12016   assert((CopyAssignOperator->isDefaulted() &&
12017           CopyAssignOperator->isOverloadedOperator() &&
12018           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
12019           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
12020           !CopyAssignOperator->isDeleted()) &&
12021          "DefineImplicitCopyAssignment called for wrong function");
12022   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
12023     return;
12024 
12025   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
12026   if (ClassDecl->isInvalidDecl()) {
12027     CopyAssignOperator->setInvalidDecl();
12028     return;
12029   }
12030 
12031   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
12032 
12033   // The exception specification is needed because we are defining the
12034   // function.
12035   ResolveExceptionSpec(CurrentLocation,
12036                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
12037 
12038   // Add a context note for diagnostics produced after this point.
12039   Scope.addContextNote(CurrentLocation);
12040 
12041   // C++11 [class.copy]p18:
12042   //   The [definition of an implicitly declared copy assignment operator] is
12043   //   deprecated if the class has a user-declared copy constructor or a
12044   //   user-declared destructor.
12045   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
12046     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
12047 
12048   // C++0x [class.copy]p30:
12049   //   The implicitly-defined or explicitly-defaulted copy assignment operator
12050   //   for a non-union class X performs memberwise copy assignment of its
12051   //   subobjects. The direct base classes of X are assigned first, in the
12052   //   order of their declaration in the base-specifier-list, and then the
12053   //   immediate non-static data members of X are assigned, in the order in
12054   //   which they were declared in the class definition.
12055 
12056   // The statements that form the synthesized function body.
12057   SmallVector<Stmt*, 8> Statements;
12058 
12059   // The parameter for the "other" object, which we are copying from.
12060   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
12061   Qualifiers OtherQuals = Other->getType().getQualifiers();
12062   QualType OtherRefType = Other->getType();
12063   if (const LValueReferenceType *OtherRef
12064                                 = OtherRefType->getAs<LValueReferenceType>()) {
12065     OtherRefType = OtherRef->getPointeeType();
12066     OtherQuals = OtherRefType.getQualifiers();
12067   }
12068 
12069   // Our location for everything implicitly-generated.
12070   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
12071                            ? CopyAssignOperator->getEndLoc()
12072                            : CopyAssignOperator->getLocation();
12073 
12074   // Builds a DeclRefExpr for the "other" object.
12075   RefBuilder OtherRef(Other, OtherRefType);
12076 
12077   // Builds the "this" pointer.
12078   ThisBuilder This;
12079 
12080   // Assign base classes.
12081   bool Invalid = false;
12082   for (auto &Base : ClassDecl->bases()) {
12083     // Form the assignment:
12084     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
12085     QualType BaseType = Base.getType().getUnqualifiedType();
12086     if (!BaseType->isRecordType()) {
12087       Invalid = true;
12088       continue;
12089     }
12090 
12091     CXXCastPath BasePath;
12092     BasePath.push_back(&Base);
12093 
12094     // Construct the "from" expression, which is an implicit cast to the
12095     // appropriately-qualified base type.
12096     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
12097                      VK_LValue, BasePath);
12098 
12099     // Dereference "this".
12100     DerefBuilder DerefThis(This);
12101     CastBuilder To(DerefThis,
12102                    Context.getQualifiedType(
12103                        BaseType, CopyAssignOperator->getMethodQualifiers()),
12104                    VK_LValue, BasePath);
12105 
12106     // Build the copy.
12107     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12108                                             To, From,
12109                                             /*CopyingBaseSubobject=*/true,
12110                                             /*Copying=*/true);
12111     if (Copy.isInvalid()) {
12112       CopyAssignOperator->setInvalidDecl();
12113       return;
12114     }
12115 
12116     // Success! Record the copy.
12117     Statements.push_back(Copy.getAs<Expr>());
12118   }
12119 
12120   // Assign non-static members.
12121   for (auto *Field : ClassDecl->fields()) {
12122     // FIXME: We should form some kind of AST representation for the implied
12123     // memcpy in a union copy operation.
12124     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12125       continue;
12126 
12127     if (Field->isInvalidDecl()) {
12128       Invalid = true;
12129       continue;
12130     }
12131 
12132     // Check for members of reference type; we can't copy those.
12133     if (Field->getType()->isReferenceType()) {
12134       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12135         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12136       Diag(Field->getLocation(), diag::note_declared_at);
12137       Invalid = true;
12138       continue;
12139     }
12140 
12141     // Check for members of const-qualified, non-class type.
12142     QualType BaseType = Context.getBaseElementType(Field->getType());
12143     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12144       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12145         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12146       Diag(Field->getLocation(), diag::note_declared_at);
12147       Invalid = true;
12148       continue;
12149     }
12150 
12151     // Suppress assigning zero-width bitfields.
12152     if (Field->isZeroLengthBitField(Context))
12153       continue;
12154 
12155     QualType FieldType = Field->getType().getNonReferenceType();
12156     if (FieldType->isIncompleteArrayType()) {
12157       assert(ClassDecl->hasFlexibleArrayMember() &&
12158              "Incomplete array type is not valid");
12159       continue;
12160     }
12161 
12162     // Build references to the field in the object we're copying from and to.
12163     CXXScopeSpec SS; // Intentionally empty
12164     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12165                               LookupMemberName);
12166     MemberLookup.addDecl(Field);
12167     MemberLookup.resolveKind();
12168 
12169     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12170 
12171     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12172 
12173     // Build the copy of this field.
12174     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12175                                             To, From,
12176                                             /*CopyingBaseSubobject=*/false,
12177                                             /*Copying=*/true);
12178     if (Copy.isInvalid()) {
12179       CopyAssignOperator->setInvalidDecl();
12180       return;
12181     }
12182 
12183     // Success! Record the copy.
12184     Statements.push_back(Copy.getAs<Stmt>());
12185   }
12186 
12187   if (!Invalid) {
12188     // Add a "return *this;"
12189     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12190 
12191     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12192     if (Return.isInvalid())
12193       Invalid = true;
12194     else
12195       Statements.push_back(Return.getAs<Stmt>());
12196   }
12197 
12198   if (Invalid) {
12199     CopyAssignOperator->setInvalidDecl();
12200     return;
12201   }
12202 
12203   StmtResult Body;
12204   {
12205     CompoundScopeRAII CompoundScope(*this);
12206     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12207                              /*isStmtExpr=*/false);
12208     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12209   }
12210   CopyAssignOperator->setBody(Body.getAs<Stmt>());
12211   CopyAssignOperator->markUsed(Context);
12212 
12213   if (ASTMutationListener *L = getASTMutationListener()) {
12214     L->CompletedImplicitDefinition(CopyAssignOperator);
12215   }
12216 }
12217 
12218 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12219   assert(ClassDecl->needsImplicitMoveAssignment());
12220 
12221   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12222   if (DSM.isAlreadyBeingDeclared())
12223     return nullptr;
12224 
12225   // Note: The following rules are largely analoguous to the move
12226   // constructor rules.
12227 
12228   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12229   if (Context.getLangOpts().OpenCLCPlusPlus)
12230     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12231   QualType RetType = Context.getLValueReferenceType(ArgType);
12232   ArgType = Context.getRValueReferenceType(ArgType);
12233 
12234   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12235                                                      CXXMoveAssignment,
12236                                                      false);
12237 
12238   //   An implicitly-declared move assignment operator is an inline public
12239   //   member of its class.
12240   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12241   SourceLocation ClassLoc = ClassDecl->getLocation();
12242   DeclarationNameInfo NameInfo(Name, ClassLoc);
12243   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
12244       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12245       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12246       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
12247       SourceLocation());
12248   MoveAssignment->setAccess(AS_public);
12249   MoveAssignment->setDefaulted();
12250   MoveAssignment->setImplicit();
12251 
12252   if (getLangOpts().CUDA) {
12253     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12254                                             MoveAssignment,
12255                                             /* ConstRHS */ false,
12256                                             /* Diagnose */ false);
12257   }
12258 
12259   // Build an exception specification pointing back at this member.
12260   FunctionProtoType::ExtProtoInfo EPI =
12261       getImplicitMethodEPI(*this, MoveAssignment);
12262   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12263 
12264   // Add the parameter to the operator.
12265   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12266                                                ClassLoc, ClassLoc,
12267                                                /*Id=*/nullptr, ArgType,
12268                                                /*TInfo=*/nullptr, SC_None,
12269                                                nullptr);
12270   MoveAssignment->setParams(FromParam);
12271 
12272   MoveAssignment->setTrivial(
12273     ClassDecl->needsOverloadResolutionForMoveAssignment()
12274       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12275       : ClassDecl->hasTrivialMoveAssignment());
12276 
12277   // Note that we have added this copy-assignment operator.
12278   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
12279 
12280   Scope *S = getScopeForContext(ClassDecl);
12281   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12282 
12283   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12284     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12285     SetDeclDeleted(MoveAssignment, ClassLoc);
12286   }
12287 
12288   if (S)
12289     PushOnScopeChains(MoveAssignment, S, false);
12290   ClassDecl->addDecl(MoveAssignment);
12291 
12292   return MoveAssignment;
12293 }
12294 
12295 /// Check if we're implicitly defining a move assignment operator for a class
12296 /// with virtual bases. Such a move assignment might move-assign the virtual
12297 /// base multiple times.
12298 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12299                                                SourceLocation CurrentLocation) {
12300   assert(!Class->isDependentContext() && "should not define dependent move");
12301 
12302   // Only a virtual base could get implicitly move-assigned multiple times.
12303   // Only a non-trivial move assignment can observe this. We only want to
12304   // diagnose if we implicitly define an assignment operator that assigns
12305   // two base classes, both of which move-assign the same virtual base.
12306   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12307       Class->getNumBases() < 2)
12308     return;
12309 
12310   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12311   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12312   VBaseMap VBases;
12313 
12314   for (auto &BI : Class->bases()) {
12315     Worklist.push_back(&BI);
12316     while (!Worklist.empty()) {
12317       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12318       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12319 
12320       // If the base has no non-trivial move assignment operators,
12321       // we don't care about moves from it.
12322       if (!Base->hasNonTrivialMoveAssignment())
12323         continue;
12324 
12325       // If there's nothing virtual here, skip it.
12326       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12327         continue;
12328 
12329       // If we're not actually going to call a move assignment for this base,
12330       // or the selected move assignment is trivial, skip it.
12331       Sema::SpecialMemberOverloadResult SMOR =
12332         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12333                               /*ConstArg*/false, /*VolatileArg*/false,
12334                               /*RValueThis*/true, /*ConstThis*/false,
12335                               /*VolatileThis*/false);
12336       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12337           !SMOR.getMethod()->isMoveAssignmentOperator())
12338         continue;
12339 
12340       if (BaseSpec->isVirtual()) {
12341         // We're going to move-assign this virtual base, and its move
12342         // assignment operator is not trivial. If this can happen for
12343         // multiple distinct direct bases of Class, diagnose it. (If it
12344         // only happens in one base, we'll diagnose it when synthesizing
12345         // that base class's move assignment operator.)
12346         CXXBaseSpecifier *&Existing =
12347             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12348                 .first->second;
12349         if (Existing && Existing != &BI) {
12350           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12351             << Class << Base;
12352           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12353               << (Base->getCanonicalDecl() ==
12354                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12355               << Base << Existing->getType() << Existing->getSourceRange();
12356           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12357               << (Base->getCanonicalDecl() ==
12358                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12359               << Base << BI.getType() << BaseSpec->getSourceRange();
12360 
12361           // Only diagnose each vbase once.
12362           Existing = nullptr;
12363         }
12364       } else {
12365         // Only walk over bases that have defaulted move assignment operators.
12366         // We assume that any user-provided move assignment operator handles
12367         // the multiple-moves-of-vbase case itself somehow.
12368         if (!SMOR.getMethod()->isDefaulted())
12369           continue;
12370 
12371         // We're going to move the base classes of Base. Add them to the list.
12372         for (auto &BI : Base->bases())
12373           Worklist.push_back(&BI);
12374       }
12375     }
12376   }
12377 }
12378 
12379 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12380                                         CXXMethodDecl *MoveAssignOperator) {
12381   assert((MoveAssignOperator->isDefaulted() &&
12382           MoveAssignOperator->isOverloadedOperator() &&
12383           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12384           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12385           !MoveAssignOperator->isDeleted()) &&
12386          "DefineImplicitMoveAssignment called for wrong function");
12387   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12388     return;
12389 
12390   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12391   if (ClassDecl->isInvalidDecl()) {
12392     MoveAssignOperator->setInvalidDecl();
12393     return;
12394   }
12395 
12396   // C++0x [class.copy]p28:
12397   //   The implicitly-defined or move assignment operator for a non-union class
12398   //   X performs memberwise move assignment of its subobjects. The direct base
12399   //   classes of X are assigned first, in the order of their declaration in the
12400   //   base-specifier-list, and then the immediate non-static data members of X
12401   //   are assigned, in the order in which they were declared in the class
12402   //   definition.
12403 
12404   // Issue a warning if our implicit move assignment operator will move
12405   // from a virtual base more than once.
12406   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12407 
12408   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12409 
12410   // The exception specification is needed because we are defining the
12411   // function.
12412   ResolveExceptionSpec(CurrentLocation,
12413                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12414 
12415   // Add a context note for diagnostics produced after this point.
12416   Scope.addContextNote(CurrentLocation);
12417 
12418   // The statements that form the synthesized function body.
12419   SmallVector<Stmt*, 8> Statements;
12420 
12421   // The parameter for the "other" object, which we are move from.
12422   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12423   QualType OtherRefType = Other->getType()->
12424       getAs<RValueReferenceType>()->getPointeeType();
12425 
12426   // Our location for everything implicitly-generated.
12427   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12428                            ? MoveAssignOperator->getEndLoc()
12429                            : MoveAssignOperator->getLocation();
12430 
12431   // Builds a reference to the "other" object.
12432   RefBuilder OtherRef(Other, OtherRefType);
12433   // Cast to rvalue.
12434   MoveCastBuilder MoveOther(OtherRef);
12435 
12436   // Builds the "this" pointer.
12437   ThisBuilder This;
12438 
12439   // Assign base classes.
12440   bool Invalid = false;
12441   for (auto &Base : ClassDecl->bases()) {
12442     // C++11 [class.copy]p28:
12443     //   It is unspecified whether subobjects representing virtual base classes
12444     //   are assigned more than once by the implicitly-defined copy assignment
12445     //   operator.
12446     // FIXME: Do not assign to a vbase that will be assigned by some other base
12447     // class. For a move-assignment, this can result in the vbase being moved
12448     // multiple times.
12449 
12450     // Form the assignment:
12451     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12452     QualType BaseType = Base.getType().getUnqualifiedType();
12453     if (!BaseType->isRecordType()) {
12454       Invalid = true;
12455       continue;
12456     }
12457 
12458     CXXCastPath BasePath;
12459     BasePath.push_back(&Base);
12460 
12461     // Construct the "from" expression, which is an implicit cast to the
12462     // appropriately-qualified base type.
12463     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12464 
12465     // Dereference "this".
12466     DerefBuilder DerefThis(This);
12467 
12468     // Implicitly cast "this" to the appropriately-qualified base type.
12469     CastBuilder To(DerefThis,
12470                    Context.getQualifiedType(
12471                        BaseType, MoveAssignOperator->getMethodQualifiers()),
12472                    VK_LValue, BasePath);
12473 
12474     // Build the move.
12475     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12476                                             To, From,
12477                                             /*CopyingBaseSubobject=*/true,
12478                                             /*Copying=*/false);
12479     if (Move.isInvalid()) {
12480       MoveAssignOperator->setInvalidDecl();
12481       return;
12482     }
12483 
12484     // Success! Record the move.
12485     Statements.push_back(Move.getAs<Expr>());
12486   }
12487 
12488   // Assign non-static members.
12489   for (auto *Field : ClassDecl->fields()) {
12490     // FIXME: We should form some kind of AST representation for the implied
12491     // memcpy in a union copy operation.
12492     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12493       continue;
12494 
12495     if (Field->isInvalidDecl()) {
12496       Invalid = true;
12497       continue;
12498     }
12499 
12500     // Check for members of reference type; we can't move those.
12501     if (Field->getType()->isReferenceType()) {
12502       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12503         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12504       Diag(Field->getLocation(), diag::note_declared_at);
12505       Invalid = true;
12506       continue;
12507     }
12508 
12509     // Check for members of const-qualified, non-class type.
12510     QualType BaseType = Context.getBaseElementType(Field->getType());
12511     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12512       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12513         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12514       Diag(Field->getLocation(), diag::note_declared_at);
12515       Invalid = true;
12516       continue;
12517     }
12518 
12519     // Suppress assigning zero-width bitfields.
12520     if (Field->isZeroLengthBitField(Context))
12521       continue;
12522 
12523     QualType FieldType = Field->getType().getNonReferenceType();
12524     if (FieldType->isIncompleteArrayType()) {
12525       assert(ClassDecl->hasFlexibleArrayMember() &&
12526              "Incomplete array type is not valid");
12527       continue;
12528     }
12529 
12530     // Build references to the field in the object we're copying from and to.
12531     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12532                               LookupMemberName);
12533     MemberLookup.addDecl(Field);
12534     MemberLookup.resolveKind();
12535     MemberBuilder From(MoveOther, OtherRefType,
12536                        /*IsArrow=*/false, MemberLookup);
12537     MemberBuilder To(This, getCurrentThisType(),
12538                      /*IsArrow=*/true, MemberLookup);
12539 
12540     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12541         "Member reference with rvalue base must be rvalue except for reference "
12542         "members, which aren't allowed for move assignment.");
12543 
12544     // Build the move of this field.
12545     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12546                                             To, From,
12547                                             /*CopyingBaseSubobject=*/false,
12548                                             /*Copying=*/false);
12549     if (Move.isInvalid()) {
12550       MoveAssignOperator->setInvalidDecl();
12551       return;
12552     }
12553 
12554     // Success! Record the copy.
12555     Statements.push_back(Move.getAs<Stmt>());
12556   }
12557 
12558   if (!Invalid) {
12559     // Add a "return *this;"
12560     ExprResult ThisObj =
12561         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12562 
12563     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12564     if (Return.isInvalid())
12565       Invalid = true;
12566     else
12567       Statements.push_back(Return.getAs<Stmt>());
12568   }
12569 
12570   if (Invalid) {
12571     MoveAssignOperator->setInvalidDecl();
12572     return;
12573   }
12574 
12575   StmtResult Body;
12576   {
12577     CompoundScopeRAII CompoundScope(*this);
12578     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12579                              /*isStmtExpr=*/false);
12580     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12581   }
12582   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12583   MoveAssignOperator->markUsed(Context);
12584 
12585   if (ASTMutationListener *L = getASTMutationListener()) {
12586     L->CompletedImplicitDefinition(MoveAssignOperator);
12587   }
12588 }
12589 
12590 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12591                                                     CXXRecordDecl *ClassDecl) {
12592   // C++ [class.copy]p4:
12593   //   If the class definition does not explicitly declare a copy
12594   //   constructor, one is declared implicitly.
12595   assert(ClassDecl->needsImplicitCopyConstructor());
12596 
12597   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12598   if (DSM.isAlreadyBeingDeclared())
12599     return nullptr;
12600 
12601   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12602   QualType ArgType = ClassType;
12603   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12604   if (Const)
12605     ArgType = ArgType.withConst();
12606 
12607   if (Context.getLangOpts().OpenCLCPlusPlus)
12608     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12609 
12610   ArgType = Context.getLValueReferenceType(ArgType);
12611 
12612   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12613                                                      CXXCopyConstructor,
12614                                                      Const);
12615 
12616   DeclarationName Name
12617     = Context.DeclarationNames.getCXXConstructorName(
12618                                            Context.getCanonicalType(ClassType));
12619   SourceLocation ClassLoc = ClassDecl->getLocation();
12620   DeclarationNameInfo NameInfo(Name, ClassLoc);
12621 
12622   //   An implicitly-declared copy constructor is an inline public
12623   //   member of its class.
12624   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12625       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12626       ExplicitSpecifier(),
12627       /*isInline=*/true,
12628       /*isImplicitlyDeclared=*/true,
12629       Constexpr ? CSK_constexpr : CSK_unspecified);
12630   CopyConstructor->setAccess(AS_public);
12631   CopyConstructor->setDefaulted();
12632 
12633   if (getLangOpts().CUDA) {
12634     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12635                                             CopyConstructor,
12636                                             /* ConstRHS */ Const,
12637                                             /* Diagnose */ false);
12638   }
12639 
12640   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
12641 
12642   // Add the parameter to the constructor.
12643   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12644                                                ClassLoc, ClassLoc,
12645                                                /*IdentifierInfo=*/nullptr,
12646                                                ArgType, /*TInfo=*/nullptr,
12647                                                SC_None, nullptr);
12648   CopyConstructor->setParams(FromParam);
12649 
12650   CopyConstructor->setTrivial(
12651       ClassDecl->needsOverloadResolutionForCopyConstructor()
12652           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12653           : ClassDecl->hasTrivialCopyConstructor());
12654 
12655   CopyConstructor->setTrivialForCall(
12656       ClassDecl->hasAttr<TrivialABIAttr>() ||
12657       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12658            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12659              TAH_ConsiderTrivialABI)
12660            : ClassDecl->hasTrivialCopyConstructorForCall()));
12661 
12662   // Note that we have declared this constructor.
12663   ++getASTContext().NumImplicitCopyConstructorsDeclared;
12664 
12665   Scope *S = getScopeForContext(ClassDecl);
12666   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12667 
12668   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12669     ClassDecl->setImplicitCopyConstructorIsDeleted();
12670     SetDeclDeleted(CopyConstructor, ClassLoc);
12671   }
12672 
12673   if (S)
12674     PushOnScopeChains(CopyConstructor, S, false);
12675   ClassDecl->addDecl(CopyConstructor);
12676 
12677   return CopyConstructor;
12678 }
12679 
12680 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12681                                          CXXConstructorDecl *CopyConstructor) {
12682   assert((CopyConstructor->isDefaulted() &&
12683           CopyConstructor->isCopyConstructor() &&
12684           !CopyConstructor->doesThisDeclarationHaveABody() &&
12685           !CopyConstructor->isDeleted()) &&
12686          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12687   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12688     return;
12689 
12690   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12691   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12692 
12693   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12694 
12695   // The exception specification is needed because we are defining the
12696   // function.
12697   ResolveExceptionSpec(CurrentLocation,
12698                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12699   MarkVTableUsed(CurrentLocation, ClassDecl);
12700 
12701   // Add a context note for diagnostics produced after this point.
12702   Scope.addContextNote(CurrentLocation);
12703 
12704   // C++11 [class.copy]p7:
12705   //   The [definition of an implicitly declared copy constructor] is
12706   //   deprecated if the class has a user-declared copy assignment operator
12707   //   or a user-declared destructor.
12708   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12709     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12710 
12711   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12712     CopyConstructor->setInvalidDecl();
12713   }  else {
12714     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12715                              ? CopyConstructor->getEndLoc()
12716                              : CopyConstructor->getLocation();
12717     Sema::CompoundScopeRAII CompoundScope(*this);
12718     CopyConstructor->setBody(
12719         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12720     CopyConstructor->markUsed(Context);
12721   }
12722 
12723   if (ASTMutationListener *L = getASTMutationListener()) {
12724     L->CompletedImplicitDefinition(CopyConstructor);
12725   }
12726 }
12727 
12728 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12729                                                     CXXRecordDecl *ClassDecl) {
12730   assert(ClassDecl->needsImplicitMoveConstructor());
12731 
12732   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12733   if (DSM.isAlreadyBeingDeclared())
12734     return nullptr;
12735 
12736   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12737 
12738   QualType ArgType = ClassType;
12739   if (Context.getLangOpts().OpenCLCPlusPlus)
12740     ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
12741   ArgType = Context.getRValueReferenceType(ArgType);
12742 
12743   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12744                                                      CXXMoveConstructor,
12745                                                      false);
12746 
12747   DeclarationName Name
12748     = Context.DeclarationNames.getCXXConstructorName(
12749                                            Context.getCanonicalType(ClassType));
12750   SourceLocation ClassLoc = ClassDecl->getLocation();
12751   DeclarationNameInfo NameInfo(Name, ClassLoc);
12752 
12753   // C++11 [class.copy]p11:
12754   //   An implicitly-declared copy/move constructor is an inline public
12755   //   member of its class.
12756   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12757       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12758       ExplicitSpecifier(),
12759       /*isInline=*/true,
12760       /*isImplicitlyDeclared=*/true,
12761       Constexpr ? CSK_constexpr : CSK_unspecified);
12762   MoveConstructor->setAccess(AS_public);
12763   MoveConstructor->setDefaulted();
12764 
12765   if (getLangOpts().CUDA) {
12766     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12767                                             MoveConstructor,
12768                                             /* ConstRHS */ false,
12769                                             /* Diagnose */ false);
12770   }
12771 
12772   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
12773 
12774   // Add the parameter to the constructor.
12775   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12776                                                ClassLoc, ClassLoc,
12777                                                /*IdentifierInfo=*/nullptr,
12778                                                ArgType, /*TInfo=*/nullptr,
12779                                                SC_None, nullptr);
12780   MoveConstructor->setParams(FromParam);
12781 
12782   MoveConstructor->setTrivial(
12783       ClassDecl->needsOverloadResolutionForMoveConstructor()
12784           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12785           : ClassDecl->hasTrivialMoveConstructor());
12786 
12787   MoveConstructor->setTrivialForCall(
12788       ClassDecl->hasAttr<TrivialABIAttr>() ||
12789       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12790            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12791                                     TAH_ConsiderTrivialABI)
12792            : ClassDecl->hasTrivialMoveConstructorForCall()));
12793 
12794   // Note that we have declared this constructor.
12795   ++getASTContext().NumImplicitMoveConstructorsDeclared;
12796 
12797   Scope *S = getScopeForContext(ClassDecl);
12798   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12799 
12800   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12801     ClassDecl->setImplicitMoveConstructorIsDeleted();
12802     SetDeclDeleted(MoveConstructor, ClassLoc);
12803   }
12804 
12805   if (S)
12806     PushOnScopeChains(MoveConstructor, S, false);
12807   ClassDecl->addDecl(MoveConstructor);
12808 
12809   return MoveConstructor;
12810 }
12811 
12812 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12813                                          CXXConstructorDecl *MoveConstructor) {
12814   assert((MoveConstructor->isDefaulted() &&
12815           MoveConstructor->isMoveConstructor() &&
12816           !MoveConstructor->doesThisDeclarationHaveABody() &&
12817           !MoveConstructor->isDeleted()) &&
12818          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12819   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12820     return;
12821 
12822   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12823   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12824 
12825   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12826 
12827   // The exception specification is needed because we are defining the
12828   // function.
12829   ResolveExceptionSpec(CurrentLocation,
12830                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12831   MarkVTableUsed(CurrentLocation, ClassDecl);
12832 
12833   // Add a context note for diagnostics produced after this point.
12834   Scope.addContextNote(CurrentLocation);
12835 
12836   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12837     MoveConstructor->setInvalidDecl();
12838   } else {
12839     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12840                              ? MoveConstructor->getEndLoc()
12841                              : MoveConstructor->getLocation();
12842     Sema::CompoundScopeRAII CompoundScope(*this);
12843     MoveConstructor->setBody(ActOnCompoundStmt(
12844         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12845     MoveConstructor->markUsed(Context);
12846   }
12847 
12848   if (ASTMutationListener *L = getASTMutationListener()) {
12849     L->CompletedImplicitDefinition(MoveConstructor);
12850   }
12851 }
12852 
12853 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12854   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12855 }
12856 
12857 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12858                             SourceLocation CurrentLocation,
12859                             CXXConversionDecl *Conv) {
12860   SynthesizedFunctionScope Scope(*this, Conv);
12861   assert(!Conv->getReturnType()->isUndeducedType());
12862 
12863   CXXRecordDecl *Lambda = Conv->getParent();
12864   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12865   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12866 
12867   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12868     CallOp = InstantiateFunctionDeclaration(
12869         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12870     if (!CallOp)
12871       return;
12872 
12873     Invoker = InstantiateFunctionDeclaration(
12874         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12875     if (!Invoker)
12876       return;
12877   }
12878 
12879   if (CallOp->isInvalidDecl())
12880     return;
12881 
12882   // Mark the call operator referenced (and add to pending instantiations
12883   // if necessary).
12884   // For both the conversion and static-invoker template specializations
12885   // we construct their body's in this function, so no need to add them
12886   // to the PendingInstantiations.
12887   MarkFunctionReferenced(CurrentLocation, CallOp);
12888 
12889   // Fill in the __invoke function with a dummy implementation. IR generation
12890   // will fill in the actual details. Update its type in case it contained
12891   // an 'auto'.
12892   Invoker->markUsed(Context);
12893   Invoker->setReferenced();
12894   Invoker->setType(Conv->getReturnType()->getPointeeType());
12895   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12896 
12897   // Construct the body of the conversion function { return __invoke; }.
12898   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12899                                        VK_LValue, Conv->getLocation());
12900   assert(FunctionRef && "Can't refer to __invoke function?");
12901   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12902   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12903                                      Conv->getLocation()));
12904   Conv->markUsed(Context);
12905   Conv->setReferenced();
12906 
12907   if (ASTMutationListener *L = getASTMutationListener()) {
12908     L->CompletedImplicitDefinition(Conv);
12909     L->CompletedImplicitDefinition(Invoker);
12910   }
12911 }
12912 
12913 
12914 
12915 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12916        SourceLocation CurrentLocation,
12917        CXXConversionDecl *Conv)
12918 {
12919   assert(!Conv->getParent()->isGenericLambda());
12920 
12921   SynthesizedFunctionScope Scope(*this, Conv);
12922 
12923   // Copy-initialize the lambda object as needed to capture it.
12924   Expr *This = ActOnCXXThis(CurrentLocation).get();
12925   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12926 
12927   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12928                                                         Conv->getLocation(),
12929                                                         Conv, DerefThis);
12930 
12931   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12932   // behavior.  Note that only the general conversion function does this
12933   // (since it's unusable otherwise); in the case where we inline the
12934   // block literal, it has block literal lifetime semantics.
12935   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12936     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12937                                           CK_CopyAndAutoreleaseBlockObject,
12938                                           BuildBlock.get(), nullptr, VK_RValue);
12939 
12940   if (BuildBlock.isInvalid()) {
12941     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12942     Conv->setInvalidDecl();
12943     return;
12944   }
12945 
12946   // Create the return statement that returns the block from the conversion
12947   // function.
12948   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12949   if (Return.isInvalid()) {
12950     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12951     Conv->setInvalidDecl();
12952     return;
12953   }
12954 
12955   // Set the body of the conversion function.
12956   Stmt *ReturnS = Return.get();
12957   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12958                                      Conv->getLocation()));
12959   Conv->markUsed(Context);
12960 
12961   // We're done; notify the mutation listener, if any.
12962   if (ASTMutationListener *L = getASTMutationListener()) {
12963     L->CompletedImplicitDefinition(Conv);
12964   }
12965 }
12966 
12967 /// Determine whether the given list arguments contains exactly one
12968 /// "real" (non-default) argument.
12969 static bool hasOneRealArgument(MultiExprArg Args) {
12970   switch (Args.size()) {
12971   case 0:
12972     return false;
12973 
12974   default:
12975     if (!Args[1]->isDefaultArgument())
12976       return false;
12977 
12978     LLVM_FALLTHROUGH;
12979   case 1:
12980     return !Args[0]->isDefaultArgument();
12981   }
12982 
12983   return false;
12984 }
12985 
12986 ExprResult
12987 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12988                             NamedDecl *FoundDecl,
12989                             CXXConstructorDecl *Constructor,
12990                             MultiExprArg ExprArgs,
12991                             bool HadMultipleCandidates,
12992                             bool IsListInitialization,
12993                             bool IsStdInitListInitialization,
12994                             bool RequiresZeroInit,
12995                             unsigned ConstructKind,
12996                             SourceRange ParenRange) {
12997   bool Elidable = false;
12998 
12999   // C++0x [class.copy]p34:
13000   //   When certain criteria are met, an implementation is allowed to
13001   //   omit the copy/move construction of a class object, even if the
13002   //   copy/move constructor and/or destructor for the object have
13003   //   side effects. [...]
13004   //     - when a temporary class object that has not been bound to a
13005   //       reference (12.2) would be copied/moved to a class object
13006   //       with the same cv-unqualified type, the copy/move operation
13007   //       can be omitted by constructing the temporary object
13008   //       directly into the target of the omitted copy/move
13009   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
13010       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
13011     Expr *SubExpr = ExprArgs[0];
13012     Elidable = SubExpr->isTemporaryObject(
13013         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
13014   }
13015 
13016   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
13017                                FoundDecl, Constructor,
13018                                Elidable, ExprArgs, HadMultipleCandidates,
13019                                IsListInitialization,
13020                                IsStdInitListInitialization, RequiresZeroInit,
13021                                ConstructKind, ParenRange);
13022 }
13023 
13024 ExprResult
13025 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13026                             NamedDecl *FoundDecl,
13027                             CXXConstructorDecl *Constructor,
13028                             bool Elidable,
13029                             MultiExprArg ExprArgs,
13030                             bool HadMultipleCandidates,
13031                             bool IsListInitialization,
13032                             bool IsStdInitListInitialization,
13033                             bool RequiresZeroInit,
13034                             unsigned ConstructKind,
13035                             SourceRange ParenRange) {
13036   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
13037     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
13038     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
13039       return ExprError();
13040   }
13041 
13042   return BuildCXXConstructExpr(
13043       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
13044       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
13045       RequiresZeroInit, ConstructKind, ParenRange);
13046 }
13047 
13048 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
13049 /// including handling of its default argument expressions.
13050 ExprResult
13051 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13052                             CXXConstructorDecl *Constructor,
13053                             bool Elidable,
13054                             MultiExprArg ExprArgs,
13055                             bool HadMultipleCandidates,
13056                             bool IsListInitialization,
13057                             bool IsStdInitListInitialization,
13058                             bool RequiresZeroInit,
13059                             unsigned ConstructKind,
13060                             SourceRange ParenRange) {
13061   assert(declaresSameEntity(
13062              Constructor->getParent(),
13063              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
13064          "given constructor for wrong type");
13065   MarkFunctionReferenced(ConstructLoc, Constructor);
13066   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
13067     return ExprError();
13068 
13069   return CXXConstructExpr::Create(
13070       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
13071       ExprArgs, HadMultipleCandidates, IsListInitialization,
13072       IsStdInitListInitialization, RequiresZeroInit,
13073       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
13074       ParenRange);
13075 }
13076 
13077 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
13078   assert(Field->hasInClassInitializer());
13079 
13080   // If we already have the in-class initializer nothing needs to be done.
13081   if (Field->getInClassInitializer())
13082     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13083 
13084   // If we might have already tried and failed to instantiate, don't try again.
13085   if (Field->isInvalidDecl())
13086     return ExprError();
13087 
13088   // Maybe we haven't instantiated the in-class initializer. Go check the
13089   // pattern FieldDecl to see if it has one.
13090   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
13091 
13092   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
13093     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
13094     DeclContext::lookup_result Lookup =
13095         ClassPattern->lookup(Field->getDeclName());
13096 
13097     // Lookup can return at most two results: the pattern for the field, or the
13098     // injected class name of the parent record. No other member can have the
13099     // same name as the field.
13100     // In modules mode, lookup can return multiple results (coming from
13101     // different modules).
13102     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
13103            "more than two lookup results for field name");
13104     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
13105     if (!Pattern) {
13106       assert(isa<CXXRecordDecl>(Lookup[0]) &&
13107              "cannot have other non-field member with same name");
13108       for (auto L : Lookup)
13109         if (isa<FieldDecl>(L)) {
13110           Pattern = cast<FieldDecl>(L);
13111           break;
13112         }
13113       assert(Pattern && "We must have set the Pattern!");
13114     }
13115 
13116     if (!Pattern->hasInClassInitializer() ||
13117         InstantiateInClassInitializer(Loc, Field, Pattern,
13118                                       getTemplateInstantiationArgs(Field))) {
13119       // Don't diagnose this again.
13120       Field->setInvalidDecl();
13121       return ExprError();
13122     }
13123     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13124   }
13125 
13126   // DR1351:
13127   //   If the brace-or-equal-initializer of a non-static data member
13128   //   invokes a defaulted default constructor of its class or of an
13129   //   enclosing class in a potentially evaluated subexpression, the
13130   //   program is ill-formed.
13131   //
13132   // This resolution is unworkable: the exception specification of the
13133   // default constructor can be needed in an unevaluated context, in
13134   // particular, in the operand of a noexcept-expression, and we can be
13135   // unable to compute an exception specification for an enclosed class.
13136   //
13137   // Any attempt to resolve the exception specification of a defaulted default
13138   // constructor before the initializer is lexically complete will ultimately
13139   // come here at which point we can diagnose it.
13140   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13141   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13142       << OutermostClass << Field;
13143   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13144   // Recover by marking the field invalid, unless we're in a SFINAE context.
13145   if (!isSFINAEContext())
13146     Field->setInvalidDecl();
13147   return ExprError();
13148 }
13149 
13150 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13151   if (VD->isInvalidDecl()) return;
13152 
13153   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13154   if (ClassDecl->isInvalidDecl()) return;
13155   if (ClassDecl->hasIrrelevantDestructor()) return;
13156   if (ClassDecl->isDependentContext()) return;
13157 
13158   if (VD->isNoDestroy(getASTContext()))
13159     return;
13160 
13161   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13162 
13163   // If this is an array, we'll require the destructor during initialization, so
13164   // we can skip over this. We still want to emit exit-time destructor warnings
13165   // though.
13166   if (!VD->getType()->isArrayType()) {
13167     MarkFunctionReferenced(VD->getLocation(), Destructor);
13168     CheckDestructorAccess(VD->getLocation(), Destructor,
13169                           PDiag(diag::err_access_dtor_var)
13170                               << VD->getDeclName() << VD->getType());
13171     DiagnoseUseOfDecl(Destructor, VD->getLocation());
13172   }
13173 
13174   if (Destructor->isTrivial()) return;
13175   if (!VD->hasGlobalStorage()) return;
13176 
13177   // Emit warning for non-trivial dtor in global scope (a real global,
13178   // class-static, function-static).
13179   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13180 
13181   // TODO: this should be re-enabled for static locals by !CXAAtExit
13182   if (!VD->isStaticLocal())
13183     Diag(VD->getLocation(), diag::warn_global_destructor);
13184 }
13185 
13186 /// Given a constructor and the set of arguments provided for the
13187 /// constructor, convert the arguments and add any required default arguments
13188 /// to form a proper call to this constructor.
13189 ///
13190 /// \returns true if an error occurred, false otherwise.
13191 bool
13192 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13193                               MultiExprArg ArgsPtr,
13194                               SourceLocation Loc,
13195                               SmallVectorImpl<Expr*> &ConvertedArgs,
13196                               bool AllowExplicit,
13197                               bool IsListInitialization) {
13198   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13199   unsigned NumArgs = ArgsPtr.size();
13200   Expr **Args = ArgsPtr.data();
13201 
13202   const FunctionProtoType *Proto
13203     = Constructor->getType()->getAs<FunctionProtoType>();
13204   assert(Proto && "Constructor without a prototype?");
13205   unsigned NumParams = Proto->getNumParams();
13206 
13207   // If too few arguments are available, we'll fill in the rest with defaults.
13208   if (NumArgs < NumParams)
13209     ConvertedArgs.reserve(NumParams);
13210   else
13211     ConvertedArgs.reserve(NumArgs);
13212 
13213   VariadicCallType CallType =
13214     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13215   SmallVector<Expr *, 8> AllArgs;
13216   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13217                                         Proto, 0,
13218                                         llvm::makeArrayRef(Args, NumArgs),
13219                                         AllArgs,
13220                                         CallType, AllowExplicit,
13221                                         IsListInitialization);
13222   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13223 
13224   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13225 
13226   CheckConstructorCall(Constructor,
13227                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13228                        Proto, Loc);
13229 
13230   return Invalid;
13231 }
13232 
13233 static inline bool
13234 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13235                                        const FunctionDecl *FnDecl) {
13236   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13237   if (isa<NamespaceDecl>(DC)) {
13238     return SemaRef.Diag(FnDecl->getLocation(),
13239                         diag::err_operator_new_delete_declared_in_namespace)
13240       << FnDecl->getDeclName();
13241   }
13242 
13243   if (isa<TranslationUnitDecl>(DC) &&
13244       FnDecl->getStorageClass() == SC_Static) {
13245     return SemaRef.Diag(FnDecl->getLocation(),
13246                         diag::err_operator_new_delete_declared_static)
13247       << FnDecl->getDeclName();
13248   }
13249 
13250   return false;
13251 }
13252 
13253 static QualType
13254 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13255   QualType QTy = PtrTy->getPointeeType();
13256   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13257   return SemaRef.Context.getPointerType(QTy);
13258 }
13259 
13260 static inline bool
13261 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13262                             CanQualType ExpectedResultType,
13263                             CanQualType ExpectedFirstParamType,
13264                             unsigned DependentParamTypeDiag,
13265                             unsigned InvalidParamTypeDiag) {
13266   QualType ResultType =
13267       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13268 
13269   // Check that the result type is not dependent.
13270   if (ResultType->isDependentType())
13271     return SemaRef.Diag(FnDecl->getLocation(),
13272                         diag::err_operator_new_delete_dependent_result_type)
13273     << FnDecl->getDeclName() << ExpectedResultType;
13274 
13275   // OpenCL C++: the operator is valid on any address space.
13276   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13277     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13278       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13279     }
13280   }
13281 
13282   // Check that the result type is what we expect.
13283   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13284     return SemaRef.Diag(FnDecl->getLocation(),
13285                         diag::err_operator_new_delete_invalid_result_type)
13286     << FnDecl->getDeclName() << ExpectedResultType;
13287 
13288   // A function template must have at least 2 parameters.
13289   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13290     return SemaRef.Diag(FnDecl->getLocation(),
13291                       diag::err_operator_new_delete_template_too_few_parameters)
13292         << FnDecl->getDeclName();
13293 
13294   // The function decl must have at least 1 parameter.
13295   if (FnDecl->getNumParams() == 0)
13296     return SemaRef.Diag(FnDecl->getLocation(),
13297                         diag::err_operator_new_delete_too_few_parameters)
13298       << FnDecl->getDeclName();
13299 
13300   // Check the first parameter type is not dependent.
13301   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13302   if (FirstParamType->isDependentType())
13303     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13304       << FnDecl->getDeclName() << ExpectedFirstParamType;
13305 
13306   // Check that the first parameter type is what we expect.
13307   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13308     // OpenCL C++: the operator is valid on any address space.
13309     if (auto *PtrTy =
13310             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13311       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13312     }
13313   }
13314   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13315       ExpectedFirstParamType)
13316     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13317     << FnDecl->getDeclName() << ExpectedFirstParamType;
13318 
13319   return false;
13320 }
13321 
13322 static bool
13323 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13324   // C++ [basic.stc.dynamic.allocation]p1:
13325   //   A program is ill-formed if an allocation function is declared in a
13326   //   namespace scope other than global scope or declared static in global
13327   //   scope.
13328   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13329     return true;
13330 
13331   CanQualType SizeTy =
13332     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13333 
13334   // C++ [basic.stc.dynamic.allocation]p1:
13335   //  The return type shall be void*. The first parameter shall have type
13336   //  std::size_t.
13337   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13338                                   SizeTy,
13339                                   diag::err_operator_new_dependent_param_type,
13340                                   diag::err_operator_new_param_type))
13341     return true;
13342 
13343   // C++ [basic.stc.dynamic.allocation]p1:
13344   //  The first parameter shall not have an associated default argument.
13345   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13346     return SemaRef.Diag(FnDecl->getLocation(),
13347                         diag::err_operator_new_default_arg)
13348       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13349 
13350   return false;
13351 }
13352 
13353 static bool
13354 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13355   // C++ [basic.stc.dynamic.deallocation]p1:
13356   //   A program is ill-formed if deallocation functions are declared in a
13357   //   namespace scope other than global scope or declared static in global
13358   //   scope.
13359   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13360     return true;
13361 
13362   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13363 
13364   // C++ P0722:
13365   //   Within a class C, the first parameter of a destroying operator delete
13366   //   shall be of type C *. The first parameter of any other deallocation
13367   //   function shall be of type void *.
13368   CanQualType ExpectedFirstParamType =
13369       MD && MD->isDestroyingOperatorDelete()
13370           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13371                 SemaRef.Context.getRecordType(MD->getParent())))
13372           : SemaRef.Context.VoidPtrTy;
13373 
13374   // C++ [basic.stc.dynamic.deallocation]p2:
13375   //   Each deallocation function shall return void
13376   if (CheckOperatorNewDeleteTypes(
13377           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13378           diag::err_operator_delete_dependent_param_type,
13379           diag::err_operator_delete_param_type))
13380     return true;
13381 
13382   // C++ P0722:
13383   //   A destroying operator delete shall be a usual deallocation function.
13384   if (MD && !MD->getParent()->isDependentContext() &&
13385       MD->isDestroyingOperatorDelete() &&
13386       !SemaRef.isUsualDeallocationFunction(MD)) {
13387     SemaRef.Diag(MD->getLocation(),
13388                  diag::err_destroying_operator_delete_not_usual);
13389     return true;
13390   }
13391 
13392   return false;
13393 }
13394 
13395 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13396 /// of this overloaded operator is well-formed. If so, returns false;
13397 /// otherwise, emits appropriate diagnostics and returns true.
13398 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13399   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13400          "Expected an overloaded operator declaration");
13401 
13402   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13403 
13404   // C++ [over.oper]p5:
13405   //   The allocation and deallocation functions, operator new,
13406   //   operator new[], operator delete and operator delete[], are
13407   //   described completely in 3.7.3. The attributes and restrictions
13408   //   found in the rest of this subclause do not apply to them unless
13409   //   explicitly stated in 3.7.3.
13410   if (Op == OO_Delete || Op == OO_Array_Delete)
13411     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13412 
13413   if (Op == OO_New || Op == OO_Array_New)
13414     return CheckOperatorNewDeclaration(*this, FnDecl);
13415 
13416   // C++ [over.oper]p6:
13417   //   An operator function shall either be a non-static member
13418   //   function or be a non-member function and have at least one
13419   //   parameter whose type is a class, a reference to a class, an
13420   //   enumeration, or a reference to an enumeration.
13421   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13422     if (MethodDecl->isStatic())
13423       return Diag(FnDecl->getLocation(),
13424                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13425   } else {
13426     bool ClassOrEnumParam = false;
13427     for (auto Param : FnDecl->parameters()) {
13428       QualType ParamType = Param->getType().getNonReferenceType();
13429       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13430           ParamType->isEnumeralType()) {
13431         ClassOrEnumParam = true;
13432         break;
13433       }
13434     }
13435 
13436     if (!ClassOrEnumParam)
13437       return Diag(FnDecl->getLocation(),
13438                   diag::err_operator_overload_needs_class_or_enum)
13439         << FnDecl->getDeclName();
13440   }
13441 
13442   // C++ [over.oper]p8:
13443   //   An operator function cannot have default arguments (8.3.6),
13444   //   except where explicitly stated below.
13445   //
13446   // Only the function-call operator allows default arguments
13447   // (C++ [over.call]p1).
13448   if (Op != OO_Call) {
13449     for (auto Param : FnDecl->parameters()) {
13450       if (Param->hasDefaultArg())
13451         return Diag(Param->getLocation(),
13452                     diag::err_operator_overload_default_arg)
13453           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13454     }
13455   }
13456 
13457   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13458     { false, false, false }
13459 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13460     , { Unary, Binary, MemberOnly }
13461 #include "clang/Basic/OperatorKinds.def"
13462   };
13463 
13464   bool CanBeUnaryOperator = OperatorUses[Op][0];
13465   bool CanBeBinaryOperator = OperatorUses[Op][1];
13466   bool MustBeMemberOperator = OperatorUses[Op][2];
13467 
13468   // C++ [over.oper]p8:
13469   //   [...] Operator functions cannot have more or fewer parameters
13470   //   than the number required for the corresponding operator, as
13471   //   described in the rest of this subclause.
13472   unsigned NumParams = FnDecl->getNumParams()
13473                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13474   if (Op != OO_Call &&
13475       ((NumParams == 1 && !CanBeUnaryOperator) ||
13476        (NumParams == 2 && !CanBeBinaryOperator) ||
13477        (NumParams < 1) || (NumParams > 2))) {
13478     // We have the wrong number of parameters.
13479     unsigned ErrorKind;
13480     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13481       ErrorKind = 2;  // 2 -> unary or binary.
13482     } else if (CanBeUnaryOperator) {
13483       ErrorKind = 0;  // 0 -> unary
13484     } else {
13485       assert(CanBeBinaryOperator &&
13486              "All non-call overloaded operators are unary or binary!");
13487       ErrorKind = 1;  // 1 -> binary
13488     }
13489 
13490     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13491       << FnDecl->getDeclName() << NumParams << ErrorKind;
13492   }
13493 
13494   // Overloaded operators other than operator() cannot be variadic.
13495   if (Op != OO_Call &&
13496       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13497     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13498       << FnDecl->getDeclName();
13499   }
13500 
13501   // Some operators must be non-static member functions.
13502   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13503     return Diag(FnDecl->getLocation(),
13504                 diag::err_operator_overload_must_be_member)
13505       << FnDecl->getDeclName();
13506   }
13507 
13508   // C++ [over.inc]p1:
13509   //   The user-defined function called operator++ implements the
13510   //   prefix and postfix ++ operator. If this function is a member
13511   //   function with no parameters, or a non-member function with one
13512   //   parameter of class or enumeration type, it defines the prefix
13513   //   increment operator ++ for objects of that type. If the function
13514   //   is a member function with one parameter (which shall be of type
13515   //   int) or a non-member function with two parameters (the second
13516   //   of which shall be of type int), it defines the postfix
13517   //   increment operator ++ for objects of that type.
13518   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13519     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13520     QualType ParamType = LastParam->getType();
13521 
13522     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13523         !ParamType->isDependentType())
13524       return Diag(LastParam->getLocation(),
13525                   diag::err_operator_overload_post_incdec_must_be_int)
13526         << LastParam->getType() << (Op == OO_MinusMinus);
13527   }
13528 
13529   return false;
13530 }
13531 
13532 static bool
13533 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13534                                           FunctionTemplateDecl *TpDecl) {
13535   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13536 
13537   // Must have one or two template parameters.
13538   if (TemplateParams->size() == 1) {
13539     NonTypeTemplateParmDecl *PmDecl =
13540         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13541 
13542     // The template parameter must be a char parameter pack.
13543     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13544         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13545       return false;
13546 
13547   } else if (TemplateParams->size() == 2) {
13548     TemplateTypeParmDecl *PmType =
13549         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13550     NonTypeTemplateParmDecl *PmArgs =
13551         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13552 
13553     // The second template parameter must be a parameter pack with the
13554     // first template parameter as its type.
13555     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13556         PmArgs->isTemplateParameterPack()) {
13557       const TemplateTypeParmType *TArgs =
13558           PmArgs->getType()->getAs<TemplateTypeParmType>();
13559       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13560           TArgs->getIndex() == PmType->getIndex()) {
13561         if (!SemaRef.inTemplateInstantiation())
13562           SemaRef.Diag(TpDecl->getLocation(),
13563                        diag::ext_string_literal_operator_template);
13564         return false;
13565       }
13566     }
13567   }
13568 
13569   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13570                diag::err_literal_operator_template)
13571       << TpDecl->getTemplateParameters()->getSourceRange();
13572   return true;
13573 }
13574 
13575 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13576 /// of this literal operator function is well-formed. If so, returns
13577 /// false; otherwise, emits appropriate diagnostics and returns true.
13578 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13579   if (isa<CXXMethodDecl>(FnDecl)) {
13580     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13581       << FnDecl->getDeclName();
13582     return true;
13583   }
13584 
13585   if (FnDecl->isExternC()) {
13586     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13587     if (const LinkageSpecDecl *LSD =
13588             FnDecl->getDeclContext()->getExternCContext())
13589       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13590     return true;
13591   }
13592 
13593   // This might be the definition of a literal operator template.
13594   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13595 
13596   // This might be a specialization of a literal operator template.
13597   if (!TpDecl)
13598     TpDecl = FnDecl->getPrimaryTemplate();
13599 
13600   // template <char...> type operator "" name() and
13601   // template <class T, T...> type operator "" name() are the only valid
13602   // template signatures, and the only valid signatures with no parameters.
13603   if (TpDecl) {
13604     if (FnDecl->param_size() != 0) {
13605       Diag(FnDecl->getLocation(),
13606            diag::err_literal_operator_template_with_params);
13607       return true;
13608     }
13609 
13610     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13611       return true;
13612 
13613   } else if (FnDecl->param_size() == 1) {
13614     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13615 
13616     QualType ParamType = Param->getType().getUnqualifiedType();
13617 
13618     // Only unsigned long long int, long double, any character type, and const
13619     // char * are allowed as the only parameters.
13620     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13621         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13622         Context.hasSameType(ParamType, Context.CharTy) ||
13623         Context.hasSameType(ParamType, Context.WideCharTy) ||
13624         Context.hasSameType(ParamType, Context.Char8Ty) ||
13625         Context.hasSameType(ParamType, Context.Char16Ty) ||
13626         Context.hasSameType(ParamType, Context.Char32Ty)) {
13627     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13628       QualType InnerType = Ptr->getPointeeType();
13629 
13630       // Pointer parameter must be a const char *.
13631       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13632                                 Context.CharTy) &&
13633             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13634         Diag(Param->getSourceRange().getBegin(),
13635              diag::err_literal_operator_param)
13636             << ParamType << "'const char *'" << Param->getSourceRange();
13637         return true;
13638       }
13639 
13640     } else if (ParamType->isRealFloatingType()) {
13641       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13642           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13643       return true;
13644 
13645     } else if (ParamType->isIntegerType()) {
13646       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13647           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13648       return true;
13649 
13650     } else {
13651       Diag(Param->getSourceRange().getBegin(),
13652            diag::err_literal_operator_invalid_param)
13653           << ParamType << Param->getSourceRange();
13654       return true;
13655     }
13656 
13657   } else if (FnDecl->param_size() == 2) {
13658     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13659 
13660     // First, verify that the first parameter is correct.
13661 
13662     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13663 
13664     // Two parameter function must have a pointer to const as a
13665     // first parameter; let's strip those qualifiers.
13666     const PointerType *PT = FirstParamType->getAs<PointerType>();
13667 
13668     if (!PT) {
13669       Diag((*Param)->getSourceRange().getBegin(),
13670            diag::err_literal_operator_param)
13671           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13672       return true;
13673     }
13674 
13675     QualType PointeeType = PT->getPointeeType();
13676     // First parameter must be const
13677     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13678       Diag((*Param)->getSourceRange().getBegin(),
13679            diag::err_literal_operator_param)
13680           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13681       return true;
13682     }
13683 
13684     QualType InnerType = PointeeType.getUnqualifiedType();
13685     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13686     // const char32_t* are allowed as the first parameter to a two-parameter
13687     // function
13688     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13689           Context.hasSameType(InnerType, Context.WideCharTy) ||
13690           Context.hasSameType(InnerType, Context.Char8Ty) ||
13691           Context.hasSameType(InnerType, Context.Char16Ty) ||
13692           Context.hasSameType(InnerType, Context.Char32Ty))) {
13693       Diag((*Param)->getSourceRange().getBegin(),
13694            diag::err_literal_operator_param)
13695           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13696       return true;
13697     }
13698 
13699     // Move on to the second and final parameter.
13700     ++Param;
13701 
13702     // The second parameter must be a std::size_t.
13703     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13704     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13705       Diag((*Param)->getSourceRange().getBegin(),
13706            diag::err_literal_operator_param)
13707           << SecondParamType << Context.getSizeType()
13708           << (*Param)->getSourceRange();
13709       return true;
13710     }
13711   } else {
13712     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13713     return true;
13714   }
13715 
13716   // Parameters are good.
13717 
13718   // A parameter-declaration-clause containing a default argument is not
13719   // equivalent to any of the permitted forms.
13720   for (auto Param : FnDecl->parameters()) {
13721     if (Param->hasDefaultArg()) {
13722       Diag(Param->getDefaultArgRange().getBegin(),
13723            diag::err_literal_operator_default_argument)
13724         << Param->getDefaultArgRange();
13725       break;
13726     }
13727   }
13728 
13729   StringRef LiteralName
13730     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13731   if (LiteralName[0] != '_' &&
13732       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13733     // C++11 [usrlit.suffix]p1:
13734     //   Literal suffix identifiers that do not start with an underscore
13735     //   are reserved for future standardization.
13736     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13737       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13738   }
13739 
13740   return false;
13741 }
13742 
13743 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13744 /// linkage specification, including the language and (if present)
13745 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13746 /// language string literal. LBraceLoc, if valid, provides the location of
13747 /// the '{' brace. Otherwise, this linkage specification does not
13748 /// have any braces.
13749 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13750                                            Expr *LangStr,
13751                                            SourceLocation LBraceLoc) {
13752   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13753   if (!Lit->isAscii()) {
13754     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13755       << LangStr->getSourceRange();
13756     return nullptr;
13757   }
13758 
13759   StringRef Lang = Lit->getString();
13760   LinkageSpecDecl::LanguageIDs Language;
13761   if (Lang == "C")
13762     Language = LinkageSpecDecl::lang_c;
13763   else if (Lang == "C++")
13764     Language = LinkageSpecDecl::lang_cxx;
13765   else {
13766     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13767       << LangStr->getSourceRange();
13768     return nullptr;
13769   }
13770 
13771   // FIXME: Add all the various semantics of linkage specifications
13772 
13773   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13774                                                LangStr->getExprLoc(), Language,
13775                                                LBraceLoc.isValid());
13776   CurContext->addDecl(D);
13777   PushDeclContext(S, D);
13778   return D;
13779 }
13780 
13781 /// ActOnFinishLinkageSpecification - Complete the definition of
13782 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13783 /// valid, it's the position of the closing '}' brace in a linkage
13784 /// specification that uses braces.
13785 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13786                                             Decl *LinkageSpec,
13787                                             SourceLocation RBraceLoc) {
13788   if (RBraceLoc.isValid()) {
13789     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13790     LSDecl->setRBraceLoc(RBraceLoc);
13791   }
13792   PopDeclContext();
13793   return LinkageSpec;
13794 }
13795 
13796 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13797                                   const ParsedAttributesView &AttrList,
13798                                   SourceLocation SemiLoc) {
13799   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13800   // Attribute declarations appertain to empty declaration so we handle
13801   // them here.
13802   ProcessDeclAttributeList(S, ED, AttrList);
13803 
13804   CurContext->addDecl(ED);
13805   return ED;
13806 }
13807 
13808 /// Perform semantic analysis for the variable declaration that
13809 /// occurs within a C++ catch clause, returning the newly-created
13810 /// variable.
13811 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13812                                          TypeSourceInfo *TInfo,
13813                                          SourceLocation StartLoc,
13814                                          SourceLocation Loc,
13815                                          IdentifierInfo *Name) {
13816   bool Invalid = false;
13817   QualType ExDeclType = TInfo->getType();
13818 
13819   // Arrays and functions decay.
13820   if (ExDeclType->isArrayType())
13821     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13822   else if (ExDeclType->isFunctionType())
13823     ExDeclType = Context.getPointerType(ExDeclType);
13824 
13825   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13826   // The exception-declaration shall not denote a pointer or reference to an
13827   // incomplete type, other than [cv] void*.
13828   // N2844 forbids rvalue references.
13829   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13830     Diag(Loc, diag::err_catch_rvalue_ref);
13831     Invalid = true;
13832   }
13833 
13834   if (ExDeclType->isVariablyModifiedType()) {
13835     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13836     Invalid = true;
13837   }
13838 
13839   QualType BaseType = ExDeclType;
13840   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13841   unsigned DK = diag::err_catch_incomplete;
13842   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13843     BaseType = Ptr->getPointeeType();
13844     Mode = 1;
13845     DK = diag::err_catch_incomplete_ptr;
13846   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13847     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13848     BaseType = Ref->getPointeeType();
13849     Mode = 2;
13850     DK = diag::err_catch_incomplete_ref;
13851   }
13852   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13853       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13854     Invalid = true;
13855 
13856   if (!Invalid && !ExDeclType->isDependentType() &&
13857       RequireNonAbstractType(Loc, ExDeclType,
13858                              diag::err_abstract_type_in_decl,
13859                              AbstractVariableType))
13860     Invalid = true;
13861 
13862   // Only the non-fragile NeXT runtime currently supports C++ catches
13863   // of ObjC types, and no runtime supports catching ObjC types by value.
13864   if (!Invalid && getLangOpts().ObjC) {
13865     QualType T = ExDeclType;
13866     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13867       T = RT->getPointeeType();
13868 
13869     if (T->isObjCObjectType()) {
13870       Diag(Loc, diag::err_objc_object_catch);
13871       Invalid = true;
13872     } else if (T->isObjCObjectPointerType()) {
13873       // FIXME: should this be a test for macosx-fragile specifically?
13874       if (getLangOpts().ObjCRuntime.isFragile())
13875         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13876     }
13877   }
13878 
13879   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13880                                     ExDeclType, TInfo, SC_None);
13881   ExDecl->setExceptionVariable(true);
13882 
13883   // In ARC, infer 'retaining' for variables of retainable type.
13884   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13885     Invalid = true;
13886 
13887   if (!Invalid && !ExDeclType->isDependentType()) {
13888     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13889       // Insulate this from anything else we might currently be parsing.
13890       EnterExpressionEvaluationContext scope(
13891           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13892 
13893       // C++ [except.handle]p16:
13894       //   The object declared in an exception-declaration or, if the
13895       //   exception-declaration does not specify a name, a temporary (12.2) is
13896       //   copy-initialized (8.5) from the exception object. [...]
13897       //   The object is destroyed when the handler exits, after the destruction
13898       //   of any automatic objects initialized within the handler.
13899       //
13900       // We just pretend to initialize the object with itself, then make sure
13901       // it can be destroyed later.
13902       QualType initType = Context.getExceptionObjectType(ExDeclType);
13903 
13904       InitializedEntity entity =
13905         InitializedEntity::InitializeVariable(ExDecl);
13906       InitializationKind initKind =
13907         InitializationKind::CreateCopy(Loc, SourceLocation());
13908 
13909       Expr *opaqueValue =
13910         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13911       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13912       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13913       if (result.isInvalid())
13914         Invalid = true;
13915       else {
13916         // If the constructor used was non-trivial, set this as the
13917         // "initializer".
13918         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13919         if (!construct->getConstructor()->isTrivial()) {
13920           Expr *init = MaybeCreateExprWithCleanups(construct);
13921           ExDecl->setInit(init);
13922         }
13923 
13924         // And make sure it's destructable.
13925         FinalizeVarWithDestructor(ExDecl, recordType);
13926       }
13927     }
13928   }
13929 
13930   if (Invalid)
13931     ExDecl->setInvalidDecl();
13932 
13933   return ExDecl;
13934 }
13935 
13936 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13937 /// handler.
13938 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13939   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13940   bool Invalid = D.isInvalidType();
13941 
13942   // Check for unexpanded parameter packs.
13943   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13944                                       UPPC_ExceptionType)) {
13945     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13946                                              D.getIdentifierLoc());
13947     Invalid = true;
13948   }
13949 
13950   IdentifierInfo *II = D.getIdentifier();
13951   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13952                                              LookupOrdinaryName,
13953                                              ForVisibleRedeclaration)) {
13954     // The scope should be freshly made just for us. There is just no way
13955     // it contains any previous declaration, except for function parameters in
13956     // a function-try-block's catch statement.
13957     assert(!S->isDeclScope(PrevDecl));
13958     if (isDeclInScope(PrevDecl, CurContext, S)) {
13959       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13960         << D.getIdentifier();
13961       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13962       Invalid = true;
13963     } else if (PrevDecl->isTemplateParameter())
13964       // Maybe we will complain about the shadowed template parameter.
13965       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13966   }
13967 
13968   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13969     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13970       << D.getCXXScopeSpec().getRange();
13971     Invalid = true;
13972   }
13973 
13974   VarDecl *ExDecl = BuildExceptionDeclaration(
13975       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
13976   if (Invalid)
13977     ExDecl->setInvalidDecl();
13978 
13979   // Add the exception declaration into this scope.
13980   if (II)
13981     PushOnScopeChains(ExDecl, S);
13982   else
13983     CurContext->addDecl(ExDecl);
13984 
13985   ProcessDeclAttributes(S, ExDecl, D);
13986   return ExDecl;
13987 }
13988 
13989 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13990                                          Expr *AssertExpr,
13991                                          Expr *AssertMessageExpr,
13992                                          SourceLocation RParenLoc) {
13993   StringLiteral *AssertMessage =
13994       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13995 
13996   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13997     return nullptr;
13998 
13999   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
14000                                       AssertMessage, RParenLoc, false);
14001 }
14002 
14003 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
14004                                          Expr *AssertExpr,
14005                                          StringLiteral *AssertMessage,
14006                                          SourceLocation RParenLoc,
14007                                          bool Failed) {
14008   assert(AssertExpr != nullptr && "Expected non-null condition");
14009   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
14010       !Failed) {
14011     // In a static_assert-declaration, the constant-expression shall be a
14012     // constant expression that can be contextually converted to bool.
14013     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
14014     if (Converted.isInvalid())
14015       Failed = true;
14016 
14017     llvm::APSInt Cond;
14018     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
14019           diag::err_static_assert_expression_is_not_constant,
14020           /*AllowFold=*/false).isInvalid())
14021       Failed = true;
14022 
14023     if (!Failed && !Cond) {
14024       SmallString<256> MsgBuffer;
14025       llvm::raw_svector_ostream Msg(MsgBuffer);
14026       if (AssertMessage)
14027         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
14028 
14029       Expr *InnerCond = nullptr;
14030       std::string InnerCondDescription;
14031       std::tie(InnerCond, InnerCondDescription) =
14032         findFailedBooleanCondition(Converted.get());
14033       if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
14034                     && !isa<IntegerLiteral>(InnerCond)) {
14035         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
14036           << InnerCondDescription << !AssertMessage
14037           << Msg.str() << InnerCond->getSourceRange();
14038       } else {
14039         Diag(StaticAssertLoc, diag::err_static_assert_failed)
14040           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
14041       }
14042       Failed = true;
14043     }
14044   }
14045 
14046   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
14047                                                   /*DiscardedValue*/false,
14048                                                   /*IsConstexpr*/true);
14049   if (FullAssertExpr.isInvalid())
14050     Failed = true;
14051   else
14052     AssertExpr = FullAssertExpr.get();
14053 
14054   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
14055                                         AssertExpr, AssertMessage, RParenLoc,
14056                                         Failed);
14057 
14058   CurContext->addDecl(Decl);
14059   return Decl;
14060 }
14061 
14062 /// Perform semantic analysis of the given friend type declaration.
14063 ///
14064 /// \returns A friend declaration that.
14065 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
14066                                       SourceLocation FriendLoc,
14067                                       TypeSourceInfo *TSInfo) {
14068   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
14069 
14070   QualType T = TSInfo->getType();
14071   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
14072 
14073   // C++03 [class.friend]p2:
14074   //   An elaborated-type-specifier shall be used in a friend declaration
14075   //   for a class.*
14076   //
14077   //   * The class-key of the elaborated-type-specifier is required.
14078   if (!CodeSynthesisContexts.empty()) {
14079     // Do not complain about the form of friend template types during any kind
14080     // of code synthesis. For template instantiation, we will have complained
14081     // when the template was defined.
14082   } else {
14083     if (!T->isElaboratedTypeSpecifier()) {
14084       // If we evaluated the type to a record type, suggest putting
14085       // a tag in front.
14086       if (const RecordType *RT = T->getAs<RecordType>()) {
14087         RecordDecl *RD = RT->getDecl();
14088 
14089         SmallString<16> InsertionText(" ");
14090         InsertionText += RD->getKindName();
14091 
14092         Diag(TypeRange.getBegin(),
14093              getLangOpts().CPlusPlus11 ?
14094                diag::warn_cxx98_compat_unelaborated_friend_type :
14095                diag::ext_unelaborated_friend_type)
14096           << (unsigned) RD->getTagKind()
14097           << T
14098           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
14099                                         InsertionText);
14100       } else {
14101         Diag(FriendLoc,
14102              getLangOpts().CPlusPlus11 ?
14103                diag::warn_cxx98_compat_nonclass_type_friend :
14104                diag::ext_nonclass_type_friend)
14105           << T
14106           << TypeRange;
14107       }
14108     } else if (T->getAs<EnumType>()) {
14109       Diag(FriendLoc,
14110            getLangOpts().CPlusPlus11 ?
14111              diag::warn_cxx98_compat_enum_friend :
14112              diag::ext_enum_friend)
14113         << T
14114         << TypeRange;
14115     }
14116 
14117     // C++11 [class.friend]p3:
14118     //   A friend declaration that does not declare a function shall have one
14119     //   of the following forms:
14120     //     friend elaborated-type-specifier ;
14121     //     friend simple-type-specifier ;
14122     //     friend typename-specifier ;
14123     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14124       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14125   }
14126 
14127   //   If the type specifier in a friend declaration designates a (possibly
14128   //   cv-qualified) class type, that class is declared as a friend; otherwise,
14129   //   the friend declaration is ignored.
14130   return FriendDecl::Create(Context, CurContext,
14131                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14132                             FriendLoc);
14133 }
14134 
14135 /// Handle a friend tag declaration where the scope specifier was
14136 /// templated.
14137 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
14138                                     unsigned TagSpec, SourceLocation TagLoc,
14139                                     CXXScopeSpec &SS, IdentifierInfo *Name,
14140                                     SourceLocation NameLoc,
14141                                     const ParsedAttributesView &Attr,
14142                                     MultiTemplateParamsArg TempParamLists) {
14143   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14144 
14145   bool IsMemberSpecialization = false;
14146   bool Invalid = false;
14147 
14148   if (TemplateParameterList *TemplateParams =
14149           MatchTemplateParametersToScopeSpecifier(
14150               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14151               IsMemberSpecialization, Invalid)) {
14152     if (TemplateParams->size() > 0) {
14153       // This is a declaration of a class template.
14154       if (Invalid)
14155         return nullptr;
14156 
14157       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14158                                 NameLoc, Attr, TemplateParams, AS_public,
14159                                 /*ModulePrivateLoc=*/SourceLocation(),
14160                                 FriendLoc, TempParamLists.size() - 1,
14161                                 TempParamLists.data()).get();
14162     } else {
14163       // The "template<>" header is extraneous.
14164       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14165         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14166       IsMemberSpecialization = true;
14167     }
14168   }
14169 
14170   if (Invalid) return nullptr;
14171 
14172   bool isAllExplicitSpecializations = true;
14173   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14174     if (TempParamLists[I]->size()) {
14175       isAllExplicitSpecializations = false;
14176       break;
14177     }
14178   }
14179 
14180   // FIXME: don't ignore attributes.
14181 
14182   // If it's explicit specializations all the way down, just forget
14183   // about the template header and build an appropriate non-templated
14184   // friend.  TODO: for source fidelity, remember the headers.
14185   if (isAllExplicitSpecializations) {
14186     if (SS.isEmpty()) {
14187       bool Owned = false;
14188       bool IsDependent = false;
14189       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14190                       Attr, AS_public,
14191                       /*ModulePrivateLoc=*/SourceLocation(),
14192                       MultiTemplateParamsArg(), Owned, IsDependent,
14193                       /*ScopedEnumKWLoc=*/SourceLocation(),
14194                       /*ScopedEnumUsesClassTag=*/false,
14195                       /*UnderlyingType=*/TypeResult(),
14196                       /*IsTypeSpecifier=*/false,
14197                       /*IsTemplateParamOrArg=*/false);
14198     }
14199 
14200     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14201     ElaboratedTypeKeyword Keyword
14202       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14203     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14204                                    *Name, NameLoc);
14205     if (T.isNull())
14206       return nullptr;
14207 
14208     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14209     if (isa<DependentNameType>(T)) {
14210       DependentNameTypeLoc TL =
14211           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14212       TL.setElaboratedKeywordLoc(TagLoc);
14213       TL.setQualifierLoc(QualifierLoc);
14214       TL.setNameLoc(NameLoc);
14215     } else {
14216       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14217       TL.setElaboratedKeywordLoc(TagLoc);
14218       TL.setQualifierLoc(QualifierLoc);
14219       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14220     }
14221 
14222     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14223                                             TSI, FriendLoc, TempParamLists);
14224     Friend->setAccess(AS_public);
14225     CurContext->addDecl(Friend);
14226     return Friend;
14227   }
14228 
14229   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14230 
14231 
14232 
14233   // Handle the case of a templated-scope friend class.  e.g.
14234   //   template <class T> class A<T>::B;
14235   // FIXME: we don't support these right now.
14236   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14237     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14238   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14239   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14240   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14241   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14242   TL.setElaboratedKeywordLoc(TagLoc);
14243   TL.setQualifierLoc(SS.getWithLocInContext(Context));
14244   TL.setNameLoc(NameLoc);
14245 
14246   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14247                                           TSI, FriendLoc, TempParamLists);
14248   Friend->setAccess(AS_public);
14249   Friend->setUnsupportedFriend(true);
14250   CurContext->addDecl(Friend);
14251   return Friend;
14252 }
14253 
14254 /// Handle a friend type declaration.  This works in tandem with
14255 /// ActOnTag.
14256 ///
14257 /// Notes on friend class templates:
14258 ///
14259 /// We generally treat friend class declarations as if they were
14260 /// declaring a class.  So, for example, the elaborated type specifier
14261 /// in a friend declaration is required to obey the restrictions of a
14262 /// class-head (i.e. no typedefs in the scope chain), template
14263 /// parameters are required to match up with simple template-ids, &c.
14264 /// However, unlike when declaring a template specialization, it's
14265 /// okay to refer to a template specialization without an empty
14266 /// template parameter declaration, e.g.
14267 ///   friend class A<T>::B<unsigned>;
14268 /// We permit this as a special case; if there are any template
14269 /// parameters present at all, require proper matching, i.e.
14270 ///   template <> template \<class T> friend class A<int>::B;
14271 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14272                                 MultiTemplateParamsArg TempParams) {
14273   SourceLocation Loc = DS.getBeginLoc();
14274 
14275   assert(DS.isFriendSpecified());
14276   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14277 
14278   // C++ [class.friend]p3:
14279   // A friend declaration that does not declare a function shall have one of
14280   // the following forms:
14281   //     friend elaborated-type-specifier ;
14282   //     friend simple-type-specifier ;
14283   //     friend typename-specifier ;
14284   //
14285   // Any declaration with a type qualifier does not have that form. (It's
14286   // legal to specify a qualified type as a friend, you just can't write the
14287   // keywords.)
14288   if (DS.getTypeQualifiers()) {
14289     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14290       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14291     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14292       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14293     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14294       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14295     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14296       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14297     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14298       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14299   }
14300 
14301   // Try to convert the decl specifier to a type.  This works for
14302   // friend templates because ActOnTag never produces a ClassTemplateDecl
14303   // for a TUK_Friend.
14304   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14305   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14306   QualType T = TSI->getType();
14307   if (TheDeclarator.isInvalidType())
14308     return nullptr;
14309 
14310   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14311     return nullptr;
14312 
14313   // This is definitely an error in C++98.  It's probably meant to
14314   // be forbidden in C++0x, too, but the specification is just
14315   // poorly written.
14316   //
14317   // The problem is with declarations like the following:
14318   //   template <T> friend A<T>::foo;
14319   // where deciding whether a class C is a friend or not now hinges
14320   // on whether there exists an instantiation of A that causes
14321   // 'foo' to equal C.  There are restrictions on class-heads
14322   // (which we declare (by fiat) elaborated friend declarations to
14323   // be) that makes this tractable.
14324   //
14325   // FIXME: handle "template <> friend class A<T>;", which
14326   // is possibly well-formed?  Who even knows?
14327   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14328     Diag(Loc, diag::err_tagless_friend_type_template)
14329       << DS.getSourceRange();
14330     return nullptr;
14331   }
14332 
14333   // C++98 [class.friend]p1: A friend of a class is a function
14334   //   or class that is not a member of the class . . .
14335   // This is fixed in DR77, which just barely didn't make the C++03
14336   // deadline.  It's also a very silly restriction that seriously
14337   // affects inner classes and which nobody else seems to implement;
14338   // thus we never diagnose it, not even in -pedantic.
14339   //
14340   // But note that we could warn about it: it's always useless to
14341   // friend one of your own members (it's not, however, worthless to
14342   // friend a member of an arbitrary specialization of your template).
14343 
14344   Decl *D;
14345   if (!TempParams.empty())
14346     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14347                                    TempParams,
14348                                    TSI,
14349                                    DS.getFriendSpecLoc());
14350   else
14351     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14352 
14353   if (!D)
14354     return nullptr;
14355 
14356   D->setAccess(AS_public);
14357   CurContext->addDecl(D);
14358 
14359   return D;
14360 }
14361 
14362 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14363                                         MultiTemplateParamsArg TemplateParams) {
14364   const DeclSpec &DS = D.getDeclSpec();
14365 
14366   assert(DS.isFriendSpecified());
14367   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14368 
14369   SourceLocation Loc = D.getIdentifierLoc();
14370   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14371 
14372   // C++ [class.friend]p1
14373   //   A friend of a class is a function or class....
14374   // Note that this sees through typedefs, which is intended.
14375   // It *doesn't* see through dependent types, which is correct
14376   // according to [temp.arg.type]p3:
14377   //   If a declaration acquires a function type through a
14378   //   type dependent on a template-parameter and this causes
14379   //   a declaration that does not use the syntactic form of a
14380   //   function declarator to have a function type, the program
14381   //   is ill-formed.
14382   if (!TInfo->getType()->isFunctionType()) {
14383     Diag(Loc, diag::err_unexpected_friend);
14384 
14385     // It might be worthwhile to try to recover by creating an
14386     // appropriate declaration.
14387     return nullptr;
14388   }
14389 
14390   // C++ [namespace.memdef]p3
14391   //  - If a friend declaration in a non-local class first declares a
14392   //    class or function, the friend class or function is a member
14393   //    of the innermost enclosing namespace.
14394   //  - The name of the friend is not found by simple name lookup
14395   //    until a matching declaration is provided in that namespace
14396   //    scope (either before or after the class declaration granting
14397   //    friendship).
14398   //  - If a friend function is called, its name may be found by the
14399   //    name lookup that considers functions from namespaces and
14400   //    classes associated with the types of the function arguments.
14401   //  - When looking for a prior declaration of a class or a function
14402   //    declared as a friend, scopes outside the innermost enclosing
14403   //    namespace scope are not considered.
14404 
14405   CXXScopeSpec &SS = D.getCXXScopeSpec();
14406   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14407   assert(NameInfo.getName());
14408 
14409   // Check for unexpanded parameter packs.
14410   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14411       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14412       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14413     return nullptr;
14414 
14415   // The context we found the declaration in, or in which we should
14416   // create the declaration.
14417   DeclContext *DC;
14418   Scope *DCScope = S;
14419   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14420                         ForExternalRedeclaration);
14421 
14422   // There are five cases here.
14423   //   - There's no scope specifier and we're in a local class. Only look
14424   //     for functions declared in the immediately-enclosing block scope.
14425   // We recover from invalid scope qualifiers as if they just weren't there.
14426   FunctionDecl *FunctionContainingLocalClass = nullptr;
14427   if ((SS.isInvalid() || !SS.isSet()) &&
14428       (FunctionContainingLocalClass =
14429            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14430     // C++11 [class.friend]p11:
14431     //   If a friend declaration appears in a local class and the name
14432     //   specified is an unqualified name, a prior declaration is
14433     //   looked up without considering scopes that are outside the
14434     //   innermost enclosing non-class scope. For a friend function
14435     //   declaration, if there is no prior declaration, the program is
14436     //   ill-formed.
14437 
14438     // Find the innermost enclosing non-class scope. This is the block
14439     // scope containing the local class definition (or for a nested class,
14440     // the outer local class).
14441     DCScope = S->getFnParent();
14442 
14443     // Look up the function name in the scope.
14444     Previous.clear(LookupLocalFriendName);
14445     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14446 
14447     if (!Previous.empty()) {
14448       // All possible previous declarations must have the same context:
14449       // either they were declared at block scope or they are members of
14450       // one of the enclosing local classes.
14451       DC = Previous.getRepresentativeDecl()->getDeclContext();
14452     } else {
14453       // This is ill-formed, but provide the context that we would have
14454       // declared the function in, if we were permitted to, for error recovery.
14455       DC = FunctionContainingLocalClass;
14456     }
14457     adjustContextForLocalExternDecl(DC);
14458 
14459     // C++ [class.friend]p6:
14460     //   A function can be defined in a friend declaration of a class if and
14461     //   only if the class is a non-local class (9.8), the function name is
14462     //   unqualified, and the function has namespace scope.
14463     if (D.isFunctionDefinition()) {
14464       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14465     }
14466 
14467   //   - There's no scope specifier, in which case we just go to the
14468   //     appropriate scope and look for a function or function template
14469   //     there as appropriate.
14470   } else if (SS.isInvalid() || !SS.isSet()) {
14471     // C++11 [namespace.memdef]p3:
14472     //   If the name in a friend declaration is neither qualified nor
14473     //   a template-id and the declaration is a function or an
14474     //   elaborated-type-specifier, the lookup to determine whether
14475     //   the entity has been previously declared shall not consider
14476     //   any scopes outside the innermost enclosing namespace.
14477     bool isTemplateId =
14478         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14479 
14480     // Find the appropriate context according to the above.
14481     DC = CurContext;
14482 
14483     // Skip class contexts.  If someone can cite chapter and verse
14484     // for this behavior, that would be nice --- it's what GCC and
14485     // EDG do, and it seems like a reasonable intent, but the spec
14486     // really only says that checks for unqualified existing
14487     // declarations should stop at the nearest enclosing namespace,
14488     // not that they should only consider the nearest enclosing
14489     // namespace.
14490     while (DC->isRecord())
14491       DC = DC->getParent();
14492 
14493     DeclContext *LookupDC = DC;
14494     while (LookupDC->isTransparentContext())
14495       LookupDC = LookupDC->getParent();
14496 
14497     while (true) {
14498       LookupQualifiedName(Previous, LookupDC);
14499 
14500       if (!Previous.empty()) {
14501         DC = LookupDC;
14502         break;
14503       }
14504 
14505       if (isTemplateId) {
14506         if (isa<TranslationUnitDecl>(LookupDC)) break;
14507       } else {
14508         if (LookupDC->isFileContext()) break;
14509       }
14510       LookupDC = LookupDC->getParent();
14511     }
14512 
14513     DCScope = getScopeForDeclContext(S, DC);
14514 
14515   //   - There's a non-dependent scope specifier, in which case we
14516   //     compute it and do a previous lookup there for a function
14517   //     or function template.
14518   } else if (!SS.getScopeRep()->isDependent()) {
14519     DC = computeDeclContext(SS);
14520     if (!DC) return nullptr;
14521 
14522     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14523 
14524     LookupQualifiedName(Previous, DC);
14525 
14526     // C++ [class.friend]p1: A friend of a class is a function or
14527     //   class that is not a member of the class . . .
14528     if (DC->Equals(CurContext))
14529       Diag(DS.getFriendSpecLoc(),
14530            getLangOpts().CPlusPlus11 ?
14531              diag::warn_cxx98_compat_friend_is_member :
14532              diag::err_friend_is_member);
14533 
14534     if (D.isFunctionDefinition()) {
14535       // C++ [class.friend]p6:
14536       //   A function can be defined in a friend declaration of a class if and
14537       //   only if the class is a non-local class (9.8), the function name is
14538       //   unqualified, and the function has namespace scope.
14539       //
14540       // FIXME: We should only do this if the scope specifier names the
14541       // innermost enclosing namespace; otherwise the fixit changes the
14542       // meaning of the code.
14543       SemaDiagnosticBuilder DB
14544         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14545 
14546       DB << SS.getScopeRep();
14547       if (DC->isFileContext())
14548         DB << FixItHint::CreateRemoval(SS.getRange());
14549       SS.clear();
14550     }
14551 
14552   //   - There's a scope specifier that does not match any template
14553   //     parameter lists, in which case we use some arbitrary context,
14554   //     create a method or method template, and wait for instantiation.
14555   //   - There's a scope specifier that does match some template
14556   //     parameter lists, which we don't handle right now.
14557   } else {
14558     if (D.isFunctionDefinition()) {
14559       // C++ [class.friend]p6:
14560       //   A function can be defined in a friend declaration of a class if and
14561       //   only if the class is a non-local class (9.8), the function name is
14562       //   unqualified, and the function has namespace scope.
14563       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14564         << SS.getScopeRep();
14565     }
14566 
14567     DC = CurContext;
14568     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14569   }
14570 
14571   if (!DC->isRecord()) {
14572     int DiagArg = -1;
14573     switch (D.getName().getKind()) {
14574     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14575     case UnqualifiedIdKind::IK_ConstructorName:
14576       DiagArg = 0;
14577       break;
14578     case UnqualifiedIdKind::IK_DestructorName:
14579       DiagArg = 1;
14580       break;
14581     case UnqualifiedIdKind::IK_ConversionFunctionId:
14582       DiagArg = 2;
14583       break;
14584     case UnqualifiedIdKind::IK_DeductionGuideName:
14585       DiagArg = 3;
14586       break;
14587     case UnqualifiedIdKind::IK_Identifier:
14588     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14589     case UnqualifiedIdKind::IK_LiteralOperatorId:
14590     case UnqualifiedIdKind::IK_OperatorFunctionId:
14591     case UnqualifiedIdKind::IK_TemplateId:
14592       break;
14593     }
14594     // This implies that it has to be an operator or function.
14595     if (DiagArg >= 0) {
14596       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14597       return nullptr;
14598     }
14599   }
14600 
14601   // FIXME: This is an egregious hack to cope with cases where the scope stack
14602   // does not contain the declaration context, i.e., in an out-of-line
14603   // definition of a class.
14604   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14605   if (!DCScope) {
14606     FakeDCScope.setEntity(DC);
14607     DCScope = &FakeDCScope;
14608   }
14609 
14610   bool AddToScope = true;
14611   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14612                                           TemplateParams, AddToScope);
14613   if (!ND) return nullptr;
14614 
14615   assert(ND->getLexicalDeclContext() == CurContext);
14616 
14617   // If we performed typo correction, we might have added a scope specifier
14618   // and changed the decl context.
14619   DC = ND->getDeclContext();
14620 
14621   // Add the function declaration to the appropriate lookup tables,
14622   // adjusting the redeclarations list as necessary.  We don't
14623   // want to do this yet if the friending class is dependent.
14624   //
14625   // Also update the scope-based lookup if the target context's
14626   // lookup context is in lexical scope.
14627   if (!CurContext->isDependentContext()) {
14628     DC = DC->getRedeclContext();
14629     DC->makeDeclVisibleInContext(ND);
14630     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14631       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14632   }
14633 
14634   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14635                                        D.getIdentifierLoc(), ND,
14636                                        DS.getFriendSpecLoc());
14637   FrD->setAccess(AS_public);
14638   CurContext->addDecl(FrD);
14639 
14640   if (ND->isInvalidDecl()) {
14641     FrD->setInvalidDecl();
14642   } else {
14643     if (DC->isRecord()) CheckFriendAccess(ND);
14644 
14645     FunctionDecl *FD;
14646     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14647       FD = FTD->getTemplatedDecl();
14648     else
14649       FD = cast<FunctionDecl>(ND);
14650 
14651     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14652     // default argument expression, that declaration shall be a definition
14653     // and shall be the only declaration of the function or function
14654     // template in the translation unit.
14655     if (functionDeclHasDefaultArgument(FD)) {
14656       // We can't look at FD->getPreviousDecl() because it may not have been set
14657       // if we're in a dependent context. If the function is known to be a
14658       // redeclaration, we will have narrowed Previous down to the right decl.
14659       if (D.isRedeclaration()) {
14660         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14661         Diag(Previous.getRepresentativeDecl()->getLocation(),
14662              diag::note_previous_declaration);
14663       } else if (!D.isFunctionDefinition())
14664         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14665     }
14666 
14667     // Mark templated-scope function declarations as unsupported.
14668     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14669       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14670         << SS.getScopeRep() << SS.getRange()
14671         << cast<CXXRecordDecl>(CurContext);
14672       FrD->setUnsupportedFriend(true);
14673     }
14674   }
14675 
14676   return ND;
14677 }
14678 
14679 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14680   AdjustDeclIfTemplate(Dcl);
14681 
14682   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14683   if (!Fn) {
14684     Diag(DelLoc, diag::err_deleted_non_function);
14685     return;
14686   }
14687 
14688   // Deleted function does not have a body.
14689   Fn->setWillHaveBody(false);
14690 
14691   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14692     // Don't consider the implicit declaration we generate for explicit
14693     // specializations. FIXME: Do not generate these implicit declarations.
14694     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14695          Prev->getPreviousDecl()) &&
14696         !Prev->isDefined()) {
14697       Diag(DelLoc, diag::err_deleted_decl_not_first);
14698       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14699            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14700                               : diag::note_previous_declaration);
14701     }
14702     // If the declaration wasn't the first, we delete the function anyway for
14703     // recovery.
14704     Fn = Fn->getCanonicalDecl();
14705   }
14706 
14707   // dllimport/dllexport cannot be deleted.
14708   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14709     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14710     Fn->setInvalidDecl();
14711   }
14712 
14713   if (Fn->isDeleted())
14714     return;
14715 
14716   // See if we're deleting a function which is already known to override a
14717   // non-deleted virtual function.
14718   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14719     bool IssuedDiagnostic = false;
14720     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14721       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14722         if (!IssuedDiagnostic) {
14723           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14724           IssuedDiagnostic = true;
14725         }
14726         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14727       }
14728     }
14729     // If this function was implicitly deleted because it was defaulted,
14730     // explain why it was deleted.
14731     if (IssuedDiagnostic && MD->isDefaulted())
14732       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14733                                 /*Diagnose*/true);
14734   }
14735 
14736   // C++11 [basic.start.main]p3:
14737   //   A program that defines main as deleted [...] is ill-formed.
14738   if (Fn->isMain())
14739     Diag(DelLoc, diag::err_deleted_main);
14740 
14741   // C++11 [dcl.fct.def.delete]p4:
14742   //  A deleted function is implicitly inline.
14743   Fn->setImplicitlyInline();
14744   Fn->setDeletedAsWritten();
14745 }
14746 
14747 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14748   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14749 
14750   if (MD) {
14751     if (MD->getParent()->isDependentType()) {
14752       MD->setDefaulted();
14753       MD->setExplicitlyDefaulted();
14754       return;
14755     }
14756 
14757     CXXSpecialMember Member = getSpecialMember(MD);
14758     if (Member == CXXInvalid) {
14759       if (!MD->isInvalidDecl())
14760         Diag(DefaultLoc, diag::err_default_special_members);
14761       return;
14762     }
14763 
14764     MD->setDefaulted();
14765     MD->setExplicitlyDefaulted();
14766 
14767     // Unset that we will have a body for this function. We might not,
14768     // if it turns out to be trivial, and we don't need this marking now
14769     // that we've marked it as defaulted.
14770     MD->setWillHaveBody(false);
14771 
14772     // If this definition appears within the record, do the checking when
14773     // the record is complete.
14774     const FunctionDecl *Primary = MD;
14775     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14776       // Ask the template instantiation pattern that actually had the
14777       // '= default' on it.
14778       Primary = Pattern;
14779 
14780     // If the method was defaulted on its first declaration, we will have
14781     // already performed the checking in CheckCompletedCXXClass. Such a
14782     // declaration doesn't trigger an implicit definition.
14783     if (Primary->getCanonicalDecl()->isDefaulted())
14784       return;
14785 
14786     CheckExplicitlyDefaultedSpecialMember(MD);
14787 
14788     if (!MD->isInvalidDecl())
14789       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14790   } else {
14791     Diag(DefaultLoc, diag::err_default_special_members);
14792   }
14793 }
14794 
14795 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14796   for (Stmt *SubStmt : S->children()) {
14797     if (!SubStmt)
14798       continue;
14799     if (isa<ReturnStmt>(SubStmt))
14800       Self.Diag(SubStmt->getBeginLoc(),
14801                 diag::err_return_in_constructor_handler);
14802     if (!isa<Expr>(SubStmt))
14803       SearchForReturnInStmt(Self, SubStmt);
14804   }
14805 }
14806 
14807 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14808   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14809     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14810     SearchForReturnInStmt(*this, Handler);
14811   }
14812 }
14813 
14814 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14815                                              const CXXMethodDecl *Old) {
14816   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14817   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14818 
14819   if (OldFT->hasExtParameterInfos()) {
14820     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14821       // A parameter of the overriding method should be annotated with noescape
14822       // if the corresponding parameter of the overridden method is annotated.
14823       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14824           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14825         Diag(New->getParamDecl(I)->getLocation(),
14826              diag::warn_overriding_method_missing_noescape);
14827         Diag(Old->getParamDecl(I)->getLocation(),
14828              diag::note_overridden_marked_noescape);
14829       }
14830   }
14831 
14832   // Virtual overrides must have the same code_seg.
14833   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14834   const auto *NewCSA = New->getAttr<CodeSegAttr>();
14835   if ((NewCSA || OldCSA) &&
14836       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14837     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14838     Diag(Old->getLocation(), diag::note_previous_declaration);
14839     return true;
14840   }
14841 
14842   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14843 
14844   // If the calling conventions match, everything is fine
14845   if (NewCC == OldCC)
14846     return false;
14847 
14848   // If the calling conventions mismatch because the new function is static,
14849   // suppress the calling convention mismatch error; the error about static
14850   // function override (err_static_overrides_virtual from
14851   // Sema::CheckFunctionDeclaration) is more clear.
14852   if (New->getStorageClass() == SC_Static)
14853     return false;
14854 
14855   Diag(New->getLocation(),
14856        diag::err_conflicting_overriding_cc_attributes)
14857     << New->getDeclName() << New->getType() << Old->getType();
14858   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14859   return true;
14860 }
14861 
14862 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14863                                              const CXXMethodDecl *Old) {
14864   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14865   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14866 
14867   if (Context.hasSameType(NewTy, OldTy) ||
14868       NewTy->isDependentType() || OldTy->isDependentType())
14869     return false;
14870 
14871   // Check if the return types are covariant
14872   QualType NewClassTy, OldClassTy;
14873 
14874   /// Both types must be pointers or references to classes.
14875   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14876     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14877       NewClassTy = NewPT->getPointeeType();
14878       OldClassTy = OldPT->getPointeeType();
14879     }
14880   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14881     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14882       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14883         NewClassTy = NewRT->getPointeeType();
14884         OldClassTy = OldRT->getPointeeType();
14885       }
14886     }
14887   }
14888 
14889   // The return types aren't either both pointers or references to a class type.
14890   if (NewClassTy.isNull()) {
14891     Diag(New->getLocation(),
14892          diag::err_different_return_type_for_overriding_virtual_function)
14893         << New->getDeclName() << NewTy << OldTy
14894         << New->getReturnTypeSourceRange();
14895     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14896         << Old->getReturnTypeSourceRange();
14897 
14898     return true;
14899   }
14900 
14901   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14902     // C++14 [class.virtual]p8:
14903     //   If the class type in the covariant return type of D::f differs from
14904     //   that of B::f, the class type in the return type of D::f shall be
14905     //   complete at the point of declaration of D::f or shall be the class
14906     //   type D.
14907     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14908       if (!RT->isBeingDefined() &&
14909           RequireCompleteType(New->getLocation(), NewClassTy,
14910                               diag::err_covariant_return_incomplete,
14911                               New->getDeclName()))
14912         return true;
14913     }
14914 
14915     // Check if the new class derives from the old class.
14916     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14917       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14918           << New->getDeclName() << NewTy << OldTy
14919           << New->getReturnTypeSourceRange();
14920       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14921           << Old->getReturnTypeSourceRange();
14922       return true;
14923     }
14924 
14925     // Check if we the conversion from derived to base is valid.
14926     if (CheckDerivedToBaseConversion(
14927             NewClassTy, OldClassTy,
14928             diag::err_covariant_return_inaccessible_base,
14929             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14930             New->getLocation(), New->getReturnTypeSourceRange(),
14931             New->getDeclName(), nullptr)) {
14932       // FIXME: this note won't trigger for delayed access control
14933       // diagnostics, and it's impossible to get an undelayed error
14934       // here from access control during the original parse because
14935       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14936       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14937           << Old->getReturnTypeSourceRange();
14938       return true;
14939     }
14940   }
14941 
14942   // The qualifiers of the return types must be the same.
14943   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14944     Diag(New->getLocation(),
14945          diag::err_covariant_return_type_different_qualifications)
14946         << New->getDeclName() << NewTy << OldTy
14947         << New->getReturnTypeSourceRange();
14948     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14949         << Old->getReturnTypeSourceRange();
14950     return true;
14951   }
14952 
14953 
14954   // The new class type must have the same or less qualifiers as the old type.
14955   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14956     Diag(New->getLocation(),
14957          diag::err_covariant_return_type_class_type_more_qualified)
14958         << New->getDeclName() << NewTy << OldTy
14959         << New->getReturnTypeSourceRange();
14960     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14961         << Old->getReturnTypeSourceRange();
14962     return true;
14963   }
14964 
14965   return false;
14966 }
14967 
14968 /// Mark the given method pure.
14969 ///
14970 /// \param Method the method to be marked pure.
14971 ///
14972 /// \param InitRange the source range that covers the "0" initializer.
14973 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14974   SourceLocation EndLoc = InitRange.getEnd();
14975   if (EndLoc.isValid())
14976     Method->setRangeEnd(EndLoc);
14977 
14978   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14979     Method->setPure();
14980     return false;
14981   }
14982 
14983   if (!Method->isInvalidDecl())
14984     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14985       << Method->getDeclName() << InitRange;
14986   return true;
14987 }
14988 
14989 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14990   if (D->getFriendObjectKind())
14991     Diag(D->getLocation(), diag::err_pure_friend);
14992   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14993     CheckPureMethod(M, ZeroLoc);
14994   else
14995     Diag(D->getLocation(), diag::err_illegal_initializer);
14996 }
14997 
14998 /// Determine whether the given declaration is a global variable or
14999 /// static data member.
15000 static bool isNonlocalVariable(const Decl *D) {
15001   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
15002     return Var->hasGlobalStorage();
15003 
15004   return false;
15005 }
15006 
15007 /// Invoked when we are about to parse an initializer for the declaration
15008 /// 'Dcl'.
15009 ///
15010 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
15011 /// static data member of class X, names should be looked up in the scope of
15012 /// class X. If the declaration had a scope specifier, a scope will have
15013 /// been created and passed in for this purpose. Otherwise, S will be null.
15014 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
15015   // If there is no declaration, there was an error parsing it.
15016   if (!D || D->isInvalidDecl())
15017     return;
15018 
15019   // We will always have a nested name specifier here, but this declaration
15020   // might not be out of line if the specifier names the current namespace:
15021   //   extern int n;
15022   //   int ::n = 0;
15023   if (S && D->isOutOfLine())
15024     EnterDeclaratorContext(S, D->getDeclContext());
15025 
15026   // If we are parsing the initializer for a static data member, push a
15027   // new expression evaluation context that is associated with this static
15028   // data member.
15029   if (isNonlocalVariable(D))
15030     PushExpressionEvaluationContext(
15031         ExpressionEvaluationContext::PotentiallyEvaluated, D);
15032 }
15033 
15034 /// Invoked after we are finished parsing an initializer for the declaration D.
15035 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
15036   // If there is no declaration, there was an error parsing it.
15037   if (!D || D->isInvalidDecl())
15038     return;
15039 
15040   if (isNonlocalVariable(D))
15041     PopExpressionEvaluationContext();
15042 
15043   if (S && D->isOutOfLine())
15044     ExitDeclaratorContext(S);
15045 }
15046 
15047 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
15048 /// C++ if/switch/while/for statement.
15049 /// e.g: "if (int x = f()) {...}"
15050 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
15051   // C++ 6.4p2:
15052   // The declarator shall not specify a function or an array.
15053   // The type-specifier-seq shall not contain typedef and shall not declare a
15054   // new class or enumeration.
15055   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
15056          "Parser allowed 'typedef' as storage class of condition decl.");
15057 
15058   Decl *Dcl = ActOnDeclarator(S, D);
15059   if (!Dcl)
15060     return true;
15061 
15062   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
15063     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
15064       << D.getSourceRange();
15065     return true;
15066   }
15067 
15068   return Dcl;
15069 }
15070 
15071 void Sema::LoadExternalVTableUses() {
15072   if (!ExternalSource)
15073     return;
15074 
15075   SmallVector<ExternalVTableUse, 4> VTables;
15076   ExternalSource->ReadUsedVTables(VTables);
15077   SmallVector<VTableUse, 4> NewUses;
15078   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
15079     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
15080       = VTablesUsed.find(VTables[I].Record);
15081     // Even if a definition wasn't required before, it may be required now.
15082     if (Pos != VTablesUsed.end()) {
15083       if (!Pos->second && VTables[I].DefinitionRequired)
15084         Pos->second = true;
15085       continue;
15086     }
15087 
15088     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
15089     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
15090   }
15091 
15092   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
15093 }
15094 
15095 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
15096                           bool DefinitionRequired) {
15097   // Ignore any vtable uses in unevaluated operands or for classes that do
15098   // not have a vtable.
15099   if (!Class->isDynamicClass() || Class->isDependentContext() ||
15100       CurContext->isDependentContext() || isUnevaluatedContext())
15101     return;
15102   // Do not mark as used if compiling for the device outside of the target
15103   // region.
15104   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15105       !isInOpenMPDeclareTargetContext() &&
15106       !isInOpenMPTargetExecutionDirective()) {
15107     if (!DefinitionRequired)
15108       MarkVirtualMembersReferenced(Loc, Class);
15109     return;
15110   }
15111 
15112   // Try to insert this class into the map.
15113   LoadExternalVTableUses();
15114   Class = Class->getCanonicalDecl();
15115   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15116     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15117   if (!Pos.second) {
15118     // If we already had an entry, check to see if we are promoting this vtable
15119     // to require a definition. If so, we need to reappend to the VTableUses
15120     // list, since we may have already processed the first entry.
15121     if (DefinitionRequired && !Pos.first->second) {
15122       Pos.first->second = true;
15123     } else {
15124       // Otherwise, we can early exit.
15125       return;
15126     }
15127   } else {
15128     // The Microsoft ABI requires that we perform the destructor body
15129     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15130     // the deleting destructor is emitted with the vtable, not with the
15131     // destructor definition as in the Itanium ABI.
15132     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15133       CXXDestructorDecl *DD = Class->getDestructor();
15134       if (DD && DD->isVirtual() && !DD->isDeleted()) {
15135         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15136           // If this is an out-of-line declaration, marking it referenced will
15137           // not do anything. Manually call CheckDestructor to look up operator
15138           // delete().
15139           ContextRAII SavedContext(*this, DD);
15140           CheckDestructor(DD);
15141         } else {
15142           MarkFunctionReferenced(Loc, Class->getDestructor());
15143         }
15144       }
15145     }
15146   }
15147 
15148   // Local classes need to have their virtual members marked
15149   // immediately. For all other classes, we mark their virtual members
15150   // at the end of the translation unit.
15151   if (Class->isLocalClass())
15152     MarkVirtualMembersReferenced(Loc, Class);
15153   else
15154     VTableUses.push_back(std::make_pair(Class, Loc));
15155 }
15156 
15157 bool Sema::DefineUsedVTables() {
15158   LoadExternalVTableUses();
15159   if (VTableUses.empty())
15160     return false;
15161 
15162   // Note: The VTableUses vector could grow as a result of marking
15163   // the members of a class as "used", so we check the size each
15164   // time through the loop and prefer indices (which are stable) to
15165   // iterators (which are not).
15166   bool DefinedAnything = false;
15167   for (unsigned I = 0; I != VTableUses.size(); ++I) {
15168     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15169     if (!Class)
15170       continue;
15171     TemplateSpecializationKind ClassTSK =
15172         Class->getTemplateSpecializationKind();
15173 
15174     SourceLocation Loc = VTableUses[I].second;
15175 
15176     bool DefineVTable = true;
15177 
15178     // If this class has a key function, but that key function is
15179     // defined in another translation unit, we don't need to emit the
15180     // vtable even though we're using it.
15181     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15182     if (KeyFunction && !KeyFunction->hasBody()) {
15183       // The key function is in another translation unit.
15184       DefineVTable = false;
15185       TemplateSpecializationKind TSK =
15186           KeyFunction->getTemplateSpecializationKind();
15187       assert(TSK != TSK_ExplicitInstantiationDefinition &&
15188              TSK != TSK_ImplicitInstantiation &&
15189              "Instantiations don't have key functions");
15190       (void)TSK;
15191     } else if (!KeyFunction) {
15192       // If we have a class with no key function that is the subject
15193       // of an explicit instantiation declaration, suppress the
15194       // vtable; it will live with the explicit instantiation
15195       // definition.
15196       bool IsExplicitInstantiationDeclaration =
15197           ClassTSK == TSK_ExplicitInstantiationDeclaration;
15198       for (auto R : Class->redecls()) {
15199         TemplateSpecializationKind TSK
15200           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15201         if (TSK == TSK_ExplicitInstantiationDeclaration)
15202           IsExplicitInstantiationDeclaration = true;
15203         else if (TSK == TSK_ExplicitInstantiationDefinition) {
15204           IsExplicitInstantiationDeclaration = false;
15205           break;
15206         }
15207       }
15208 
15209       if (IsExplicitInstantiationDeclaration)
15210         DefineVTable = false;
15211     }
15212 
15213     // The exception specifications for all virtual members may be needed even
15214     // if we are not providing an authoritative form of the vtable in this TU.
15215     // We may choose to emit it available_externally anyway.
15216     if (!DefineVTable) {
15217       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15218       continue;
15219     }
15220 
15221     // Mark all of the virtual members of this class as referenced, so
15222     // that we can build a vtable. Then, tell the AST consumer that a
15223     // vtable for this class is required.
15224     DefinedAnything = true;
15225     MarkVirtualMembersReferenced(Loc, Class);
15226     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15227     if (VTablesUsed[Canonical])
15228       Consumer.HandleVTable(Class);
15229 
15230     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15231     // no key function or the key function is inlined. Don't warn in C++ ABIs
15232     // that lack key functions, since the user won't be able to make one.
15233     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15234         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15235       const FunctionDecl *KeyFunctionDef = nullptr;
15236       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15237                            KeyFunctionDef->isInlined())) {
15238         Diag(Class->getLocation(),
15239              ClassTSK == TSK_ExplicitInstantiationDefinition
15240                  ? diag::warn_weak_template_vtable
15241                  : diag::warn_weak_vtable)
15242             << Class;
15243       }
15244     }
15245   }
15246   VTableUses.clear();
15247 
15248   return DefinedAnything;
15249 }
15250 
15251 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15252                                                  const CXXRecordDecl *RD) {
15253   for (const auto *I : RD->methods())
15254     if (I->isVirtual() && !I->isPure())
15255       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15256 }
15257 
15258 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15259                                         const CXXRecordDecl *RD,
15260                                         bool ConstexprOnly) {
15261   // Mark all functions which will appear in RD's vtable as used.
15262   CXXFinalOverriderMap FinalOverriders;
15263   RD->getFinalOverriders(FinalOverriders);
15264   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15265                                             E = FinalOverriders.end();
15266        I != E; ++I) {
15267     for (OverridingMethods::const_iterator OI = I->second.begin(),
15268                                            OE = I->second.end();
15269          OI != OE; ++OI) {
15270       assert(OI->second.size() > 0 && "no final overrider");
15271       CXXMethodDecl *Overrider = OI->second.front().Method;
15272 
15273       // C++ [basic.def.odr]p2:
15274       //   [...] A virtual member function is used if it is not pure. [...]
15275       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
15276         MarkFunctionReferenced(Loc, Overrider);
15277     }
15278   }
15279 
15280   // Only classes that have virtual bases need a VTT.
15281   if (RD->getNumVBases() == 0)
15282     return;
15283 
15284   for (const auto &I : RD->bases()) {
15285     const CXXRecordDecl *Base =
15286         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15287     if (Base->getNumVBases() == 0)
15288       continue;
15289     MarkVirtualMembersReferenced(Loc, Base);
15290   }
15291 }
15292 
15293 /// SetIvarInitializers - This routine builds initialization ASTs for the
15294 /// Objective-C implementation whose ivars need be initialized.
15295 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15296   if (!getLangOpts().CPlusPlus)
15297     return;
15298   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15299     SmallVector<ObjCIvarDecl*, 8> ivars;
15300     CollectIvarsToConstructOrDestruct(OID, ivars);
15301     if (ivars.empty())
15302       return;
15303     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15304     for (unsigned i = 0; i < ivars.size(); i++) {
15305       FieldDecl *Field = ivars[i];
15306       if (Field->isInvalidDecl())
15307         continue;
15308 
15309       CXXCtorInitializer *Member;
15310       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15311       InitializationKind InitKind =
15312         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15313 
15314       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15315       ExprResult MemberInit =
15316         InitSeq.Perform(*this, InitEntity, InitKind, None);
15317       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15318       // Note, MemberInit could actually come back empty if no initialization
15319       // is required (e.g., because it would call a trivial default constructor)
15320       if (!MemberInit.get() || MemberInit.isInvalid())
15321         continue;
15322 
15323       Member =
15324         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15325                                          SourceLocation(),
15326                                          MemberInit.getAs<Expr>(),
15327                                          SourceLocation());
15328       AllToInit.push_back(Member);
15329 
15330       // Be sure that the destructor is accessible and is marked as referenced.
15331       if (const RecordType *RecordTy =
15332               Context.getBaseElementType(Field->getType())
15333                   ->getAs<RecordType>()) {
15334         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15335         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15336           MarkFunctionReferenced(Field->getLocation(), Destructor);
15337           CheckDestructorAccess(Field->getLocation(), Destructor,
15338                             PDiag(diag::err_access_dtor_ivar)
15339                               << Context.getBaseElementType(Field->getType()));
15340         }
15341       }
15342     }
15343     ObjCImplementation->setIvarInitializers(Context,
15344                                             AllToInit.data(), AllToInit.size());
15345   }
15346 }
15347 
15348 static
15349 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15350                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15351                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15352                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15353                            Sema &S) {
15354   if (Ctor->isInvalidDecl())
15355     return;
15356 
15357   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15358 
15359   // Target may not be determinable yet, for instance if this is a dependent
15360   // call in an uninstantiated template.
15361   if (Target) {
15362     const FunctionDecl *FNTarget = nullptr;
15363     (void)Target->hasBody(FNTarget);
15364     Target = const_cast<CXXConstructorDecl*>(
15365       cast_or_null<CXXConstructorDecl>(FNTarget));
15366   }
15367 
15368   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15369                      // Avoid dereferencing a null pointer here.
15370                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15371 
15372   if (!Current.insert(Canonical).second)
15373     return;
15374 
15375   // We know that beyond here, we aren't chaining into a cycle.
15376   if (!Target || !Target->isDelegatingConstructor() ||
15377       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15378     Valid.insert(Current.begin(), Current.end());
15379     Current.clear();
15380   // We've hit a cycle.
15381   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15382              Current.count(TCanonical)) {
15383     // If we haven't diagnosed this cycle yet, do so now.
15384     if (!Invalid.count(TCanonical)) {
15385       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15386              diag::warn_delegating_ctor_cycle)
15387         << Ctor;
15388 
15389       // Don't add a note for a function delegating directly to itself.
15390       if (TCanonical != Canonical)
15391         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15392 
15393       CXXConstructorDecl *C = Target;
15394       while (C->getCanonicalDecl() != Canonical) {
15395         const FunctionDecl *FNTarget = nullptr;
15396         (void)C->getTargetConstructor()->hasBody(FNTarget);
15397         assert(FNTarget && "Ctor cycle through bodiless function");
15398 
15399         C = const_cast<CXXConstructorDecl*>(
15400           cast<CXXConstructorDecl>(FNTarget));
15401         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15402       }
15403     }
15404 
15405     Invalid.insert(Current.begin(), Current.end());
15406     Current.clear();
15407   } else {
15408     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15409   }
15410 }
15411 
15412 
15413 void Sema::CheckDelegatingCtorCycles() {
15414   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15415 
15416   for (DelegatingCtorDeclsType::iterator
15417          I = DelegatingCtorDecls.begin(ExternalSource),
15418          E = DelegatingCtorDecls.end();
15419        I != E; ++I)
15420     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15421 
15422   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15423     (*CI)->setInvalidDecl();
15424 }
15425 
15426 namespace {
15427   /// AST visitor that finds references to the 'this' expression.
15428   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15429     Sema &S;
15430 
15431   public:
15432     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15433 
15434     bool VisitCXXThisExpr(CXXThisExpr *E) {
15435       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15436         << E->isImplicit();
15437       return false;
15438     }
15439   };
15440 }
15441 
15442 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15443   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15444   if (!TSInfo)
15445     return false;
15446 
15447   TypeLoc TL = TSInfo->getTypeLoc();
15448   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15449   if (!ProtoTL)
15450     return false;
15451 
15452   // C++11 [expr.prim.general]p3:
15453   //   [The expression this] shall not appear before the optional
15454   //   cv-qualifier-seq and it shall not appear within the declaration of a
15455   //   static member function (although its type and value category are defined
15456   //   within a static member function as they are within a non-static member
15457   //   function). [ Note: this is because declaration matching does not occur
15458   //  until the complete declarator is known. - end note ]
15459   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15460   FindCXXThisExpr Finder(*this);
15461 
15462   // If the return type came after the cv-qualifier-seq, check it now.
15463   if (Proto->hasTrailingReturn() &&
15464       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15465     return true;
15466 
15467   // Check the exception specification.
15468   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15469     return true;
15470 
15471   return checkThisInStaticMemberFunctionAttributes(Method);
15472 }
15473 
15474 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15475   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15476   if (!TSInfo)
15477     return false;
15478 
15479   TypeLoc TL = TSInfo->getTypeLoc();
15480   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15481   if (!ProtoTL)
15482     return false;
15483 
15484   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15485   FindCXXThisExpr Finder(*this);
15486 
15487   switch (Proto->getExceptionSpecType()) {
15488   case EST_Unparsed:
15489   case EST_Uninstantiated:
15490   case EST_Unevaluated:
15491   case EST_BasicNoexcept:
15492   case EST_NoThrow:
15493   case EST_DynamicNone:
15494   case EST_MSAny:
15495   case EST_None:
15496     break;
15497 
15498   case EST_DependentNoexcept:
15499   case EST_NoexceptFalse:
15500   case EST_NoexceptTrue:
15501     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15502       return true;
15503     LLVM_FALLTHROUGH;
15504 
15505   case EST_Dynamic:
15506     for (const auto &E : Proto->exceptions()) {
15507       if (!Finder.TraverseType(E))
15508         return true;
15509     }
15510     break;
15511   }
15512 
15513   return false;
15514 }
15515 
15516 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15517   FindCXXThisExpr Finder(*this);
15518 
15519   // Check attributes.
15520   for (const auto *A : Method->attrs()) {
15521     // FIXME: This should be emitted by tblgen.
15522     Expr *Arg = nullptr;
15523     ArrayRef<Expr *> Args;
15524     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15525       Arg = G->getArg();
15526     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15527       Arg = G->getArg();
15528     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15529       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15530     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15531       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15532     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15533       Arg = ETLF->getSuccessValue();
15534       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15535     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15536       Arg = STLF->getSuccessValue();
15537       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15538     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15539       Arg = LR->getArg();
15540     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15541       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15542     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15543       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15544     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15545       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15546     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15547       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15548     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15549       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15550 
15551     if (Arg && !Finder.TraverseStmt(Arg))
15552       return true;
15553 
15554     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15555       if (!Finder.TraverseStmt(Args[I]))
15556         return true;
15557     }
15558   }
15559 
15560   return false;
15561 }
15562 
15563 void Sema::checkExceptionSpecification(
15564     bool IsTopLevel, ExceptionSpecificationType EST,
15565     ArrayRef<ParsedType> DynamicExceptions,
15566     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15567     SmallVectorImpl<QualType> &Exceptions,
15568     FunctionProtoType::ExceptionSpecInfo &ESI) {
15569   Exceptions.clear();
15570   ESI.Type = EST;
15571   if (EST == EST_Dynamic) {
15572     Exceptions.reserve(DynamicExceptions.size());
15573     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15574       // FIXME: Preserve type source info.
15575       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15576 
15577       if (IsTopLevel) {
15578         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15579         collectUnexpandedParameterPacks(ET, Unexpanded);
15580         if (!Unexpanded.empty()) {
15581           DiagnoseUnexpandedParameterPacks(
15582               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15583               Unexpanded);
15584           continue;
15585         }
15586       }
15587 
15588       // Check that the type is valid for an exception spec, and
15589       // drop it if not.
15590       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15591         Exceptions.push_back(ET);
15592     }
15593     ESI.Exceptions = Exceptions;
15594     return;
15595   }
15596 
15597   if (isComputedNoexcept(EST)) {
15598     assert((NoexceptExpr->isTypeDependent() ||
15599             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15600             Context.BoolTy) &&
15601            "Parser should have made sure that the expression is boolean");
15602     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15603       ESI.Type = EST_BasicNoexcept;
15604       return;
15605     }
15606 
15607     ESI.NoexceptExpr = NoexceptExpr;
15608     return;
15609   }
15610 }
15611 
15612 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15613              ExceptionSpecificationType EST,
15614              SourceRange SpecificationRange,
15615              ArrayRef<ParsedType> DynamicExceptions,
15616              ArrayRef<SourceRange> DynamicExceptionRanges,
15617              Expr *NoexceptExpr) {
15618   if (!MethodD)
15619     return;
15620 
15621   // Dig out the method we're referring to.
15622   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15623     MethodD = FunTmpl->getTemplatedDecl();
15624 
15625   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15626   if (!Method)
15627     return;
15628 
15629   // Check the exception specification.
15630   llvm::SmallVector<QualType, 4> Exceptions;
15631   FunctionProtoType::ExceptionSpecInfo ESI;
15632   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15633                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15634                               ESI);
15635 
15636   // Update the exception specification on the function type.
15637   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15638 
15639   if (Method->isStatic())
15640     checkThisInStaticMemberFunctionExceptionSpec(Method);
15641 
15642   if (Method->isVirtual()) {
15643     // Check overrides, which we previously had to delay.
15644     for (const CXXMethodDecl *O : Method->overridden_methods())
15645       CheckOverridingFunctionExceptionSpec(Method, O);
15646   }
15647 }
15648 
15649 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15650 ///
15651 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15652                                        SourceLocation DeclStart, Declarator &D,
15653                                        Expr *BitWidth,
15654                                        InClassInitStyle InitStyle,
15655                                        AccessSpecifier AS,
15656                                        const ParsedAttr &MSPropertyAttr) {
15657   IdentifierInfo *II = D.getIdentifier();
15658   if (!II) {
15659     Diag(DeclStart, diag::err_anonymous_property);
15660     return nullptr;
15661   }
15662   SourceLocation Loc = D.getIdentifierLoc();
15663 
15664   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15665   QualType T = TInfo->getType();
15666   if (getLangOpts().CPlusPlus) {
15667     CheckExtraCXXDefaultArguments(D);
15668 
15669     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15670                                         UPPC_DataMemberType)) {
15671       D.setInvalidType();
15672       T = Context.IntTy;
15673       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15674     }
15675   }
15676 
15677   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15678 
15679   if (D.getDeclSpec().isInlineSpecified())
15680     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15681         << getLangOpts().CPlusPlus17;
15682   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15683     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15684          diag::err_invalid_thread)
15685       << DeclSpec::getSpecifierName(TSCS);
15686 
15687   // Check to see if this name was declared as a member previously
15688   NamedDecl *PrevDecl = nullptr;
15689   LookupResult Previous(*this, II, Loc, LookupMemberName,
15690                         ForVisibleRedeclaration);
15691   LookupName(Previous, S);
15692   switch (Previous.getResultKind()) {
15693   case LookupResult::Found:
15694   case LookupResult::FoundUnresolvedValue:
15695     PrevDecl = Previous.getAsSingle<NamedDecl>();
15696     break;
15697 
15698   case LookupResult::FoundOverloaded:
15699     PrevDecl = Previous.getRepresentativeDecl();
15700     break;
15701 
15702   case LookupResult::NotFound:
15703   case LookupResult::NotFoundInCurrentInstantiation:
15704   case LookupResult::Ambiguous:
15705     break;
15706   }
15707 
15708   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15709     // Maybe we will complain about the shadowed template parameter.
15710     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15711     // Just pretend that we didn't see the previous declaration.
15712     PrevDecl = nullptr;
15713   }
15714 
15715   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15716     PrevDecl = nullptr;
15717 
15718   SourceLocation TSSL = D.getBeginLoc();
15719   MSPropertyDecl *NewPD =
15720       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15721                              MSPropertyAttr.getPropertyDataGetter(),
15722                              MSPropertyAttr.getPropertyDataSetter());
15723   ProcessDeclAttributes(TUScope, NewPD, D);
15724   NewPD->setAccess(AS);
15725 
15726   if (NewPD->isInvalidDecl())
15727     Record->setInvalidDecl();
15728 
15729   if (D.getDeclSpec().isModulePrivateSpecified())
15730     NewPD->setModulePrivate();
15731 
15732   if (NewPD->isInvalidDecl() && PrevDecl) {
15733     // Don't introduce NewFD into scope; there's already something
15734     // with the same name in the same scope.
15735   } else if (II) {
15736     PushOnScopeChains(NewPD, S);
15737   } else
15738     Record->addDecl(NewPD);
15739 
15740   return NewPD;
15741 }
15742