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 or the lookup of 'value' is empty,
1034   // it's not tuple-like.
1035   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1036       R.empty())
1037     return IsTupleLike::NotTupleLike;
1038 
1039   // If we get this far, we've committed to the tuple interpretation, but
1040   // we can still fail if there actually isn't a usable ::value.
1041 
1042   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1043     LookupResult &R;
1044     TemplateArgumentListInfo &Args;
1045     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1046         : R(R), Args(Args) {}
1047     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1048       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1049           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1050     }
1051   } Diagnoser(R, Args);
1052 
1053   ExprResult E =
1054       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1055   if (E.isInvalid())
1056     return IsTupleLike::Error;
1057 
1058   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1059   if (E.isInvalid())
1060     return IsTupleLike::Error;
1061 
1062   return IsTupleLike::TupleLike;
1063 }
1064 
1065 /// \return std::tuple_element<I, T>::type.
1066 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1067                                         unsigned I, QualType T) {
1068   // Form template argument list for tuple_element<I, T>.
1069   TemplateArgumentListInfo Args(Loc, Loc);
1070   Args.addArgument(
1071       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1072   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1073 
1074   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1075   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1076   if (lookupStdTypeTraitMember(
1077           S, R, Loc, "tuple_element", Args,
1078           diag::err_decomp_decl_std_tuple_element_not_specialized))
1079     return QualType();
1080 
1081   auto *TD = R.getAsSingle<TypeDecl>();
1082   if (!TD) {
1083     R.suppressDiagnostics();
1084     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1085       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1086     if (!R.empty())
1087       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1088     return QualType();
1089   }
1090 
1091   return S.Context.getTypeDeclType(TD);
1092 }
1093 
1094 namespace {
1095 struct BindingDiagnosticTrap {
1096   Sema &S;
1097   DiagnosticErrorTrap Trap;
1098   BindingDecl *BD;
1099 
1100   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1101       : S(S), Trap(S.Diags), BD(BD) {}
1102   ~BindingDiagnosticTrap() {
1103     if (Trap.hasErrorOccurred())
1104       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1105   }
1106 };
1107 }
1108 
1109 static bool checkTupleLikeDecomposition(Sema &S,
1110                                         ArrayRef<BindingDecl *> Bindings,
1111                                         VarDecl *Src, QualType DecompType,
1112                                         const llvm::APSInt &TupleSize) {
1113   if ((int64_t)Bindings.size() != TupleSize) {
1114     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1115         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1116         << (TupleSize < Bindings.size());
1117     return true;
1118   }
1119 
1120   if (Bindings.empty())
1121     return false;
1122 
1123   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1124 
1125   // [dcl.decomp]p3:
1126   //   The unqualified-id get is looked up in the scope of E by class member
1127   //   access lookup ...
1128   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1129   bool UseMemberGet = false;
1130   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1131     if (auto *RD = DecompType->getAsCXXRecordDecl())
1132       S.LookupQualifiedName(MemberGet, RD);
1133     if (MemberGet.isAmbiguous())
1134       return true;
1135     //   ... and if that finds at least one declaration that is a function
1136     //   template whose first template parameter is a non-type parameter ...
1137     for (NamedDecl *D : MemberGet) {
1138       if (FunctionTemplateDecl *FTD =
1139               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1140         TemplateParameterList *TPL = FTD->getTemplateParameters();
1141         if (TPL->size() != 0 &&
1142             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1143           //   ... the initializer is e.get<i>().
1144           UseMemberGet = true;
1145           break;
1146         }
1147       }
1148     }
1149   }
1150 
1151   unsigned I = 0;
1152   for (auto *B : Bindings) {
1153     BindingDiagnosticTrap Trap(S, B);
1154     SourceLocation Loc = B->getLocation();
1155 
1156     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1157     if (E.isInvalid())
1158       return true;
1159 
1160     //   e is an lvalue if the type of the entity is an lvalue reference and
1161     //   an xvalue otherwise
1162     if (!Src->getType()->isLValueReferenceType())
1163       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1164                                    E.get(), nullptr, VK_XValue);
1165 
1166     TemplateArgumentListInfo Args(Loc, Loc);
1167     Args.addArgument(
1168         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1169 
1170     if (UseMemberGet) {
1171       //   if [lookup of member get] finds at least one declaration, the
1172       //   initializer is e.get<i-1>().
1173       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1174                                      CXXScopeSpec(), SourceLocation(), nullptr,
1175                                      MemberGet, &Args, nullptr);
1176       if (E.isInvalid())
1177         return true;
1178 
1179       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1180     } else {
1181       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1182       //   in the associated namespaces.
1183       Expr *Get = UnresolvedLookupExpr::Create(
1184           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1185           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1186           UnresolvedSetIterator(), UnresolvedSetIterator());
1187 
1188       Expr *Arg = E.get();
1189       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1190     }
1191     if (E.isInvalid())
1192       return true;
1193     Expr *Init = E.get();
1194 
1195     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1196     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1197     if (T.isNull())
1198       return true;
1199 
1200     //   each vi is a variable of type "reference to T" initialized with the
1201     //   initializer, where the reference is an lvalue reference if the
1202     //   initializer is an lvalue and an rvalue reference otherwise
1203     QualType RefType =
1204         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1205     if (RefType.isNull())
1206       return true;
1207     auto *RefVD = VarDecl::Create(
1208         S.Context, Src->getDeclContext(), Loc, Loc,
1209         B->getDeclName().getAsIdentifierInfo(), RefType,
1210         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1211     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1212     RefVD->setTSCSpec(Src->getTSCSpec());
1213     RefVD->setImplicit();
1214     if (Src->isInlineSpecified())
1215       RefVD->setInlineSpecified();
1216     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1217 
1218     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1219     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1220     InitializationSequence Seq(S, Entity, Kind, Init);
1221     E = Seq.Perform(S, Entity, Kind, Init);
1222     if (E.isInvalid())
1223       return true;
1224     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1225     if (E.isInvalid())
1226       return true;
1227     RefVD->setInit(E.get());
1228     if (!E.get()->isValueDependent())
1229       RefVD->checkInitIsICE();
1230 
1231     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1232                                    DeclarationNameInfo(B->getDeclName(), Loc),
1233                                    RefVD);
1234     if (E.isInvalid())
1235       return true;
1236 
1237     B->setBinding(T, E.get());
1238     I++;
1239   }
1240 
1241   return false;
1242 }
1243 
1244 /// Find the base class to decompose in a built-in decomposition of a class type.
1245 /// This base class search is, unfortunately, not quite like any other that we
1246 /// perform anywhere else in C++.
1247 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1248                                                 const CXXRecordDecl *RD,
1249                                                 CXXCastPath &BasePath) {
1250   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1251                           CXXBasePath &Path) {
1252     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1253   };
1254 
1255   const CXXRecordDecl *ClassWithFields = nullptr;
1256   AccessSpecifier AS = AS_public;
1257   if (RD->hasDirectFields())
1258     // [dcl.decomp]p4:
1259     //   Otherwise, all of E's non-static data members shall be public direct
1260     //   members of E ...
1261     ClassWithFields = RD;
1262   else {
1263     //   ... or of ...
1264     CXXBasePaths Paths;
1265     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1266     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1267       // If no classes have fields, just decompose RD itself. (This will work
1268       // if and only if zero bindings were provided.)
1269       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1270     }
1271 
1272     CXXBasePath *BestPath = nullptr;
1273     for (auto &P : Paths) {
1274       if (!BestPath)
1275         BestPath = &P;
1276       else if (!S.Context.hasSameType(P.back().Base->getType(),
1277                                       BestPath->back().Base->getType())) {
1278         //   ... the same ...
1279         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1280           << false << RD << BestPath->back().Base->getType()
1281           << P.back().Base->getType();
1282         return DeclAccessPair();
1283       } else if (P.Access < BestPath->Access) {
1284         BestPath = &P;
1285       }
1286     }
1287 
1288     //   ... unambiguous ...
1289     QualType BaseType = BestPath->back().Base->getType();
1290     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1291       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1292         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1293       return DeclAccessPair();
1294     }
1295 
1296     //   ... [accessible, implied by other rules] base class of E.
1297     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1298                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1299     AS = BestPath->Access;
1300 
1301     ClassWithFields = BaseType->getAsCXXRecordDecl();
1302     S.BuildBasePathArray(Paths, BasePath);
1303   }
1304 
1305   // The above search did not check whether the selected class itself has base
1306   // classes with fields, so check that now.
1307   CXXBasePaths Paths;
1308   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1309     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1310       << (ClassWithFields == RD) << RD << ClassWithFields
1311       << Paths.front().back().Base->getType();
1312     return DeclAccessPair();
1313   }
1314 
1315   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1316 }
1317 
1318 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1319                                      ValueDecl *Src, QualType DecompType,
1320                                      const CXXRecordDecl *OrigRD) {
1321   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1322                             diag::err_incomplete_type))
1323     return true;
1324 
1325   CXXCastPath BasePath;
1326   DeclAccessPair BasePair =
1327       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1328   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1329   if (!RD)
1330     return true;
1331   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1332                                                  DecompType.getQualifiers());
1333 
1334   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1335     unsigned NumFields =
1336         std::count_if(RD->field_begin(), RD->field_end(),
1337                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1338     assert(Bindings.size() != NumFields);
1339     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1340         << DecompType << (unsigned)Bindings.size() << NumFields
1341         << (NumFields < Bindings.size());
1342     return true;
1343   };
1344 
1345   //   all of E's non-static data members shall be [...] well-formed
1346   //   when named as e.name in the context of the structured binding,
1347   //   E shall not have an anonymous union member, ...
1348   unsigned I = 0;
1349   for (auto *FD : RD->fields()) {
1350     if (FD->isUnnamedBitfield())
1351       continue;
1352 
1353     if (FD->isAnonymousStructOrUnion()) {
1354       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1355         << DecompType << FD->getType()->isUnionType();
1356       S.Diag(FD->getLocation(), diag::note_declared_at);
1357       return true;
1358     }
1359 
1360     // We have a real field to bind.
1361     if (I >= Bindings.size())
1362       return DiagnoseBadNumberOfBindings();
1363     auto *B = Bindings[I++];
1364     SourceLocation Loc = B->getLocation();
1365 
1366     // The field must be accessible in the context of the structured binding.
1367     // We already checked that the base class is accessible.
1368     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1369     // const_cast here.
1370     S.CheckStructuredBindingMemberAccess(
1371         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1372         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1373                                      BasePair.getAccess(), FD->getAccess())));
1374 
1375     // Initialize the binding to Src.FD.
1376     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1377     if (E.isInvalid())
1378       return true;
1379     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1380                             VK_LValue, &BasePath);
1381     if (E.isInvalid())
1382       return true;
1383     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1384                                   CXXScopeSpec(), FD,
1385                                   DeclAccessPair::make(FD, FD->getAccess()),
1386                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1387     if (E.isInvalid())
1388       return true;
1389 
1390     // If the type of the member is T, the referenced type is cv T, where cv is
1391     // the cv-qualification of the decomposition expression.
1392     //
1393     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1394     // 'const' to the type of the field.
1395     Qualifiers Q = DecompType.getQualifiers();
1396     if (FD->isMutable())
1397       Q.removeConst();
1398     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1399   }
1400 
1401   if (I != Bindings.size())
1402     return DiagnoseBadNumberOfBindings();
1403 
1404   return false;
1405 }
1406 
1407 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1408   QualType DecompType = DD->getType();
1409 
1410   // If the type of the decomposition is dependent, then so is the type of
1411   // each binding.
1412   if (DecompType->isDependentType()) {
1413     for (auto *B : DD->bindings())
1414       B->setType(Context.DependentTy);
1415     return;
1416   }
1417 
1418   DecompType = DecompType.getNonReferenceType();
1419   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1420 
1421   // C++1z [dcl.decomp]/2:
1422   //   If E is an array type [...]
1423   // As an extension, we also support decomposition of built-in complex and
1424   // vector types.
1425   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1426     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1427       DD->setInvalidDecl();
1428     return;
1429   }
1430   if (auto *VT = DecompType->getAs<VectorType>()) {
1431     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1432       DD->setInvalidDecl();
1433     return;
1434   }
1435   if (auto *CT = DecompType->getAs<ComplexType>()) {
1436     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1437       DD->setInvalidDecl();
1438     return;
1439   }
1440 
1441   // C++1z [dcl.decomp]/3:
1442   //   if the expression std::tuple_size<E>::value is a well-formed integral
1443   //   constant expression, [...]
1444   llvm::APSInt TupleSize(32);
1445   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1446   case IsTupleLike::Error:
1447     DD->setInvalidDecl();
1448     return;
1449 
1450   case IsTupleLike::TupleLike:
1451     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1452       DD->setInvalidDecl();
1453     return;
1454 
1455   case IsTupleLike::NotTupleLike:
1456     break;
1457   }
1458 
1459   // C++1z [dcl.dcl]/8:
1460   //   [E shall be of array or non-union class type]
1461   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1462   if (!RD || RD->isUnion()) {
1463     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1464         << DD << !RD << DecompType;
1465     DD->setInvalidDecl();
1466     return;
1467   }
1468 
1469   // C++1z [dcl.decomp]/4:
1470   //   all of E's non-static data members shall be [...] direct members of
1471   //   E or of the same unambiguous public base class of E, ...
1472   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1473     DD->setInvalidDecl();
1474 }
1475 
1476 /// Merge the exception specifications of two variable declarations.
1477 ///
1478 /// This is called when there's a redeclaration of a VarDecl. The function
1479 /// checks if the redeclaration might have an exception specification and
1480 /// validates compatibility and merges the specs if necessary.
1481 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1482   // Shortcut if exceptions are disabled.
1483   if (!getLangOpts().CXXExceptions)
1484     return;
1485 
1486   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1487          "Should only be called if types are otherwise the same.");
1488 
1489   QualType NewType = New->getType();
1490   QualType OldType = Old->getType();
1491 
1492   // We're only interested in pointers and references to functions, as well
1493   // as pointers to member functions.
1494   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1495     NewType = R->getPointeeType();
1496     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1497   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1498     NewType = P->getPointeeType();
1499     OldType = OldType->getAs<PointerType>()->getPointeeType();
1500   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1501     NewType = M->getPointeeType();
1502     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1503   }
1504 
1505   if (!NewType->isFunctionProtoType())
1506     return;
1507 
1508   // There's lots of special cases for functions. For function pointers, system
1509   // libraries are hopefully not as broken so that we don't need these
1510   // workarounds.
1511   if (CheckEquivalentExceptionSpec(
1512         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1513         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1514     New->setInvalidDecl();
1515   }
1516 }
1517 
1518 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1519 /// function declaration are well-formed according to C++
1520 /// [dcl.fct.default].
1521 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1522   unsigned NumParams = FD->getNumParams();
1523   unsigned p;
1524 
1525   // Find first parameter with a default argument
1526   for (p = 0; p < NumParams; ++p) {
1527     ParmVarDecl *Param = FD->getParamDecl(p);
1528     if (Param->hasDefaultArg())
1529       break;
1530   }
1531 
1532   // C++11 [dcl.fct.default]p4:
1533   //   In a given function declaration, each parameter subsequent to a parameter
1534   //   with a default argument shall have a default argument supplied in this or
1535   //   a previous declaration or shall be a function parameter pack. A default
1536   //   argument shall not be redefined by a later declaration (not even to the
1537   //   same value).
1538   unsigned LastMissingDefaultArg = 0;
1539   for (; p < NumParams; ++p) {
1540     ParmVarDecl *Param = FD->getParamDecl(p);
1541     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1542       if (Param->isInvalidDecl())
1543         /* We already complained about this parameter. */;
1544       else if (Param->getIdentifier())
1545         Diag(Param->getLocation(),
1546              diag::err_param_default_argument_missing_name)
1547           << Param->getIdentifier();
1548       else
1549         Diag(Param->getLocation(),
1550              diag::err_param_default_argument_missing);
1551 
1552       LastMissingDefaultArg = p;
1553     }
1554   }
1555 
1556   if (LastMissingDefaultArg > 0) {
1557     // Some default arguments were missing. Clear out all of the
1558     // default arguments up to (and including) the last missing
1559     // default argument, so that we leave the function parameters
1560     // in a semantically valid state.
1561     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1562       ParmVarDecl *Param = FD->getParamDecl(p);
1563       if (Param->hasDefaultArg()) {
1564         Param->setDefaultArg(nullptr);
1565       }
1566     }
1567   }
1568 }
1569 
1570 /// Check that the given type is a literal type. Issue a diagnostic if not,
1571 /// if Kind is Diagnose.
1572 /// \return \c true if a problem has been found (and optionally diagnosed).
1573 template <typename... Ts>
1574 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1575                              SourceLocation Loc, QualType T, unsigned DiagID,
1576                              Ts &&...DiagArgs) {
1577   if (T->isDependentType())
1578     return false;
1579 
1580   switch (Kind) {
1581   case Sema::CheckConstexprKind::Diagnose:
1582     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1583                                       std::forward<Ts>(DiagArgs)...);
1584 
1585   case Sema::CheckConstexprKind::CheckValid:
1586     return !T->isLiteralType(SemaRef.Context);
1587   }
1588 
1589   llvm_unreachable("unknown CheckConstexprKind");
1590 }
1591 
1592 // CheckConstexprParameterTypes - Check whether a function's parameter types
1593 // are all literal types. If so, return true. If not, produce a suitable
1594 // diagnostic and return false.
1595 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1596                                          const FunctionDecl *FD,
1597                                          Sema::CheckConstexprKind Kind) {
1598   unsigned ArgIndex = 0;
1599   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1600   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1601                                               e = FT->param_type_end();
1602        i != e; ++i, ++ArgIndex) {
1603     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1604     SourceLocation ParamLoc = PD->getLocation();
1605     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1606                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1607                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1608                          FD->isConsteval()))
1609       return false;
1610   }
1611   return true;
1612 }
1613 
1614 /// Get diagnostic %select index for tag kind for
1615 /// record diagnostic message.
1616 /// WARNING: Indexes apply to particular diagnostics only!
1617 ///
1618 /// \returns diagnostic %select index.
1619 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1620   switch (Tag) {
1621   case TTK_Struct: return 0;
1622   case TTK_Interface: return 1;
1623   case TTK_Class:  return 2;
1624   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1625   }
1626 }
1627 
1628 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1629                                        Stmt *Body,
1630                                        Sema::CheckConstexprKind Kind);
1631 
1632 // Check whether a function declaration satisfies the requirements of a
1633 // constexpr function definition or a constexpr constructor definition. If so,
1634 // return true. If not, produce appropriate diagnostics (unless asked not to by
1635 // Kind) and return false.
1636 //
1637 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1638 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1639                                             CheckConstexprKind Kind) {
1640   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1641   if (MD && MD->isInstance()) {
1642     // C++11 [dcl.constexpr]p4:
1643     //  The definition of a constexpr constructor shall satisfy the following
1644     //  constraints:
1645     //  - the class shall not have any virtual base classes;
1646     //
1647     // FIXME: This only applies to constructors, not arbitrary member
1648     // functions.
1649     const CXXRecordDecl *RD = MD->getParent();
1650     if (RD->getNumVBases()) {
1651       if (Kind == CheckConstexprKind::CheckValid)
1652         return false;
1653 
1654       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1655         << isa<CXXConstructorDecl>(NewFD)
1656         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1657       for (const auto &I : RD->vbases())
1658         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1659             << I.getSourceRange();
1660       return false;
1661     }
1662   }
1663 
1664   if (!isa<CXXConstructorDecl>(NewFD)) {
1665     // C++11 [dcl.constexpr]p3:
1666     //  The definition of a constexpr function shall satisfy the following
1667     //  constraints:
1668     // - it shall not be virtual; (removed in C++20)
1669     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1670     if (Method && Method->isVirtual()) {
1671       if (getLangOpts().CPlusPlus2a) {
1672         if (Kind == CheckConstexprKind::Diagnose)
1673           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1674       } else {
1675         if (Kind == CheckConstexprKind::CheckValid)
1676           return false;
1677 
1678         Method = Method->getCanonicalDecl();
1679         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1680 
1681         // If it's not obvious why this function is virtual, find an overridden
1682         // function which uses the 'virtual' keyword.
1683         const CXXMethodDecl *WrittenVirtual = Method;
1684         while (!WrittenVirtual->isVirtualAsWritten())
1685           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1686         if (WrittenVirtual != Method)
1687           Diag(WrittenVirtual->getLocation(),
1688                diag::note_overridden_virtual_function);
1689         return false;
1690       }
1691     }
1692 
1693     // - its return type shall be a literal type;
1694     QualType RT = NewFD->getReturnType();
1695     if (CheckLiteralType(*this, Kind, NewFD->getLocation(), RT,
1696                          diag::err_constexpr_non_literal_return,
1697                          NewFD->isConsteval()))
1698       return false;
1699   }
1700 
1701   // - each of its parameter types shall be a literal type;
1702   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1703     return false;
1704 
1705   Stmt *Body = NewFD->getBody();
1706   assert(Body &&
1707          "CheckConstexprFunctionDefinition called on function with no body");
1708   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1709 }
1710 
1711 /// Check the given declaration statement is legal within a constexpr function
1712 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1713 ///
1714 /// \return true if the body is OK (maybe only as an extension), false if we
1715 ///         have diagnosed a problem.
1716 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1717                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1718                                    Sema::CheckConstexprKind Kind) {
1719   // C++11 [dcl.constexpr]p3 and p4:
1720   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1721   //  contain only
1722   for (const auto *DclIt : DS->decls()) {
1723     switch (DclIt->getKind()) {
1724     case Decl::StaticAssert:
1725     case Decl::Using:
1726     case Decl::UsingShadow:
1727     case Decl::UsingDirective:
1728     case Decl::UnresolvedUsingTypename:
1729     case Decl::UnresolvedUsingValue:
1730       //   - static_assert-declarations
1731       //   - using-declarations,
1732       //   - using-directives,
1733       continue;
1734 
1735     case Decl::Typedef:
1736     case Decl::TypeAlias: {
1737       //   - typedef declarations and alias-declarations that do not define
1738       //     classes or enumerations,
1739       const auto *TN = cast<TypedefNameDecl>(DclIt);
1740       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1741         // Don't allow variably-modified types in constexpr functions.
1742         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1743           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1744           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1745             << TL.getSourceRange() << TL.getType()
1746             << isa<CXXConstructorDecl>(Dcl);
1747         }
1748         return false;
1749       }
1750       continue;
1751     }
1752 
1753     case Decl::Enum:
1754     case Decl::CXXRecord:
1755       // C++1y allows types to be defined, not just declared.
1756       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1757         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1758           SemaRef.Diag(DS->getBeginLoc(),
1759                        SemaRef.getLangOpts().CPlusPlus14
1760                            ? diag::warn_cxx11_compat_constexpr_type_definition
1761                            : diag::ext_constexpr_type_definition)
1762               << isa<CXXConstructorDecl>(Dcl);
1763         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1764           return false;
1765         }
1766       }
1767       continue;
1768 
1769     case Decl::EnumConstant:
1770     case Decl::IndirectField:
1771     case Decl::ParmVar:
1772       // These can only appear with other declarations which are banned in
1773       // C++11 and permitted in C++1y, so ignore them.
1774       continue;
1775 
1776     case Decl::Var:
1777     case Decl::Decomposition: {
1778       // C++1y [dcl.constexpr]p3 allows anything except:
1779       //   a definition of a variable of non-literal type or of static or
1780       //   thread storage duration or for which no initialization is performed.
1781       const auto *VD = cast<VarDecl>(DclIt);
1782       if (VD->isThisDeclarationADefinition()) {
1783         if (VD->isStaticLocal()) {
1784           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1785             SemaRef.Diag(VD->getLocation(),
1786                          diag::err_constexpr_local_var_static)
1787               << isa<CXXConstructorDecl>(Dcl)
1788               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1789           }
1790           return false;
1791         }
1792         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1793                              diag::err_constexpr_local_var_non_literal_type,
1794                              isa<CXXConstructorDecl>(Dcl)))
1795           return false;
1796         if (!VD->getType()->isDependentType() &&
1797             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1798           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1799             SemaRef.Diag(VD->getLocation(),
1800                          diag::err_constexpr_local_var_no_init)
1801               << isa<CXXConstructorDecl>(Dcl);
1802           }
1803           return false;
1804         }
1805       }
1806       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1807         SemaRef.Diag(VD->getLocation(),
1808                      SemaRef.getLangOpts().CPlusPlus14
1809                       ? diag::warn_cxx11_compat_constexpr_local_var
1810                       : diag::ext_constexpr_local_var)
1811           << isa<CXXConstructorDecl>(Dcl);
1812       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1813         return false;
1814       }
1815       continue;
1816     }
1817 
1818     case Decl::NamespaceAlias:
1819     case Decl::Function:
1820       // These are disallowed in C++11 and permitted in C++1y. Allow them
1821       // everywhere as an extension.
1822       if (!Cxx1yLoc.isValid())
1823         Cxx1yLoc = DS->getBeginLoc();
1824       continue;
1825 
1826     default:
1827       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1828         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1829             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1830       }
1831       return false;
1832     }
1833   }
1834 
1835   return true;
1836 }
1837 
1838 /// Check that the given field is initialized within a constexpr constructor.
1839 ///
1840 /// \param Dcl The constexpr constructor being checked.
1841 /// \param Field The field being checked. This may be a member of an anonymous
1842 ///        struct or union nested within the class being checked.
1843 /// \param Inits All declarations, including anonymous struct/union members and
1844 ///        indirect members, for which any initialization was provided.
1845 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1846 ///        multiple notes for different members to the same error.
1847 /// \param Kind Whether we're diagnosing a constructor as written or determining
1848 ///        whether the formal requirements are satisfied.
1849 /// \return \c false if we're checking for validity and the constructor does
1850 ///         not satisfy the requirements on a constexpr constructor.
1851 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1852                                           const FunctionDecl *Dcl,
1853                                           FieldDecl *Field,
1854                                           llvm::SmallSet<Decl*, 16> &Inits,
1855                                           bool &Diagnosed,
1856                                           Sema::CheckConstexprKind Kind) {
1857   if (Field->isInvalidDecl())
1858     return true;
1859 
1860   if (Field->isUnnamedBitfield())
1861     return true;
1862 
1863   // Anonymous unions with no variant members and empty anonymous structs do not
1864   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1865   // indirect fields don't need initializing.
1866   if (Field->isAnonymousStructOrUnion() &&
1867       (Field->getType()->isUnionType()
1868            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1869            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1870     return true;
1871 
1872   if (!Inits.count(Field)) {
1873     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1874       if (!Diagnosed) {
1875         SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1876         Diagnosed = true;
1877       }
1878       SemaRef.Diag(Field->getLocation(),
1879                    diag::note_constexpr_ctor_missing_init);
1880     } else {
1881       return false;
1882     }
1883   } else if (Field->isAnonymousStructOrUnion()) {
1884     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1885     for (auto *I : RD->fields())
1886       // If an anonymous union contains an anonymous struct of which any member
1887       // is initialized, all members must be initialized.
1888       if (!RD->isUnion() || Inits.count(I))
1889         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1890                                            Kind))
1891           return false;
1892   }
1893   return true;
1894 }
1895 
1896 /// Check the provided statement is allowed in a constexpr function
1897 /// definition.
1898 static bool
1899 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1900                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1901                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
1902                            Sema::CheckConstexprKind Kind) {
1903   // - its function-body shall be [...] a compound-statement that contains only
1904   switch (S->getStmtClass()) {
1905   case Stmt::NullStmtClass:
1906     //   - null statements,
1907     return true;
1908 
1909   case Stmt::DeclStmtClass:
1910     //   - static_assert-declarations
1911     //   - using-declarations,
1912     //   - using-directives,
1913     //   - typedef declarations and alias-declarations that do not define
1914     //     classes or enumerations,
1915     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
1916       return false;
1917     return true;
1918 
1919   case Stmt::ReturnStmtClass:
1920     //   - and exactly one return statement;
1921     if (isa<CXXConstructorDecl>(Dcl)) {
1922       // C++1y allows return statements in constexpr constructors.
1923       if (!Cxx1yLoc.isValid())
1924         Cxx1yLoc = S->getBeginLoc();
1925       return true;
1926     }
1927 
1928     ReturnStmts.push_back(S->getBeginLoc());
1929     return true;
1930 
1931   case Stmt::CompoundStmtClass: {
1932     // C++1y allows compound-statements.
1933     if (!Cxx1yLoc.isValid())
1934       Cxx1yLoc = S->getBeginLoc();
1935 
1936     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1937     for (auto *BodyIt : CompStmt->body()) {
1938       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1939                                       Cxx1yLoc, Cxx2aLoc, Kind))
1940         return false;
1941     }
1942     return true;
1943   }
1944 
1945   case Stmt::AttributedStmtClass:
1946     if (!Cxx1yLoc.isValid())
1947       Cxx1yLoc = S->getBeginLoc();
1948     return true;
1949 
1950   case Stmt::IfStmtClass: {
1951     // C++1y allows if-statements.
1952     if (!Cxx1yLoc.isValid())
1953       Cxx1yLoc = S->getBeginLoc();
1954 
1955     IfStmt *If = cast<IfStmt>(S);
1956     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1957                                     Cxx1yLoc, Cxx2aLoc, Kind))
1958       return false;
1959     if (If->getElse() &&
1960         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1961                                     Cxx1yLoc, Cxx2aLoc, Kind))
1962       return false;
1963     return true;
1964   }
1965 
1966   case Stmt::WhileStmtClass:
1967   case Stmt::DoStmtClass:
1968   case Stmt::ForStmtClass:
1969   case Stmt::CXXForRangeStmtClass:
1970   case Stmt::ContinueStmtClass:
1971     // C++1y allows all of these. We don't allow them as extensions in C++11,
1972     // because they don't make sense without variable mutation.
1973     if (!SemaRef.getLangOpts().CPlusPlus14)
1974       break;
1975     if (!Cxx1yLoc.isValid())
1976       Cxx1yLoc = S->getBeginLoc();
1977     for (Stmt *SubStmt : S->children())
1978       if (SubStmt &&
1979           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1980                                       Cxx1yLoc, Cxx2aLoc, Kind))
1981         return false;
1982     return true;
1983 
1984   case Stmt::SwitchStmtClass:
1985   case Stmt::CaseStmtClass:
1986   case Stmt::DefaultStmtClass:
1987   case Stmt::BreakStmtClass:
1988     // C++1y allows switch-statements, and since they don't need variable
1989     // mutation, we can reasonably allow them in C++11 as an extension.
1990     if (!Cxx1yLoc.isValid())
1991       Cxx1yLoc = S->getBeginLoc();
1992     for (Stmt *SubStmt : S->children())
1993       if (SubStmt &&
1994           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1995                                       Cxx1yLoc, Cxx2aLoc, Kind))
1996         return false;
1997     return true;
1998 
1999   case Stmt::GCCAsmStmtClass:
2000   case Stmt::MSAsmStmtClass:
2001     // C++2a allows inline assembly statements.
2002   case Stmt::CXXTryStmtClass:
2003     if (Cxx2aLoc.isInvalid())
2004       Cxx2aLoc = S->getBeginLoc();
2005     for (Stmt *SubStmt : S->children()) {
2006       if (SubStmt &&
2007           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2008                                       Cxx1yLoc, Cxx2aLoc, Kind))
2009         return false;
2010     }
2011     return true;
2012 
2013   case Stmt::CXXCatchStmtClass:
2014     // Do not bother checking the language mode (already covered by the
2015     // try block check).
2016     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2017                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2018                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2019       return false;
2020     return true;
2021 
2022   default:
2023     if (!isa<Expr>(S))
2024       break;
2025 
2026     // C++1y allows expression-statements.
2027     if (!Cxx1yLoc.isValid())
2028       Cxx1yLoc = S->getBeginLoc();
2029     return true;
2030   }
2031 
2032   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2033     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2034         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2035   }
2036   return false;
2037 }
2038 
2039 /// Check the body for the given constexpr function declaration only contains
2040 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2041 ///
2042 /// \return true if the body is OK, false if we have found or diagnosed a
2043 /// problem.
2044 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2045                                        Stmt *Body,
2046                                        Sema::CheckConstexprKind Kind) {
2047   SmallVector<SourceLocation, 4> ReturnStmts;
2048 
2049   if (isa<CXXTryStmt>(Body)) {
2050     // C++11 [dcl.constexpr]p3:
2051     //  The definition of a constexpr function shall satisfy the following
2052     //  constraints: [...]
2053     // - its function-body shall be = delete, = default, or a
2054     //   compound-statement
2055     //
2056     // C++11 [dcl.constexpr]p4:
2057     //  In the definition of a constexpr constructor, [...]
2058     // - its function-body shall not be a function-try-block;
2059     //
2060     // This restriction is lifted in C++2a, as long as inner statements also
2061     // apply the general constexpr rules.
2062     switch (Kind) {
2063     case Sema::CheckConstexprKind::CheckValid:
2064       if (!SemaRef.getLangOpts().CPlusPlus2a)
2065         return false;
2066       break;
2067 
2068     case Sema::CheckConstexprKind::Diagnose:
2069       SemaRef.Diag(Body->getBeginLoc(),
2070            !SemaRef.getLangOpts().CPlusPlus2a
2071                ? diag::ext_constexpr_function_try_block_cxx2a
2072                : diag::warn_cxx17_compat_constexpr_function_try_block)
2073           << isa<CXXConstructorDecl>(Dcl);
2074       break;
2075     }
2076   }
2077 
2078   // - its function-body shall be [...] a compound-statement that contains only
2079   //   [... list of cases ...]
2080   //
2081   // Note that walking the children here is enough to properly check for
2082   // CompoundStmt and CXXTryStmt body.
2083   SourceLocation Cxx1yLoc, Cxx2aLoc;
2084   for (Stmt *SubStmt : Body->children()) {
2085     if (SubStmt &&
2086         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2087                                     Cxx1yLoc, Cxx2aLoc, Kind))
2088       return false;
2089   }
2090 
2091   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2092     // If this is only valid as an extension, report that we don't satisfy the
2093     // constraints of the current language.
2094     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) ||
2095         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2096       return false;
2097   } else if (Cxx2aLoc.isValid()) {
2098     SemaRef.Diag(Cxx2aLoc,
2099          SemaRef.getLangOpts().CPlusPlus2a
2100            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2101            : diag::ext_constexpr_body_invalid_stmt_cxx2a)
2102       << isa<CXXConstructorDecl>(Dcl);
2103   } else if (Cxx1yLoc.isValid()) {
2104     SemaRef.Diag(Cxx1yLoc,
2105          SemaRef.getLangOpts().CPlusPlus14
2106            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2107            : diag::ext_constexpr_body_invalid_stmt)
2108       << isa<CXXConstructorDecl>(Dcl);
2109   }
2110 
2111   if (const CXXConstructorDecl *Constructor
2112         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2113     const CXXRecordDecl *RD = Constructor->getParent();
2114     // DR1359:
2115     // - every non-variant non-static data member and base class sub-object
2116     //   shall be initialized;
2117     // DR1460:
2118     // - if the class is a union having variant members, exactly one of them
2119     //   shall be initialized;
2120     if (RD->isUnion()) {
2121       if (Constructor->getNumCtorInitializers() == 0 &&
2122           RD->hasVariantMembers()) {
2123         if (Kind == Sema::CheckConstexprKind::Diagnose)
2124           SemaRef.Diag(Dcl->getLocation(),
2125                        diag::err_constexpr_union_ctor_no_init);
2126         return false;
2127       }
2128     } else if (!Constructor->isDependentContext() &&
2129                !Constructor->isDelegatingConstructor()) {
2130       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2131 
2132       // Skip detailed checking if we have enough initializers, and we would
2133       // allow at most one initializer per member.
2134       bool AnyAnonStructUnionMembers = false;
2135       unsigned Fields = 0;
2136       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2137            E = RD->field_end(); I != E; ++I, ++Fields) {
2138         if (I->isAnonymousStructOrUnion()) {
2139           AnyAnonStructUnionMembers = true;
2140           break;
2141         }
2142       }
2143       // DR1460:
2144       // - if the class is a union-like class, but is not a union, for each of
2145       //   its anonymous union members having variant members, exactly one of
2146       //   them shall be initialized;
2147       if (AnyAnonStructUnionMembers ||
2148           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2149         // Check initialization of non-static data members. Base classes are
2150         // always initialized so do not need to be checked. Dependent bases
2151         // might not have initializers in the member initializer list.
2152         llvm::SmallSet<Decl*, 16> Inits;
2153         for (const auto *I: Constructor->inits()) {
2154           if (FieldDecl *FD = I->getMember())
2155             Inits.insert(FD);
2156           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2157             Inits.insert(ID->chain_begin(), ID->chain_end());
2158         }
2159 
2160         bool Diagnosed = false;
2161         for (auto *I : RD->fields())
2162           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2163                                              Kind))
2164             return false;
2165       }
2166     }
2167   } else {
2168     if (ReturnStmts.empty()) {
2169       // C++1y doesn't require constexpr functions to contain a 'return'
2170       // statement. We still do, unless the return type might be void, because
2171       // otherwise if there's no return statement, the function cannot
2172       // be used in a core constant expression.
2173       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2174                 (Dcl->getReturnType()->isVoidType() ||
2175                  Dcl->getReturnType()->isDependentType());
2176       switch (Kind) {
2177       case Sema::CheckConstexprKind::Diagnose:
2178         SemaRef.Diag(Dcl->getLocation(),
2179                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2180                         : diag::err_constexpr_body_no_return)
2181             << Dcl->isConsteval();
2182         if (!OK)
2183           return false;
2184         break;
2185 
2186       case Sema::CheckConstexprKind::CheckValid:
2187         // The formal requirements don't include this rule in C++14, even
2188         // though the "must be able to produce a constant expression" rules
2189         // still imply it in some cases.
2190         if (!SemaRef.getLangOpts().CPlusPlus14)
2191           return false;
2192         break;
2193       }
2194     } else if (ReturnStmts.size() > 1) {
2195       switch (Kind) {
2196       case Sema::CheckConstexprKind::Diagnose:
2197         SemaRef.Diag(
2198             ReturnStmts.back(),
2199             SemaRef.getLangOpts().CPlusPlus14
2200                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2201                 : diag::ext_constexpr_body_multiple_return);
2202         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2203           SemaRef.Diag(ReturnStmts[I],
2204                        diag::note_constexpr_body_previous_return);
2205         break;
2206 
2207       case Sema::CheckConstexprKind::CheckValid:
2208         if (!SemaRef.getLangOpts().CPlusPlus14)
2209           return false;
2210         break;
2211       }
2212     }
2213   }
2214 
2215   // C++11 [dcl.constexpr]p5:
2216   //   if no function argument values exist such that the function invocation
2217   //   substitution would produce a constant expression, the program is
2218   //   ill-formed; no diagnostic required.
2219   // C++11 [dcl.constexpr]p3:
2220   //   - every constructor call and implicit conversion used in initializing the
2221   //     return value shall be one of those allowed in a constant expression.
2222   // C++11 [dcl.constexpr]p4:
2223   //   - every constructor involved in initializing non-static data members and
2224   //     base class sub-objects shall be a constexpr constructor.
2225   //
2226   // Note that this rule is distinct from the "requirements for a constexpr
2227   // function", so is not checked in CheckValid mode.
2228   SmallVector<PartialDiagnosticAt, 8> Diags;
2229   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2230       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2231     SemaRef.Diag(Dcl->getLocation(),
2232                  diag::ext_constexpr_function_never_constant_expr)
2233         << isa<CXXConstructorDecl>(Dcl);
2234     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2235       SemaRef.Diag(Diags[I].first, Diags[I].second);
2236     // Don't return false here: we allow this for compatibility in
2237     // system headers.
2238   }
2239 
2240   return true;
2241 }
2242 
2243 /// Get the class that is directly named by the current context. This is the
2244 /// class for which an unqualified-id in this scope could name a constructor
2245 /// or destructor.
2246 ///
2247 /// If the scope specifier denotes a class, this will be that class.
2248 /// If the scope specifier is empty, this will be the class whose
2249 /// member-specification we are currently within. Otherwise, there
2250 /// is no such class.
2251 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2252   assert(getLangOpts().CPlusPlus && "No class names in C!");
2253 
2254   if (SS && SS->isInvalid())
2255     return nullptr;
2256 
2257   if (SS && SS->isNotEmpty()) {
2258     DeclContext *DC = computeDeclContext(*SS, true);
2259     return dyn_cast_or_null<CXXRecordDecl>(DC);
2260   }
2261 
2262   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2263 }
2264 
2265 /// isCurrentClassName - Determine whether the identifier II is the
2266 /// name of the class type currently being defined. In the case of
2267 /// nested classes, this will only return true if II is the name of
2268 /// the innermost class.
2269 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2270                               const CXXScopeSpec *SS) {
2271   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2272   return CurDecl && &II == CurDecl->getIdentifier();
2273 }
2274 
2275 /// Determine whether the identifier II is a typo for the name of
2276 /// the class type currently being defined. If so, update it to the identifier
2277 /// that should have been used.
2278 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2279   assert(getLangOpts().CPlusPlus && "No class names in C!");
2280 
2281   if (!getLangOpts().SpellChecking)
2282     return false;
2283 
2284   CXXRecordDecl *CurDecl;
2285   if (SS && SS->isSet() && !SS->isInvalid()) {
2286     DeclContext *DC = computeDeclContext(*SS, true);
2287     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2288   } else
2289     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2290 
2291   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2292       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2293           < II->getLength()) {
2294     II = CurDecl->getIdentifier();
2295     return true;
2296   }
2297 
2298   return false;
2299 }
2300 
2301 /// Determine whether the given class is a base class of the given
2302 /// class, including looking at dependent bases.
2303 static bool findCircularInheritance(const CXXRecordDecl *Class,
2304                                     const CXXRecordDecl *Current) {
2305   SmallVector<const CXXRecordDecl*, 8> Queue;
2306 
2307   Class = Class->getCanonicalDecl();
2308   while (true) {
2309     for (const auto &I : Current->bases()) {
2310       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2311       if (!Base)
2312         continue;
2313 
2314       Base = Base->getDefinition();
2315       if (!Base)
2316         continue;
2317 
2318       if (Base->getCanonicalDecl() == Class)
2319         return true;
2320 
2321       Queue.push_back(Base);
2322     }
2323 
2324     if (Queue.empty())
2325       return false;
2326 
2327     Current = Queue.pop_back_val();
2328   }
2329 
2330   return false;
2331 }
2332 
2333 /// Check the validity of a C++ base class specifier.
2334 ///
2335 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2336 /// and returns NULL otherwise.
2337 CXXBaseSpecifier *
2338 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2339                          SourceRange SpecifierRange,
2340                          bool Virtual, AccessSpecifier Access,
2341                          TypeSourceInfo *TInfo,
2342                          SourceLocation EllipsisLoc) {
2343   QualType BaseType = TInfo->getType();
2344 
2345   // C++ [class.union]p1:
2346   //   A union shall not have base classes.
2347   if (Class->isUnion()) {
2348     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2349       << SpecifierRange;
2350     return nullptr;
2351   }
2352 
2353   if (EllipsisLoc.isValid() &&
2354       !TInfo->getType()->containsUnexpandedParameterPack()) {
2355     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2356       << TInfo->getTypeLoc().getSourceRange();
2357     EllipsisLoc = SourceLocation();
2358   }
2359 
2360   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2361 
2362   if (BaseType->isDependentType()) {
2363     // Make sure that we don't have circular inheritance among our dependent
2364     // bases. For non-dependent bases, the check for completeness below handles
2365     // this.
2366     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2367       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2368           ((BaseDecl = BaseDecl->getDefinition()) &&
2369            findCircularInheritance(Class, BaseDecl))) {
2370         Diag(BaseLoc, diag::err_circular_inheritance)
2371           << BaseType << Context.getTypeDeclType(Class);
2372 
2373         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2374           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2375             << BaseType;
2376 
2377         return nullptr;
2378       }
2379     }
2380 
2381     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2382                                           Class->getTagKind() == TTK_Class,
2383                                           Access, TInfo, EllipsisLoc);
2384   }
2385 
2386   // Base specifiers must be record types.
2387   if (!BaseType->isRecordType()) {
2388     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2389     return nullptr;
2390   }
2391 
2392   // C++ [class.union]p1:
2393   //   A union shall not be used as a base class.
2394   if (BaseType->isUnionType()) {
2395     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2396     return nullptr;
2397   }
2398 
2399   // For the MS ABI, propagate DLL attributes to base class templates.
2400   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2401     if (Attr *ClassAttr = getDLLAttr(Class)) {
2402       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2403               BaseType->getAsCXXRecordDecl())) {
2404         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2405                                             BaseLoc);
2406       }
2407     }
2408   }
2409 
2410   // C++ [class.derived]p2:
2411   //   The class-name in a base-specifier shall not be an incompletely
2412   //   defined class.
2413   if (RequireCompleteType(BaseLoc, BaseType,
2414                           diag::err_incomplete_base_class, SpecifierRange)) {
2415     Class->setInvalidDecl();
2416     return nullptr;
2417   }
2418 
2419   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2420   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2421   assert(BaseDecl && "Record type has no declaration");
2422   BaseDecl = BaseDecl->getDefinition();
2423   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2424   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2425   assert(CXXBaseDecl && "Base type is not a C++ type");
2426 
2427   // Microsoft docs say:
2428   // "If a base-class has a code_seg attribute, derived classes must have the
2429   // same attribute."
2430   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2431   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2432   if ((DerivedCSA || BaseCSA) &&
2433       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2434     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2435     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2436       << CXXBaseDecl;
2437     return nullptr;
2438   }
2439 
2440   // A class which contains a flexible array member is not suitable for use as a
2441   // base class:
2442   //   - If the layout determines that a base comes before another base,
2443   //     the flexible array member would index into the subsequent base.
2444   //   - If the layout determines that base comes before the derived class,
2445   //     the flexible array member would index into the derived class.
2446   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2447     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2448       << CXXBaseDecl->getDeclName();
2449     return nullptr;
2450   }
2451 
2452   // C++ [class]p3:
2453   //   If a class is marked final and it appears as a base-type-specifier in
2454   //   base-clause, the program is ill-formed.
2455   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2456     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2457       << CXXBaseDecl->getDeclName()
2458       << FA->isSpelledAsSealed();
2459     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2460         << CXXBaseDecl->getDeclName() << FA->getRange();
2461     return nullptr;
2462   }
2463 
2464   if (BaseDecl->isInvalidDecl())
2465     Class->setInvalidDecl();
2466 
2467   // Create the base specifier.
2468   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2469                                         Class->getTagKind() == TTK_Class,
2470                                         Access, TInfo, EllipsisLoc);
2471 }
2472 
2473 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2474 /// one entry in the base class list of a class specifier, for
2475 /// example:
2476 ///    class foo : public bar, virtual private baz {
2477 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2478 BaseResult
2479 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2480                          ParsedAttributes &Attributes,
2481                          bool Virtual, AccessSpecifier Access,
2482                          ParsedType basetype, SourceLocation BaseLoc,
2483                          SourceLocation EllipsisLoc) {
2484   if (!classdecl)
2485     return true;
2486 
2487   AdjustDeclIfTemplate(classdecl);
2488   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2489   if (!Class)
2490     return true;
2491 
2492   // We haven't yet attached the base specifiers.
2493   Class->setIsParsingBaseSpecifiers();
2494 
2495   // We do not support any C++11 attributes on base-specifiers yet.
2496   // Diagnose any attributes we see.
2497   for (const ParsedAttr &AL : Attributes) {
2498     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2499       continue;
2500     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2501                           ? (unsigned)diag::warn_unknown_attribute_ignored
2502                           : (unsigned)diag::err_base_specifier_attribute)
2503         << AL.getName();
2504   }
2505 
2506   TypeSourceInfo *TInfo = nullptr;
2507   GetTypeFromParser(basetype, &TInfo);
2508 
2509   if (EllipsisLoc.isInvalid() &&
2510       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2511                                       UPPC_BaseType))
2512     return true;
2513 
2514   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2515                                                       Virtual, Access, TInfo,
2516                                                       EllipsisLoc))
2517     return BaseSpec;
2518   else
2519     Class->setInvalidDecl();
2520 
2521   return true;
2522 }
2523 
2524 /// Use small set to collect indirect bases.  As this is only used
2525 /// locally, there's no need to abstract the small size parameter.
2526 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2527 
2528 /// Recursively add the bases of Type.  Don't add Type itself.
2529 static void
2530 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2531                   const QualType &Type)
2532 {
2533   // Even though the incoming type is a base, it might not be
2534   // a class -- it could be a template parm, for instance.
2535   if (auto Rec = Type->getAs<RecordType>()) {
2536     auto Decl = Rec->getAsCXXRecordDecl();
2537 
2538     // Iterate over its bases.
2539     for (const auto &BaseSpec : Decl->bases()) {
2540       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2541         .getUnqualifiedType();
2542       if (Set.insert(Base).second)
2543         // If we've not already seen it, recurse.
2544         NoteIndirectBases(Context, Set, Base);
2545     }
2546   }
2547 }
2548 
2549 /// Performs the actual work of attaching the given base class
2550 /// specifiers to a C++ class.
2551 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2552                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2553  if (Bases.empty())
2554     return false;
2555 
2556   // Used to keep track of which base types we have already seen, so
2557   // that we can properly diagnose redundant direct base types. Note
2558   // that the key is always the unqualified canonical type of the base
2559   // class.
2560   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2561 
2562   // Used to track indirect bases so we can see if a direct base is
2563   // ambiguous.
2564   IndirectBaseSet IndirectBaseTypes;
2565 
2566   // Copy non-redundant base specifiers into permanent storage.
2567   unsigned NumGoodBases = 0;
2568   bool Invalid = false;
2569   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2570     QualType NewBaseType
2571       = Context.getCanonicalType(Bases[idx]->getType());
2572     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2573 
2574     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2575     if (KnownBase) {
2576       // C++ [class.mi]p3:
2577       //   A class shall not be specified as a direct base class of a
2578       //   derived class more than once.
2579       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2580           << KnownBase->getType() << Bases[idx]->getSourceRange();
2581 
2582       // Delete the duplicate base class specifier; we're going to
2583       // overwrite its pointer later.
2584       Context.Deallocate(Bases[idx]);
2585 
2586       Invalid = true;
2587     } else {
2588       // Okay, add this new base class.
2589       KnownBase = Bases[idx];
2590       Bases[NumGoodBases++] = Bases[idx];
2591 
2592       // Note this base's direct & indirect bases, if there could be ambiguity.
2593       if (Bases.size() > 1)
2594         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2595 
2596       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2597         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2598         if (Class->isInterface() &&
2599               (!RD->isInterfaceLike() ||
2600                KnownBase->getAccessSpecifier() != AS_public)) {
2601           // The Microsoft extension __interface does not permit bases that
2602           // are not themselves public interfaces.
2603           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2604               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2605               << RD->getSourceRange();
2606           Invalid = true;
2607         }
2608         if (RD->hasAttr<WeakAttr>())
2609           Class->addAttr(WeakAttr::CreateImplicit(Context));
2610       }
2611     }
2612   }
2613 
2614   // Attach the remaining base class specifiers to the derived class.
2615   Class->setBases(Bases.data(), NumGoodBases);
2616 
2617   // Check that the only base classes that are duplicate are virtual.
2618   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2619     // Check whether this direct base is inaccessible due to ambiguity.
2620     QualType BaseType = Bases[idx]->getType();
2621 
2622     // Skip all dependent types in templates being used as base specifiers.
2623     // Checks below assume that the base specifier is a CXXRecord.
2624     if (BaseType->isDependentType())
2625       continue;
2626 
2627     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2628       .getUnqualifiedType();
2629 
2630     if (IndirectBaseTypes.count(CanonicalBase)) {
2631       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2632                          /*DetectVirtual=*/true);
2633       bool found
2634         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2635       assert(found);
2636       (void)found;
2637 
2638       if (Paths.isAmbiguous(CanonicalBase))
2639         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2640             << BaseType << getAmbiguousPathsDisplayString(Paths)
2641             << Bases[idx]->getSourceRange();
2642       else
2643         assert(Bases[idx]->isVirtual());
2644     }
2645 
2646     // Delete the base class specifier, since its data has been copied
2647     // into the CXXRecordDecl.
2648     Context.Deallocate(Bases[idx]);
2649   }
2650 
2651   return Invalid;
2652 }
2653 
2654 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2655 /// class, after checking whether there are any duplicate base
2656 /// classes.
2657 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2658                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2659   if (!ClassDecl || Bases.empty())
2660     return;
2661 
2662   AdjustDeclIfTemplate(ClassDecl);
2663   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2664 }
2665 
2666 /// Determine whether the type \p Derived is a C++ class that is
2667 /// derived from the type \p Base.
2668 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2669   if (!getLangOpts().CPlusPlus)
2670     return false;
2671 
2672   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2673   if (!DerivedRD)
2674     return false;
2675 
2676   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2677   if (!BaseRD)
2678     return false;
2679 
2680   // If either the base or the derived type is invalid, don't try to
2681   // check whether one is derived from the other.
2682   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2683     return false;
2684 
2685   // FIXME: In a modules build, do we need the entire path to be visible for us
2686   // to be able to use the inheritance relationship?
2687   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2688     return false;
2689 
2690   return DerivedRD->isDerivedFrom(BaseRD);
2691 }
2692 
2693 /// Determine whether the type \p Derived is a C++ class that is
2694 /// derived from the type \p Base.
2695 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2696                          CXXBasePaths &Paths) {
2697   if (!getLangOpts().CPlusPlus)
2698     return false;
2699 
2700   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2701   if (!DerivedRD)
2702     return false;
2703 
2704   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2705   if (!BaseRD)
2706     return false;
2707 
2708   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2709     return false;
2710 
2711   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2712 }
2713 
2714 static void BuildBasePathArray(const CXXBasePath &Path,
2715                                CXXCastPath &BasePathArray) {
2716   // We first go backward and check if we have a virtual base.
2717   // FIXME: It would be better if CXXBasePath had the base specifier for
2718   // the nearest virtual base.
2719   unsigned Start = 0;
2720   for (unsigned I = Path.size(); I != 0; --I) {
2721     if (Path[I - 1].Base->isVirtual()) {
2722       Start = I - 1;
2723       break;
2724     }
2725   }
2726 
2727   // Now add all bases.
2728   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2729     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2730 }
2731 
2732 
2733 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2734                               CXXCastPath &BasePathArray) {
2735   assert(BasePathArray.empty() && "Base path array must be empty!");
2736   assert(Paths.isRecordingPaths() && "Must record paths!");
2737   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2738 }
2739 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2740 /// conversion (where Derived and Base are class types) is
2741 /// well-formed, meaning that the conversion is unambiguous (and
2742 /// that all of the base classes are accessible). Returns true
2743 /// and emits a diagnostic if the code is ill-formed, returns false
2744 /// otherwise. Loc is the location where this routine should point to
2745 /// if there is an error, and Range is the source range to highlight
2746 /// if there is an error.
2747 ///
2748 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2749 /// diagnostic for the respective type of error will be suppressed, but the
2750 /// check for ill-formed code will still be performed.
2751 bool
2752 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2753                                    unsigned InaccessibleBaseID,
2754                                    unsigned AmbigiousBaseConvID,
2755                                    SourceLocation Loc, SourceRange Range,
2756                                    DeclarationName Name,
2757                                    CXXCastPath *BasePath,
2758                                    bool IgnoreAccess) {
2759   // First, determine whether the path from Derived to Base is
2760   // ambiguous. This is slightly more expensive than checking whether
2761   // the Derived to Base conversion exists, because here we need to
2762   // explore multiple paths to determine if there is an ambiguity.
2763   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2764                      /*DetectVirtual=*/false);
2765   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2766   if (!DerivationOkay)
2767     return true;
2768 
2769   const CXXBasePath *Path = nullptr;
2770   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2771     Path = &Paths.front();
2772 
2773   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2774   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2775   // user to access such bases.
2776   if (!Path && getLangOpts().MSVCCompat) {
2777     for (const CXXBasePath &PossiblePath : Paths) {
2778       if (PossiblePath.size() == 1) {
2779         Path = &PossiblePath;
2780         if (AmbigiousBaseConvID)
2781           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2782               << Base << Derived << Range;
2783         break;
2784       }
2785     }
2786   }
2787 
2788   if (Path) {
2789     if (!IgnoreAccess) {
2790       // Check that the base class can be accessed.
2791       switch (
2792           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2793       case AR_inaccessible:
2794         return true;
2795       case AR_accessible:
2796       case AR_dependent:
2797       case AR_delayed:
2798         break;
2799       }
2800     }
2801 
2802     // Build a base path if necessary.
2803     if (BasePath)
2804       ::BuildBasePathArray(*Path, *BasePath);
2805     return false;
2806   }
2807 
2808   if (AmbigiousBaseConvID) {
2809     // We know that the derived-to-base conversion is ambiguous, and
2810     // we're going to produce a diagnostic. Perform the derived-to-base
2811     // search just one more time to compute all of the possible paths so
2812     // that we can print them out. This is more expensive than any of
2813     // the previous derived-to-base checks we've done, but at this point
2814     // performance isn't as much of an issue.
2815     Paths.clear();
2816     Paths.setRecordingPaths(true);
2817     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2818     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2819     (void)StillOkay;
2820 
2821     // Build up a textual representation of the ambiguous paths, e.g.,
2822     // D -> B -> A, that will be used to illustrate the ambiguous
2823     // conversions in the diagnostic. We only print one of the paths
2824     // to each base class subobject.
2825     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2826 
2827     Diag(Loc, AmbigiousBaseConvID)
2828     << Derived << Base << PathDisplayStr << Range << Name;
2829   }
2830   return true;
2831 }
2832 
2833 bool
2834 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2835                                    SourceLocation Loc, SourceRange Range,
2836                                    CXXCastPath *BasePath,
2837                                    bool IgnoreAccess) {
2838   return CheckDerivedToBaseConversion(
2839       Derived, Base, diag::err_upcast_to_inaccessible_base,
2840       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2841       BasePath, IgnoreAccess);
2842 }
2843 
2844 
2845 /// Builds a string representing ambiguous paths from a
2846 /// specific derived class to different subobjects of the same base
2847 /// class.
2848 ///
2849 /// This function builds a string that can be used in error messages
2850 /// to show the different paths that one can take through the
2851 /// inheritance hierarchy to go from the derived class to different
2852 /// subobjects of a base class. The result looks something like this:
2853 /// @code
2854 /// struct D -> struct B -> struct A
2855 /// struct D -> struct C -> struct A
2856 /// @endcode
2857 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2858   std::string PathDisplayStr;
2859   std::set<unsigned> DisplayedPaths;
2860   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2861        Path != Paths.end(); ++Path) {
2862     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2863       // We haven't displayed a path to this particular base
2864       // class subobject yet.
2865       PathDisplayStr += "\n    ";
2866       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2867       for (CXXBasePath::const_iterator Element = Path->begin();
2868            Element != Path->end(); ++Element)
2869         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2870     }
2871   }
2872 
2873   return PathDisplayStr;
2874 }
2875 
2876 //===----------------------------------------------------------------------===//
2877 // C++ class member Handling
2878 //===----------------------------------------------------------------------===//
2879 
2880 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2881 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2882                                 SourceLocation ColonLoc,
2883                                 const ParsedAttributesView &Attrs) {
2884   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2885   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2886                                                   ASLoc, ColonLoc);
2887   CurContext->addHiddenDecl(ASDecl);
2888   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2889 }
2890 
2891 /// CheckOverrideControl - Check C++11 override control semantics.
2892 void Sema::CheckOverrideControl(NamedDecl *D) {
2893   if (D->isInvalidDecl())
2894     return;
2895 
2896   // We only care about "override" and "final" declarations.
2897   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2898     return;
2899 
2900   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2901 
2902   // We can't check dependent instance methods.
2903   if (MD && MD->isInstance() &&
2904       (MD->getParent()->hasAnyDependentBases() ||
2905        MD->getType()->isDependentType()))
2906     return;
2907 
2908   if (MD && !MD->isVirtual()) {
2909     // If we have a non-virtual method, check if if hides a virtual method.
2910     // (In that case, it's most likely the method has the wrong type.)
2911     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2912     FindHiddenVirtualMethods(MD, OverloadedMethods);
2913 
2914     if (!OverloadedMethods.empty()) {
2915       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2916         Diag(OA->getLocation(),
2917              diag::override_keyword_hides_virtual_member_function)
2918           << "override" << (OverloadedMethods.size() > 1);
2919       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2920         Diag(FA->getLocation(),
2921              diag::override_keyword_hides_virtual_member_function)
2922           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2923           << (OverloadedMethods.size() > 1);
2924       }
2925       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2926       MD->setInvalidDecl();
2927       return;
2928     }
2929     // Fall through into the general case diagnostic.
2930     // FIXME: We might want to attempt typo correction here.
2931   }
2932 
2933   if (!MD || !MD->isVirtual()) {
2934     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2935       Diag(OA->getLocation(),
2936            diag::override_keyword_only_allowed_on_virtual_member_functions)
2937         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2938       D->dropAttr<OverrideAttr>();
2939     }
2940     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2941       Diag(FA->getLocation(),
2942            diag::override_keyword_only_allowed_on_virtual_member_functions)
2943         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2944         << FixItHint::CreateRemoval(FA->getLocation());
2945       D->dropAttr<FinalAttr>();
2946     }
2947     return;
2948   }
2949 
2950   // C++11 [class.virtual]p5:
2951   //   If a function is marked with the virt-specifier override and
2952   //   does not override a member function of a base class, the program is
2953   //   ill-formed.
2954   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2955   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2956     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2957       << MD->getDeclName();
2958 }
2959 
2960 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2961   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2962     return;
2963   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2964   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2965     return;
2966 
2967   SourceLocation Loc = MD->getLocation();
2968   SourceLocation SpellingLoc = Loc;
2969   if (getSourceManager().isMacroArgExpansion(Loc))
2970     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2971   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2972   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2973       return;
2974 
2975   if (MD->size_overridden_methods() > 0) {
2976     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2977                           ? diag::warn_destructor_marked_not_override_overriding
2978                           : diag::warn_function_marked_not_override_overriding;
2979     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2980     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2981     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2982   }
2983 }
2984 
2985 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2986 /// function overrides a virtual member function marked 'final', according to
2987 /// C++11 [class.virtual]p4.
2988 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2989                                                   const CXXMethodDecl *Old) {
2990   FinalAttr *FA = Old->getAttr<FinalAttr>();
2991   if (!FA)
2992     return false;
2993 
2994   Diag(New->getLocation(), diag::err_final_function_overridden)
2995     << New->getDeclName()
2996     << FA->isSpelledAsSealed();
2997   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2998   return true;
2999 }
3000 
3001 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3002   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3003   // FIXME: Destruction of ObjC lifetime types has side-effects.
3004   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3005     return !RD->isCompleteDefinition() ||
3006            !RD->hasTrivialDefaultConstructor() ||
3007            !RD->hasTrivialDestructor();
3008   return false;
3009 }
3010 
3011 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3012   ParsedAttributesView::const_iterator Itr =
3013       llvm::find_if(list, [](const ParsedAttr &AL) {
3014         return AL.isDeclspecPropertyAttribute();
3015       });
3016   if (Itr != list.end())
3017     return &*Itr;
3018   return nullptr;
3019 }
3020 
3021 // Check if there is a field shadowing.
3022 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3023                                       DeclarationName FieldName,
3024                                       const CXXRecordDecl *RD,
3025                                       bool DeclIsField) {
3026   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3027     return;
3028 
3029   // To record a shadowed field in a base
3030   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3031   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3032                            CXXBasePath &Path) {
3033     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3034     // Record an ambiguous path directly
3035     if (Bases.find(Base) != Bases.end())
3036       return true;
3037     for (const auto Field : Base->lookup(FieldName)) {
3038       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3039           Field->getAccess() != AS_private) {
3040         assert(Field->getAccess() != AS_none);
3041         assert(Bases.find(Base) == Bases.end());
3042         Bases[Base] = Field;
3043         return true;
3044       }
3045     }
3046     return false;
3047   };
3048 
3049   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3050                      /*DetectVirtual=*/true);
3051   if (!RD->lookupInBases(FieldShadowed, Paths))
3052     return;
3053 
3054   for (const auto &P : Paths) {
3055     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3056     auto It = Bases.find(Base);
3057     // Skip duplicated bases
3058     if (It == Bases.end())
3059       continue;
3060     auto BaseField = It->second;
3061     assert(BaseField->getAccess() != AS_private);
3062     if (AS_none !=
3063         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3064       Diag(Loc, diag::warn_shadow_field)
3065         << FieldName << RD << Base << DeclIsField;
3066       Diag(BaseField->getLocation(), diag::note_shadow_field);
3067       Bases.erase(It);
3068     }
3069   }
3070 }
3071 
3072 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3073 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3074 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3075 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3076 /// present (but parsing it has been deferred).
3077 NamedDecl *
3078 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3079                                MultiTemplateParamsArg TemplateParameterLists,
3080                                Expr *BW, const VirtSpecifiers &VS,
3081                                InClassInitStyle InitStyle) {
3082   const DeclSpec &DS = D.getDeclSpec();
3083   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3084   DeclarationName Name = NameInfo.getName();
3085   SourceLocation Loc = NameInfo.getLoc();
3086 
3087   // For anonymous bitfields, the location should point to the type.
3088   if (Loc.isInvalid())
3089     Loc = D.getBeginLoc();
3090 
3091   Expr *BitWidth = static_cast<Expr*>(BW);
3092 
3093   assert(isa<CXXRecordDecl>(CurContext));
3094   assert(!DS.isFriendSpecified());
3095 
3096   bool isFunc = D.isDeclarationOfFunction();
3097   const ParsedAttr *MSPropertyAttr =
3098       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3099 
3100   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3101     // The Microsoft extension __interface only permits public member functions
3102     // and prohibits constructors, destructors, operators, non-public member
3103     // functions, static methods and data members.
3104     unsigned InvalidDecl;
3105     bool ShowDeclName = true;
3106     if (!isFunc &&
3107         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3108       InvalidDecl = 0;
3109     else if (!isFunc)
3110       InvalidDecl = 1;
3111     else if (AS != AS_public)
3112       InvalidDecl = 2;
3113     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3114       InvalidDecl = 3;
3115     else switch (Name.getNameKind()) {
3116       case DeclarationName::CXXConstructorName:
3117         InvalidDecl = 4;
3118         ShowDeclName = false;
3119         break;
3120 
3121       case DeclarationName::CXXDestructorName:
3122         InvalidDecl = 5;
3123         ShowDeclName = false;
3124         break;
3125 
3126       case DeclarationName::CXXOperatorName:
3127       case DeclarationName::CXXConversionFunctionName:
3128         InvalidDecl = 6;
3129         break;
3130 
3131       default:
3132         InvalidDecl = 0;
3133         break;
3134     }
3135 
3136     if (InvalidDecl) {
3137       if (ShowDeclName)
3138         Diag(Loc, diag::err_invalid_member_in_interface)
3139           << (InvalidDecl-1) << Name;
3140       else
3141         Diag(Loc, diag::err_invalid_member_in_interface)
3142           << (InvalidDecl-1) << "";
3143       return nullptr;
3144     }
3145   }
3146 
3147   // C++ 9.2p6: A member shall not be declared to have automatic storage
3148   // duration (auto, register) or with the extern storage-class-specifier.
3149   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3150   // data members and cannot be applied to names declared const or static,
3151   // and cannot be applied to reference members.
3152   switch (DS.getStorageClassSpec()) {
3153   case DeclSpec::SCS_unspecified:
3154   case DeclSpec::SCS_typedef:
3155   case DeclSpec::SCS_static:
3156     break;
3157   case DeclSpec::SCS_mutable:
3158     if (isFunc) {
3159       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3160 
3161       // FIXME: It would be nicer if the keyword was ignored only for this
3162       // declarator. Otherwise we could get follow-up errors.
3163       D.getMutableDeclSpec().ClearStorageClassSpecs();
3164     }
3165     break;
3166   default:
3167     Diag(DS.getStorageClassSpecLoc(),
3168          diag::err_storageclass_invalid_for_member);
3169     D.getMutableDeclSpec().ClearStorageClassSpecs();
3170     break;
3171   }
3172 
3173   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3174                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3175                       !isFunc);
3176 
3177   if (DS.hasConstexprSpecifier() && isInstField) {
3178     SemaDiagnosticBuilder B =
3179         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3180     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3181     if (InitStyle == ICIS_NoInit) {
3182       B << 0 << 0;
3183       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3184         B << FixItHint::CreateRemoval(ConstexprLoc);
3185       else {
3186         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3187         D.getMutableDeclSpec().ClearConstexprSpec();
3188         const char *PrevSpec;
3189         unsigned DiagID;
3190         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3191             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3192         (void)Failed;
3193         assert(!Failed && "Making a constexpr member const shouldn't fail");
3194       }
3195     } else {
3196       B << 1;
3197       const char *PrevSpec;
3198       unsigned DiagID;
3199       if (D.getMutableDeclSpec().SetStorageClassSpec(
3200           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3201           Context.getPrintingPolicy())) {
3202         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3203                "This is the only DeclSpec that should fail to be applied");
3204         B << 1;
3205       } else {
3206         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3207         isInstField = false;
3208       }
3209     }
3210   }
3211 
3212   NamedDecl *Member;
3213   if (isInstField) {
3214     CXXScopeSpec &SS = D.getCXXScopeSpec();
3215 
3216     // Data members must have identifiers for names.
3217     if (!Name.isIdentifier()) {
3218       Diag(Loc, diag::err_bad_variable_name)
3219         << Name;
3220       return nullptr;
3221     }
3222 
3223     IdentifierInfo *II = Name.getAsIdentifierInfo();
3224 
3225     // Member field could not be with "template" keyword.
3226     // So TemplateParameterLists should be empty in this case.
3227     if (TemplateParameterLists.size()) {
3228       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3229       if (TemplateParams->size()) {
3230         // There is no such thing as a member field template.
3231         Diag(D.getIdentifierLoc(), diag::err_template_member)
3232             << II
3233             << SourceRange(TemplateParams->getTemplateLoc(),
3234                 TemplateParams->getRAngleLoc());
3235       } else {
3236         // There is an extraneous 'template<>' for this member.
3237         Diag(TemplateParams->getTemplateLoc(),
3238             diag::err_template_member_noparams)
3239             << II
3240             << SourceRange(TemplateParams->getTemplateLoc(),
3241                 TemplateParams->getRAngleLoc());
3242       }
3243       return nullptr;
3244     }
3245 
3246     if (SS.isSet() && !SS.isInvalid()) {
3247       // The user provided a superfluous scope specifier inside a class
3248       // definition:
3249       //
3250       // class X {
3251       //   int X::member;
3252       // };
3253       if (DeclContext *DC = computeDeclContext(SS, false))
3254         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3255                                      D.getName().getKind() ==
3256                                          UnqualifiedIdKind::IK_TemplateId);
3257       else
3258         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3259           << Name << SS.getRange();
3260 
3261       SS.clear();
3262     }
3263 
3264     if (MSPropertyAttr) {
3265       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3266                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3267       if (!Member)
3268         return nullptr;
3269       isInstField = false;
3270     } else {
3271       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3272                                 BitWidth, InitStyle, AS);
3273       if (!Member)
3274         return nullptr;
3275     }
3276 
3277     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3278   } else {
3279     Member = HandleDeclarator(S, D, TemplateParameterLists);
3280     if (!Member)
3281       return nullptr;
3282 
3283     // Non-instance-fields can't have a bitfield.
3284     if (BitWidth) {
3285       if (Member->isInvalidDecl()) {
3286         // don't emit another diagnostic.
3287       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3288         // C++ 9.6p3: A bit-field shall not be a static member.
3289         // "static member 'A' cannot be a bit-field"
3290         Diag(Loc, diag::err_static_not_bitfield)
3291           << Name << BitWidth->getSourceRange();
3292       } else if (isa<TypedefDecl>(Member)) {
3293         // "typedef member 'x' cannot be a bit-field"
3294         Diag(Loc, diag::err_typedef_not_bitfield)
3295           << Name << BitWidth->getSourceRange();
3296       } else {
3297         // A function typedef ("typedef int f(); f a;").
3298         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3299         Diag(Loc, diag::err_not_integral_type_bitfield)
3300           << Name << cast<ValueDecl>(Member)->getType()
3301           << BitWidth->getSourceRange();
3302       }
3303 
3304       BitWidth = nullptr;
3305       Member->setInvalidDecl();
3306     }
3307 
3308     NamedDecl *NonTemplateMember = Member;
3309     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3310       NonTemplateMember = FunTmpl->getTemplatedDecl();
3311     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3312       NonTemplateMember = VarTmpl->getTemplatedDecl();
3313 
3314     Member->setAccess(AS);
3315 
3316     // If we have declared a member function template or static data member
3317     // template, set the access of the templated declaration as well.
3318     if (NonTemplateMember != Member)
3319       NonTemplateMember->setAccess(AS);
3320 
3321     // C++ [temp.deduct.guide]p3:
3322     //   A deduction guide [...] for a member class template [shall be
3323     //   declared] with the same access [as the template].
3324     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3325       auto *TD = DG->getDeducedTemplate();
3326       // Access specifiers are only meaningful if both the template and the
3327       // deduction guide are from the same scope.
3328       if (AS != TD->getAccess() &&
3329           TD->getDeclContext()->getRedeclContext()->Equals(
3330               DG->getDeclContext()->getRedeclContext())) {
3331         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3332         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3333             << TD->getAccess();
3334         const AccessSpecDecl *LastAccessSpec = nullptr;
3335         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3336           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3337             LastAccessSpec = AccessSpec;
3338         }
3339         assert(LastAccessSpec && "differing access with no access specifier");
3340         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3341             << AS;
3342       }
3343     }
3344   }
3345 
3346   if (VS.isOverrideSpecified())
3347     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3348   if (VS.isFinalSpecified())
3349     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3350                                             VS.isFinalSpelledSealed()));
3351 
3352   if (VS.getLastLocation().isValid()) {
3353     // Update the end location of a method that has a virt-specifiers.
3354     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3355       MD->setRangeEnd(VS.getLastLocation());
3356   }
3357 
3358   CheckOverrideControl(Member);
3359 
3360   assert((Name || isInstField) && "No identifier for non-field ?");
3361 
3362   if (isInstField) {
3363     FieldDecl *FD = cast<FieldDecl>(Member);
3364     FieldCollector->Add(FD);
3365 
3366     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3367       // Remember all explicit private FieldDecls that have a name, no side
3368       // effects and are not part of a dependent type declaration.
3369       if (!FD->isImplicit() && FD->getDeclName() &&
3370           FD->getAccess() == AS_private &&
3371           !FD->hasAttr<UnusedAttr>() &&
3372           !FD->getParent()->isDependentContext() &&
3373           !InitializationHasSideEffects(*FD))
3374         UnusedPrivateFields.insert(FD);
3375     }
3376   }
3377 
3378   return Member;
3379 }
3380 
3381 namespace {
3382   class UninitializedFieldVisitor
3383       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3384     Sema &S;
3385     // List of Decls to generate a warning on.  Also remove Decls that become
3386     // initialized.
3387     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3388     // List of base classes of the record.  Classes are removed after their
3389     // initializers.
3390     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3391     // Vector of decls to be removed from the Decl set prior to visiting the
3392     // nodes.  These Decls may have been initialized in the prior initializer.
3393     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3394     // If non-null, add a note to the warning pointing back to the constructor.
3395     const CXXConstructorDecl *Constructor;
3396     // Variables to hold state when processing an initializer list.  When
3397     // InitList is true, special case initialization of FieldDecls matching
3398     // InitListFieldDecl.
3399     bool InitList;
3400     FieldDecl *InitListFieldDecl;
3401     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3402 
3403   public:
3404     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3405     UninitializedFieldVisitor(Sema &S,
3406                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3407                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3408       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3409         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3410 
3411     // Returns true if the use of ME is not an uninitialized use.
3412     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3413                                          bool CheckReferenceOnly) {
3414       llvm::SmallVector<FieldDecl*, 4> Fields;
3415       bool ReferenceField = false;
3416       while (ME) {
3417         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3418         if (!FD)
3419           return false;
3420         Fields.push_back(FD);
3421         if (FD->getType()->isReferenceType())
3422           ReferenceField = true;
3423         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3424       }
3425 
3426       // Binding a reference to an uninitialized field is not an
3427       // uninitialized use.
3428       if (CheckReferenceOnly && !ReferenceField)
3429         return true;
3430 
3431       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3432       // Discard the first field since it is the field decl that is being
3433       // initialized.
3434       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3435         UsedFieldIndex.push_back((*I)->getFieldIndex());
3436       }
3437 
3438       for (auto UsedIter = UsedFieldIndex.begin(),
3439                 UsedEnd = UsedFieldIndex.end(),
3440                 OrigIter = InitFieldIndex.begin(),
3441                 OrigEnd = InitFieldIndex.end();
3442            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3443         if (*UsedIter < *OrigIter)
3444           return true;
3445         if (*UsedIter > *OrigIter)
3446           break;
3447       }
3448 
3449       return false;
3450     }
3451 
3452     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3453                           bool AddressOf) {
3454       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3455         return;
3456 
3457       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3458       // or union.
3459       MemberExpr *FieldME = ME;
3460 
3461       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3462 
3463       Expr *Base = ME;
3464       while (MemberExpr *SubME =
3465                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3466 
3467         if (isa<VarDecl>(SubME->getMemberDecl()))
3468           return;
3469 
3470         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3471           if (!FD->isAnonymousStructOrUnion())
3472             FieldME = SubME;
3473 
3474         if (!FieldME->getType().isPODType(S.Context))
3475           AllPODFields = false;
3476 
3477         Base = SubME->getBase();
3478       }
3479 
3480       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3481         return;
3482 
3483       if (AddressOf && AllPODFields)
3484         return;
3485 
3486       ValueDecl* FoundVD = FieldME->getMemberDecl();
3487 
3488       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3489         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3490           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3491         }
3492 
3493         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3494           QualType T = BaseCast->getType();
3495           if (T->isPointerType() &&
3496               BaseClasses.count(T->getPointeeType())) {
3497             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3498                 << T->getPointeeType() << FoundVD;
3499           }
3500         }
3501       }
3502 
3503       if (!Decls.count(FoundVD))
3504         return;
3505 
3506       const bool IsReference = FoundVD->getType()->isReferenceType();
3507 
3508       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3509         // Special checking for initializer lists.
3510         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3511           return;
3512         }
3513       } else {
3514         // Prevent double warnings on use of unbounded references.
3515         if (CheckReferenceOnly && !IsReference)
3516           return;
3517       }
3518 
3519       unsigned diag = IsReference
3520           ? diag::warn_reference_field_is_uninit
3521           : diag::warn_field_is_uninit;
3522       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3523       if (Constructor)
3524         S.Diag(Constructor->getLocation(),
3525                diag::note_uninit_in_this_constructor)
3526           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3527 
3528     }
3529 
3530     void HandleValue(Expr *E, bool AddressOf) {
3531       E = E->IgnoreParens();
3532 
3533       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3534         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3535                          AddressOf /*AddressOf*/);
3536         return;
3537       }
3538 
3539       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3540         Visit(CO->getCond());
3541         HandleValue(CO->getTrueExpr(), AddressOf);
3542         HandleValue(CO->getFalseExpr(), AddressOf);
3543         return;
3544       }
3545 
3546       if (BinaryConditionalOperator *BCO =
3547               dyn_cast<BinaryConditionalOperator>(E)) {
3548         Visit(BCO->getCond());
3549         HandleValue(BCO->getFalseExpr(), AddressOf);
3550         return;
3551       }
3552 
3553       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3554         HandleValue(OVE->getSourceExpr(), AddressOf);
3555         return;
3556       }
3557 
3558       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3559         switch (BO->getOpcode()) {
3560         default:
3561           break;
3562         case(BO_PtrMemD):
3563         case(BO_PtrMemI):
3564           HandleValue(BO->getLHS(), AddressOf);
3565           Visit(BO->getRHS());
3566           return;
3567         case(BO_Comma):
3568           Visit(BO->getLHS());
3569           HandleValue(BO->getRHS(), AddressOf);
3570           return;
3571         }
3572       }
3573 
3574       Visit(E);
3575     }
3576 
3577     void CheckInitListExpr(InitListExpr *ILE) {
3578       InitFieldIndex.push_back(0);
3579       for (auto Child : ILE->children()) {
3580         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3581           CheckInitListExpr(SubList);
3582         } else {
3583           Visit(Child);
3584         }
3585         ++InitFieldIndex.back();
3586       }
3587       InitFieldIndex.pop_back();
3588     }
3589 
3590     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3591                           FieldDecl *Field, const Type *BaseClass) {
3592       // Remove Decls that may have been initialized in the previous
3593       // initializer.
3594       for (ValueDecl* VD : DeclsToRemove)
3595         Decls.erase(VD);
3596       DeclsToRemove.clear();
3597 
3598       Constructor = FieldConstructor;
3599       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3600 
3601       if (ILE && Field) {
3602         InitList = true;
3603         InitListFieldDecl = Field;
3604         InitFieldIndex.clear();
3605         CheckInitListExpr(ILE);
3606       } else {
3607         InitList = false;
3608         Visit(E);
3609       }
3610 
3611       if (Field)
3612         Decls.erase(Field);
3613       if (BaseClass)
3614         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3615     }
3616 
3617     void VisitMemberExpr(MemberExpr *ME) {
3618       // All uses of unbounded reference fields will warn.
3619       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3620     }
3621 
3622     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3623       if (E->getCastKind() == CK_LValueToRValue) {
3624         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3625         return;
3626       }
3627 
3628       Inherited::VisitImplicitCastExpr(E);
3629     }
3630 
3631     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3632       if (E->getConstructor()->isCopyConstructor()) {
3633         Expr *ArgExpr = E->getArg(0);
3634         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3635           if (ILE->getNumInits() == 1)
3636             ArgExpr = ILE->getInit(0);
3637         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3638           if (ICE->getCastKind() == CK_NoOp)
3639             ArgExpr = ICE->getSubExpr();
3640         HandleValue(ArgExpr, false /*AddressOf*/);
3641         return;
3642       }
3643       Inherited::VisitCXXConstructExpr(E);
3644     }
3645 
3646     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3647       Expr *Callee = E->getCallee();
3648       if (isa<MemberExpr>(Callee)) {
3649         HandleValue(Callee, false /*AddressOf*/);
3650         for (auto Arg : E->arguments())
3651           Visit(Arg);
3652         return;
3653       }
3654 
3655       Inherited::VisitCXXMemberCallExpr(E);
3656     }
3657 
3658     void VisitCallExpr(CallExpr *E) {
3659       // Treat std::move as a use.
3660       if (E->isCallToStdMove()) {
3661         HandleValue(E->getArg(0), /*AddressOf=*/false);
3662         return;
3663       }
3664 
3665       Inherited::VisitCallExpr(E);
3666     }
3667 
3668     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3669       Expr *Callee = E->getCallee();
3670 
3671       if (isa<UnresolvedLookupExpr>(Callee))
3672         return Inherited::VisitCXXOperatorCallExpr(E);
3673 
3674       Visit(Callee);
3675       for (auto Arg : E->arguments())
3676         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3677     }
3678 
3679     void VisitBinaryOperator(BinaryOperator *E) {
3680       // If a field assignment is detected, remove the field from the
3681       // uninitiailized field set.
3682       if (E->getOpcode() == BO_Assign)
3683         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3684           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3685             if (!FD->getType()->isReferenceType())
3686               DeclsToRemove.push_back(FD);
3687 
3688       if (E->isCompoundAssignmentOp()) {
3689         HandleValue(E->getLHS(), false /*AddressOf*/);
3690         Visit(E->getRHS());
3691         return;
3692       }
3693 
3694       Inherited::VisitBinaryOperator(E);
3695     }
3696 
3697     void VisitUnaryOperator(UnaryOperator *E) {
3698       if (E->isIncrementDecrementOp()) {
3699         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3700         return;
3701       }
3702       if (E->getOpcode() == UO_AddrOf) {
3703         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3704           HandleValue(ME->getBase(), true /*AddressOf*/);
3705           return;
3706         }
3707       }
3708 
3709       Inherited::VisitUnaryOperator(E);
3710     }
3711   };
3712 
3713   // Diagnose value-uses of fields to initialize themselves, e.g.
3714   //   foo(foo)
3715   // where foo is not also a parameter to the constructor.
3716   // Also diagnose across field uninitialized use such as
3717   //   x(y), y(x)
3718   // TODO: implement -Wuninitialized and fold this into that framework.
3719   static void DiagnoseUninitializedFields(
3720       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3721 
3722     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3723                                            Constructor->getLocation())) {
3724       return;
3725     }
3726 
3727     if (Constructor->isInvalidDecl())
3728       return;
3729 
3730     const CXXRecordDecl *RD = Constructor->getParent();
3731 
3732     if (RD->getDescribedClassTemplate())
3733       return;
3734 
3735     // Holds fields that are uninitialized.
3736     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3737 
3738     // At the beginning, all fields are uninitialized.
3739     for (auto *I : RD->decls()) {
3740       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3741         UninitializedFields.insert(FD);
3742       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3743         UninitializedFields.insert(IFD->getAnonField());
3744       }
3745     }
3746 
3747     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3748     for (auto I : RD->bases())
3749       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3750 
3751     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3752       return;
3753 
3754     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3755                                                    UninitializedFields,
3756                                                    UninitializedBaseClasses);
3757 
3758     for (const auto *FieldInit : Constructor->inits()) {
3759       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3760         break;
3761 
3762       Expr *InitExpr = FieldInit->getInit();
3763       if (!InitExpr)
3764         continue;
3765 
3766       if (CXXDefaultInitExpr *Default =
3767               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3768         InitExpr = Default->getExpr();
3769         if (!InitExpr)
3770           continue;
3771         // In class initializers will point to the constructor.
3772         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3773                                               FieldInit->getAnyMember(),
3774                                               FieldInit->getBaseClass());
3775       } else {
3776         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3777                                               FieldInit->getAnyMember(),
3778                                               FieldInit->getBaseClass());
3779       }
3780     }
3781   }
3782 } // namespace
3783 
3784 /// Enter a new C++ default initializer scope. After calling this, the
3785 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3786 /// parsing or instantiating the initializer failed.
3787 void Sema::ActOnStartCXXInClassMemberInitializer() {
3788   // Create a synthetic function scope to represent the call to the constructor
3789   // that notionally surrounds a use of this initializer.
3790   PushFunctionScope();
3791 }
3792 
3793 /// This is invoked after parsing an in-class initializer for a
3794 /// non-static C++ class member, and after instantiating an in-class initializer
3795 /// in a class template. Such actions are deferred until the class is complete.
3796 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3797                                                   SourceLocation InitLoc,
3798                                                   Expr *InitExpr) {
3799   // Pop the notional constructor scope we created earlier.
3800   PopFunctionScopeInfo(nullptr, D);
3801 
3802   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3803   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3804          "must set init style when field is created");
3805 
3806   if (!InitExpr) {
3807     D->setInvalidDecl();
3808     if (FD)
3809       FD->removeInClassInitializer();
3810     return;
3811   }
3812 
3813   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3814     FD->setInvalidDecl();
3815     FD->removeInClassInitializer();
3816     return;
3817   }
3818 
3819   ExprResult Init = InitExpr;
3820   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3821     InitializedEntity Entity =
3822         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3823     InitializationKind Kind =
3824         FD->getInClassInitStyle() == ICIS_ListInit
3825             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3826                                                    InitExpr->getBeginLoc(),
3827                                                    InitExpr->getEndLoc())
3828             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3829     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3830     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3831     if (Init.isInvalid()) {
3832       FD->setInvalidDecl();
3833       return;
3834     }
3835   }
3836 
3837   // C++11 [class.base.init]p7:
3838   //   The initialization of each base and member constitutes a
3839   //   full-expression.
3840   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3841   if (Init.isInvalid()) {
3842     FD->setInvalidDecl();
3843     return;
3844   }
3845 
3846   InitExpr = Init.get();
3847 
3848   FD->setInClassInitializer(InitExpr);
3849 }
3850 
3851 /// Find the direct and/or virtual base specifiers that
3852 /// correspond to the given base type, for use in base initialization
3853 /// within a constructor.
3854 static bool FindBaseInitializer(Sema &SemaRef,
3855                                 CXXRecordDecl *ClassDecl,
3856                                 QualType BaseType,
3857                                 const CXXBaseSpecifier *&DirectBaseSpec,
3858                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3859   // First, check for a direct base class.
3860   DirectBaseSpec = nullptr;
3861   for (const auto &Base : ClassDecl->bases()) {
3862     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3863       // We found a direct base of this type. That's what we're
3864       // initializing.
3865       DirectBaseSpec = &Base;
3866       break;
3867     }
3868   }
3869 
3870   // Check for a virtual base class.
3871   // FIXME: We might be able to short-circuit this if we know in advance that
3872   // there are no virtual bases.
3873   VirtualBaseSpec = nullptr;
3874   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3875     // We haven't found a base yet; search the class hierarchy for a
3876     // virtual base class.
3877     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3878                        /*DetectVirtual=*/false);
3879     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3880                               SemaRef.Context.getTypeDeclType(ClassDecl),
3881                               BaseType, Paths)) {
3882       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3883            Path != Paths.end(); ++Path) {
3884         if (Path->back().Base->isVirtual()) {
3885           VirtualBaseSpec = Path->back().Base;
3886           break;
3887         }
3888       }
3889     }
3890   }
3891 
3892   return DirectBaseSpec || VirtualBaseSpec;
3893 }
3894 
3895 /// Handle a C++ member initializer using braced-init-list syntax.
3896 MemInitResult
3897 Sema::ActOnMemInitializer(Decl *ConstructorD,
3898                           Scope *S,
3899                           CXXScopeSpec &SS,
3900                           IdentifierInfo *MemberOrBase,
3901                           ParsedType TemplateTypeTy,
3902                           const DeclSpec &DS,
3903                           SourceLocation IdLoc,
3904                           Expr *InitList,
3905                           SourceLocation EllipsisLoc) {
3906   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3907                              DS, IdLoc, InitList,
3908                              EllipsisLoc);
3909 }
3910 
3911 /// Handle a C++ member initializer using parentheses syntax.
3912 MemInitResult
3913 Sema::ActOnMemInitializer(Decl *ConstructorD,
3914                           Scope *S,
3915                           CXXScopeSpec &SS,
3916                           IdentifierInfo *MemberOrBase,
3917                           ParsedType TemplateTypeTy,
3918                           const DeclSpec &DS,
3919                           SourceLocation IdLoc,
3920                           SourceLocation LParenLoc,
3921                           ArrayRef<Expr *> Args,
3922                           SourceLocation RParenLoc,
3923                           SourceLocation EllipsisLoc) {
3924   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3925   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3926                              DS, IdLoc, List, EllipsisLoc);
3927 }
3928 
3929 namespace {
3930 
3931 // Callback to only accept typo corrections that can be a valid C++ member
3932 // intializer: either a non-static field member or a base class.
3933 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
3934 public:
3935   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3936       : ClassDecl(ClassDecl) {}
3937 
3938   bool ValidateCandidate(const TypoCorrection &candidate) override {
3939     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3940       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3941         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3942       return isa<TypeDecl>(ND);
3943     }
3944     return false;
3945   }
3946 
3947   std::unique_ptr<CorrectionCandidateCallback> clone() override {
3948     return std::make_unique<MemInitializerValidatorCCC>(*this);
3949   }
3950 
3951 private:
3952   CXXRecordDecl *ClassDecl;
3953 };
3954 
3955 }
3956 
3957 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3958                                              CXXScopeSpec &SS,
3959                                              ParsedType TemplateTypeTy,
3960                                              IdentifierInfo *MemberOrBase) {
3961   if (SS.getScopeRep() || TemplateTypeTy)
3962     return nullptr;
3963   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3964   if (Result.empty())
3965     return nullptr;
3966   ValueDecl *Member;
3967   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3968       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3969     return Member;
3970   return nullptr;
3971 }
3972 
3973 /// Handle a C++ member initializer.
3974 MemInitResult
3975 Sema::BuildMemInitializer(Decl *ConstructorD,
3976                           Scope *S,
3977                           CXXScopeSpec &SS,
3978                           IdentifierInfo *MemberOrBase,
3979                           ParsedType TemplateTypeTy,
3980                           const DeclSpec &DS,
3981                           SourceLocation IdLoc,
3982                           Expr *Init,
3983                           SourceLocation EllipsisLoc) {
3984   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3985   if (!Res.isUsable())
3986     return true;
3987   Init = Res.get();
3988 
3989   if (!ConstructorD)
3990     return true;
3991 
3992   AdjustDeclIfTemplate(ConstructorD);
3993 
3994   CXXConstructorDecl *Constructor
3995     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3996   if (!Constructor) {
3997     // The user wrote a constructor initializer on a function that is
3998     // not a C++ constructor. Ignore the error for now, because we may
3999     // have more member initializers coming; we'll diagnose it just
4000     // once in ActOnMemInitializers.
4001     return true;
4002   }
4003 
4004   CXXRecordDecl *ClassDecl = Constructor->getParent();
4005 
4006   // C++ [class.base.init]p2:
4007   //   Names in a mem-initializer-id are looked up in the scope of the
4008   //   constructor's class and, if not found in that scope, are looked
4009   //   up in the scope containing the constructor's definition.
4010   //   [Note: if the constructor's class contains a member with the
4011   //   same name as a direct or virtual base class of the class, a
4012   //   mem-initializer-id naming the member or base class and composed
4013   //   of a single identifier refers to the class member. A
4014   //   mem-initializer-id for the hidden base class may be specified
4015   //   using a qualified name. ]
4016 
4017   // Look for a member, first.
4018   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4019           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4020     if (EllipsisLoc.isValid())
4021       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4022           << MemberOrBase
4023           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4024 
4025     return BuildMemberInitializer(Member, Init, IdLoc);
4026   }
4027   // It didn't name a member, so see if it names a class.
4028   QualType BaseType;
4029   TypeSourceInfo *TInfo = nullptr;
4030 
4031   if (TemplateTypeTy) {
4032     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4033     if (BaseType.isNull())
4034       return true;
4035   } else if (DS.getTypeSpecType() == TST_decltype) {
4036     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4037   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4038     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4039     return true;
4040   } else {
4041     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4042     LookupParsedName(R, S, &SS);
4043 
4044     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4045     if (!TyD) {
4046       if (R.isAmbiguous()) return true;
4047 
4048       // We don't want access-control diagnostics here.
4049       R.suppressDiagnostics();
4050 
4051       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4052         bool NotUnknownSpecialization = false;
4053         DeclContext *DC = computeDeclContext(SS, false);
4054         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4055           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4056 
4057         if (!NotUnknownSpecialization) {
4058           // When the scope specifier can refer to a member of an unknown
4059           // specialization, we take it as a type name.
4060           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4061                                        SS.getWithLocInContext(Context),
4062                                        *MemberOrBase, IdLoc);
4063           if (BaseType.isNull())
4064             return true;
4065 
4066           TInfo = Context.CreateTypeSourceInfo(BaseType);
4067           DependentNameTypeLoc TL =
4068               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4069           if (!TL.isNull()) {
4070             TL.setNameLoc(IdLoc);
4071             TL.setElaboratedKeywordLoc(SourceLocation());
4072             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4073           }
4074 
4075           R.clear();
4076           R.setLookupName(MemberOrBase);
4077         }
4078       }
4079 
4080       // If no results were found, try to correct typos.
4081       TypoCorrection Corr;
4082       MemInitializerValidatorCCC CCC(ClassDecl);
4083       if (R.empty() && BaseType.isNull() &&
4084           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4085                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4086         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4087           // We have found a non-static data member with a similar
4088           // name to what was typed; complain and initialize that
4089           // member.
4090           diagnoseTypo(Corr,
4091                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4092                          << MemberOrBase << true);
4093           return BuildMemberInitializer(Member, Init, IdLoc);
4094         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4095           const CXXBaseSpecifier *DirectBaseSpec;
4096           const CXXBaseSpecifier *VirtualBaseSpec;
4097           if (FindBaseInitializer(*this, ClassDecl,
4098                                   Context.getTypeDeclType(Type),
4099                                   DirectBaseSpec, VirtualBaseSpec)) {
4100             // We have found a direct or virtual base class with a
4101             // similar name to what was typed; complain and initialize
4102             // that base class.
4103             diagnoseTypo(Corr,
4104                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4105                            << MemberOrBase << false,
4106                          PDiag() /*Suppress note, we provide our own.*/);
4107 
4108             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4109                                                               : VirtualBaseSpec;
4110             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4111                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4112 
4113             TyD = Type;
4114           }
4115         }
4116       }
4117 
4118       if (!TyD && BaseType.isNull()) {
4119         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4120           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4121         return true;
4122       }
4123     }
4124 
4125     if (BaseType.isNull()) {
4126       BaseType = Context.getTypeDeclType(TyD);
4127       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4128       if (SS.isSet()) {
4129         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4130                                              BaseType);
4131         TInfo = Context.CreateTypeSourceInfo(BaseType);
4132         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4133         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4134         TL.setElaboratedKeywordLoc(SourceLocation());
4135         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4136       }
4137     }
4138   }
4139 
4140   if (!TInfo)
4141     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4142 
4143   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4144 }
4145 
4146 MemInitResult
4147 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4148                              SourceLocation IdLoc) {
4149   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4150   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4151   assert((DirectMember || IndirectMember) &&
4152          "Member must be a FieldDecl or IndirectFieldDecl");
4153 
4154   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4155     return true;
4156 
4157   if (Member->isInvalidDecl())
4158     return true;
4159 
4160   MultiExprArg Args;
4161   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4162     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4163   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4164     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4165   } else {
4166     // Template instantiation doesn't reconstruct ParenListExprs for us.
4167     Args = Init;
4168   }
4169 
4170   SourceRange InitRange = Init->getSourceRange();
4171 
4172   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4173     // Can't check initialization for a member of dependent type or when
4174     // any of the arguments are type-dependent expressions.
4175     DiscardCleanupsInEvaluationContext();
4176   } else {
4177     bool InitList = false;
4178     if (isa<InitListExpr>(Init)) {
4179       InitList = true;
4180       Args = Init;
4181     }
4182 
4183     // Initialize the member.
4184     InitializedEntity MemberEntity =
4185       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4186                    : InitializedEntity::InitializeMember(IndirectMember,
4187                                                          nullptr);
4188     InitializationKind Kind =
4189         InitList ? InitializationKind::CreateDirectList(
4190                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4191                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4192                                                     InitRange.getEnd());
4193 
4194     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4195     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4196                                             nullptr);
4197     if (MemberInit.isInvalid())
4198       return true;
4199 
4200     // C++11 [class.base.init]p7:
4201     //   The initialization of each base and member constitutes a
4202     //   full-expression.
4203     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4204                                      /*DiscardedValue*/ false);
4205     if (MemberInit.isInvalid())
4206       return true;
4207 
4208     Init = MemberInit.get();
4209   }
4210 
4211   if (DirectMember) {
4212     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4213                                             InitRange.getBegin(), Init,
4214                                             InitRange.getEnd());
4215   } else {
4216     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4217                                             InitRange.getBegin(), Init,
4218                                             InitRange.getEnd());
4219   }
4220 }
4221 
4222 MemInitResult
4223 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4224                                  CXXRecordDecl *ClassDecl) {
4225   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4226   if (!LangOpts.CPlusPlus11)
4227     return Diag(NameLoc, diag::err_delegating_ctor)
4228       << TInfo->getTypeLoc().getLocalSourceRange();
4229   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4230 
4231   bool InitList = true;
4232   MultiExprArg Args = Init;
4233   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4234     InitList = false;
4235     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4236   }
4237 
4238   SourceRange InitRange = Init->getSourceRange();
4239   // Initialize the object.
4240   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4241                                      QualType(ClassDecl->getTypeForDecl(), 0));
4242   InitializationKind Kind =
4243       InitList ? InitializationKind::CreateDirectList(
4244                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4245                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4246                                                   InitRange.getEnd());
4247   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4248   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4249                                               Args, nullptr);
4250   if (DelegationInit.isInvalid())
4251     return true;
4252 
4253   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4254          "Delegating constructor with no target?");
4255 
4256   // C++11 [class.base.init]p7:
4257   //   The initialization of each base and member constitutes a
4258   //   full-expression.
4259   DelegationInit = ActOnFinishFullExpr(
4260       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4261   if (DelegationInit.isInvalid())
4262     return true;
4263 
4264   // If we are in a dependent context, template instantiation will
4265   // perform this type-checking again. Just save the arguments that we
4266   // received in a ParenListExpr.
4267   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4268   // of the information that we have about the base
4269   // initializer. However, deconstructing the ASTs is a dicey process,
4270   // and this approach is far more likely to get the corner cases right.
4271   if (CurContext->isDependentContext())
4272     DelegationInit = Init;
4273 
4274   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4275                                           DelegationInit.getAs<Expr>(),
4276                                           InitRange.getEnd());
4277 }
4278 
4279 MemInitResult
4280 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4281                            Expr *Init, CXXRecordDecl *ClassDecl,
4282                            SourceLocation EllipsisLoc) {
4283   SourceLocation BaseLoc
4284     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4285 
4286   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4287     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4288              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4289 
4290   // C++ [class.base.init]p2:
4291   //   [...] Unless the mem-initializer-id names a nonstatic data
4292   //   member of the constructor's class or a direct or virtual base
4293   //   of that class, the mem-initializer is ill-formed. A
4294   //   mem-initializer-list can initialize a base class using any
4295   //   name that denotes that base class type.
4296   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4297 
4298   SourceRange InitRange = Init->getSourceRange();
4299   if (EllipsisLoc.isValid()) {
4300     // This is a pack expansion.
4301     if (!BaseType->containsUnexpandedParameterPack())  {
4302       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4303         << SourceRange(BaseLoc, InitRange.getEnd());
4304 
4305       EllipsisLoc = SourceLocation();
4306     }
4307   } else {
4308     // Check for any unexpanded parameter packs.
4309     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4310       return true;
4311 
4312     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4313       return true;
4314   }
4315 
4316   // Check for direct and virtual base classes.
4317   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4318   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4319   if (!Dependent) {
4320     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4321                                        BaseType))
4322       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4323 
4324     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4325                         VirtualBaseSpec);
4326 
4327     // C++ [base.class.init]p2:
4328     // Unless the mem-initializer-id names a nonstatic data member of the
4329     // constructor's class or a direct or virtual base of that class, the
4330     // mem-initializer is ill-formed.
4331     if (!DirectBaseSpec && !VirtualBaseSpec) {
4332       // If the class has any dependent bases, then it's possible that
4333       // one of those types will resolve to the same type as
4334       // BaseType. Therefore, just treat this as a dependent base
4335       // class initialization.  FIXME: Should we try to check the
4336       // initialization anyway? It seems odd.
4337       if (ClassDecl->hasAnyDependentBases())
4338         Dependent = true;
4339       else
4340         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4341           << BaseType << Context.getTypeDeclType(ClassDecl)
4342           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4343     }
4344   }
4345 
4346   if (Dependent) {
4347     DiscardCleanupsInEvaluationContext();
4348 
4349     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4350                                             /*IsVirtual=*/false,
4351                                             InitRange.getBegin(), Init,
4352                                             InitRange.getEnd(), EllipsisLoc);
4353   }
4354 
4355   // C++ [base.class.init]p2:
4356   //   If a mem-initializer-id is ambiguous because it designates both
4357   //   a direct non-virtual base class and an inherited virtual base
4358   //   class, the mem-initializer is ill-formed.
4359   if (DirectBaseSpec && VirtualBaseSpec)
4360     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4361       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4362 
4363   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4364   if (!BaseSpec)
4365     BaseSpec = VirtualBaseSpec;
4366 
4367   // Initialize the base.
4368   bool InitList = true;
4369   MultiExprArg Args = Init;
4370   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4371     InitList = false;
4372     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4373   }
4374 
4375   InitializedEntity BaseEntity =
4376     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4377   InitializationKind Kind =
4378       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4379                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4380                                                   InitRange.getEnd());
4381   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4382   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4383   if (BaseInit.isInvalid())
4384     return true;
4385 
4386   // C++11 [class.base.init]p7:
4387   //   The initialization of each base and member constitutes a
4388   //   full-expression.
4389   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4390                                  /*DiscardedValue*/ false);
4391   if (BaseInit.isInvalid())
4392     return true;
4393 
4394   // If we are in a dependent context, template instantiation will
4395   // perform this type-checking again. Just save the arguments that we
4396   // received in a ParenListExpr.
4397   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4398   // of the information that we have about the base
4399   // initializer. However, deconstructing the ASTs is a dicey process,
4400   // and this approach is far more likely to get the corner cases right.
4401   if (CurContext->isDependentContext())
4402     BaseInit = Init;
4403 
4404   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4405                                           BaseSpec->isVirtual(),
4406                                           InitRange.getBegin(),
4407                                           BaseInit.getAs<Expr>(),
4408                                           InitRange.getEnd(), EllipsisLoc);
4409 }
4410 
4411 // Create a static_cast\<T&&>(expr).
4412 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4413   if (T.isNull()) T = E->getType();
4414   QualType TargetType = SemaRef.BuildReferenceType(
4415       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4416   SourceLocation ExprLoc = E->getBeginLoc();
4417   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4418       TargetType, ExprLoc);
4419 
4420   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4421                                    SourceRange(ExprLoc, ExprLoc),
4422                                    E->getSourceRange()).get();
4423 }
4424 
4425 /// ImplicitInitializerKind - How an implicit base or member initializer should
4426 /// initialize its base or member.
4427 enum ImplicitInitializerKind {
4428   IIK_Default,
4429   IIK_Copy,
4430   IIK_Move,
4431   IIK_Inherit
4432 };
4433 
4434 static bool
4435 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4436                              ImplicitInitializerKind ImplicitInitKind,
4437                              CXXBaseSpecifier *BaseSpec,
4438                              bool IsInheritedVirtualBase,
4439                              CXXCtorInitializer *&CXXBaseInit) {
4440   InitializedEntity InitEntity
4441     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4442                                         IsInheritedVirtualBase);
4443 
4444   ExprResult BaseInit;
4445 
4446   switch (ImplicitInitKind) {
4447   case IIK_Inherit:
4448   case IIK_Default: {
4449     InitializationKind InitKind
4450       = InitializationKind::CreateDefault(Constructor->getLocation());
4451     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4452     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4453     break;
4454   }
4455 
4456   case IIK_Move:
4457   case IIK_Copy: {
4458     bool Moving = ImplicitInitKind == IIK_Move;
4459     ParmVarDecl *Param = Constructor->getParamDecl(0);
4460     QualType ParamType = Param->getType().getNonReferenceType();
4461 
4462     Expr *CopyCtorArg =
4463       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4464                           SourceLocation(), Param, false,
4465                           Constructor->getLocation(), ParamType,
4466                           VK_LValue, nullptr);
4467 
4468     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4469 
4470     // Cast to the base class to avoid ambiguities.
4471     QualType ArgTy =
4472       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4473                                        ParamType.getQualifiers());
4474 
4475     if (Moving) {
4476       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4477     }
4478 
4479     CXXCastPath BasePath;
4480     BasePath.push_back(BaseSpec);
4481     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4482                                             CK_UncheckedDerivedToBase,
4483                                             Moving ? VK_XValue : VK_LValue,
4484                                             &BasePath).get();
4485 
4486     InitializationKind InitKind
4487       = InitializationKind::CreateDirect(Constructor->getLocation(),
4488                                          SourceLocation(), SourceLocation());
4489     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4490     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4491     break;
4492   }
4493   }
4494 
4495   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4496   if (BaseInit.isInvalid())
4497     return true;
4498 
4499   CXXBaseInit =
4500     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4501                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4502                                                         SourceLocation()),
4503                                              BaseSpec->isVirtual(),
4504                                              SourceLocation(),
4505                                              BaseInit.getAs<Expr>(),
4506                                              SourceLocation(),
4507                                              SourceLocation());
4508 
4509   return false;
4510 }
4511 
4512 static bool RefersToRValueRef(Expr *MemRef) {
4513   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4514   return Referenced->getType()->isRValueReferenceType();
4515 }
4516 
4517 static bool
4518 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4519                                ImplicitInitializerKind ImplicitInitKind,
4520                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4521                                CXXCtorInitializer *&CXXMemberInit) {
4522   if (Field->isInvalidDecl())
4523     return true;
4524 
4525   SourceLocation Loc = Constructor->getLocation();
4526 
4527   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4528     bool Moving = ImplicitInitKind == IIK_Move;
4529     ParmVarDecl *Param = Constructor->getParamDecl(0);
4530     QualType ParamType = Param->getType().getNonReferenceType();
4531 
4532     // Suppress copying zero-width bitfields.
4533     if (Field->isZeroLengthBitField(SemaRef.Context))
4534       return false;
4535 
4536     Expr *MemberExprBase =
4537       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4538                           SourceLocation(), Param, false,
4539                           Loc, ParamType, VK_LValue, nullptr);
4540 
4541     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4542 
4543     if (Moving) {
4544       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4545     }
4546 
4547     // Build a reference to this field within the parameter.
4548     CXXScopeSpec SS;
4549     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4550                               Sema::LookupMemberName);
4551     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4552                                   : cast<ValueDecl>(Field), AS_public);
4553     MemberLookup.resolveKind();
4554     ExprResult CtorArg
4555       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4556                                          ParamType, Loc,
4557                                          /*IsArrow=*/false,
4558                                          SS,
4559                                          /*TemplateKWLoc=*/SourceLocation(),
4560                                          /*FirstQualifierInScope=*/nullptr,
4561                                          MemberLookup,
4562                                          /*TemplateArgs=*/nullptr,
4563                                          /*S*/nullptr);
4564     if (CtorArg.isInvalid())
4565       return true;
4566 
4567     // C++11 [class.copy]p15:
4568     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4569     //     with static_cast<T&&>(x.m);
4570     if (RefersToRValueRef(CtorArg.get())) {
4571       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4572     }
4573 
4574     InitializedEntity Entity =
4575         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4576                                                        /*Implicit*/ true)
4577                  : InitializedEntity::InitializeMember(Field, nullptr,
4578                                                        /*Implicit*/ true);
4579 
4580     // Direct-initialize to use the copy constructor.
4581     InitializationKind InitKind =
4582       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4583 
4584     Expr *CtorArgE = CtorArg.getAs<Expr>();
4585     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4586     ExprResult MemberInit =
4587         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4588     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4589     if (MemberInit.isInvalid())
4590       return true;
4591 
4592     if (Indirect)
4593       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4594           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4595     else
4596       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4597           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4598     return false;
4599   }
4600 
4601   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4602          "Unhandled implicit init kind!");
4603 
4604   QualType FieldBaseElementType =
4605     SemaRef.Context.getBaseElementType(Field->getType());
4606 
4607   if (FieldBaseElementType->isRecordType()) {
4608     InitializedEntity InitEntity =
4609         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4610                                                        /*Implicit*/ true)
4611                  : InitializedEntity::InitializeMember(Field, nullptr,
4612                                                        /*Implicit*/ true);
4613     InitializationKind InitKind =
4614       InitializationKind::CreateDefault(Loc);
4615 
4616     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4617     ExprResult MemberInit =
4618       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4619 
4620     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4621     if (MemberInit.isInvalid())
4622       return true;
4623 
4624     if (Indirect)
4625       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4626                                                                Indirect, Loc,
4627                                                                Loc,
4628                                                                MemberInit.get(),
4629                                                                Loc);
4630     else
4631       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4632                                                                Field, Loc, Loc,
4633                                                                MemberInit.get(),
4634                                                                Loc);
4635     return false;
4636   }
4637 
4638   if (!Field->getParent()->isUnion()) {
4639     if (FieldBaseElementType->isReferenceType()) {
4640       SemaRef.Diag(Constructor->getLocation(),
4641                    diag::err_uninitialized_member_in_ctor)
4642       << (int)Constructor->isImplicit()
4643       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4644       << 0 << Field->getDeclName();
4645       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4646       return true;
4647     }
4648 
4649     if (FieldBaseElementType.isConstQualified()) {
4650       SemaRef.Diag(Constructor->getLocation(),
4651                    diag::err_uninitialized_member_in_ctor)
4652       << (int)Constructor->isImplicit()
4653       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4654       << 1 << Field->getDeclName();
4655       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4656       return true;
4657     }
4658   }
4659 
4660   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4661     // ARC and Weak:
4662     //   Default-initialize Objective-C pointers to NULL.
4663     CXXMemberInit
4664       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4665                                                  Loc, Loc,
4666                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4667                                                  Loc);
4668     return false;
4669   }
4670 
4671   // Nothing to initialize.
4672   CXXMemberInit = nullptr;
4673   return false;
4674 }
4675 
4676 namespace {
4677 struct BaseAndFieldInfo {
4678   Sema &S;
4679   CXXConstructorDecl *Ctor;
4680   bool AnyErrorsInInits;
4681   ImplicitInitializerKind IIK;
4682   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4683   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4684   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4685 
4686   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4687     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4688     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4689     if (Ctor->getInheritedConstructor())
4690       IIK = IIK_Inherit;
4691     else if (Generated && Ctor->isCopyConstructor())
4692       IIK = IIK_Copy;
4693     else if (Generated && Ctor->isMoveConstructor())
4694       IIK = IIK_Move;
4695     else
4696       IIK = IIK_Default;
4697   }
4698 
4699   bool isImplicitCopyOrMove() const {
4700     switch (IIK) {
4701     case IIK_Copy:
4702     case IIK_Move:
4703       return true;
4704 
4705     case IIK_Default:
4706     case IIK_Inherit:
4707       return false;
4708     }
4709 
4710     llvm_unreachable("Invalid ImplicitInitializerKind!");
4711   }
4712 
4713   bool addFieldInitializer(CXXCtorInitializer *Init) {
4714     AllToInit.push_back(Init);
4715 
4716     // Check whether this initializer makes the field "used".
4717     if (Init->getInit()->HasSideEffects(S.Context))
4718       S.UnusedPrivateFields.remove(Init->getAnyMember());
4719 
4720     return false;
4721   }
4722 
4723   bool isInactiveUnionMember(FieldDecl *Field) {
4724     RecordDecl *Record = Field->getParent();
4725     if (!Record->isUnion())
4726       return false;
4727 
4728     if (FieldDecl *Active =
4729             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4730       return Active != Field->getCanonicalDecl();
4731 
4732     // In an implicit copy or move constructor, ignore any in-class initializer.
4733     if (isImplicitCopyOrMove())
4734       return true;
4735 
4736     // If there's no explicit initialization, the field is active only if it
4737     // has an in-class initializer...
4738     if (Field->hasInClassInitializer())
4739       return false;
4740     // ... or it's an anonymous struct or union whose class has an in-class
4741     // initializer.
4742     if (!Field->isAnonymousStructOrUnion())
4743       return true;
4744     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4745     return !FieldRD->hasInClassInitializer();
4746   }
4747 
4748   /// Determine whether the given field is, or is within, a union member
4749   /// that is inactive (because there was an initializer given for a different
4750   /// member of the union, or because the union was not initialized at all).
4751   bool isWithinInactiveUnionMember(FieldDecl *Field,
4752                                    IndirectFieldDecl *Indirect) {
4753     if (!Indirect)
4754       return isInactiveUnionMember(Field);
4755 
4756     for (auto *C : Indirect->chain()) {
4757       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4758       if (Field && isInactiveUnionMember(Field))
4759         return true;
4760     }
4761     return false;
4762   }
4763 };
4764 }
4765 
4766 /// Determine whether the given type is an incomplete or zero-lenfgth
4767 /// array type.
4768 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4769   if (T->isIncompleteArrayType())
4770     return true;
4771 
4772   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4773     if (!ArrayT->getSize())
4774       return true;
4775 
4776     T = ArrayT->getElementType();
4777   }
4778 
4779   return false;
4780 }
4781 
4782 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4783                                     FieldDecl *Field,
4784                                     IndirectFieldDecl *Indirect = nullptr) {
4785   if (Field->isInvalidDecl())
4786     return false;
4787 
4788   // Overwhelmingly common case: we have a direct initializer for this field.
4789   if (CXXCtorInitializer *Init =
4790           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4791     return Info.addFieldInitializer(Init);
4792 
4793   // C++11 [class.base.init]p8:
4794   //   if the entity is a non-static data member that has a
4795   //   brace-or-equal-initializer and either
4796   //   -- the constructor's class is a union and no other variant member of that
4797   //      union is designated by a mem-initializer-id or
4798   //   -- the constructor's class is not a union, and, if the entity is a member
4799   //      of an anonymous union, no other member of that union is designated by
4800   //      a mem-initializer-id,
4801   //   the entity is initialized as specified in [dcl.init].
4802   //
4803   // We also apply the same rules to handle anonymous structs within anonymous
4804   // unions.
4805   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4806     return false;
4807 
4808   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4809     ExprResult DIE =
4810         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4811     if (DIE.isInvalid())
4812       return true;
4813 
4814     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4815     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4816 
4817     CXXCtorInitializer *Init;
4818     if (Indirect)
4819       Init = new (SemaRef.Context)
4820           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4821                              SourceLocation(), DIE.get(), SourceLocation());
4822     else
4823       Init = new (SemaRef.Context)
4824           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4825                              SourceLocation(), DIE.get(), SourceLocation());
4826     return Info.addFieldInitializer(Init);
4827   }
4828 
4829   // Don't initialize incomplete or zero-length arrays.
4830   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4831     return false;
4832 
4833   // Don't try to build an implicit initializer if there were semantic
4834   // errors in any of the initializers (and therefore we might be
4835   // missing some that the user actually wrote).
4836   if (Info.AnyErrorsInInits)
4837     return false;
4838 
4839   CXXCtorInitializer *Init = nullptr;
4840   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4841                                      Indirect, Init))
4842     return true;
4843 
4844   if (!Init)
4845     return false;
4846 
4847   return Info.addFieldInitializer(Init);
4848 }
4849 
4850 bool
4851 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4852                                CXXCtorInitializer *Initializer) {
4853   assert(Initializer->isDelegatingInitializer());
4854   Constructor->setNumCtorInitializers(1);
4855   CXXCtorInitializer **initializer =
4856     new (Context) CXXCtorInitializer*[1];
4857   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4858   Constructor->setCtorInitializers(initializer);
4859 
4860   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4861     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4862     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4863   }
4864 
4865   DelegatingCtorDecls.push_back(Constructor);
4866 
4867   DiagnoseUninitializedFields(*this, Constructor);
4868 
4869   return false;
4870 }
4871 
4872 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4873                                ArrayRef<CXXCtorInitializer *> Initializers) {
4874   if (Constructor->isDependentContext()) {
4875     // Just store the initializers as written, they will be checked during
4876     // instantiation.
4877     if (!Initializers.empty()) {
4878       Constructor->setNumCtorInitializers(Initializers.size());
4879       CXXCtorInitializer **baseOrMemberInitializers =
4880         new (Context) CXXCtorInitializer*[Initializers.size()];
4881       memcpy(baseOrMemberInitializers, Initializers.data(),
4882              Initializers.size() * sizeof(CXXCtorInitializer*));
4883       Constructor->setCtorInitializers(baseOrMemberInitializers);
4884     }
4885 
4886     // Let template instantiation know whether we had errors.
4887     if (AnyErrors)
4888       Constructor->setInvalidDecl();
4889 
4890     return false;
4891   }
4892 
4893   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4894 
4895   // We need to build the initializer AST according to order of construction
4896   // and not what user specified in the Initializers list.
4897   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4898   if (!ClassDecl)
4899     return true;
4900 
4901   bool HadError = false;
4902 
4903   for (unsigned i = 0; i < Initializers.size(); i++) {
4904     CXXCtorInitializer *Member = Initializers[i];
4905 
4906     if (Member->isBaseInitializer())
4907       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4908     else {
4909       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4910 
4911       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4912         for (auto *C : F->chain()) {
4913           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4914           if (FD && FD->getParent()->isUnion())
4915             Info.ActiveUnionMember.insert(std::make_pair(
4916                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4917         }
4918       } else if (FieldDecl *FD = Member->getMember()) {
4919         if (FD->getParent()->isUnion())
4920           Info.ActiveUnionMember.insert(std::make_pair(
4921               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4922       }
4923     }
4924   }
4925 
4926   // Keep track of the direct virtual bases.
4927   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4928   for (auto &I : ClassDecl->bases()) {
4929     if (I.isVirtual())
4930       DirectVBases.insert(&I);
4931   }
4932 
4933   // Push virtual bases before others.
4934   for (auto &VBase : ClassDecl->vbases()) {
4935     if (CXXCtorInitializer *Value
4936         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4937       // [class.base.init]p7, per DR257:
4938       //   A mem-initializer where the mem-initializer-id names a virtual base
4939       //   class is ignored during execution of a constructor of any class that
4940       //   is not the most derived class.
4941       if (ClassDecl->isAbstract()) {
4942         // FIXME: Provide a fixit to remove the base specifier. This requires
4943         // tracking the location of the associated comma for a base specifier.
4944         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4945           << VBase.getType() << ClassDecl;
4946         DiagnoseAbstractType(ClassDecl);
4947       }
4948 
4949       Info.AllToInit.push_back(Value);
4950     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4951       // [class.base.init]p8, per DR257:
4952       //   If a given [...] base class is not named by a mem-initializer-id
4953       //   [...] and the entity is not a virtual base class of an abstract
4954       //   class, then [...] the entity is default-initialized.
4955       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4956       CXXCtorInitializer *CXXBaseInit;
4957       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4958                                        &VBase, IsInheritedVirtualBase,
4959                                        CXXBaseInit)) {
4960         HadError = true;
4961         continue;
4962       }
4963 
4964       Info.AllToInit.push_back(CXXBaseInit);
4965     }
4966   }
4967 
4968   // Non-virtual bases.
4969   for (auto &Base : ClassDecl->bases()) {
4970     // Virtuals are in the virtual base list and already constructed.
4971     if (Base.isVirtual())
4972       continue;
4973 
4974     if (CXXCtorInitializer *Value
4975           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4976       Info.AllToInit.push_back(Value);
4977     } else if (!AnyErrors) {
4978       CXXCtorInitializer *CXXBaseInit;
4979       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4980                                        &Base, /*IsInheritedVirtualBase=*/false,
4981                                        CXXBaseInit)) {
4982         HadError = true;
4983         continue;
4984       }
4985 
4986       Info.AllToInit.push_back(CXXBaseInit);
4987     }
4988   }
4989 
4990   // Fields.
4991   for (auto *Mem : ClassDecl->decls()) {
4992     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4993       // C++ [class.bit]p2:
4994       //   A declaration for a bit-field that omits the identifier declares an
4995       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4996       //   initialized.
4997       if (F->isUnnamedBitfield())
4998         continue;
4999 
5000       // If we're not generating the implicit copy/move constructor, then we'll
5001       // handle anonymous struct/union fields based on their individual
5002       // indirect fields.
5003       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5004         continue;
5005 
5006       if (CollectFieldInitializer(*this, Info, F))
5007         HadError = true;
5008       continue;
5009     }
5010 
5011     // Beyond this point, we only consider default initialization.
5012     if (Info.isImplicitCopyOrMove())
5013       continue;
5014 
5015     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5016       if (F->getType()->isIncompleteArrayType()) {
5017         assert(ClassDecl->hasFlexibleArrayMember() &&
5018                "Incomplete array type is not valid");
5019         continue;
5020       }
5021 
5022       // Initialize each field of an anonymous struct individually.
5023       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5024         HadError = true;
5025 
5026       continue;
5027     }
5028   }
5029 
5030   unsigned NumInitializers = Info.AllToInit.size();
5031   if (NumInitializers > 0) {
5032     Constructor->setNumCtorInitializers(NumInitializers);
5033     CXXCtorInitializer **baseOrMemberInitializers =
5034       new (Context) CXXCtorInitializer*[NumInitializers];
5035     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5036            NumInitializers * sizeof(CXXCtorInitializer*));
5037     Constructor->setCtorInitializers(baseOrMemberInitializers);
5038 
5039     // Constructors implicitly reference the base and member
5040     // destructors.
5041     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5042                                            Constructor->getParent());
5043   }
5044 
5045   return HadError;
5046 }
5047 
5048 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5049   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5050     const RecordDecl *RD = RT->getDecl();
5051     if (RD->isAnonymousStructOrUnion()) {
5052       for (auto *Field : RD->fields())
5053         PopulateKeysForFields(Field, IdealInits);
5054       return;
5055     }
5056   }
5057   IdealInits.push_back(Field->getCanonicalDecl());
5058 }
5059 
5060 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5061   return Context.getCanonicalType(BaseType).getTypePtr();
5062 }
5063 
5064 static const void *GetKeyForMember(ASTContext &Context,
5065                                    CXXCtorInitializer *Member) {
5066   if (!Member->isAnyMemberInitializer())
5067     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5068 
5069   return Member->getAnyMember()->getCanonicalDecl();
5070 }
5071 
5072 static void DiagnoseBaseOrMemInitializerOrder(
5073     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5074     ArrayRef<CXXCtorInitializer *> Inits) {
5075   if (Constructor->getDeclContext()->isDependentContext())
5076     return;
5077 
5078   // Don't check initializers order unless the warning is enabled at the
5079   // location of at least one initializer.
5080   bool ShouldCheckOrder = false;
5081   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5082     CXXCtorInitializer *Init = Inits[InitIndex];
5083     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5084                                  Init->getSourceLocation())) {
5085       ShouldCheckOrder = true;
5086       break;
5087     }
5088   }
5089   if (!ShouldCheckOrder)
5090     return;
5091 
5092   // Build the list of bases and members in the order that they'll
5093   // actually be initialized.  The explicit initializers should be in
5094   // this same order but may be missing things.
5095   SmallVector<const void*, 32> IdealInitKeys;
5096 
5097   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5098 
5099   // 1. Virtual bases.
5100   for (const auto &VBase : ClassDecl->vbases())
5101     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5102 
5103   // 2. Non-virtual bases.
5104   for (const auto &Base : ClassDecl->bases()) {
5105     if (Base.isVirtual())
5106       continue;
5107     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5108   }
5109 
5110   // 3. Direct fields.
5111   for (auto *Field : ClassDecl->fields()) {
5112     if (Field->isUnnamedBitfield())
5113       continue;
5114 
5115     PopulateKeysForFields(Field, IdealInitKeys);
5116   }
5117 
5118   unsigned NumIdealInits = IdealInitKeys.size();
5119   unsigned IdealIndex = 0;
5120 
5121   CXXCtorInitializer *PrevInit = nullptr;
5122   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5123     CXXCtorInitializer *Init = Inits[InitIndex];
5124     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5125 
5126     // Scan forward to try to find this initializer in the idealized
5127     // initializers list.
5128     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5129       if (InitKey == IdealInitKeys[IdealIndex])
5130         break;
5131 
5132     // If we didn't find this initializer, it must be because we
5133     // scanned past it on a previous iteration.  That can only
5134     // happen if we're out of order;  emit a warning.
5135     if (IdealIndex == NumIdealInits && PrevInit) {
5136       Sema::SemaDiagnosticBuilder D =
5137         SemaRef.Diag(PrevInit->getSourceLocation(),
5138                      diag::warn_initializer_out_of_order);
5139 
5140       if (PrevInit->isAnyMemberInitializer())
5141         D << 0 << PrevInit->getAnyMember()->getDeclName();
5142       else
5143         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5144 
5145       if (Init->isAnyMemberInitializer())
5146         D << 0 << Init->getAnyMember()->getDeclName();
5147       else
5148         D << 1 << Init->getTypeSourceInfo()->getType();
5149 
5150       // Move back to the initializer's location in the ideal list.
5151       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5152         if (InitKey == IdealInitKeys[IdealIndex])
5153           break;
5154 
5155       assert(IdealIndex < NumIdealInits &&
5156              "initializer not found in initializer list");
5157     }
5158 
5159     PrevInit = Init;
5160   }
5161 }
5162 
5163 namespace {
5164 bool CheckRedundantInit(Sema &S,
5165                         CXXCtorInitializer *Init,
5166                         CXXCtorInitializer *&PrevInit) {
5167   if (!PrevInit) {
5168     PrevInit = Init;
5169     return false;
5170   }
5171 
5172   if (FieldDecl *Field = Init->getAnyMember())
5173     S.Diag(Init->getSourceLocation(),
5174            diag::err_multiple_mem_initialization)
5175       << Field->getDeclName()
5176       << Init->getSourceRange();
5177   else {
5178     const Type *BaseClass = Init->getBaseClass();
5179     assert(BaseClass && "neither field nor base");
5180     S.Diag(Init->getSourceLocation(),
5181            diag::err_multiple_base_initialization)
5182       << QualType(BaseClass, 0)
5183       << Init->getSourceRange();
5184   }
5185   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5186     << 0 << PrevInit->getSourceRange();
5187 
5188   return true;
5189 }
5190 
5191 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5192 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5193 
5194 bool CheckRedundantUnionInit(Sema &S,
5195                              CXXCtorInitializer *Init,
5196                              RedundantUnionMap &Unions) {
5197   FieldDecl *Field = Init->getAnyMember();
5198   RecordDecl *Parent = Field->getParent();
5199   NamedDecl *Child = Field;
5200 
5201   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5202     if (Parent->isUnion()) {
5203       UnionEntry &En = Unions[Parent];
5204       if (En.first && En.first != Child) {
5205         S.Diag(Init->getSourceLocation(),
5206                diag::err_multiple_mem_union_initialization)
5207           << Field->getDeclName()
5208           << Init->getSourceRange();
5209         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5210           << 0 << En.second->getSourceRange();
5211         return true;
5212       }
5213       if (!En.first) {
5214         En.first = Child;
5215         En.second = Init;
5216       }
5217       if (!Parent->isAnonymousStructOrUnion())
5218         return false;
5219     }
5220 
5221     Child = Parent;
5222     Parent = cast<RecordDecl>(Parent->getDeclContext());
5223   }
5224 
5225   return false;
5226 }
5227 }
5228 
5229 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5230 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5231                                 SourceLocation ColonLoc,
5232                                 ArrayRef<CXXCtorInitializer*> MemInits,
5233                                 bool AnyErrors) {
5234   if (!ConstructorDecl)
5235     return;
5236 
5237   AdjustDeclIfTemplate(ConstructorDecl);
5238 
5239   CXXConstructorDecl *Constructor
5240     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5241 
5242   if (!Constructor) {
5243     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5244     return;
5245   }
5246 
5247   // Mapping for the duplicate initializers check.
5248   // For member initializers, this is keyed with a FieldDecl*.
5249   // For base initializers, this is keyed with a Type*.
5250   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5251 
5252   // Mapping for the inconsistent anonymous-union initializers check.
5253   RedundantUnionMap MemberUnions;
5254 
5255   bool HadError = false;
5256   for (unsigned i = 0; i < MemInits.size(); i++) {
5257     CXXCtorInitializer *Init = MemInits[i];
5258 
5259     // Set the source order index.
5260     Init->setSourceOrder(i);
5261 
5262     if (Init->isAnyMemberInitializer()) {
5263       const void *Key = GetKeyForMember(Context, Init);
5264       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5265           CheckRedundantUnionInit(*this, Init, MemberUnions))
5266         HadError = true;
5267     } else if (Init->isBaseInitializer()) {
5268       const void *Key = GetKeyForMember(Context, Init);
5269       if (CheckRedundantInit(*this, Init, Members[Key]))
5270         HadError = true;
5271     } else {
5272       assert(Init->isDelegatingInitializer());
5273       // This must be the only initializer
5274       if (MemInits.size() != 1) {
5275         Diag(Init->getSourceLocation(),
5276              diag::err_delegating_initializer_alone)
5277           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5278         // We will treat this as being the only initializer.
5279       }
5280       SetDelegatingInitializer(Constructor, MemInits[i]);
5281       // Return immediately as the initializer is set.
5282       return;
5283     }
5284   }
5285 
5286   if (HadError)
5287     return;
5288 
5289   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5290 
5291   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5292 
5293   DiagnoseUninitializedFields(*this, Constructor);
5294 }
5295 
5296 void
5297 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5298                                              CXXRecordDecl *ClassDecl) {
5299   // Ignore dependent contexts. Also ignore unions, since their members never
5300   // have destructors implicitly called.
5301   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5302     return;
5303 
5304   // FIXME: all the access-control diagnostics are positioned on the
5305   // field/base declaration.  That's probably good; that said, the
5306   // user might reasonably want to know why the destructor is being
5307   // emitted, and we currently don't say.
5308 
5309   // Non-static data members.
5310   for (auto *Field : ClassDecl->fields()) {
5311     if (Field->isInvalidDecl())
5312       continue;
5313 
5314     // Don't destroy incomplete or zero-length arrays.
5315     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5316       continue;
5317 
5318     QualType FieldType = Context.getBaseElementType(Field->getType());
5319 
5320     const RecordType* RT = FieldType->getAs<RecordType>();
5321     if (!RT)
5322       continue;
5323 
5324     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5325     if (FieldClassDecl->isInvalidDecl())
5326       continue;
5327     if (FieldClassDecl->hasIrrelevantDestructor())
5328       continue;
5329     // The destructor for an implicit anonymous union member is never invoked.
5330     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5331       continue;
5332 
5333     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5334     assert(Dtor && "No dtor found for FieldClassDecl!");
5335     CheckDestructorAccess(Field->getLocation(), Dtor,
5336                           PDiag(diag::err_access_dtor_field)
5337                             << Field->getDeclName()
5338                             << FieldType);
5339 
5340     MarkFunctionReferenced(Location, Dtor);
5341     DiagnoseUseOfDecl(Dtor, Location);
5342   }
5343 
5344   // We only potentially invoke the destructors of potentially constructed
5345   // subobjects.
5346   bool VisitVirtualBases = !ClassDecl->isAbstract();
5347 
5348   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5349 
5350   // Bases.
5351   for (const auto &Base : ClassDecl->bases()) {
5352     // Bases are always records in a well-formed non-dependent class.
5353     const RecordType *RT = Base.getType()->getAs<RecordType>();
5354 
5355     // Remember direct virtual bases.
5356     if (Base.isVirtual()) {
5357       if (!VisitVirtualBases)
5358         continue;
5359       DirectVirtualBases.insert(RT);
5360     }
5361 
5362     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5363     // If our base class is invalid, we probably can't get its dtor anyway.
5364     if (BaseClassDecl->isInvalidDecl())
5365       continue;
5366     if (BaseClassDecl->hasIrrelevantDestructor())
5367       continue;
5368 
5369     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5370     assert(Dtor && "No dtor found for BaseClassDecl!");
5371 
5372     // FIXME: caret should be on the start of the class name
5373     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5374                           PDiag(diag::err_access_dtor_base)
5375                               << Base.getType() << Base.getSourceRange(),
5376                           Context.getTypeDeclType(ClassDecl));
5377 
5378     MarkFunctionReferenced(Location, Dtor);
5379     DiagnoseUseOfDecl(Dtor, Location);
5380   }
5381 
5382   if (!VisitVirtualBases)
5383     return;
5384 
5385   // Virtual bases.
5386   for (const auto &VBase : ClassDecl->vbases()) {
5387     // Bases are always records in a well-formed non-dependent class.
5388     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5389 
5390     // Ignore direct virtual bases.
5391     if (DirectVirtualBases.count(RT))
5392       continue;
5393 
5394     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5395     // If our base class is invalid, we probably can't get its dtor anyway.
5396     if (BaseClassDecl->isInvalidDecl())
5397       continue;
5398     if (BaseClassDecl->hasIrrelevantDestructor())
5399       continue;
5400 
5401     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5402     assert(Dtor && "No dtor found for BaseClassDecl!");
5403     if (CheckDestructorAccess(
5404             ClassDecl->getLocation(), Dtor,
5405             PDiag(diag::err_access_dtor_vbase)
5406                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5407             Context.getTypeDeclType(ClassDecl)) ==
5408         AR_accessible) {
5409       CheckDerivedToBaseConversion(
5410           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5411           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5412           SourceRange(), DeclarationName(), nullptr);
5413     }
5414 
5415     MarkFunctionReferenced(Location, Dtor);
5416     DiagnoseUseOfDecl(Dtor, Location);
5417   }
5418 }
5419 
5420 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5421   if (!CDtorDecl)
5422     return;
5423 
5424   if (CXXConstructorDecl *Constructor
5425       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5426     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5427     DiagnoseUninitializedFields(*this, Constructor);
5428   }
5429 }
5430 
5431 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5432   if (!getLangOpts().CPlusPlus)
5433     return false;
5434 
5435   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5436   if (!RD)
5437     return false;
5438 
5439   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5440   // class template specialization here, but doing so breaks a lot of code.
5441 
5442   // We can't answer whether something is abstract until it has a
5443   // definition. If it's currently being defined, we'll walk back
5444   // over all the declarations when we have a full definition.
5445   const CXXRecordDecl *Def = RD->getDefinition();
5446   if (!Def || Def->isBeingDefined())
5447     return false;
5448 
5449   return RD->isAbstract();
5450 }
5451 
5452 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5453                                   TypeDiagnoser &Diagnoser) {
5454   if (!isAbstractType(Loc, T))
5455     return false;
5456 
5457   T = Context.getBaseElementType(T);
5458   Diagnoser.diagnose(*this, Loc, T);
5459   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5460   return true;
5461 }
5462 
5463 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5464   // Check if we've already emitted the list of pure virtual functions
5465   // for this class.
5466   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5467     return;
5468 
5469   // If the diagnostic is suppressed, don't emit the notes. We're only
5470   // going to emit them once, so try to attach them to a diagnostic we're
5471   // actually going to show.
5472   if (Diags.isLastDiagnosticIgnored())
5473     return;
5474 
5475   CXXFinalOverriderMap FinalOverriders;
5476   RD->getFinalOverriders(FinalOverriders);
5477 
5478   // Keep a set of seen pure methods so we won't diagnose the same method
5479   // more than once.
5480   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5481 
5482   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5483                                    MEnd = FinalOverriders.end();
5484        M != MEnd;
5485        ++M) {
5486     for (OverridingMethods::iterator SO = M->second.begin(),
5487                                   SOEnd = M->second.end();
5488          SO != SOEnd; ++SO) {
5489       // C++ [class.abstract]p4:
5490       //   A class is abstract if it contains or inherits at least one
5491       //   pure virtual function for which the final overrider is pure
5492       //   virtual.
5493 
5494       //
5495       if (SO->second.size() != 1)
5496         continue;
5497 
5498       if (!SO->second.front().Method->isPure())
5499         continue;
5500 
5501       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5502         continue;
5503 
5504       Diag(SO->second.front().Method->getLocation(),
5505            diag::note_pure_virtual_function)
5506         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5507     }
5508   }
5509 
5510   if (!PureVirtualClassDiagSet)
5511     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5512   PureVirtualClassDiagSet->insert(RD);
5513 }
5514 
5515 namespace {
5516 struct AbstractUsageInfo {
5517   Sema &S;
5518   CXXRecordDecl *Record;
5519   CanQualType AbstractType;
5520   bool Invalid;
5521 
5522   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5523     : S(S), Record(Record),
5524       AbstractType(S.Context.getCanonicalType(
5525                    S.Context.getTypeDeclType(Record))),
5526       Invalid(false) {}
5527 
5528   void DiagnoseAbstractType() {
5529     if (Invalid) return;
5530     S.DiagnoseAbstractType(Record);
5531     Invalid = true;
5532   }
5533 
5534   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5535 };
5536 
5537 struct CheckAbstractUsage {
5538   AbstractUsageInfo &Info;
5539   const NamedDecl *Ctx;
5540 
5541   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5542     : Info(Info), Ctx(Ctx) {}
5543 
5544   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5545     switch (TL.getTypeLocClass()) {
5546 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5547 #define TYPELOC(CLASS, PARENT) \
5548     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5549 #include "clang/AST/TypeLocNodes.def"
5550     }
5551   }
5552 
5553   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5554     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5555     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5556       if (!TL.getParam(I))
5557         continue;
5558 
5559       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5560       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5561     }
5562   }
5563 
5564   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5565     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5566   }
5567 
5568   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5569     // Visit the type parameters from a permissive context.
5570     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5571       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5572       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5573         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5574           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5575       // TODO: other template argument types?
5576     }
5577   }
5578 
5579   // Visit pointee types from a permissive context.
5580 #define CheckPolymorphic(Type) \
5581   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5582     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5583   }
5584   CheckPolymorphic(PointerTypeLoc)
5585   CheckPolymorphic(ReferenceTypeLoc)
5586   CheckPolymorphic(MemberPointerTypeLoc)
5587   CheckPolymorphic(BlockPointerTypeLoc)
5588   CheckPolymorphic(AtomicTypeLoc)
5589 
5590   /// Handle all the types we haven't given a more specific
5591   /// implementation for above.
5592   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5593     // Every other kind of type that we haven't called out already
5594     // that has an inner type is either (1) sugar or (2) contains that
5595     // inner type in some way as a subobject.
5596     if (TypeLoc Next = TL.getNextTypeLoc())
5597       return Visit(Next, Sel);
5598 
5599     // If there's no inner type and we're in a permissive context,
5600     // don't diagnose.
5601     if (Sel == Sema::AbstractNone) return;
5602 
5603     // Check whether the type matches the abstract type.
5604     QualType T = TL.getType();
5605     if (T->isArrayType()) {
5606       Sel = Sema::AbstractArrayType;
5607       T = Info.S.Context.getBaseElementType(T);
5608     }
5609     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5610     if (CT != Info.AbstractType) return;
5611 
5612     // It matched; do some magic.
5613     if (Sel == Sema::AbstractArrayType) {
5614       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5615         << T << TL.getSourceRange();
5616     } else {
5617       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5618         << Sel << T << TL.getSourceRange();
5619     }
5620     Info.DiagnoseAbstractType();
5621   }
5622 };
5623 
5624 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5625                                   Sema::AbstractDiagSelID Sel) {
5626   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5627 }
5628 
5629 }
5630 
5631 /// Check for invalid uses of an abstract type in a method declaration.
5632 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5633                                     CXXMethodDecl *MD) {
5634   // No need to do the check on definitions, which require that
5635   // the return/param types be complete.
5636   if (MD->doesThisDeclarationHaveABody())
5637     return;
5638 
5639   // For safety's sake, just ignore it if we don't have type source
5640   // information.  This should never happen for non-implicit methods,
5641   // but...
5642   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5643     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5644 }
5645 
5646 /// Check for invalid uses of an abstract type within a class definition.
5647 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5648                                     CXXRecordDecl *RD) {
5649   for (auto *D : RD->decls()) {
5650     if (D->isImplicit()) continue;
5651 
5652     // Methods and method templates.
5653     if (isa<CXXMethodDecl>(D)) {
5654       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5655     } else if (isa<FunctionTemplateDecl>(D)) {
5656       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5657       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5658 
5659     // Fields and static variables.
5660     } else if (isa<FieldDecl>(D)) {
5661       FieldDecl *FD = cast<FieldDecl>(D);
5662       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5663         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5664     } else if (isa<VarDecl>(D)) {
5665       VarDecl *VD = cast<VarDecl>(D);
5666       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5667         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5668 
5669     // Nested classes and class templates.
5670     } else if (isa<CXXRecordDecl>(D)) {
5671       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5672     } else if (isa<ClassTemplateDecl>(D)) {
5673       CheckAbstractClassUsage(Info,
5674                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5675     }
5676   }
5677 }
5678 
5679 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5680   Attr *ClassAttr = getDLLAttr(Class);
5681   if (!ClassAttr)
5682     return;
5683 
5684   assert(ClassAttr->getKind() == attr::DLLExport);
5685 
5686   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5687 
5688   if (TSK == TSK_ExplicitInstantiationDeclaration)
5689     // Don't go any further if this is just an explicit instantiation
5690     // declaration.
5691     return;
5692 
5693   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5694     S.MarkVTableUsed(Class->getLocation(), Class, true);
5695 
5696   for (Decl *Member : Class->decls()) {
5697     // Defined static variables that are members of an exported base
5698     // class must be marked export too.
5699     auto *VD = dyn_cast<VarDecl>(Member);
5700     if (VD && Member->getAttr<DLLExportAttr>() &&
5701         VD->getStorageClass() == SC_Static &&
5702         TSK == TSK_ImplicitInstantiation)
5703       S.MarkVariableReferenced(VD->getLocation(), VD);
5704 
5705     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5706     if (!MD)
5707       continue;
5708 
5709     if (Member->getAttr<DLLExportAttr>()) {
5710       if (MD->isUserProvided()) {
5711         // Instantiate non-default class member functions ...
5712 
5713         // .. except for certain kinds of template specializations.
5714         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5715           continue;
5716 
5717         S.MarkFunctionReferenced(Class->getLocation(), MD);
5718 
5719         // The function will be passed to the consumer when its definition is
5720         // encountered.
5721       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5722                  MD->isCopyAssignmentOperator() ||
5723                  MD->isMoveAssignmentOperator()) {
5724         // Synthesize and instantiate non-trivial implicit methods, explicitly
5725         // defaulted methods, and the copy and move assignment operators. The
5726         // latter are exported even if they are trivial, because the address of
5727         // an operator can be taken and should compare equal across libraries.
5728         DiagnosticErrorTrap Trap(S.Diags);
5729         S.MarkFunctionReferenced(Class->getLocation(), MD);
5730         if (Trap.hasErrorOccurred()) {
5731           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5732               << Class << !S.getLangOpts().CPlusPlus11;
5733           break;
5734         }
5735 
5736         // There is no later point when we will see the definition of this
5737         // function, so pass it to the consumer now.
5738         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5739       }
5740     }
5741   }
5742 }
5743 
5744 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5745                                                         CXXRecordDecl *Class) {
5746   // Only the MS ABI has default constructor closures, so we don't need to do
5747   // this semantic checking anywhere else.
5748   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5749     return;
5750 
5751   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5752   for (Decl *Member : Class->decls()) {
5753     // Look for exported default constructors.
5754     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5755     if (!CD || !CD->isDefaultConstructor())
5756       continue;
5757     auto *Attr = CD->getAttr<DLLExportAttr>();
5758     if (!Attr)
5759       continue;
5760 
5761     // If the class is non-dependent, mark the default arguments as ODR-used so
5762     // that we can properly codegen the constructor closure.
5763     if (!Class->isDependentContext()) {
5764       for (ParmVarDecl *PD : CD->parameters()) {
5765         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5766         S.DiscardCleanupsInEvaluationContext();
5767       }
5768     }
5769 
5770     if (LastExportedDefaultCtor) {
5771       S.Diag(LastExportedDefaultCtor->getLocation(),
5772              diag::err_attribute_dll_ambiguous_default_ctor)
5773           << Class;
5774       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5775           << CD->getDeclName();
5776       return;
5777     }
5778     LastExportedDefaultCtor = CD;
5779   }
5780 }
5781 
5782 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5783   // Mark any compiler-generated routines with the implicit code_seg attribute.
5784   for (auto *Method : Class->methods()) {
5785     if (Method->isUserProvided())
5786       continue;
5787     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5788       Method->addAttr(A);
5789   }
5790 }
5791 
5792 /// Check class-level dllimport/dllexport attribute.
5793 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5794   Attr *ClassAttr = getDLLAttr(Class);
5795 
5796   // MSVC inherits DLL attributes to partial class template specializations.
5797   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5798     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5799       if (Attr *TemplateAttr =
5800               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5801         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5802         A->setInherited(true);
5803         ClassAttr = A;
5804       }
5805     }
5806   }
5807 
5808   if (!ClassAttr)
5809     return;
5810 
5811   if (!Class->isExternallyVisible()) {
5812     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5813         << Class << ClassAttr;
5814     return;
5815   }
5816 
5817   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5818       !ClassAttr->isInherited()) {
5819     // Diagnose dll attributes on members of class with dll attribute.
5820     for (Decl *Member : Class->decls()) {
5821       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5822         continue;
5823       InheritableAttr *MemberAttr = getDLLAttr(Member);
5824       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5825         continue;
5826 
5827       Diag(MemberAttr->getLocation(),
5828              diag::err_attribute_dll_member_of_dll_class)
5829           << MemberAttr << ClassAttr;
5830       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5831       Member->setInvalidDecl();
5832     }
5833   }
5834 
5835   if (Class->getDescribedClassTemplate())
5836     // Don't inherit dll attribute until the template is instantiated.
5837     return;
5838 
5839   // The class is either imported or exported.
5840   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5841 
5842   // Check if this was a dllimport attribute propagated from a derived class to
5843   // a base class template specialization. We don't apply these attributes to
5844   // static data members.
5845   const bool PropagatedImport =
5846       !ClassExported &&
5847       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5848 
5849   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5850 
5851   // Ignore explicit dllexport on explicit class template instantiation
5852   // declarations, except in MinGW mode.
5853   if (ClassExported && !ClassAttr->isInherited() &&
5854       TSK == TSK_ExplicitInstantiationDeclaration &&
5855       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
5856     Class->dropAttr<DLLExportAttr>();
5857     return;
5858   }
5859 
5860   // Force declaration of implicit members so they can inherit the attribute.
5861   ForceDeclarationOfImplicitMembers(Class);
5862 
5863   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5864   // seem to be true in practice?
5865 
5866   for (Decl *Member : Class->decls()) {
5867     VarDecl *VD = dyn_cast<VarDecl>(Member);
5868     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5869 
5870     // Only methods and static fields inherit the attributes.
5871     if (!VD && !MD)
5872       continue;
5873 
5874     if (MD) {
5875       // Don't process deleted methods.
5876       if (MD->isDeleted())
5877         continue;
5878 
5879       if (MD->isInlined()) {
5880         // MinGW does not import or export inline methods. But do it for
5881         // template instantiations.
5882         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5883             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
5884             TSK != TSK_ExplicitInstantiationDeclaration &&
5885             TSK != TSK_ExplicitInstantiationDefinition)
5886           continue;
5887 
5888         // MSVC versions before 2015 don't export the move assignment operators
5889         // and move constructor, so don't attempt to import/export them if
5890         // we have a definition.
5891         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5892         if ((MD->isMoveAssignmentOperator() ||
5893              (Ctor && Ctor->isMoveConstructor())) &&
5894             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5895           continue;
5896 
5897         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5898         // operator is exported anyway.
5899         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5900             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5901           continue;
5902       }
5903     }
5904 
5905     // Don't apply dllimport attributes to static data members of class template
5906     // instantiations when the attribute is propagated from a derived class.
5907     if (VD && PropagatedImport)
5908       continue;
5909 
5910     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5911       continue;
5912 
5913     if (!getDLLAttr(Member)) {
5914       InheritableAttr *NewAttr = nullptr;
5915 
5916       // Do not export/import inline function when -fno-dllexport-inlines is
5917       // passed. But add attribute for later local static var check.
5918       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5919           TSK != TSK_ExplicitInstantiationDeclaration &&
5920           TSK != TSK_ExplicitInstantiationDefinition) {
5921         if (ClassExported) {
5922           NewAttr = ::new (getASTContext())
5923             DLLExportStaticLocalAttr(ClassAttr->getRange(),
5924                                      getASTContext(),
5925                                      ClassAttr->getSpellingListIndex());
5926         } else {
5927           NewAttr = ::new (getASTContext())
5928             DLLImportStaticLocalAttr(ClassAttr->getRange(),
5929                                      getASTContext(),
5930                                      ClassAttr->getSpellingListIndex());
5931         }
5932       } else {
5933         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5934       }
5935 
5936       NewAttr->setInherited(true);
5937       Member->addAttr(NewAttr);
5938 
5939       if (MD) {
5940         // Propagate DLLAttr to friend re-declarations of MD that have already
5941         // been constructed.
5942         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5943              FD = FD->getPreviousDecl()) {
5944           if (FD->getFriendObjectKind() == Decl::FOK_None)
5945             continue;
5946           assert(!getDLLAttr(FD) &&
5947                  "friend re-decl should not already have a DLLAttr");
5948           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5949           NewAttr->setInherited(true);
5950           FD->addAttr(NewAttr);
5951         }
5952       }
5953     }
5954   }
5955 
5956   if (ClassExported)
5957     DelayedDllExportClasses.push_back(Class);
5958 }
5959 
5960 /// Perform propagation of DLL attributes from a derived class to a
5961 /// templated base class for MS compatibility.
5962 void Sema::propagateDLLAttrToBaseClassTemplate(
5963     CXXRecordDecl *Class, Attr *ClassAttr,
5964     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5965   if (getDLLAttr(
5966           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5967     // If the base class template has a DLL attribute, don't try to change it.
5968     return;
5969   }
5970 
5971   auto TSK = BaseTemplateSpec->getSpecializationKind();
5972   if (!getDLLAttr(BaseTemplateSpec) &&
5973       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5974        TSK == TSK_ImplicitInstantiation)) {
5975     // The template hasn't been instantiated yet (or it has, but only as an
5976     // explicit instantiation declaration or implicit instantiation, which means
5977     // we haven't codegenned any members yet), so propagate the attribute.
5978     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5979     NewAttr->setInherited(true);
5980     BaseTemplateSpec->addAttr(NewAttr);
5981 
5982     // If this was an import, mark that we propagated it from a derived class to
5983     // a base class template specialization.
5984     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5985       ImportAttr->setPropagatedToBaseTemplate();
5986 
5987     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5988     // needs to be run again to work see the new attribute. Otherwise this will
5989     // get run whenever the template is instantiated.
5990     if (TSK != TSK_Undeclared)
5991       checkClassLevelDLLAttribute(BaseTemplateSpec);
5992 
5993     return;
5994   }
5995 
5996   if (getDLLAttr(BaseTemplateSpec)) {
5997     // The template has already been specialized or instantiated with an
5998     // attribute, explicitly or through propagation. We should not try to change
5999     // it.
6000     return;
6001   }
6002 
6003   // The template was previously instantiated or explicitly specialized without
6004   // a dll attribute, It's too late for us to add an attribute, so warn that
6005   // this is unsupported.
6006   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6007       << BaseTemplateSpec->isExplicitSpecialization();
6008   Diag(ClassAttr->getLocation(), diag::note_attribute);
6009   if (BaseTemplateSpec->isExplicitSpecialization()) {
6010     Diag(BaseTemplateSpec->getLocation(),
6011            diag::note_template_class_explicit_specialization_was_here)
6012         << BaseTemplateSpec;
6013   } else {
6014     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6015            diag::note_template_class_instantiation_was_here)
6016         << BaseTemplateSpec;
6017   }
6018 }
6019 
6020 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
6021                                         SourceLocation DefaultLoc) {
6022   switch (S.getSpecialMember(MD)) {
6023   case Sema::CXXDefaultConstructor:
6024     S.DefineImplicitDefaultConstructor(DefaultLoc,
6025                                        cast<CXXConstructorDecl>(MD));
6026     break;
6027   case Sema::CXXCopyConstructor:
6028     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
6029     break;
6030   case Sema::CXXCopyAssignment:
6031     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
6032     break;
6033   case Sema::CXXDestructor:
6034     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
6035     break;
6036   case Sema::CXXMoveConstructor:
6037     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
6038     break;
6039   case Sema::CXXMoveAssignment:
6040     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
6041     break;
6042   case Sema::CXXInvalid:
6043     llvm_unreachable("Invalid special member.");
6044   }
6045 }
6046 
6047 /// Determine whether a type is permitted to be passed or returned in
6048 /// registers, per C++ [class.temporary]p3.
6049 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6050                                TargetInfo::CallingConvKind CCK) {
6051   if (D->isDependentType() || D->isInvalidDecl())
6052     return false;
6053 
6054   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6055   // The PS4 platform ABI follows the behavior of Clang 3.2.
6056   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6057     return !D->hasNonTrivialDestructorForCall() &&
6058            !D->hasNonTrivialCopyConstructorForCall();
6059 
6060   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6061     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6062     bool DtorIsTrivialForCall = false;
6063 
6064     // If a class has at least one non-deleted, trivial copy constructor, it
6065     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6066     //
6067     // Note: This permits classes with non-trivial copy or move ctors to be
6068     // passed in registers, so long as they *also* have a trivial copy ctor,
6069     // which is non-conforming.
6070     if (D->needsImplicitCopyConstructor()) {
6071       if (!D->defaultedCopyConstructorIsDeleted()) {
6072         if (D->hasTrivialCopyConstructor())
6073           CopyCtorIsTrivial = true;
6074         if (D->hasTrivialCopyConstructorForCall())
6075           CopyCtorIsTrivialForCall = true;
6076       }
6077     } else {
6078       for (const CXXConstructorDecl *CD : D->ctors()) {
6079         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6080           if (CD->isTrivial())
6081             CopyCtorIsTrivial = true;
6082           if (CD->isTrivialForCall())
6083             CopyCtorIsTrivialForCall = true;
6084         }
6085       }
6086     }
6087 
6088     if (D->needsImplicitDestructor()) {
6089       if (!D->defaultedDestructorIsDeleted() &&
6090           D->hasTrivialDestructorForCall())
6091         DtorIsTrivialForCall = true;
6092     } else if (const auto *DD = D->getDestructor()) {
6093       if (!DD->isDeleted() && DD->isTrivialForCall())
6094         DtorIsTrivialForCall = true;
6095     }
6096 
6097     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6098     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6099       return true;
6100 
6101     // If a class has a destructor, we'd really like to pass it indirectly
6102     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6103     // impossible for small types, which it will pass in a single register or
6104     // stack slot. Most objects with dtors are large-ish, so handle that early.
6105     // We can't call out all large objects as being indirect because there are
6106     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6107     // how we pass large POD types.
6108 
6109     // Note: This permits small classes with nontrivial destructors to be
6110     // passed in registers, which is non-conforming.
6111     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6112     uint64_t TypeSize = isAArch64 ? 128 : 64;
6113 
6114     if (CopyCtorIsTrivial &&
6115         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6116       return true;
6117     return false;
6118   }
6119 
6120   // Per C++ [class.temporary]p3, the relevant condition is:
6121   //   each copy constructor, move constructor, and destructor of X is
6122   //   either trivial or deleted, and X has at least one non-deleted copy
6123   //   or move constructor
6124   bool HasNonDeletedCopyOrMove = false;
6125 
6126   if (D->needsImplicitCopyConstructor() &&
6127       !D->defaultedCopyConstructorIsDeleted()) {
6128     if (!D->hasTrivialCopyConstructorForCall())
6129       return false;
6130     HasNonDeletedCopyOrMove = true;
6131   }
6132 
6133   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6134       !D->defaultedMoveConstructorIsDeleted()) {
6135     if (!D->hasTrivialMoveConstructorForCall())
6136       return false;
6137     HasNonDeletedCopyOrMove = true;
6138   }
6139 
6140   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6141       !D->hasTrivialDestructorForCall())
6142     return false;
6143 
6144   for (const CXXMethodDecl *MD : D->methods()) {
6145     if (MD->isDeleted())
6146       continue;
6147 
6148     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6149     if (CD && CD->isCopyOrMoveConstructor())
6150       HasNonDeletedCopyOrMove = true;
6151     else if (!isa<CXXDestructorDecl>(MD))
6152       continue;
6153 
6154     if (!MD->isTrivialForCall())
6155       return false;
6156   }
6157 
6158   return HasNonDeletedCopyOrMove;
6159 }
6160 
6161 /// Perform semantic checks on a class definition that has been
6162 /// completing, introducing implicitly-declared members, checking for
6163 /// abstract types, etc.
6164 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
6165   if (!Record)
6166     return;
6167 
6168   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6169     AbstractUsageInfo Info(*this, Record);
6170     CheckAbstractClassUsage(Info, Record);
6171   }
6172 
6173   // If this is not an aggregate type and has no user-declared constructor,
6174   // complain about any non-static data members of reference or const scalar
6175   // type, since they will never get initializers.
6176   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6177       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6178       !Record->isLambda()) {
6179     bool Complained = false;
6180     for (const auto *F : Record->fields()) {
6181       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6182         continue;
6183 
6184       if (F->getType()->isReferenceType() ||
6185           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6186         if (!Complained) {
6187           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6188             << Record->getTagKind() << Record;
6189           Complained = true;
6190         }
6191 
6192         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6193           << F->getType()->isReferenceType()
6194           << F->getDeclName();
6195       }
6196     }
6197   }
6198 
6199   if (Record->getIdentifier()) {
6200     // C++ [class.mem]p13:
6201     //   If T is the name of a class, then each of the following shall have a
6202     //   name different from T:
6203     //     - every member of every anonymous union that is a member of class T.
6204     //
6205     // C++ [class.mem]p14:
6206     //   In addition, if class T has a user-declared constructor (12.1), every
6207     //   non-static data member of class T shall have a name different from T.
6208     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6209     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6210          ++I) {
6211       NamedDecl *D = (*I)->getUnderlyingDecl();
6212       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6213            Record->hasUserDeclaredConstructor()) ||
6214           isa<IndirectFieldDecl>(D)) {
6215         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6216           << D->getDeclName();
6217         break;
6218       }
6219     }
6220   }
6221 
6222   // Warn if the class has virtual methods but non-virtual public destructor.
6223   if (Record->isPolymorphic() && !Record->isDependentType()) {
6224     CXXDestructorDecl *dtor = Record->getDestructor();
6225     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6226         !Record->hasAttr<FinalAttr>())
6227       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6228            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6229   }
6230 
6231   if (Record->isAbstract()) {
6232     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6233       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6234         << FA->isSpelledAsSealed();
6235       DiagnoseAbstractType(Record);
6236     }
6237   }
6238 
6239   // See if trivial_abi has to be dropped.
6240   if (Record->hasAttr<TrivialABIAttr>())
6241     checkIllFormedTrivialABIStruct(*Record);
6242 
6243   // Set HasTrivialSpecialMemberForCall if the record has attribute
6244   // "trivial_abi".
6245   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6246 
6247   if (HasTrivialABI)
6248     Record->setHasTrivialSpecialMemberForCall();
6249 
6250   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6251     // Check whether the explicitly-defaulted special members are valid.
6252     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6253       CheckExplicitlyDefaultedSpecialMember(M);
6254 
6255     // For an explicitly defaulted or deleted special member, we defer
6256     // determining triviality until the class is complete. That time is now!
6257     CXXSpecialMember CSM = getSpecialMember(M);
6258     if (!M->isImplicit() && !M->isUserProvided()) {
6259       if (CSM != CXXInvalid) {
6260         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6261         // Inform the class that we've finished declaring this member.
6262         Record->finishedDefaultedOrDeletedMember(M);
6263         M->setTrivialForCall(
6264             HasTrivialABI ||
6265             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6266         Record->setTrivialForCallFlags(M);
6267       }
6268     }
6269 
6270     // Set triviality for the purpose of calls if this is a user-provided
6271     // copy/move constructor or destructor.
6272     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6273          CSM == CXXDestructor) && M->isUserProvided()) {
6274       M->setTrivialForCall(HasTrivialABI);
6275       Record->setTrivialForCallFlags(M);
6276     }
6277 
6278     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6279         M->hasAttr<DLLExportAttr>()) {
6280       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6281           M->isTrivial() &&
6282           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6283            CSM == CXXDestructor))
6284         M->dropAttr<DLLExportAttr>();
6285 
6286       if (M->hasAttr<DLLExportAttr>()) {
6287         // Define after any fields with in-class initializers have been parsed.
6288         DelayedDllExportMemberFunctions.push_back(M);
6289       }
6290     }
6291   };
6292 
6293   bool HasMethodWithOverrideControl = false,
6294        HasOverridingMethodWithoutOverrideControl = false;
6295   if (!Record->isDependentType()) {
6296     // Check the destructor before any other member function. We need to
6297     // determine whether it's trivial in order to determine whether the claas
6298     // type is a literal type, which is a prerequisite for determining whether
6299     // other special member functions are valid and whether they're implicitly
6300     // 'constexpr'.
6301     if (CXXDestructorDecl *Dtor = Record->getDestructor())
6302       CompleteMemberFunction(Dtor);
6303 
6304     for (auto *M : Record->methods()) {
6305       // See if a method overloads virtual methods in a base
6306       // class without overriding any.
6307       if (!M->isStatic())
6308         DiagnoseHiddenVirtualMethods(M);
6309       if (M->hasAttr<OverrideAttr>())
6310         HasMethodWithOverrideControl = true;
6311       else if (M->size_overridden_methods() > 0)
6312         HasOverridingMethodWithoutOverrideControl = true;
6313 
6314       if (!isa<CXXDestructorDecl>(M))
6315         CompleteMemberFunction(M);
6316     }
6317   }
6318 
6319   if (HasMethodWithOverrideControl &&
6320       HasOverridingMethodWithoutOverrideControl) {
6321     // At least one method has the 'override' control declared.
6322     // Diagnose all other overridden methods which do not have 'override' specified on them.
6323     for (auto *M : Record->methods())
6324       DiagnoseAbsenceOfOverrideControl(M);
6325   }
6326 
6327   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6328   // whether this class uses any C++ features that are implemented
6329   // completely differently in MSVC, and if so, emit a diagnostic.
6330   // That diagnostic defaults to an error, but we allow projects to
6331   // map it down to a warning (or ignore it).  It's a fairly common
6332   // practice among users of the ms_struct pragma to mass-annotate
6333   // headers, sweeping up a bunch of types that the project doesn't
6334   // really rely on MSVC-compatible layout for.  We must therefore
6335   // support "ms_struct except for C++ stuff" as a secondary ABI.
6336   if (Record->isMsStruct(Context) &&
6337       (Record->isPolymorphic() || Record->getNumBases())) {
6338     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6339   }
6340 
6341   checkClassLevelDLLAttribute(Record);
6342   checkClassLevelCodeSegAttribute(Record);
6343 
6344   bool ClangABICompat4 =
6345       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6346   TargetInfo::CallingConvKind CCK =
6347       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6348   bool CanPass = canPassInRegisters(*this, Record, CCK);
6349 
6350   // Do not change ArgPassingRestrictions if it has already been set to
6351   // APK_CanNeverPassInRegs.
6352   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6353     Record->setArgPassingRestrictions(CanPass
6354                                           ? RecordDecl::APK_CanPassInRegs
6355                                           : RecordDecl::APK_CannotPassInRegs);
6356 
6357   // If canPassInRegisters returns true despite the record having a non-trivial
6358   // destructor, the record is destructed in the callee. This happens only when
6359   // the record or one of its subobjects has a field annotated with trivial_abi
6360   // or a field qualified with ObjC __strong/__weak.
6361   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6362     Record->setParamDestroyedInCallee(true);
6363   else if (Record->hasNonTrivialDestructor())
6364     Record->setParamDestroyedInCallee(CanPass);
6365 
6366   if (getLangOpts().ForceEmitVTables) {
6367     // If we want to emit all the vtables, we need to mark it as used.  This
6368     // is especially required for cases like vtable assumption loads.
6369     MarkVTableUsed(Record->getInnerLocStart(), Record);
6370   }
6371 }
6372 
6373 /// Look up the special member function that would be called by a special
6374 /// member function for a subobject of class type.
6375 ///
6376 /// \param Class The class type of the subobject.
6377 /// \param CSM The kind of special member function.
6378 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6379 /// \param ConstRHS True if this is a copy operation with a const object
6380 ///        on its RHS, that is, if the argument to the outer special member
6381 ///        function is 'const' and this is not a field marked 'mutable'.
6382 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6383     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6384     unsigned FieldQuals, bool ConstRHS) {
6385   unsigned LHSQuals = 0;
6386   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6387     LHSQuals = FieldQuals;
6388 
6389   unsigned RHSQuals = FieldQuals;
6390   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6391     RHSQuals = 0;
6392   else if (ConstRHS)
6393     RHSQuals |= Qualifiers::Const;
6394 
6395   return S.LookupSpecialMember(Class, CSM,
6396                                RHSQuals & Qualifiers::Const,
6397                                RHSQuals & Qualifiers::Volatile,
6398                                false,
6399                                LHSQuals & Qualifiers::Const,
6400                                LHSQuals & Qualifiers::Volatile);
6401 }
6402 
6403 class Sema::InheritedConstructorInfo {
6404   Sema &S;
6405   SourceLocation UseLoc;
6406 
6407   /// A mapping from the base classes through which the constructor was
6408   /// inherited to the using shadow declaration in that base class (or a null
6409   /// pointer if the constructor was declared in that base class).
6410   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6411       InheritedFromBases;
6412 
6413 public:
6414   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6415                            ConstructorUsingShadowDecl *Shadow)
6416       : S(S), UseLoc(UseLoc) {
6417     bool DiagnosedMultipleConstructedBases = false;
6418     CXXRecordDecl *ConstructedBase = nullptr;
6419     UsingDecl *ConstructedBaseUsing = nullptr;
6420 
6421     // Find the set of such base class subobjects and check that there's a
6422     // unique constructed subobject.
6423     for (auto *D : Shadow->redecls()) {
6424       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6425       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6426       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6427 
6428       InheritedFromBases.insert(
6429           std::make_pair(DNominatedBase->getCanonicalDecl(),
6430                          DShadow->getNominatedBaseClassShadowDecl()));
6431       if (DShadow->constructsVirtualBase())
6432         InheritedFromBases.insert(
6433             std::make_pair(DConstructedBase->getCanonicalDecl(),
6434                            DShadow->getConstructedBaseClassShadowDecl()));
6435       else
6436         assert(DNominatedBase == DConstructedBase);
6437 
6438       // [class.inhctor.init]p2:
6439       //   If the constructor was inherited from multiple base class subobjects
6440       //   of type B, the program is ill-formed.
6441       if (!ConstructedBase) {
6442         ConstructedBase = DConstructedBase;
6443         ConstructedBaseUsing = D->getUsingDecl();
6444       } else if (ConstructedBase != DConstructedBase &&
6445                  !Shadow->isInvalidDecl()) {
6446         if (!DiagnosedMultipleConstructedBases) {
6447           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6448               << Shadow->getTargetDecl();
6449           S.Diag(ConstructedBaseUsing->getLocation(),
6450                diag::note_ambiguous_inherited_constructor_using)
6451               << ConstructedBase;
6452           DiagnosedMultipleConstructedBases = true;
6453         }
6454         S.Diag(D->getUsingDecl()->getLocation(),
6455                diag::note_ambiguous_inherited_constructor_using)
6456             << DConstructedBase;
6457       }
6458     }
6459 
6460     if (DiagnosedMultipleConstructedBases)
6461       Shadow->setInvalidDecl();
6462   }
6463 
6464   /// Find the constructor to use for inherited construction of a base class,
6465   /// and whether that base class constructor inherits the constructor from a
6466   /// virtual base class (in which case it won't actually invoke it).
6467   std::pair<CXXConstructorDecl *, bool>
6468   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6469     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6470     if (It == InheritedFromBases.end())
6471       return std::make_pair(nullptr, false);
6472 
6473     // This is an intermediary class.
6474     if (It->second)
6475       return std::make_pair(
6476           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6477           It->second->constructsVirtualBase());
6478 
6479     // This is the base class from which the constructor was inherited.
6480     return std::make_pair(Ctor, false);
6481   }
6482 };
6483 
6484 /// Is the special member function which would be selected to perform the
6485 /// specified operation on the specified class type a constexpr constructor?
6486 static bool
6487 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6488                          Sema::CXXSpecialMember CSM, unsigned Quals,
6489                          bool ConstRHS,
6490                          CXXConstructorDecl *InheritedCtor = nullptr,
6491                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6492   // If we're inheriting a constructor, see if we need to call it for this base
6493   // class.
6494   if (InheritedCtor) {
6495     assert(CSM == Sema::CXXDefaultConstructor);
6496     auto BaseCtor =
6497         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6498     if (BaseCtor)
6499       return BaseCtor->isConstexpr();
6500   }
6501 
6502   if (CSM == Sema::CXXDefaultConstructor)
6503     return ClassDecl->hasConstexprDefaultConstructor();
6504 
6505   Sema::SpecialMemberOverloadResult SMOR =
6506       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6507   if (!SMOR.getMethod())
6508     // A constructor we wouldn't select can't be "involved in initializing"
6509     // anything.
6510     return true;
6511   return SMOR.getMethod()->isConstexpr();
6512 }
6513 
6514 /// Determine whether the specified special member function would be constexpr
6515 /// if it were implicitly defined.
6516 static bool defaultedSpecialMemberIsConstexpr(
6517     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6518     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6519     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6520   if (!S.getLangOpts().CPlusPlus11)
6521     return false;
6522 
6523   // C++11 [dcl.constexpr]p4:
6524   // In the definition of a constexpr constructor [...]
6525   bool Ctor = true;
6526   switch (CSM) {
6527   case Sema::CXXDefaultConstructor:
6528     if (Inherited)
6529       break;
6530     // Since default constructor lookup is essentially trivial (and cannot
6531     // involve, for instance, template instantiation), we compute whether a
6532     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6533     //
6534     // This is important for performance; we need to know whether the default
6535     // constructor is constexpr to determine whether the type is a literal type.
6536     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6537 
6538   case Sema::CXXCopyConstructor:
6539   case Sema::CXXMoveConstructor:
6540     // For copy or move constructors, we need to perform overload resolution.
6541     break;
6542 
6543   case Sema::CXXCopyAssignment:
6544   case Sema::CXXMoveAssignment:
6545     if (!S.getLangOpts().CPlusPlus14)
6546       return false;
6547     // In C++1y, we need to perform overload resolution.
6548     Ctor = false;
6549     break;
6550 
6551   case Sema::CXXDestructor:
6552   case Sema::CXXInvalid:
6553     return false;
6554   }
6555 
6556   //   -- if the class is a non-empty union, or for each non-empty anonymous
6557   //      union member of a non-union class, exactly one non-static data member
6558   //      shall be initialized; [DR1359]
6559   //
6560   // If we squint, this is guaranteed, since exactly one non-static data member
6561   // will be initialized (if the constructor isn't deleted), we just don't know
6562   // which one.
6563   if (Ctor && ClassDecl->isUnion())
6564     return CSM == Sema::CXXDefaultConstructor
6565                ? ClassDecl->hasInClassInitializer() ||
6566                      !ClassDecl->hasVariantMembers()
6567                : true;
6568 
6569   //   -- the class shall not have any virtual base classes;
6570   if (Ctor && ClassDecl->getNumVBases())
6571     return false;
6572 
6573   // C++1y [class.copy]p26:
6574   //   -- [the class] is a literal type, and
6575   if (!Ctor && !ClassDecl->isLiteral())
6576     return false;
6577 
6578   //   -- every constructor involved in initializing [...] base class
6579   //      sub-objects shall be a constexpr constructor;
6580   //   -- the assignment operator selected to copy/move each direct base
6581   //      class is a constexpr function, and
6582   for (const auto &B : ClassDecl->bases()) {
6583     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6584     if (!BaseType) continue;
6585 
6586     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6587     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6588                                   InheritedCtor, Inherited))
6589       return false;
6590   }
6591 
6592   //   -- every constructor involved in initializing non-static data members
6593   //      [...] shall be a constexpr constructor;
6594   //   -- every non-static data member and base class sub-object shall be
6595   //      initialized
6596   //   -- for each non-static data member of X that is of class type (or array
6597   //      thereof), the assignment operator selected to copy/move that member is
6598   //      a constexpr function
6599   for (const auto *F : ClassDecl->fields()) {
6600     if (F->isInvalidDecl())
6601       continue;
6602     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6603       continue;
6604     QualType BaseType = S.Context.getBaseElementType(F->getType());
6605     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6606       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6607       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6608                                     BaseType.getCVRQualifiers(),
6609                                     ConstArg && !F->isMutable()))
6610         return false;
6611     } else if (CSM == Sema::CXXDefaultConstructor) {
6612       return false;
6613     }
6614   }
6615 
6616   // All OK, it's constexpr!
6617   return true;
6618 }
6619 
6620 static Sema::ImplicitExceptionSpecification
6621 ComputeDefaultedSpecialMemberExceptionSpec(
6622     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6623     Sema::InheritedConstructorInfo *ICI);
6624 
6625 static Sema::ImplicitExceptionSpecification
6626 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6627   auto CSM = S.getSpecialMember(MD);
6628   if (CSM != Sema::CXXInvalid)
6629     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6630 
6631   auto *CD = cast<CXXConstructorDecl>(MD);
6632   assert(CD->getInheritedConstructor() &&
6633          "only special members have implicit exception specs");
6634   Sema::InheritedConstructorInfo ICI(
6635       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6636   return ComputeDefaultedSpecialMemberExceptionSpec(
6637       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6638 }
6639 
6640 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6641                                                             CXXMethodDecl *MD) {
6642   FunctionProtoType::ExtProtoInfo EPI;
6643 
6644   // Build an exception specification pointing back at this member.
6645   EPI.ExceptionSpec.Type = EST_Unevaluated;
6646   EPI.ExceptionSpec.SourceDecl = MD;
6647 
6648   // Set the calling convention to the default for C++ instance methods.
6649   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6650       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6651                                             /*IsCXXMethod=*/true));
6652   return EPI;
6653 }
6654 
6655 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6656   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6657   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6658     return;
6659 
6660   // Evaluate the exception specification.
6661   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6662   auto ESI = IES.getExceptionSpec();
6663 
6664   // Update the type of the special member to use it.
6665   UpdateExceptionSpec(MD, ESI);
6666 
6667   // A user-provided destructor can be defined outside the class. When that
6668   // happens, be sure to update the exception specification on both
6669   // declarations.
6670   const FunctionProtoType *CanonicalFPT =
6671     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6672   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6673     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6674 }
6675 
6676 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6677   CXXRecordDecl *RD = MD->getParent();
6678   CXXSpecialMember CSM = getSpecialMember(MD);
6679 
6680   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6681          "not an explicitly-defaulted special member");
6682 
6683   // Whether this was the first-declared instance of the constructor.
6684   // This affects whether we implicitly add an exception spec and constexpr.
6685   bool First = MD == MD->getCanonicalDecl();
6686 
6687   bool HadError = false;
6688 
6689   // C++11 [dcl.fct.def.default]p1:
6690   //   A function that is explicitly defaulted shall
6691   //     -- be a special member function (checked elsewhere),
6692   //     -- have the same type (except for ref-qualifiers, and except that a
6693   //        copy operation can take a non-const reference) as an implicit
6694   //        declaration, and
6695   //     -- not have default arguments.
6696   // C++2a changes the second bullet to instead delete the function if it's
6697   // defaulted on its first declaration, unless it's "an assignment operator,
6698   // and its return type differs or its parameter type is not a reference".
6699   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6700   bool ShouldDeleteForTypeMismatch = false;
6701   unsigned ExpectedParams = 1;
6702   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6703     ExpectedParams = 0;
6704   if (MD->getNumParams() != ExpectedParams) {
6705     // This checks for default arguments: a copy or move constructor with a
6706     // default argument is classified as a default constructor, and assignment
6707     // operations and destructors can't have default arguments.
6708     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6709       << CSM << MD->getSourceRange();
6710     HadError = true;
6711   } else if (MD->isVariadic()) {
6712     if (DeleteOnTypeMismatch)
6713       ShouldDeleteForTypeMismatch = true;
6714     else {
6715       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6716         << CSM << MD->getSourceRange();
6717       HadError = true;
6718     }
6719   }
6720 
6721   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6722 
6723   bool CanHaveConstParam = false;
6724   if (CSM == CXXCopyConstructor)
6725     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6726   else if (CSM == CXXCopyAssignment)
6727     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6728 
6729   QualType ReturnType = Context.VoidTy;
6730   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6731     // Check for return type matching.
6732     ReturnType = Type->getReturnType();
6733 
6734     QualType DeclType = Context.getTypeDeclType(RD);
6735     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
6736     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
6737 
6738     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6739       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6740         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6741       HadError = true;
6742     }
6743 
6744     // A defaulted special member cannot have cv-qualifiers.
6745     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
6746       if (DeleteOnTypeMismatch)
6747         ShouldDeleteForTypeMismatch = true;
6748       else {
6749         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6750           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6751         HadError = true;
6752       }
6753     }
6754   }
6755 
6756   // Check for parameter type matching.
6757   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6758   bool HasConstParam = false;
6759   if (ExpectedParams && ArgType->isReferenceType()) {
6760     // Argument must be reference to possibly-const T.
6761     QualType ReferentType = ArgType->getPointeeType();
6762     HasConstParam = ReferentType.isConstQualified();
6763 
6764     if (ReferentType.isVolatileQualified()) {
6765       if (DeleteOnTypeMismatch)
6766         ShouldDeleteForTypeMismatch = true;
6767       else {
6768         Diag(MD->getLocation(),
6769              diag::err_defaulted_special_member_volatile_param) << CSM;
6770         HadError = true;
6771       }
6772     }
6773 
6774     if (HasConstParam && !CanHaveConstParam) {
6775       if (DeleteOnTypeMismatch)
6776         ShouldDeleteForTypeMismatch = true;
6777       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6778         Diag(MD->getLocation(),
6779              diag::err_defaulted_special_member_copy_const_param)
6780           << (CSM == CXXCopyAssignment);
6781         // FIXME: Explain why this special member can't be const.
6782         HadError = true;
6783       } else {
6784         Diag(MD->getLocation(),
6785              diag::err_defaulted_special_member_move_const_param)
6786           << (CSM == CXXMoveAssignment);
6787         HadError = true;
6788       }
6789     }
6790   } else if (ExpectedParams) {
6791     // A copy assignment operator can take its argument by value, but a
6792     // defaulted one cannot.
6793     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6794     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6795     HadError = true;
6796   }
6797 
6798   // C++11 [dcl.fct.def.default]p2:
6799   //   An explicitly-defaulted function may be declared constexpr only if it
6800   //   would have been implicitly declared as constexpr,
6801   // Do not apply this rule to members of class templates, since core issue 1358
6802   // makes such functions always instantiate to constexpr functions. For
6803   // functions which cannot be constexpr (for non-constructors in C++11 and for
6804   // destructors in C++1y), this is checked elsewhere.
6805   //
6806   // FIXME: This should not apply if the member is deleted.
6807   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6808                                                      HasConstParam);
6809   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6810                                  : isa<CXXConstructorDecl>(MD)) &&
6811       MD->isConstexpr() && !Constexpr &&
6812       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6813     Diag(MD->getBeginLoc(), MD->isConsteval()
6814                                 ? diag::err_incorrect_defaulted_consteval
6815                                 : diag::err_incorrect_defaulted_constexpr)
6816         << CSM;
6817     // FIXME: Explain why the special member can't be constexpr.
6818     HadError = true;
6819   }
6820 
6821   if (First) {
6822     // C++2a [dcl.fct.def.default]p3:
6823     //   If a function is explicitly defaulted on its first declaration, it is
6824     //   implicitly considered to be constexpr if the implicit declaration
6825     //   would be.
6826     MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified);
6827 
6828     if (!Type->hasExceptionSpec()) {
6829       // C++2a [except.spec]p3:
6830       //   If a declaration of a function does not have a noexcept-specifier
6831       //   [and] is defaulted on its first declaration, [...] the exception
6832       //   specification is as specified below
6833       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6834       EPI.ExceptionSpec.Type = EST_Unevaluated;
6835       EPI.ExceptionSpec.SourceDecl = MD;
6836       MD->setType(Context.getFunctionType(ReturnType,
6837                                           llvm::makeArrayRef(&ArgType,
6838                                                              ExpectedParams),
6839                                           EPI));
6840     }
6841   }
6842 
6843   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6844     if (First) {
6845       SetDeclDeleted(MD, MD->getLocation());
6846       if (!inTemplateInstantiation() && !HadError) {
6847         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6848         if (ShouldDeleteForTypeMismatch) {
6849           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6850         } else {
6851           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6852         }
6853       }
6854       if (ShouldDeleteForTypeMismatch && !HadError) {
6855         Diag(MD->getLocation(),
6856              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6857       }
6858     } else {
6859       // C++11 [dcl.fct.def.default]p4:
6860       //   [For a] user-provided explicitly-defaulted function [...] if such a
6861       //   function is implicitly defined as deleted, the program is ill-formed.
6862       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6863       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
6864       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6865       HadError = true;
6866     }
6867   }
6868 
6869   if (HadError)
6870     MD->setInvalidDecl();
6871 }
6872 
6873 void Sema::CheckDelayedMemberExceptionSpecs() {
6874   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6875   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6876 
6877   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6878   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6879 
6880   // Perform any deferred checking of exception specifications for virtual
6881   // destructors.
6882   for (auto &Check : Overriding)
6883     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6884 
6885   // Perform any deferred checking of exception specifications for befriended
6886   // special members.
6887   for (auto &Check : Equivalent)
6888     CheckEquivalentExceptionSpec(Check.second, Check.first);
6889 }
6890 
6891 namespace {
6892 /// CRTP base class for visiting operations performed by a special member
6893 /// function (or inherited constructor).
6894 template<typename Derived>
6895 struct SpecialMemberVisitor {
6896   Sema &S;
6897   CXXMethodDecl *MD;
6898   Sema::CXXSpecialMember CSM;
6899   Sema::InheritedConstructorInfo *ICI;
6900 
6901   // Properties of the special member, computed for convenience.
6902   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6903 
6904   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6905                        Sema::InheritedConstructorInfo *ICI)
6906       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6907     switch (CSM) {
6908     case Sema::CXXDefaultConstructor:
6909     case Sema::CXXCopyConstructor:
6910     case Sema::CXXMoveConstructor:
6911       IsConstructor = true;
6912       break;
6913     case Sema::CXXCopyAssignment:
6914     case Sema::CXXMoveAssignment:
6915       IsAssignment = true;
6916       break;
6917     case Sema::CXXDestructor:
6918       break;
6919     case Sema::CXXInvalid:
6920       llvm_unreachable("invalid special member kind");
6921     }
6922 
6923     if (MD->getNumParams()) {
6924       if (const ReferenceType *RT =
6925               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6926         ConstArg = RT->getPointeeType().isConstQualified();
6927     }
6928   }
6929 
6930   Derived &getDerived() { return static_cast<Derived&>(*this); }
6931 
6932   /// Is this a "move" special member?
6933   bool isMove() const {
6934     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6935   }
6936 
6937   /// Look up the corresponding special member in the given class.
6938   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6939                                              unsigned Quals, bool IsMutable) {
6940     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6941                                        ConstArg && !IsMutable);
6942   }
6943 
6944   /// Look up the constructor for the specified base class to see if it's
6945   /// overridden due to this being an inherited constructor.
6946   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6947     if (!ICI)
6948       return {};
6949     assert(CSM == Sema::CXXDefaultConstructor);
6950     auto *BaseCtor =
6951       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6952     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6953       return MD;
6954     return {};
6955   }
6956 
6957   /// A base or member subobject.
6958   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6959 
6960   /// Get the location to use for a subobject in diagnostics.
6961   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6962     // FIXME: For an indirect virtual base, the direct base leading to
6963     // the indirect virtual base would be a more useful choice.
6964     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6965       return B->getBaseTypeLoc();
6966     else
6967       return Subobj.get<FieldDecl*>()->getLocation();
6968   }
6969 
6970   enum BasesToVisit {
6971     /// Visit all non-virtual (direct) bases.
6972     VisitNonVirtualBases,
6973     /// Visit all direct bases, virtual or not.
6974     VisitDirectBases,
6975     /// Visit all non-virtual bases, and all virtual bases if the class
6976     /// is not abstract.
6977     VisitPotentiallyConstructedBases,
6978     /// Visit all direct or virtual bases.
6979     VisitAllBases
6980   };
6981 
6982   // Visit the bases and members of the class.
6983   bool visit(BasesToVisit Bases) {
6984     CXXRecordDecl *RD = MD->getParent();
6985 
6986     if (Bases == VisitPotentiallyConstructedBases)
6987       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6988 
6989     for (auto &B : RD->bases())
6990       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6991           getDerived().visitBase(&B))
6992         return true;
6993 
6994     if (Bases == VisitAllBases)
6995       for (auto &B : RD->vbases())
6996         if (getDerived().visitBase(&B))
6997           return true;
6998 
6999     for (auto *F : RD->fields())
7000       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
7001           getDerived().visitField(F))
7002         return true;
7003 
7004     return false;
7005   }
7006 };
7007 }
7008 
7009 namespace {
7010 struct SpecialMemberDeletionInfo
7011     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
7012   bool Diagnose;
7013 
7014   SourceLocation Loc;
7015 
7016   bool AllFieldsAreConst;
7017 
7018   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
7019                             Sema::CXXSpecialMember CSM,
7020                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
7021       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
7022         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
7023 
7024   bool inUnion() const { return MD->getParent()->isUnion(); }
7025 
7026   Sema::CXXSpecialMember getEffectiveCSM() {
7027     return ICI ? Sema::CXXInvalid : CSM;
7028   }
7029 
7030   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
7031 
7032   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
7033   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
7034 
7035   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
7036   bool shouldDeleteForField(FieldDecl *FD);
7037   bool shouldDeleteForAllConstMembers();
7038 
7039   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
7040                                      unsigned Quals);
7041   bool shouldDeleteForSubobjectCall(Subobject Subobj,
7042                                     Sema::SpecialMemberOverloadResult SMOR,
7043                                     bool IsDtorCallInCtor);
7044 
7045   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
7046 };
7047 }
7048 
7049 /// Is the given special member inaccessible when used on the given
7050 /// sub-object.
7051 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
7052                                              CXXMethodDecl *target) {
7053   /// If we're operating on a base class, the object type is the
7054   /// type of this special member.
7055   QualType objectTy;
7056   AccessSpecifier access = target->getAccess();
7057   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
7058     objectTy = S.Context.getTypeDeclType(MD->getParent());
7059     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
7060 
7061   // If we're operating on a field, the object type is the type of the field.
7062   } else {
7063     objectTy = S.Context.getTypeDeclType(target->getParent());
7064   }
7065 
7066   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
7067 }
7068 
7069 /// Check whether we should delete a special member due to the implicit
7070 /// definition containing a call to a special member of a subobject.
7071 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
7072     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
7073     bool IsDtorCallInCtor) {
7074   CXXMethodDecl *Decl = SMOR.getMethod();
7075   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
7076 
7077   int DiagKind = -1;
7078 
7079   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
7080     DiagKind = !Decl ? 0 : 1;
7081   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7082     DiagKind = 2;
7083   else if (!isAccessible(Subobj, Decl))
7084     DiagKind = 3;
7085   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
7086            !Decl->isTrivial()) {
7087     // A member of a union must have a trivial corresponding special member.
7088     // As a weird special case, a destructor call from a union's constructor
7089     // must be accessible and non-deleted, but need not be trivial. Such a
7090     // destructor is never actually called, but is semantically checked as
7091     // if it were.
7092     DiagKind = 4;
7093   }
7094 
7095   if (DiagKind == -1)
7096     return false;
7097 
7098   if (Diagnose) {
7099     if (Field) {
7100       S.Diag(Field->getLocation(),
7101              diag::note_deleted_special_member_class_subobject)
7102         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
7103         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
7104     } else {
7105       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
7106       S.Diag(Base->getBeginLoc(),
7107              diag::note_deleted_special_member_class_subobject)
7108           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7109           << Base->getType() << DiagKind << IsDtorCallInCtor
7110           << /*IsObjCPtr*/false;
7111     }
7112 
7113     if (DiagKind == 1)
7114       S.NoteDeletedFunction(Decl);
7115     // FIXME: Explain inaccessibility if DiagKind == 3.
7116   }
7117 
7118   return true;
7119 }
7120 
7121 /// Check whether we should delete a special member function due to having a
7122 /// direct or virtual base class or non-static data member of class type M.
7123 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
7124     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
7125   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
7126   bool IsMutable = Field && Field->isMutable();
7127 
7128   // C++11 [class.ctor]p5:
7129   // -- any direct or virtual base class, or non-static data member with no
7130   //    brace-or-equal-initializer, has class type M (or array thereof) and
7131   //    either M has no default constructor or overload resolution as applied
7132   //    to M's default constructor results in an ambiguity or in a function
7133   //    that is deleted or inaccessible
7134   // C++11 [class.copy]p11, C++11 [class.copy]p23:
7135   // -- a direct or virtual base class B that cannot be copied/moved because
7136   //    overload resolution, as applied to B's corresponding special member,
7137   //    results in an ambiguity or a function that is deleted or inaccessible
7138   //    from the defaulted special member
7139   // C++11 [class.dtor]p5:
7140   // -- any direct or virtual base class [...] has a type with a destructor
7141   //    that is deleted or inaccessible
7142   if (!(CSM == Sema::CXXDefaultConstructor &&
7143         Field && Field->hasInClassInitializer()) &&
7144       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
7145                                    false))
7146     return true;
7147 
7148   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
7149   // -- any direct or virtual base class or non-static data member has a
7150   //    type with a destructor that is deleted or inaccessible
7151   if (IsConstructor) {
7152     Sema::SpecialMemberOverloadResult SMOR =
7153         S.LookupSpecialMember(Class, Sema::CXXDestructor,
7154                               false, false, false, false, false);
7155     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
7156       return true;
7157   }
7158 
7159   return false;
7160 }
7161 
7162 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
7163     FieldDecl *FD, QualType FieldType) {
7164   // The defaulted special functions are defined as deleted if this is a variant
7165   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
7166   // type under ARC.
7167   if (!FieldType.hasNonTrivialObjCLifetime())
7168     return false;
7169 
7170   // Don't make the defaulted default constructor defined as deleted if the
7171   // member has an in-class initializer.
7172   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
7173     return false;
7174 
7175   if (Diagnose) {
7176     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
7177     S.Diag(FD->getLocation(),
7178            diag::note_deleted_special_member_class_subobject)
7179         << getEffectiveCSM() << ParentClass << /*IsField*/true
7180         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
7181   }
7182 
7183   return true;
7184 }
7185 
7186 /// Check whether we should delete a special member function due to the class
7187 /// having a particular direct or virtual base class.
7188 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
7189   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
7190   // If program is correct, BaseClass cannot be null, but if it is, the error
7191   // must be reported elsewhere.
7192   if (!BaseClass)
7193     return false;
7194   // If we have an inheriting constructor, check whether we're calling an
7195   // inherited constructor instead of a default constructor.
7196   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
7197   if (auto *BaseCtor = SMOR.getMethod()) {
7198     // Note that we do not check access along this path; other than that,
7199     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
7200     // FIXME: Check that the base has a usable destructor! Sink this into
7201     // shouldDeleteForClassSubobject.
7202     if (BaseCtor->isDeleted() && Diagnose) {
7203       S.Diag(Base->getBeginLoc(),
7204              diag::note_deleted_special_member_class_subobject)
7205           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7206           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
7207           << /*IsObjCPtr*/false;
7208       S.NoteDeletedFunction(BaseCtor);
7209     }
7210     return BaseCtor->isDeleted();
7211   }
7212   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7213 }
7214 
7215 /// Check whether we should delete a special member function due to the class
7216 /// having a particular non-static data member.
7217 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7218   QualType FieldType = S.Context.getBaseElementType(FD->getType());
7219   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7220 
7221   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
7222     return true;
7223 
7224   if (CSM == Sema::CXXDefaultConstructor) {
7225     // For a default constructor, all references must be initialized in-class
7226     // and, if a union, it must have a non-const member.
7227     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7228       if (Diagnose)
7229         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7230           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7231       return true;
7232     }
7233     // C++11 [class.ctor]p5: any non-variant non-static data member of
7234     // const-qualified type (or array thereof) with no
7235     // brace-or-equal-initializer does not have a user-provided default
7236     // constructor.
7237     if (!inUnion() && FieldType.isConstQualified() &&
7238         !FD->hasInClassInitializer() &&
7239         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7240       if (Diagnose)
7241         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7242           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7243       return true;
7244     }
7245 
7246     if (inUnion() && !FieldType.isConstQualified())
7247       AllFieldsAreConst = false;
7248   } else if (CSM == Sema::CXXCopyConstructor) {
7249     // For a copy constructor, data members must not be of rvalue reference
7250     // type.
7251     if (FieldType->isRValueReferenceType()) {
7252       if (Diagnose)
7253         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7254           << MD->getParent() << FD << FieldType;
7255       return true;
7256     }
7257   } else if (IsAssignment) {
7258     // For an assignment operator, data members must not be of reference type.
7259     if (FieldType->isReferenceType()) {
7260       if (Diagnose)
7261         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7262           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7263       return true;
7264     }
7265     if (!FieldRecord && FieldType.isConstQualified()) {
7266       // C++11 [class.copy]p23:
7267       // -- a non-static data member of const non-class type (or array thereof)
7268       if (Diagnose)
7269         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7270           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7271       return true;
7272     }
7273   }
7274 
7275   if (FieldRecord) {
7276     // Some additional restrictions exist on the variant members.
7277     if (!inUnion() && FieldRecord->isUnion() &&
7278         FieldRecord->isAnonymousStructOrUnion()) {
7279       bool AllVariantFieldsAreConst = true;
7280 
7281       // FIXME: Handle anonymous unions declared within anonymous unions.
7282       for (auto *UI : FieldRecord->fields()) {
7283         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7284 
7285         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
7286           return true;
7287 
7288         if (!UnionFieldType.isConstQualified())
7289           AllVariantFieldsAreConst = false;
7290 
7291         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7292         if (UnionFieldRecord &&
7293             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7294                                           UnionFieldType.getCVRQualifiers()))
7295           return true;
7296       }
7297 
7298       // At least one member in each anonymous union must be non-const
7299       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7300           !FieldRecord->field_empty()) {
7301         if (Diagnose)
7302           S.Diag(FieldRecord->getLocation(),
7303                  diag::note_deleted_default_ctor_all_const)
7304             << !!ICI << MD->getParent() << /*anonymous union*/1;
7305         return true;
7306       }
7307 
7308       // Don't check the implicit member of the anonymous union type.
7309       // This is technically non-conformant, but sanity demands it.
7310       return false;
7311     }
7312 
7313     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7314                                       FieldType.getCVRQualifiers()))
7315       return true;
7316   }
7317 
7318   return false;
7319 }
7320 
7321 /// C++11 [class.ctor] p5:
7322 ///   A defaulted default constructor for a class X is defined as deleted if
7323 /// X is a union and all of its variant members are of const-qualified type.
7324 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7325   // This is a silly definition, because it gives an empty union a deleted
7326   // default constructor. Don't do that.
7327   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7328     bool AnyFields = false;
7329     for (auto *F : MD->getParent()->fields())
7330       if ((AnyFields = !F->isUnnamedBitfield()))
7331         break;
7332     if (!AnyFields)
7333       return false;
7334     if (Diagnose)
7335       S.Diag(MD->getParent()->getLocation(),
7336              diag::note_deleted_default_ctor_all_const)
7337         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7338     return true;
7339   }
7340   return false;
7341 }
7342 
7343 /// Determine whether a defaulted special member function should be defined as
7344 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7345 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7346 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7347                                      InheritedConstructorInfo *ICI,
7348                                      bool Diagnose) {
7349   if (MD->isInvalidDecl())
7350     return false;
7351   CXXRecordDecl *RD = MD->getParent();
7352   assert(!RD->isDependentType() && "do deletion after instantiation");
7353   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7354     return false;
7355 
7356   // C++11 [expr.lambda.prim]p19:
7357   //   The closure type associated with a lambda-expression has a
7358   //   deleted (8.4.3) default constructor and a deleted copy
7359   //   assignment operator.
7360   // C++2a adds back these operators if the lambda has no lambda-capture.
7361   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7362       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7363     if (Diagnose)
7364       Diag(RD->getLocation(), diag::note_lambda_decl);
7365     return true;
7366   }
7367 
7368   // For an anonymous struct or union, the copy and assignment special members
7369   // will never be used, so skip the check. For an anonymous union declared at
7370   // namespace scope, the constructor and destructor are used.
7371   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7372       RD->isAnonymousStructOrUnion())
7373     return false;
7374 
7375   // C++11 [class.copy]p7, p18:
7376   //   If the class definition declares a move constructor or move assignment
7377   //   operator, an implicitly declared copy constructor or copy assignment
7378   //   operator is defined as deleted.
7379   if (MD->isImplicit() &&
7380       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7381     CXXMethodDecl *UserDeclaredMove = nullptr;
7382 
7383     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7384     // deletion of the corresponding copy operation, not both copy operations.
7385     // MSVC 2015 has adopted the standards conforming behavior.
7386     bool DeletesOnlyMatchingCopy =
7387         getLangOpts().MSVCCompat &&
7388         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7389 
7390     if (RD->hasUserDeclaredMoveConstructor() &&
7391         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7392       if (!Diagnose) return true;
7393 
7394       // Find any user-declared move constructor.
7395       for (auto *I : RD->ctors()) {
7396         if (I->isMoveConstructor()) {
7397           UserDeclaredMove = I;
7398           break;
7399         }
7400       }
7401       assert(UserDeclaredMove);
7402     } else if (RD->hasUserDeclaredMoveAssignment() &&
7403                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7404       if (!Diagnose) return true;
7405 
7406       // Find any user-declared move assignment operator.
7407       for (auto *I : RD->methods()) {
7408         if (I->isMoveAssignmentOperator()) {
7409           UserDeclaredMove = I;
7410           break;
7411         }
7412       }
7413       assert(UserDeclaredMove);
7414     }
7415 
7416     if (UserDeclaredMove) {
7417       Diag(UserDeclaredMove->getLocation(),
7418            diag::note_deleted_copy_user_declared_move)
7419         << (CSM == CXXCopyAssignment) << RD
7420         << UserDeclaredMove->isMoveAssignmentOperator();
7421       return true;
7422     }
7423   }
7424 
7425   // Do access control from the special member function
7426   ContextRAII MethodContext(*this, MD);
7427 
7428   // C++11 [class.dtor]p5:
7429   // -- for a virtual destructor, lookup of the non-array deallocation function
7430   //    results in an ambiguity or in a function that is deleted or inaccessible
7431   if (CSM == CXXDestructor && MD->isVirtual()) {
7432     FunctionDecl *OperatorDelete = nullptr;
7433     DeclarationName Name =
7434       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7435     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7436                                  OperatorDelete, /*Diagnose*/false)) {
7437       if (Diagnose)
7438         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7439       return true;
7440     }
7441   }
7442 
7443   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7444 
7445   // Per DR1611, do not consider virtual bases of constructors of abstract
7446   // classes, since we are not going to construct them.
7447   // Per DR1658, do not consider virtual bases of destructors of abstract
7448   // classes either.
7449   // Per DR2180, for assignment operators we only assign (and thus only
7450   // consider) direct bases.
7451   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7452                                  : SMI.VisitPotentiallyConstructedBases))
7453     return true;
7454 
7455   if (SMI.shouldDeleteForAllConstMembers())
7456     return true;
7457 
7458   if (getLangOpts().CUDA) {
7459     // We should delete the special member in CUDA mode if target inference
7460     // failed.
7461     // For inherited constructors (non-null ICI), CSM may be passed so that MD
7462     // is treated as certain special member, which may not reflect what special
7463     // member MD really is. However inferCUDATargetForImplicitSpecialMember
7464     // expects CSM to match MD, therefore recalculate CSM.
7465     assert(ICI || CSM == getSpecialMember(MD));
7466     auto RealCSM = CSM;
7467     if (ICI)
7468       RealCSM = getSpecialMember(MD);
7469 
7470     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7471                                                    SMI.ConstArg, Diagnose);
7472   }
7473 
7474   return false;
7475 }
7476 
7477 /// Perform lookup for a special member of the specified kind, and determine
7478 /// whether it is trivial. If the triviality can be determined without the
7479 /// lookup, skip it. This is intended for use when determining whether a
7480 /// special member of a containing object is trivial, and thus does not ever
7481 /// perform overload resolution for default constructors.
7482 ///
7483 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7484 /// member that was most likely to be intended to be trivial, if any.
7485 ///
7486 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7487 /// determine whether the special member is trivial.
7488 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7489                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7490                                      bool ConstRHS,
7491                                      Sema::TrivialABIHandling TAH,
7492                                      CXXMethodDecl **Selected) {
7493   if (Selected)
7494     *Selected = nullptr;
7495 
7496   switch (CSM) {
7497   case Sema::CXXInvalid:
7498     llvm_unreachable("not a special member");
7499 
7500   case Sema::CXXDefaultConstructor:
7501     // C++11 [class.ctor]p5:
7502     //   A default constructor is trivial if:
7503     //    - all the [direct subobjects] have trivial default constructors
7504     //
7505     // Note, no overload resolution is performed in this case.
7506     if (RD->hasTrivialDefaultConstructor())
7507       return true;
7508 
7509     if (Selected) {
7510       // If there's a default constructor which could have been trivial, dig it
7511       // out. Otherwise, if there's any user-provided default constructor, point
7512       // to that as an example of why there's not a trivial one.
7513       CXXConstructorDecl *DefCtor = nullptr;
7514       if (RD->needsImplicitDefaultConstructor())
7515         S.DeclareImplicitDefaultConstructor(RD);
7516       for (auto *CI : RD->ctors()) {
7517         if (!CI->isDefaultConstructor())
7518           continue;
7519         DefCtor = CI;
7520         if (!DefCtor->isUserProvided())
7521           break;
7522       }
7523 
7524       *Selected = DefCtor;
7525     }
7526 
7527     return false;
7528 
7529   case Sema::CXXDestructor:
7530     // C++11 [class.dtor]p5:
7531     //   A destructor is trivial if:
7532     //    - all the direct [subobjects] have trivial destructors
7533     if (RD->hasTrivialDestructor() ||
7534         (TAH == Sema::TAH_ConsiderTrivialABI &&
7535          RD->hasTrivialDestructorForCall()))
7536       return true;
7537 
7538     if (Selected) {
7539       if (RD->needsImplicitDestructor())
7540         S.DeclareImplicitDestructor(RD);
7541       *Selected = RD->getDestructor();
7542     }
7543 
7544     return false;
7545 
7546   case Sema::CXXCopyConstructor:
7547     // C++11 [class.copy]p12:
7548     //   A copy constructor is trivial if:
7549     //    - the constructor selected to copy each direct [subobject] is trivial
7550     if (RD->hasTrivialCopyConstructor() ||
7551         (TAH == Sema::TAH_ConsiderTrivialABI &&
7552          RD->hasTrivialCopyConstructorForCall())) {
7553       if (Quals == Qualifiers::Const)
7554         // We must either select the trivial copy constructor or reach an
7555         // ambiguity; no need to actually perform overload resolution.
7556         return true;
7557     } else if (!Selected) {
7558       return false;
7559     }
7560     // In C++98, we are not supposed to perform overload resolution here, but we
7561     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7562     // cases like B as having a non-trivial copy constructor:
7563     //   struct A { template<typename T> A(T&); };
7564     //   struct B { mutable A a; };
7565     goto NeedOverloadResolution;
7566 
7567   case Sema::CXXCopyAssignment:
7568     // C++11 [class.copy]p25:
7569     //   A copy assignment operator is trivial if:
7570     //    - the assignment operator selected to copy each direct [subobject] is
7571     //      trivial
7572     if (RD->hasTrivialCopyAssignment()) {
7573       if (Quals == Qualifiers::Const)
7574         return true;
7575     } else if (!Selected) {
7576       return false;
7577     }
7578     // In C++98, we are not supposed to perform overload resolution here, but we
7579     // treat that as a language defect.
7580     goto NeedOverloadResolution;
7581 
7582   case Sema::CXXMoveConstructor:
7583   case Sema::CXXMoveAssignment:
7584   NeedOverloadResolution:
7585     Sema::SpecialMemberOverloadResult SMOR =
7586         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7587 
7588     // The standard doesn't describe how to behave if the lookup is ambiguous.
7589     // We treat it as not making the member non-trivial, just like the standard
7590     // mandates for the default constructor. This should rarely matter, because
7591     // the member will also be deleted.
7592     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7593       return true;
7594 
7595     if (!SMOR.getMethod()) {
7596       assert(SMOR.getKind() ==
7597              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7598       return false;
7599     }
7600 
7601     // We deliberately don't check if we found a deleted special member. We're
7602     // not supposed to!
7603     if (Selected)
7604       *Selected = SMOR.getMethod();
7605 
7606     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7607         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7608       return SMOR.getMethod()->isTrivialForCall();
7609     return SMOR.getMethod()->isTrivial();
7610   }
7611 
7612   llvm_unreachable("unknown special method kind");
7613 }
7614 
7615 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7616   for (auto *CI : RD->ctors())
7617     if (!CI->isImplicit())
7618       return CI;
7619 
7620   // Look for constructor templates.
7621   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7622   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7623     if (CXXConstructorDecl *CD =
7624           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7625       return CD;
7626   }
7627 
7628   return nullptr;
7629 }
7630 
7631 /// The kind of subobject we are checking for triviality. The values of this
7632 /// enumeration are used in diagnostics.
7633 enum TrivialSubobjectKind {
7634   /// The subobject is a base class.
7635   TSK_BaseClass,
7636   /// The subobject is a non-static data member.
7637   TSK_Field,
7638   /// The object is actually the complete object.
7639   TSK_CompleteObject
7640 };
7641 
7642 /// Check whether the special member selected for a given type would be trivial.
7643 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7644                                       QualType SubType, bool ConstRHS,
7645                                       Sema::CXXSpecialMember CSM,
7646                                       TrivialSubobjectKind Kind,
7647                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7648   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7649   if (!SubRD)
7650     return true;
7651 
7652   CXXMethodDecl *Selected;
7653   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7654                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7655     return true;
7656 
7657   if (Diagnose) {
7658     if (ConstRHS)
7659       SubType.addConst();
7660 
7661     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7662       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7663         << Kind << SubType.getUnqualifiedType();
7664       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7665         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7666     } else if (!Selected)
7667       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7668         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7669     else if (Selected->isUserProvided()) {
7670       if (Kind == TSK_CompleteObject)
7671         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7672           << Kind << SubType.getUnqualifiedType() << CSM;
7673       else {
7674         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7675           << Kind << SubType.getUnqualifiedType() << CSM;
7676         S.Diag(Selected->getLocation(), diag::note_declared_at);
7677       }
7678     } else {
7679       if (Kind != TSK_CompleteObject)
7680         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7681           << Kind << SubType.getUnqualifiedType() << CSM;
7682 
7683       // Explain why the defaulted or deleted special member isn't trivial.
7684       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7685                                Diagnose);
7686     }
7687   }
7688 
7689   return false;
7690 }
7691 
7692 /// Check whether the members of a class type allow a special member to be
7693 /// trivial.
7694 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7695                                      Sema::CXXSpecialMember CSM,
7696                                      bool ConstArg,
7697                                      Sema::TrivialABIHandling TAH,
7698                                      bool Diagnose) {
7699   for (const auto *FI : RD->fields()) {
7700     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7701       continue;
7702 
7703     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7704 
7705     // Pretend anonymous struct or union members are members of this class.
7706     if (FI->isAnonymousStructOrUnion()) {
7707       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7708                                     CSM, ConstArg, TAH, Diagnose))
7709         return false;
7710       continue;
7711     }
7712 
7713     // C++11 [class.ctor]p5:
7714     //   A default constructor is trivial if [...]
7715     //    -- no non-static data member of its class has a
7716     //       brace-or-equal-initializer
7717     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7718       if (Diagnose)
7719         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7720       return false;
7721     }
7722 
7723     // Objective C ARC 4.3.5:
7724     //   [...] nontrivally ownership-qualified types are [...] not trivially
7725     //   default constructible, copy constructible, move constructible, copy
7726     //   assignable, move assignable, or destructible [...]
7727     if (FieldType.hasNonTrivialObjCLifetime()) {
7728       if (Diagnose)
7729         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7730           << RD << FieldType.getObjCLifetime();
7731       return false;
7732     }
7733 
7734     bool ConstRHS = ConstArg && !FI->isMutable();
7735     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7736                                    CSM, TSK_Field, TAH, Diagnose))
7737       return false;
7738   }
7739 
7740   return true;
7741 }
7742 
7743 /// Diagnose why the specified class does not have a trivial special member of
7744 /// the given kind.
7745 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7746   QualType Ty = Context.getRecordType(RD);
7747 
7748   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7749   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7750                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7751                             /*Diagnose*/true);
7752 }
7753 
7754 /// Determine whether a defaulted or deleted special member function is trivial,
7755 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7756 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7757 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7758                                   TrivialABIHandling TAH, bool Diagnose) {
7759   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7760 
7761   CXXRecordDecl *RD = MD->getParent();
7762 
7763   bool ConstArg = false;
7764 
7765   // C++11 [class.copy]p12, p25: [DR1593]
7766   //   A [special member] is trivial if [...] its parameter-type-list is
7767   //   equivalent to the parameter-type-list of an implicit declaration [...]
7768   switch (CSM) {
7769   case CXXDefaultConstructor:
7770   case CXXDestructor:
7771     // Trivial default constructors and destructors cannot have parameters.
7772     break;
7773 
7774   case CXXCopyConstructor:
7775   case CXXCopyAssignment: {
7776     // Trivial copy operations always have const, non-volatile parameter types.
7777     ConstArg = true;
7778     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7779     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7780     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7781       if (Diagnose)
7782         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7783           << Param0->getSourceRange() << Param0->getType()
7784           << Context.getLValueReferenceType(
7785                Context.getRecordType(RD).withConst());
7786       return false;
7787     }
7788     break;
7789   }
7790 
7791   case CXXMoveConstructor:
7792   case CXXMoveAssignment: {
7793     // Trivial move operations always have non-cv-qualified parameters.
7794     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7795     const RValueReferenceType *RT =
7796       Param0->getType()->getAs<RValueReferenceType>();
7797     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7798       if (Diagnose)
7799         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7800           << Param0->getSourceRange() << Param0->getType()
7801           << Context.getRValueReferenceType(Context.getRecordType(RD));
7802       return false;
7803     }
7804     break;
7805   }
7806 
7807   case CXXInvalid:
7808     llvm_unreachable("not a special member");
7809   }
7810 
7811   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7812     if (Diagnose)
7813       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7814            diag::note_nontrivial_default_arg)
7815         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7816     return false;
7817   }
7818   if (MD->isVariadic()) {
7819     if (Diagnose)
7820       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7821     return false;
7822   }
7823 
7824   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7825   //   A copy/move [constructor or assignment operator] is trivial if
7826   //    -- the [member] selected to copy/move each direct base class subobject
7827   //       is trivial
7828   //
7829   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7830   //   A [default constructor or destructor] is trivial if
7831   //    -- all the direct base classes have trivial [default constructors or
7832   //       destructors]
7833   for (const auto &BI : RD->bases())
7834     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7835                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7836       return false;
7837 
7838   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7839   //   A copy/move [constructor or assignment operator] for a class X is
7840   //   trivial if
7841   //    -- for each non-static data member of X that is of class type (or array
7842   //       thereof), the constructor selected to copy/move that member is
7843   //       trivial
7844   //
7845   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7846   //   A [default constructor or destructor] is trivial if
7847   //    -- for all of the non-static data members of its class that are of class
7848   //       type (or array thereof), each such class has a trivial [default
7849   //       constructor or destructor]
7850   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7851     return false;
7852 
7853   // C++11 [class.dtor]p5:
7854   //   A destructor is trivial if [...]
7855   //    -- the destructor is not virtual
7856   if (CSM == CXXDestructor && MD->isVirtual()) {
7857     if (Diagnose)
7858       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7859     return false;
7860   }
7861 
7862   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7863   //   A [special member] for class X is trivial if [...]
7864   //    -- class X has no virtual functions and no virtual base classes
7865   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7866     if (!Diagnose)
7867       return false;
7868 
7869     if (RD->getNumVBases()) {
7870       // Check for virtual bases. We already know that the corresponding
7871       // member in all bases is trivial, so vbases must all be direct.
7872       CXXBaseSpecifier &BS = *RD->vbases_begin();
7873       assert(BS.isVirtual());
7874       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7875       return false;
7876     }
7877 
7878     // Must have a virtual method.
7879     for (const auto *MI : RD->methods()) {
7880       if (MI->isVirtual()) {
7881         SourceLocation MLoc = MI->getBeginLoc();
7882         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7883         return false;
7884       }
7885     }
7886 
7887     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7888   }
7889 
7890   // Looks like it's trivial!
7891   return true;
7892 }
7893 
7894 namespace {
7895 struct FindHiddenVirtualMethod {
7896   Sema *S;
7897   CXXMethodDecl *Method;
7898   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7899   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7900 
7901 private:
7902   /// Check whether any most overridden method from MD in Methods
7903   static bool CheckMostOverridenMethods(
7904       const CXXMethodDecl *MD,
7905       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7906     if (MD->size_overridden_methods() == 0)
7907       return Methods.count(MD->getCanonicalDecl());
7908     for (const CXXMethodDecl *O : MD->overridden_methods())
7909       if (CheckMostOverridenMethods(O, Methods))
7910         return true;
7911     return false;
7912   }
7913 
7914 public:
7915   /// Member lookup function that determines whether a given C++
7916   /// method overloads virtual methods in a base class without overriding any,
7917   /// to be used with CXXRecordDecl::lookupInBases().
7918   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7919     RecordDecl *BaseRecord =
7920         Specifier->getType()->getAs<RecordType>()->getDecl();
7921 
7922     DeclarationName Name = Method->getDeclName();
7923     assert(Name.getNameKind() == DeclarationName::Identifier);
7924 
7925     bool foundSameNameMethod = false;
7926     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7927     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7928          Path.Decls = Path.Decls.slice(1)) {
7929       NamedDecl *D = Path.Decls.front();
7930       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7931         MD = MD->getCanonicalDecl();
7932         foundSameNameMethod = true;
7933         // Interested only in hidden virtual methods.
7934         if (!MD->isVirtual())
7935           continue;
7936         // If the method we are checking overrides a method from its base
7937         // don't warn about the other overloaded methods. Clang deviates from
7938         // GCC by only diagnosing overloads of inherited virtual functions that
7939         // do not override any other virtual functions in the base. GCC's
7940         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7941         // function from a base class. These cases may be better served by a
7942         // warning (not specific to virtual functions) on call sites when the
7943         // call would select a different function from the base class, were it
7944         // visible.
7945         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7946         if (!S->IsOverload(Method, MD, false))
7947           return true;
7948         // Collect the overload only if its hidden.
7949         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7950           overloadedMethods.push_back(MD);
7951       }
7952     }
7953 
7954     if (foundSameNameMethod)
7955       OverloadedMethods.append(overloadedMethods.begin(),
7956                                overloadedMethods.end());
7957     return foundSameNameMethod;
7958   }
7959 };
7960 } // end anonymous namespace
7961 
7962 /// Add the most overriden methods from MD to Methods
7963 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7964                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7965   if (MD->size_overridden_methods() == 0)
7966     Methods.insert(MD->getCanonicalDecl());
7967   else
7968     for (const CXXMethodDecl *O : MD->overridden_methods())
7969       AddMostOverridenMethods(O, Methods);
7970 }
7971 
7972 /// Check if a method overloads virtual methods in a base class without
7973 /// overriding any.
7974 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7975                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7976   if (!MD->getDeclName().isIdentifier())
7977     return;
7978 
7979   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7980                      /*bool RecordPaths=*/false,
7981                      /*bool DetectVirtual=*/false);
7982   FindHiddenVirtualMethod FHVM;
7983   FHVM.Method = MD;
7984   FHVM.S = this;
7985 
7986   // Keep the base methods that were overridden or introduced in the subclass
7987   // by 'using' in a set. A base method not in this set is hidden.
7988   CXXRecordDecl *DC = MD->getParent();
7989   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7990   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7991     NamedDecl *ND = *I;
7992     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7993       ND = shad->getTargetDecl();
7994     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7995       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7996   }
7997 
7998   if (DC->lookupInBases(FHVM, Paths))
7999     OverloadedMethods = FHVM.OverloadedMethods;
8000 }
8001 
8002 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
8003                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
8004   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
8005     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
8006     PartialDiagnostic PD = PDiag(
8007          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
8008     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
8009     Diag(overloadedMD->getLocation(), PD);
8010   }
8011 }
8012 
8013 /// Diagnose methods which overload virtual methods in a base class
8014 /// without overriding any.
8015 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
8016   if (MD->isInvalidDecl())
8017     return;
8018 
8019   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
8020     return;
8021 
8022   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
8023   FindHiddenVirtualMethods(MD, OverloadedMethods);
8024   if (!OverloadedMethods.empty()) {
8025     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
8026       << MD << (OverloadedMethods.size() > 1);
8027 
8028     NoteHiddenVirtualMethods(MD, OverloadedMethods);
8029   }
8030 }
8031 
8032 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
8033   auto PrintDiagAndRemoveAttr = [&]() {
8034     // No diagnostics if this is a template instantiation.
8035     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
8036       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
8037            diag::ext_cannot_use_trivial_abi) << &RD;
8038     RD.dropAttr<TrivialABIAttr>();
8039   };
8040 
8041   // Ill-formed if the struct has virtual functions.
8042   if (RD.isPolymorphic()) {
8043     PrintDiagAndRemoveAttr();
8044     return;
8045   }
8046 
8047   for (const auto &B : RD.bases()) {
8048     // Ill-formed if the base class is non-trivial for the purpose of calls or a
8049     // virtual base.
8050     if ((!B.getType()->isDependentType() &&
8051          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
8052         B.isVirtual()) {
8053       PrintDiagAndRemoveAttr();
8054       return;
8055     }
8056   }
8057 
8058   for (const auto *FD : RD.fields()) {
8059     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
8060     // non-trivial for the purpose of calls.
8061     QualType FT = FD->getType();
8062     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
8063       PrintDiagAndRemoveAttr();
8064       return;
8065     }
8066 
8067     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
8068       if (!RT->isDependentType() &&
8069           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
8070         PrintDiagAndRemoveAttr();
8071         return;
8072       }
8073   }
8074 }
8075 
8076 void Sema::ActOnFinishCXXMemberSpecification(
8077     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
8078     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
8079   if (!TagDecl)
8080     return;
8081 
8082   AdjustDeclIfTemplate(TagDecl);
8083 
8084   for (const ParsedAttr &AL : AttrList) {
8085     if (AL.getKind() != ParsedAttr::AT_Visibility)
8086       continue;
8087     AL.setInvalid();
8088     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
8089         << AL.getName();
8090   }
8091 
8092   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
8093               // strict aliasing violation!
8094               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
8095               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
8096 
8097   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
8098 }
8099 
8100 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
8101 /// special functions, such as the default constructor, copy
8102 /// constructor, or destructor, to the given C++ class (C++
8103 /// [special]p1).  This routine can only be executed just before the
8104 /// definition of the class is complete.
8105 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
8106   if (ClassDecl->needsImplicitDefaultConstructor()) {
8107     ++getASTContext().NumImplicitDefaultConstructors;
8108 
8109     if (ClassDecl->hasInheritedConstructor())
8110       DeclareImplicitDefaultConstructor(ClassDecl);
8111   }
8112 
8113   if (ClassDecl->needsImplicitCopyConstructor()) {
8114     ++getASTContext().NumImplicitCopyConstructors;
8115 
8116     // If the properties or semantics of the copy constructor couldn't be
8117     // determined while the class was being declared, force a declaration
8118     // of it now.
8119     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
8120         ClassDecl->hasInheritedConstructor())
8121       DeclareImplicitCopyConstructor(ClassDecl);
8122     // For the MS ABI we need to know whether the copy ctor is deleted. A
8123     // prerequisite for deleting the implicit copy ctor is that the class has a
8124     // move ctor or move assignment that is either user-declared or whose
8125     // semantics are inherited from a subobject. FIXME: We should provide a more
8126     // direct way for CodeGen to ask whether the constructor was deleted.
8127     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8128              (ClassDecl->hasUserDeclaredMoveConstructor() ||
8129               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8130               ClassDecl->hasUserDeclaredMoveAssignment() ||
8131               ClassDecl->needsOverloadResolutionForMoveAssignment()))
8132       DeclareImplicitCopyConstructor(ClassDecl);
8133   }
8134 
8135   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
8136     ++getASTContext().NumImplicitMoveConstructors;
8137 
8138     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8139         ClassDecl->hasInheritedConstructor())
8140       DeclareImplicitMoveConstructor(ClassDecl);
8141   }
8142 
8143   if (ClassDecl->needsImplicitCopyAssignment()) {
8144     ++getASTContext().NumImplicitCopyAssignmentOperators;
8145 
8146     // If we have a dynamic class, then the copy assignment operator may be
8147     // virtual, so we have to declare it immediately. This ensures that, e.g.,
8148     // it shows up in the right place in the vtable and that we diagnose
8149     // problems with the implicit exception specification.
8150     if (ClassDecl->isDynamicClass() ||
8151         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
8152         ClassDecl->hasInheritedAssignment())
8153       DeclareImplicitCopyAssignment(ClassDecl);
8154   }
8155 
8156   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
8157     ++getASTContext().NumImplicitMoveAssignmentOperators;
8158 
8159     // Likewise for the move assignment operator.
8160     if (ClassDecl->isDynamicClass() ||
8161         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
8162         ClassDecl->hasInheritedAssignment())
8163       DeclareImplicitMoveAssignment(ClassDecl);
8164   }
8165 
8166   if (ClassDecl->needsImplicitDestructor()) {
8167     ++getASTContext().NumImplicitDestructors;
8168 
8169     // If we have a dynamic class, then the destructor may be virtual, so we
8170     // have to declare the destructor immediately. This ensures that, e.g., it
8171     // shows up in the right place in the vtable and that we diagnose problems
8172     // with the implicit exception specification.
8173     if (ClassDecl->isDynamicClass() ||
8174         ClassDecl->needsOverloadResolutionForDestructor())
8175       DeclareImplicitDestructor(ClassDecl);
8176   }
8177 }
8178 
8179 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
8180   if (!D)
8181     return 0;
8182 
8183   // The order of template parameters is not important here. All names
8184   // get added to the same scope.
8185   SmallVector<TemplateParameterList *, 4> ParameterLists;
8186 
8187   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8188     D = TD->getTemplatedDecl();
8189 
8190   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
8191     ParameterLists.push_back(PSD->getTemplateParameters());
8192 
8193   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
8194     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
8195       ParameterLists.push_back(DD->getTemplateParameterList(i));
8196 
8197     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8198       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
8199         ParameterLists.push_back(FTD->getTemplateParameters());
8200     }
8201   }
8202 
8203   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8204     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
8205       ParameterLists.push_back(TD->getTemplateParameterList(i));
8206 
8207     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
8208       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
8209         ParameterLists.push_back(CTD->getTemplateParameters());
8210     }
8211   }
8212 
8213   unsigned Count = 0;
8214   for (TemplateParameterList *Params : ParameterLists) {
8215     if (Params->size() > 0)
8216       // Ignore explicit specializations; they don't contribute to the template
8217       // depth.
8218       ++Count;
8219     for (NamedDecl *Param : *Params) {
8220       if (Param->getDeclName()) {
8221         S->AddDecl(Param);
8222         IdResolver.AddDecl(Param);
8223       }
8224     }
8225   }
8226 
8227   return Count;
8228 }
8229 
8230 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8231   if (!RecordD) return;
8232   AdjustDeclIfTemplate(RecordD);
8233   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8234   PushDeclContext(S, Record);
8235 }
8236 
8237 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8238   if (!RecordD) return;
8239   PopDeclContext();
8240 }
8241 
8242 /// This is used to implement the constant expression evaluation part of the
8243 /// attribute enable_if extension. There is nothing in standard C++ which would
8244 /// require reentering parameters.
8245 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8246   if (!Param)
8247     return;
8248 
8249   S->AddDecl(Param);
8250   if (Param->getDeclName())
8251     IdResolver.AddDecl(Param);
8252 }
8253 
8254 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
8255 /// parsing a top-level (non-nested) C++ class, and we are now
8256 /// parsing those parts of the given Method declaration that could
8257 /// not be parsed earlier (C++ [class.mem]p2), such as default
8258 /// arguments. This action should enter the scope of the given
8259 /// Method declaration as if we had just parsed the qualified method
8260 /// name. However, it should not bring the parameters into scope;
8261 /// that will be performed by ActOnDelayedCXXMethodParameter.
8262 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8263 }
8264 
8265 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8266 /// C++ method declaration. We're (re-)introducing the given
8267 /// function parameter into scope for use in parsing later parts of
8268 /// the method declaration. For example, we could see an
8269 /// ActOnParamDefaultArgument event for this parameter.
8270 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8271   if (!ParamD)
8272     return;
8273 
8274   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8275 
8276   // If this parameter has an unparsed default argument, clear it out
8277   // to make way for the parsed default argument.
8278   if (Param->hasUnparsedDefaultArg())
8279     Param->setDefaultArg(nullptr);
8280 
8281   S->AddDecl(Param);
8282   if (Param->getDeclName())
8283     IdResolver.AddDecl(Param);
8284 }
8285 
8286 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8287 /// processing the delayed method declaration for Method. The method
8288 /// declaration is now considered finished. There may be a separate
8289 /// ActOnStartOfFunctionDef action later (not necessarily
8290 /// immediately!) for this method, if it was also defined inside the
8291 /// class body.
8292 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8293   if (!MethodD)
8294     return;
8295 
8296   AdjustDeclIfTemplate(MethodD);
8297 
8298   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8299 
8300   // Now that we have our default arguments, check the constructor
8301   // again. It could produce additional diagnostics or affect whether
8302   // the class has implicitly-declared destructors, among other
8303   // things.
8304   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8305     CheckConstructor(Constructor);
8306 
8307   // Check the default arguments, which we may have added.
8308   if (!Method->isInvalidDecl())
8309     CheckCXXDefaultArguments(Method);
8310 }
8311 
8312 // Emit the given diagnostic for each non-address-space qualifier.
8313 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
8314 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
8315   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8316   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
8317     bool DiagOccured = false;
8318     FTI.MethodQualifiers->forEachQualifier(
8319         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
8320                                    SourceLocation SL) {
8321           // This diagnostic should be emitted on any qualifier except an addr
8322           // space qualifier. However, forEachQualifier currently doesn't visit
8323           // addr space qualifiers, so there's no way to write this condition
8324           // right now; we just diagnose on everything.
8325           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
8326           DiagOccured = true;
8327         });
8328     if (DiagOccured)
8329       D.setInvalidType();
8330   }
8331 }
8332 
8333 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8334 /// the well-formedness of the constructor declarator @p D with type @p
8335 /// R. If there are any errors in the declarator, this routine will
8336 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8337 /// will be updated to reflect a well-formed type for the constructor and
8338 /// returned.
8339 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8340                                           StorageClass &SC) {
8341   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8342 
8343   // C++ [class.ctor]p3:
8344   //   A constructor shall not be virtual (10.3) or static (9.4). A
8345   //   constructor can be invoked for a const, volatile or const
8346   //   volatile object. A constructor shall not be declared const,
8347   //   volatile, or const volatile (9.3.2).
8348   if (isVirtual) {
8349     if (!D.isInvalidType())
8350       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8351         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8352         << SourceRange(D.getIdentifierLoc());
8353     D.setInvalidType();
8354   }
8355   if (SC == SC_Static) {
8356     if (!D.isInvalidType())
8357       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8358         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8359         << SourceRange(D.getIdentifierLoc());
8360     D.setInvalidType();
8361     SC = SC_None;
8362   }
8363 
8364   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8365     diagnoseIgnoredQualifiers(
8366         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8367         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8368         D.getDeclSpec().getRestrictSpecLoc(),
8369         D.getDeclSpec().getAtomicSpecLoc());
8370     D.setInvalidType();
8371   }
8372 
8373   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
8374 
8375   // C++0x [class.ctor]p4:
8376   //   A constructor shall not be declared with a ref-qualifier.
8377   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8378   if (FTI.hasRefQualifier()) {
8379     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8380       << FTI.RefQualifierIsLValueRef
8381       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8382     D.setInvalidType();
8383   }
8384 
8385   // Rebuild the function type "R" without any type qualifiers (in
8386   // case any of the errors above fired) and with "void" as the
8387   // return type, since constructors don't have return types.
8388   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8389   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8390     return R;
8391 
8392   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8393   EPI.TypeQuals = Qualifiers();
8394   EPI.RefQualifier = RQ_None;
8395 
8396   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8397 }
8398 
8399 /// CheckConstructor - Checks a fully-formed constructor for
8400 /// well-formedness, issuing any diagnostics required. Returns true if
8401 /// the constructor declarator is invalid.
8402 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8403   CXXRecordDecl *ClassDecl
8404     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8405   if (!ClassDecl)
8406     return Constructor->setInvalidDecl();
8407 
8408   // C++ [class.copy]p3:
8409   //   A declaration of a constructor for a class X is ill-formed if
8410   //   its first parameter is of type (optionally cv-qualified) X and
8411   //   either there are no other parameters or else all other
8412   //   parameters have default arguments.
8413   if (!Constructor->isInvalidDecl() &&
8414       ((Constructor->getNumParams() == 1) ||
8415        (Constructor->getNumParams() > 1 &&
8416         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8417       Constructor->getTemplateSpecializationKind()
8418                                               != TSK_ImplicitInstantiation) {
8419     QualType ParamType = Constructor->getParamDecl(0)->getType();
8420     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8421     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8422       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8423       const char *ConstRef
8424         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8425                                                         : " const &";
8426       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8427         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8428 
8429       // FIXME: Rather that making the constructor invalid, we should endeavor
8430       // to fix the type.
8431       Constructor->setInvalidDecl();
8432     }
8433   }
8434 }
8435 
8436 /// CheckDestructor - Checks a fully-formed destructor definition for
8437 /// well-formedness, issuing any diagnostics required.  Returns true
8438 /// on error.
8439 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8440   CXXRecordDecl *RD = Destructor->getParent();
8441 
8442   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8443     SourceLocation Loc;
8444 
8445     if (!Destructor->isImplicit())
8446       Loc = Destructor->getLocation();
8447     else
8448       Loc = RD->getLocation();
8449 
8450     // If we have a virtual destructor, look up the deallocation function
8451     if (FunctionDecl *OperatorDelete =
8452             FindDeallocationFunctionForDestructor(Loc, RD)) {
8453       Expr *ThisArg = nullptr;
8454 
8455       // If the notional 'delete this' expression requires a non-trivial
8456       // conversion from 'this' to the type of a destroying operator delete's
8457       // first parameter, perform that conversion now.
8458       if (OperatorDelete->isDestroyingOperatorDelete()) {
8459         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8460         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8461           // C++ [class.dtor]p13:
8462           //   ... as if for the expression 'delete this' appearing in a
8463           //   non-virtual destructor of the destructor's class.
8464           ContextRAII SwitchContext(*this, Destructor);
8465           ExprResult This =
8466               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8467           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8468           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8469           if (This.isInvalid()) {
8470             // FIXME: Register this as a context note so that it comes out
8471             // in the right order.
8472             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8473             return true;
8474           }
8475           ThisArg = This.get();
8476         }
8477       }
8478 
8479       DiagnoseUseOfDecl(OperatorDelete, Loc);
8480       MarkFunctionReferenced(Loc, OperatorDelete);
8481       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8482     }
8483   }
8484 
8485   return false;
8486 }
8487 
8488 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8489 /// the well-formednes of the destructor declarator @p D with type @p
8490 /// R. If there are any errors in the declarator, this routine will
8491 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8492 /// will be updated to reflect a well-formed type for the destructor and
8493 /// returned.
8494 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8495                                          StorageClass& SC) {
8496   // C++ [class.dtor]p1:
8497   //   [...] A typedef-name that names a class is a class-name
8498   //   (7.1.3); however, a typedef-name that names a class shall not
8499   //   be used as the identifier in the declarator for a destructor
8500   //   declaration.
8501   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8502   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8503     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8504       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8505   else if (const TemplateSpecializationType *TST =
8506              DeclaratorType->getAs<TemplateSpecializationType>())
8507     if (TST->isTypeAlias())
8508       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8509         << DeclaratorType << 1;
8510 
8511   // C++ [class.dtor]p2:
8512   //   A destructor is used to destroy objects of its class type. A
8513   //   destructor takes no parameters, and no return type can be
8514   //   specified for it (not even void). The address of a destructor
8515   //   shall not be taken. A destructor shall not be static. A
8516   //   destructor can be invoked for a const, volatile or const
8517   //   volatile object. A destructor shall not be declared const,
8518   //   volatile or const volatile (9.3.2).
8519   if (SC == SC_Static) {
8520     if (!D.isInvalidType())
8521       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8522         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8523         << SourceRange(D.getIdentifierLoc())
8524         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8525 
8526     SC = SC_None;
8527   }
8528   if (!D.isInvalidType()) {
8529     // Destructors don't have return types, but the parser will
8530     // happily parse something like:
8531     //
8532     //   class X {
8533     //     float ~X();
8534     //   };
8535     //
8536     // The return type will be eliminated later.
8537     if (D.getDeclSpec().hasTypeSpecifier())
8538       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8539         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8540         << SourceRange(D.getIdentifierLoc());
8541     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8542       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8543                                 SourceLocation(),
8544                                 D.getDeclSpec().getConstSpecLoc(),
8545                                 D.getDeclSpec().getVolatileSpecLoc(),
8546                                 D.getDeclSpec().getRestrictSpecLoc(),
8547                                 D.getDeclSpec().getAtomicSpecLoc());
8548       D.setInvalidType();
8549     }
8550   }
8551 
8552   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
8553 
8554   // C++0x [class.dtor]p2:
8555   //   A destructor shall not be declared with a ref-qualifier.
8556   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8557   if (FTI.hasRefQualifier()) {
8558     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8559       << FTI.RefQualifierIsLValueRef
8560       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8561     D.setInvalidType();
8562   }
8563 
8564   // Make sure we don't have any parameters.
8565   if (FTIHasNonVoidParameters(FTI)) {
8566     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8567 
8568     // Delete the parameters.
8569     FTI.freeParams();
8570     D.setInvalidType();
8571   }
8572 
8573   // Make sure the destructor isn't variadic.
8574   if (FTI.isVariadic) {
8575     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8576     D.setInvalidType();
8577   }
8578 
8579   // Rebuild the function type "R" without any type qualifiers or
8580   // parameters (in case any of the errors above fired) and with
8581   // "void" as the return type, since destructors don't have return
8582   // types.
8583   if (!D.isInvalidType())
8584     return R;
8585 
8586   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8587   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8588   EPI.Variadic = false;
8589   EPI.TypeQuals = Qualifiers();
8590   EPI.RefQualifier = RQ_None;
8591   return Context.getFunctionType(Context.VoidTy, None, EPI);
8592 }
8593 
8594 static void extendLeft(SourceRange &R, SourceRange Before) {
8595   if (Before.isInvalid())
8596     return;
8597   R.setBegin(Before.getBegin());
8598   if (R.getEnd().isInvalid())
8599     R.setEnd(Before.getEnd());
8600 }
8601 
8602 static void extendRight(SourceRange &R, SourceRange After) {
8603   if (After.isInvalid())
8604     return;
8605   if (R.getBegin().isInvalid())
8606     R.setBegin(After.getBegin());
8607   R.setEnd(After.getEnd());
8608 }
8609 
8610 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8611 /// well-formednes of the conversion function declarator @p D with
8612 /// type @p R. If there are any errors in the declarator, this routine
8613 /// will emit diagnostics and return true. Otherwise, it will return
8614 /// false. Either way, the type @p R will be updated to reflect a
8615 /// well-formed type for the conversion operator.
8616 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8617                                      StorageClass& SC) {
8618   // C++ [class.conv.fct]p1:
8619   //   Neither parameter types nor return type can be specified. The
8620   //   type of a conversion function (8.3.5) is "function taking no
8621   //   parameter returning conversion-type-id."
8622   if (SC == SC_Static) {
8623     if (!D.isInvalidType())
8624       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8625         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8626         << D.getName().getSourceRange();
8627     D.setInvalidType();
8628     SC = SC_None;
8629   }
8630 
8631   TypeSourceInfo *ConvTSI = nullptr;
8632   QualType ConvType =
8633       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8634 
8635   const DeclSpec &DS = D.getDeclSpec();
8636   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8637     // Conversion functions don't have return types, but the parser will
8638     // happily parse something like:
8639     //
8640     //   class X {
8641     //     float operator bool();
8642     //   };
8643     //
8644     // The return type will be changed later anyway.
8645     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8646       << SourceRange(DS.getTypeSpecTypeLoc())
8647       << SourceRange(D.getIdentifierLoc());
8648     D.setInvalidType();
8649   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8650     // It's also plausible that the user writes type qualifiers in the wrong
8651     // place, such as:
8652     //   struct S { const operator int(); };
8653     // FIXME: we could provide a fixit to move the qualifiers onto the
8654     // conversion type.
8655     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8656         << SourceRange(D.getIdentifierLoc()) << 0;
8657     D.setInvalidType();
8658   }
8659 
8660   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8661 
8662   // Make sure we don't have any parameters.
8663   if (Proto->getNumParams() > 0) {
8664     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8665 
8666     // Delete the parameters.
8667     D.getFunctionTypeInfo().freeParams();
8668     D.setInvalidType();
8669   } else if (Proto->isVariadic()) {
8670     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8671     D.setInvalidType();
8672   }
8673 
8674   // Diagnose "&operator bool()" and other such nonsense.  This
8675   // is actually a gcc extension which we don't support.
8676   if (Proto->getReturnType() != ConvType) {
8677     bool NeedsTypedef = false;
8678     SourceRange Before, After;
8679 
8680     // Walk the chunks and extract information on them for our diagnostic.
8681     bool PastFunctionChunk = false;
8682     for (auto &Chunk : D.type_objects()) {
8683       switch (Chunk.Kind) {
8684       case DeclaratorChunk::Function:
8685         if (!PastFunctionChunk) {
8686           if (Chunk.Fun.HasTrailingReturnType) {
8687             TypeSourceInfo *TRT = nullptr;
8688             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8689             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8690           }
8691           PastFunctionChunk = true;
8692           break;
8693         }
8694         LLVM_FALLTHROUGH;
8695       case DeclaratorChunk::Array:
8696         NeedsTypedef = true;
8697         extendRight(After, Chunk.getSourceRange());
8698         break;
8699 
8700       case DeclaratorChunk::Pointer:
8701       case DeclaratorChunk::BlockPointer:
8702       case DeclaratorChunk::Reference:
8703       case DeclaratorChunk::MemberPointer:
8704       case DeclaratorChunk::Pipe:
8705         extendLeft(Before, Chunk.getSourceRange());
8706         break;
8707 
8708       case DeclaratorChunk::Paren:
8709         extendLeft(Before, Chunk.Loc);
8710         extendRight(After, Chunk.EndLoc);
8711         break;
8712       }
8713     }
8714 
8715     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8716                          After.isValid()  ? After.getBegin() :
8717                                             D.getIdentifierLoc();
8718     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8719     DB << Before << After;
8720 
8721     if (!NeedsTypedef) {
8722       DB << /*don't need a typedef*/0;
8723 
8724       // If we can provide a correct fix-it hint, do so.
8725       if (After.isInvalid() && ConvTSI) {
8726         SourceLocation InsertLoc =
8727             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8728         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8729            << FixItHint::CreateInsertionFromRange(
8730                   InsertLoc, CharSourceRange::getTokenRange(Before))
8731            << FixItHint::CreateRemoval(Before);
8732       }
8733     } else if (!Proto->getReturnType()->isDependentType()) {
8734       DB << /*typedef*/1 << Proto->getReturnType();
8735     } else if (getLangOpts().CPlusPlus11) {
8736       DB << /*alias template*/2 << Proto->getReturnType();
8737     } else {
8738       DB << /*might not be fixable*/3;
8739     }
8740 
8741     // Recover by incorporating the other type chunks into the result type.
8742     // Note, this does *not* change the name of the function. This is compatible
8743     // with the GCC extension:
8744     //   struct S { &operator int(); } s;
8745     //   int &r = s.operator int(); // ok in GCC
8746     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8747     ConvType = Proto->getReturnType();
8748   }
8749 
8750   // C++ [class.conv.fct]p4:
8751   //   The conversion-type-id shall not represent a function type nor
8752   //   an array type.
8753   if (ConvType->isArrayType()) {
8754     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8755     ConvType = Context.getPointerType(ConvType);
8756     D.setInvalidType();
8757   } else if (ConvType->isFunctionType()) {
8758     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8759     ConvType = Context.getPointerType(ConvType);
8760     D.setInvalidType();
8761   }
8762 
8763   // Rebuild the function type "R" without any parameters (in case any
8764   // of the errors above fired) and with the conversion type as the
8765   // return type.
8766   if (D.isInvalidType())
8767     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8768 
8769   // C++0x explicit conversion operators.
8770   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a)
8771     Diag(DS.getExplicitSpecLoc(),
8772          getLangOpts().CPlusPlus11
8773              ? diag::warn_cxx98_compat_explicit_conversion_functions
8774              : diag::ext_explicit_conversion_functions)
8775         << SourceRange(DS.getExplicitSpecRange());
8776 }
8777 
8778 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8779 /// the declaration of the given C++ conversion function. This routine
8780 /// is responsible for recording the conversion function in the C++
8781 /// class, if possible.
8782 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8783   assert(Conversion && "Expected to receive a conversion function declaration");
8784 
8785   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8786 
8787   // Make sure we aren't redeclaring the conversion function.
8788   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8789 
8790   // C++ [class.conv.fct]p1:
8791   //   [...] A conversion function is never used to convert a
8792   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8793   //   same object type (or a reference to it), to a (possibly
8794   //   cv-qualified) base class of that type (or a reference to it),
8795   //   or to (possibly cv-qualified) void.
8796   // FIXME: Suppress this warning if the conversion function ends up being a
8797   // virtual function that overrides a virtual function in a base class.
8798   QualType ClassType
8799     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8800   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8801     ConvType = ConvTypeRef->getPointeeType();
8802   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8803       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8804     /* Suppress diagnostics for instantiations. */;
8805   else if (ConvType->isRecordType()) {
8806     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8807     if (ConvType == ClassType)
8808       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8809         << ClassType;
8810     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8811       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8812         <<  ClassType << ConvType;
8813   } else if (ConvType->isVoidType()) {
8814     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8815       << ClassType << ConvType;
8816   }
8817 
8818   if (FunctionTemplateDecl *ConversionTemplate
8819                                 = Conversion->getDescribedFunctionTemplate())
8820     return ConversionTemplate;
8821 
8822   return Conversion;
8823 }
8824 
8825 namespace {
8826 /// Utility class to accumulate and print a diagnostic listing the invalid
8827 /// specifier(s) on a declaration.
8828 struct BadSpecifierDiagnoser {
8829   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8830       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8831   ~BadSpecifierDiagnoser() {
8832     Diagnostic << Specifiers;
8833   }
8834 
8835   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8836     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8837   }
8838   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8839     return check(SpecLoc,
8840                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8841   }
8842   void check(SourceLocation SpecLoc, const char *Spec) {
8843     if (SpecLoc.isInvalid()) return;
8844     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8845     if (!Specifiers.empty()) Specifiers += " ";
8846     Specifiers += Spec;
8847   }
8848 
8849   Sema &S;
8850   Sema::SemaDiagnosticBuilder Diagnostic;
8851   std::string Specifiers;
8852 };
8853 }
8854 
8855 /// Check the validity of a declarator that we parsed for a deduction-guide.
8856 /// These aren't actually declarators in the grammar, so we need to check that
8857 /// the user didn't specify any pieces that are not part of the deduction-guide
8858 /// grammar.
8859 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8860                                          StorageClass &SC) {
8861   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8862   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8863   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8864 
8865   // C++ [temp.deduct.guide]p3:
8866   //   A deduction-gide shall be declared in the same scope as the
8867   //   corresponding class template.
8868   if (!CurContext->getRedeclContext()->Equals(
8869           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8870     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8871       << GuidedTemplateDecl;
8872     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8873   }
8874 
8875   auto &DS = D.getMutableDeclSpec();
8876   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8877   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8878       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8879       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
8880     BadSpecifierDiagnoser Diagnoser(
8881         *this, D.getIdentifierLoc(),
8882         diag::err_deduction_guide_invalid_specifier);
8883 
8884     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8885     DS.ClearStorageClassSpecs();
8886     SC = SC_None;
8887 
8888     // 'explicit' is permitted.
8889     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8890     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8891     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8892     DS.ClearConstexprSpec();
8893 
8894     Diagnoser.check(DS.getConstSpecLoc(), "const");
8895     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8896     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8897     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8898     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8899     DS.ClearTypeQualifiers();
8900 
8901     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8902     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8903     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8904     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8905     DS.ClearTypeSpecType();
8906   }
8907 
8908   if (D.isInvalidType())
8909     return;
8910 
8911   // Check the declarator is simple enough.
8912   bool FoundFunction = false;
8913   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8914     if (Chunk.Kind == DeclaratorChunk::Paren)
8915       continue;
8916     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8917       Diag(D.getDeclSpec().getBeginLoc(),
8918            diag::err_deduction_guide_with_complex_decl)
8919           << D.getSourceRange();
8920       break;
8921     }
8922     if (!Chunk.Fun.hasTrailingReturnType()) {
8923       Diag(D.getName().getBeginLoc(),
8924            diag::err_deduction_guide_no_trailing_return_type);
8925       break;
8926     }
8927 
8928     // Check that the return type is written as a specialization of
8929     // the template specified as the deduction-guide's name.
8930     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8931     TypeSourceInfo *TSI = nullptr;
8932     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8933     assert(TSI && "deduction guide has valid type but invalid return type?");
8934     bool AcceptableReturnType = false;
8935     bool MightInstantiateToSpecialization = false;
8936     if (auto RetTST =
8937             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8938       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8939       bool TemplateMatches =
8940           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8941       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8942         AcceptableReturnType = true;
8943       else {
8944         // This could still instantiate to the right type, unless we know it
8945         // names the wrong class template.
8946         auto *TD = SpecifiedName.getAsTemplateDecl();
8947         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8948                                              !TemplateMatches);
8949       }
8950     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8951       MightInstantiateToSpecialization = true;
8952     }
8953 
8954     if (!AcceptableReturnType) {
8955       Diag(TSI->getTypeLoc().getBeginLoc(),
8956            diag::err_deduction_guide_bad_trailing_return_type)
8957           << GuidedTemplate << TSI->getType()
8958           << MightInstantiateToSpecialization
8959           << TSI->getTypeLoc().getSourceRange();
8960     }
8961 
8962     // Keep going to check that we don't have any inner declarator pieces (we
8963     // could still have a function returning a pointer to a function).
8964     FoundFunction = true;
8965   }
8966 
8967   if (D.isFunctionDefinition())
8968     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8969 }
8970 
8971 //===----------------------------------------------------------------------===//
8972 // Namespace Handling
8973 //===----------------------------------------------------------------------===//
8974 
8975 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8976 /// reopened.
8977 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8978                                             SourceLocation Loc,
8979                                             IdentifierInfo *II, bool *IsInline,
8980                                             NamespaceDecl *PrevNS) {
8981   assert(*IsInline != PrevNS->isInline());
8982 
8983   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8984   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8985   // inline namespaces, with the intention of bringing names into namespace std.
8986   //
8987   // We support this just well enough to get that case working; this is not
8988   // sufficient to support reopening namespaces as inline in general.
8989   if (*IsInline && II && II->getName().startswith("__atomic") &&
8990       S.getSourceManager().isInSystemHeader(Loc)) {
8991     // Mark all prior declarations of the namespace as inline.
8992     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8993          NS = NS->getPreviousDecl())
8994       NS->setInline(*IsInline);
8995     // Patch up the lookup table for the containing namespace. This isn't really
8996     // correct, but it's good enough for this particular case.
8997     for (auto *I : PrevNS->decls())
8998       if (auto *ND = dyn_cast<NamedDecl>(I))
8999         PrevNS->getParent()->makeDeclVisibleInContext(ND);
9000     return;
9001   }
9002 
9003   if (PrevNS->isInline())
9004     // The user probably just forgot the 'inline', so suggest that it
9005     // be added back.
9006     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
9007       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
9008   else
9009     S.Diag(Loc, diag::err_inline_namespace_mismatch);
9010 
9011   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
9012   *IsInline = PrevNS->isInline();
9013 }
9014 
9015 /// ActOnStartNamespaceDef - This is called at the start of a namespace
9016 /// definition.
9017 Decl *Sema::ActOnStartNamespaceDef(
9018     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
9019     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
9020     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
9021   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
9022   // For anonymous namespace, take the location of the left brace.
9023   SourceLocation Loc = II ? IdentLoc : LBrace;
9024   bool IsInline = InlineLoc.isValid();
9025   bool IsInvalid = false;
9026   bool IsStd = false;
9027   bool AddToKnown = false;
9028   Scope *DeclRegionScope = NamespcScope->getParent();
9029 
9030   NamespaceDecl *PrevNS = nullptr;
9031   if (II) {
9032     // C++ [namespace.def]p2:
9033     //   The identifier in an original-namespace-definition shall not
9034     //   have been previously defined in the declarative region in
9035     //   which the original-namespace-definition appears. The
9036     //   identifier in an original-namespace-definition is the name of
9037     //   the namespace. Subsequently in that declarative region, it is
9038     //   treated as an original-namespace-name.
9039     //
9040     // Since namespace names are unique in their scope, and we don't
9041     // look through using directives, just look for any ordinary names
9042     // as if by qualified name lookup.
9043     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
9044                    ForExternalRedeclaration);
9045     LookupQualifiedName(R, CurContext->getRedeclContext());
9046     NamedDecl *PrevDecl =
9047         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
9048     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
9049 
9050     if (PrevNS) {
9051       // This is an extended namespace definition.
9052       if (IsInline != PrevNS->isInline())
9053         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
9054                                         &IsInline, PrevNS);
9055     } else if (PrevDecl) {
9056       // This is an invalid name redefinition.
9057       Diag(Loc, diag::err_redefinition_different_kind)
9058         << II;
9059       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9060       IsInvalid = true;
9061       // Continue on to push Namespc as current DeclContext and return it.
9062     } else if (II->isStr("std") &&
9063                CurContext->getRedeclContext()->isTranslationUnit()) {
9064       // This is the first "real" definition of the namespace "std", so update
9065       // our cache of the "std" namespace to point at this definition.
9066       PrevNS = getStdNamespace();
9067       IsStd = true;
9068       AddToKnown = !IsInline;
9069     } else {
9070       // We've seen this namespace for the first time.
9071       AddToKnown = !IsInline;
9072     }
9073   } else {
9074     // Anonymous namespaces.
9075 
9076     // Determine whether the parent already has an anonymous namespace.
9077     DeclContext *Parent = CurContext->getRedeclContext();
9078     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
9079       PrevNS = TU->getAnonymousNamespace();
9080     } else {
9081       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
9082       PrevNS = ND->getAnonymousNamespace();
9083     }
9084 
9085     if (PrevNS && IsInline != PrevNS->isInline())
9086       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
9087                                       &IsInline, PrevNS);
9088   }
9089 
9090   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
9091                                                  StartLoc, Loc, II, PrevNS);
9092   if (IsInvalid)
9093     Namespc->setInvalidDecl();
9094 
9095   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
9096   AddPragmaAttributes(DeclRegionScope, Namespc);
9097 
9098   // FIXME: Should we be merging attributes?
9099   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
9100     PushNamespaceVisibilityAttr(Attr, Loc);
9101 
9102   if (IsStd)
9103     StdNamespace = Namespc;
9104   if (AddToKnown)
9105     KnownNamespaces[Namespc] = false;
9106 
9107   if (II) {
9108     PushOnScopeChains(Namespc, DeclRegionScope);
9109   } else {
9110     // Link the anonymous namespace into its parent.
9111     DeclContext *Parent = CurContext->getRedeclContext();
9112     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
9113       TU->setAnonymousNamespace(Namespc);
9114     } else {
9115       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
9116     }
9117 
9118     CurContext->addDecl(Namespc);
9119 
9120     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
9121     //   behaves as if it were replaced by
9122     //     namespace unique { /* empty body */ }
9123     //     using namespace unique;
9124     //     namespace unique { namespace-body }
9125     //   where all occurrences of 'unique' in a translation unit are
9126     //   replaced by the same identifier and this identifier differs
9127     //   from all other identifiers in the entire program.
9128 
9129     // We just create the namespace with an empty name and then add an
9130     // implicit using declaration, just like the standard suggests.
9131     //
9132     // CodeGen enforces the "universally unique" aspect by giving all
9133     // declarations semantically contained within an anonymous
9134     // namespace internal linkage.
9135 
9136     if (!PrevNS) {
9137       UD = UsingDirectiveDecl::Create(Context, Parent,
9138                                       /* 'using' */ LBrace,
9139                                       /* 'namespace' */ SourceLocation(),
9140                                       /* qualifier */ NestedNameSpecifierLoc(),
9141                                       /* identifier */ SourceLocation(),
9142                                       Namespc,
9143                                       /* Ancestor */ Parent);
9144       UD->setImplicit();
9145       Parent->addDecl(UD);
9146     }
9147   }
9148 
9149   ActOnDocumentableDecl(Namespc);
9150 
9151   // Although we could have an invalid decl (i.e. the namespace name is a
9152   // redefinition), push it as current DeclContext and try to continue parsing.
9153   // FIXME: We should be able to push Namespc here, so that the each DeclContext
9154   // for the namespace has the declarations that showed up in that particular
9155   // namespace definition.
9156   PushDeclContext(NamespcScope, Namespc);
9157   return Namespc;
9158 }
9159 
9160 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
9161 /// is a namespace alias, returns the namespace it points to.
9162 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
9163   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
9164     return AD->getNamespace();
9165   return dyn_cast_or_null<NamespaceDecl>(D);
9166 }
9167 
9168 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
9169 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
9170 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
9171   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
9172   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
9173   Namespc->setRBraceLoc(RBrace);
9174   PopDeclContext();
9175   if (Namespc->hasAttr<VisibilityAttr>())
9176     PopPragmaVisibility(true, RBrace);
9177   // If this namespace contains an export-declaration, export it now.
9178   if (DeferredExportedNamespaces.erase(Namespc))
9179     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
9180 }
9181 
9182 CXXRecordDecl *Sema::getStdBadAlloc() const {
9183   return cast_or_null<CXXRecordDecl>(
9184                                   StdBadAlloc.get(Context.getExternalSource()));
9185 }
9186 
9187 EnumDecl *Sema::getStdAlignValT() const {
9188   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9189 }
9190 
9191 NamespaceDecl *Sema::getStdNamespace() const {
9192   return cast_or_null<NamespaceDecl>(
9193                                  StdNamespace.get(Context.getExternalSource()));
9194 }
9195 
9196 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
9197   if (!StdExperimentalNamespaceCache) {
9198     if (auto Std = getStdNamespace()) {
9199       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9200                           SourceLocation(), LookupNamespaceName);
9201       if (!LookupQualifiedName(Result, Std) ||
9202           !(StdExperimentalNamespaceCache =
9203                 Result.getAsSingle<NamespaceDecl>()))
9204         Result.suppressDiagnostics();
9205     }
9206   }
9207   return StdExperimentalNamespaceCache;
9208 }
9209 
9210 namespace {
9211 
9212 enum UnsupportedSTLSelect {
9213   USS_InvalidMember,
9214   USS_MissingMember,
9215   USS_NonTrivial,
9216   USS_Other
9217 };
9218 
9219 struct InvalidSTLDiagnoser {
9220   Sema &S;
9221   SourceLocation Loc;
9222   QualType TyForDiags;
9223 
9224   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9225                       const VarDecl *VD = nullptr) {
9226     {
9227       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9228                << TyForDiags << ((int)Sel);
9229       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9230         assert(!Name.empty());
9231         D << Name;
9232       }
9233     }
9234     if (Sel == USS_InvalidMember) {
9235       S.Diag(VD->getLocation(), diag::note_var_declared_here)
9236           << VD << VD->getSourceRange();
9237     }
9238     return QualType();
9239   }
9240 };
9241 } // namespace
9242 
9243 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9244                                            SourceLocation Loc) {
9245   assert(getLangOpts().CPlusPlus &&
9246          "Looking for comparison category type outside of C++.");
9247 
9248   // Check if we've already successfully checked the comparison category type
9249   // before. If so, skip checking it again.
9250   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9251   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9252     return Info->getType();
9253 
9254   // If lookup failed
9255   if (!Info) {
9256     std::string NameForDiags = "std::";
9257     NameForDiags += ComparisonCategories::getCategoryString(Kind);
9258     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9259         << NameForDiags;
9260     return QualType();
9261   }
9262 
9263   assert(Info->Kind == Kind);
9264   assert(Info->Record);
9265 
9266   // Update the Record decl in case we encountered a forward declaration on our
9267   // first pass. FIXME: This is a bit of a hack.
9268   if (Info->Record->hasDefinition())
9269     Info->Record = Info->Record->getDefinition();
9270 
9271   // Use an elaborated type for diagnostics which has a name containing the
9272   // prepended 'std' namespace but not any inline namespace names.
9273   QualType TyForDiags = [&]() {
9274     auto *NNS =
9275         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9276     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9277   }();
9278 
9279   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9280     return QualType();
9281 
9282   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9283 
9284   if (!Info->Record->isTriviallyCopyable())
9285     return UnsupportedSTLError(USS_NonTrivial);
9286 
9287   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9288     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9289     // Tolerate empty base classes.
9290     if (Base->isEmpty())
9291       continue;
9292     // Reject STL implementations which have at least one non-empty base.
9293     return UnsupportedSTLError();
9294   }
9295 
9296   // Check that the STL has implemented the types using a single integer field.
9297   // This expectation allows better codegen for builtin operators. We require:
9298   //   (1) The class has exactly one field.
9299   //   (2) The field is an integral or enumeration type.
9300   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9301   if (std::distance(FIt, FEnd) != 1 ||
9302       !FIt->getType()->isIntegralOrEnumerationType()) {
9303     return UnsupportedSTLError();
9304   }
9305 
9306   // Build each of the require values and store them in Info.
9307   for (ComparisonCategoryResult CCR :
9308        ComparisonCategories::getPossibleResultsForType(Kind)) {
9309     StringRef MemName = ComparisonCategories::getResultString(CCR);
9310     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9311 
9312     if (!ValInfo)
9313       return UnsupportedSTLError(USS_MissingMember, MemName);
9314 
9315     VarDecl *VD = ValInfo->VD;
9316     assert(VD && "should not be null!");
9317 
9318     // Attempt to diagnose reasons why the STL definition of this type
9319     // might be foobar, including it failing to be a constant expression.
9320     // TODO Handle more ways the lookup or result can be invalid.
9321     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9322         !VD->checkInitIsICE())
9323       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9324 
9325     // Attempt to evaluate the var decl as a constant expression and extract
9326     // the value of its first field as a ICE. If this fails, the STL
9327     // implementation is not supported.
9328     if (!ValInfo->hasValidIntValue())
9329       return UnsupportedSTLError();
9330 
9331     MarkVariableReferenced(Loc, VD);
9332   }
9333 
9334   // We've successfully built the required types and expressions. Update
9335   // the cache and return the newly cached value.
9336   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9337   return Info->getType();
9338 }
9339 
9340 /// Retrieve the special "std" namespace, which may require us to
9341 /// implicitly define the namespace.
9342 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9343   if (!StdNamespace) {
9344     // The "std" namespace has not yet been defined, so build one implicitly.
9345     StdNamespace = NamespaceDecl::Create(Context,
9346                                          Context.getTranslationUnitDecl(),
9347                                          /*Inline=*/false,
9348                                          SourceLocation(), SourceLocation(),
9349                                          &PP.getIdentifierTable().get("std"),
9350                                          /*PrevDecl=*/nullptr);
9351     getStdNamespace()->setImplicit(true);
9352   }
9353 
9354   return getStdNamespace();
9355 }
9356 
9357 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9358   assert(getLangOpts().CPlusPlus &&
9359          "Looking for std::initializer_list outside of C++.");
9360 
9361   // We're looking for implicit instantiations of
9362   // template <typename E> class std::initializer_list.
9363 
9364   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9365     return false;
9366 
9367   ClassTemplateDecl *Template = nullptr;
9368   const TemplateArgument *Arguments = nullptr;
9369 
9370   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9371 
9372     ClassTemplateSpecializationDecl *Specialization =
9373         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9374     if (!Specialization)
9375       return false;
9376 
9377     Template = Specialization->getSpecializedTemplate();
9378     Arguments = Specialization->getTemplateArgs().data();
9379   } else if (const TemplateSpecializationType *TST =
9380                  Ty->getAs<TemplateSpecializationType>()) {
9381     Template = dyn_cast_or_null<ClassTemplateDecl>(
9382         TST->getTemplateName().getAsTemplateDecl());
9383     Arguments = TST->getArgs();
9384   }
9385   if (!Template)
9386     return false;
9387 
9388   if (!StdInitializerList) {
9389     // Haven't recognized std::initializer_list yet, maybe this is it.
9390     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9391     if (TemplateClass->getIdentifier() !=
9392             &PP.getIdentifierTable().get("initializer_list") ||
9393         !getStdNamespace()->InEnclosingNamespaceSetOf(
9394             TemplateClass->getDeclContext()))
9395       return false;
9396     // This is a template called std::initializer_list, but is it the right
9397     // template?
9398     TemplateParameterList *Params = Template->getTemplateParameters();
9399     if (Params->getMinRequiredArguments() != 1)
9400       return false;
9401     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9402       return false;
9403 
9404     // It's the right template.
9405     StdInitializerList = Template;
9406   }
9407 
9408   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9409     return false;
9410 
9411   // This is an instance of std::initializer_list. Find the argument type.
9412   if (Element)
9413     *Element = Arguments[0].getAsType();
9414   return true;
9415 }
9416 
9417 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9418   NamespaceDecl *Std = S.getStdNamespace();
9419   if (!Std) {
9420     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9421     return nullptr;
9422   }
9423 
9424   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9425                       Loc, Sema::LookupOrdinaryName);
9426   if (!S.LookupQualifiedName(Result, Std)) {
9427     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9428     return nullptr;
9429   }
9430   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9431   if (!Template) {
9432     Result.suppressDiagnostics();
9433     // We found something weird. Complain about the first thing we found.
9434     NamedDecl *Found = *Result.begin();
9435     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9436     return nullptr;
9437   }
9438 
9439   // We found some template called std::initializer_list. Now verify that it's
9440   // correct.
9441   TemplateParameterList *Params = Template->getTemplateParameters();
9442   if (Params->getMinRequiredArguments() != 1 ||
9443       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9444     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9445     return nullptr;
9446   }
9447 
9448   return Template;
9449 }
9450 
9451 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9452   if (!StdInitializerList) {
9453     StdInitializerList = LookupStdInitializerList(*this, Loc);
9454     if (!StdInitializerList)
9455       return QualType();
9456   }
9457 
9458   TemplateArgumentListInfo Args(Loc, Loc);
9459   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9460                                        Context.getTrivialTypeSourceInfo(Element,
9461                                                                         Loc)));
9462   return Context.getCanonicalType(
9463       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9464 }
9465 
9466 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9467   // C++ [dcl.init.list]p2:
9468   //   A constructor is an initializer-list constructor if its first parameter
9469   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9470   //   std::initializer_list<E> for some type E, and either there are no other
9471   //   parameters or else all other parameters have default arguments.
9472   if (Ctor->getNumParams() < 1 ||
9473       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9474     return false;
9475 
9476   QualType ArgType = Ctor->getParamDecl(0)->getType();
9477   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9478     ArgType = RT->getPointeeType().getUnqualifiedType();
9479 
9480   return isStdInitializerList(ArgType, nullptr);
9481 }
9482 
9483 /// Determine whether a using statement is in a context where it will be
9484 /// apply in all contexts.
9485 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9486   switch (CurContext->getDeclKind()) {
9487     case Decl::TranslationUnit:
9488       return true;
9489     case Decl::LinkageSpec:
9490       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9491     default:
9492       return false;
9493   }
9494 }
9495 
9496 namespace {
9497 
9498 // Callback to only accept typo corrections that are namespaces.
9499 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
9500 public:
9501   bool ValidateCandidate(const TypoCorrection &candidate) override {
9502     if (NamedDecl *ND = candidate.getCorrectionDecl())
9503       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9504     return false;
9505   }
9506 
9507   std::unique_ptr<CorrectionCandidateCallback> clone() override {
9508     return std::make_unique<NamespaceValidatorCCC>(*this);
9509   }
9510 };
9511 
9512 }
9513 
9514 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9515                                        CXXScopeSpec &SS,
9516                                        SourceLocation IdentLoc,
9517                                        IdentifierInfo *Ident) {
9518   R.clear();
9519   NamespaceValidatorCCC CCC{};
9520   if (TypoCorrection Corrected =
9521           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
9522                         Sema::CTK_ErrorRecovery)) {
9523     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9524       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9525       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9526                               Ident->getName().equals(CorrectedStr);
9527       S.diagnoseTypo(Corrected,
9528                      S.PDiag(diag::err_using_directive_member_suggest)
9529                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9530                      S.PDiag(diag::note_namespace_defined_here));
9531     } else {
9532       S.diagnoseTypo(Corrected,
9533                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9534                      S.PDiag(diag::note_namespace_defined_here));
9535     }
9536     R.addDecl(Corrected.getFoundDecl());
9537     return true;
9538   }
9539   return false;
9540 }
9541 
9542 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9543                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9544                                 SourceLocation IdentLoc,
9545                                 IdentifierInfo *NamespcName,
9546                                 const ParsedAttributesView &AttrList) {
9547   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9548   assert(NamespcName && "Invalid NamespcName.");
9549   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9550 
9551   // This can only happen along a recovery path.
9552   while (S->isTemplateParamScope())
9553     S = S->getParent();
9554   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9555 
9556   UsingDirectiveDecl *UDir = nullptr;
9557   NestedNameSpecifier *Qualifier = nullptr;
9558   if (SS.isSet())
9559     Qualifier = SS.getScopeRep();
9560 
9561   // Lookup namespace name.
9562   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9563   LookupParsedName(R, S, &SS);
9564   if (R.isAmbiguous())
9565     return nullptr;
9566 
9567   if (R.empty()) {
9568     R.clear();
9569     // Allow "using namespace std;" or "using namespace ::std;" even if
9570     // "std" hasn't been defined yet, for GCC compatibility.
9571     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9572         NamespcName->isStr("std")) {
9573       Diag(IdentLoc, diag::ext_using_undefined_std);
9574       R.addDecl(getOrCreateStdNamespace());
9575       R.resolveKind();
9576     }
9577     // Otherwise, attempt typo correction.
9578     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9579   }
9580 
9581   if (!R.empty()) {
9582     NamedDecl *Named = R.getRepresentativeDecl();
9583     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9584     assert(NS && "expected namespace decl");
9585 
9586     // The use of a nested name specifier may trigger deprecation warnings.
9587     DiagnoseUseOfDecl(Named, IdentLoc);
9588 
9589     // C++ [namespace.udir]p1:
9590     //   A using-directive specifies that the names in the nominated
9591     //   namespace can be used in the scope in which the
9592     //   using-directive appears after the using-directive. During
9593     //   unqualified name lookup (3.4.1), the names appear as if they
9594     //   were declared in the nearest enclosing namespace which
9595     //   contains both the using-directive and the nominated
9596     //   namespace. [Note: in this context, "contains" means "contains
9597     //   directly or indirectly". ]
9598 
9599     // Find enclosing context containing both using-directive and
9600     // nominated namespace.
9601     DeclContext *CommonAncestor = NS;
9602     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9603       CommonAncestor = CommonAncestor->getParent();
9604 
9605     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9606                                       SS.getWithLocInContext(Context),
9607                                       IdentLoc, Named, CommonAncestor);
9608 
9609     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9610         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9611       Diag(IdentLoc, diag::warn_using_directive_in_header);
9612     }
9613 
9614     PushUsingDirective(S, UDir);
9615   } else {
9616     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9617   }
9618 
9619   if (UDir)
9620     ProcessDeclAttributeList(S, UDir, AttrList);
9621 
9622   return UDir;
9623 }
9624 
9625 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9626   // If the scope has an associated entity and the using directive is at
9627   // namespace or translation unit scope, add the UsingDirectiveDecl into
9628   // its lookup structure so qualified name lookup can find it.
9629   DeclContext *Ctx = S->getEntity();
9630   if (Ctx && !Ctx->isFunctionOrMethod())
9631     Ctx->addDecl(UDir);
9632   else
9633     // Otherwise, it is at block scope. The using-directives will affect lookup
9634     // only to the end of the scope.
9635     S->PushUsingDirective(UDir);
9636 }
9637 
9638 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9639                                   SourceLocation UsingLoc,
9640                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
9641                                   UnqualifiedId &Name,
9642                                   SourceLocation EllipsisLoc,
9643                                   const ParsedAttributesView &AttrList) {
9644   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9645 
9646   if (SS.isEmpty()) {
9647     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9648     return nullptr;
9649   }
9650 
9651   switch (Name.getKind()) {
9652   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9653   case UnqualifiedIdKind::IK_Identifier:
9654   case UnqualifiedIdKind::IK_OperatorFunctionId:
9655   case UnqualifiedIdKind::IK_LiteralOperatorId:
9656   case UnqualifiedIdKind::IK_ConversionFunctionId:
9657     break;
9658 
9659   case UnqualifiedIdKind::IK_ConstructorName:
9660   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9661     // C++11 inheriting constructors.
9662     Diag(Name.getBeginLoc(),
9663          getLangOpts().CPlusPlus11
9664              ? diag::warn_cxx98_compat_using_decl_constructor
9665              : diag::err_using_decl_constructor)
9666         << SS.getRange();
9667 
9668     if (getLangOpts().CPlusPlus11) break;
9669 
9670     return nullptr;
9671 
9672   case UnqualifiedIdKind::IK_DestructorName:
9673     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9674     return nullptr;
9675 
9676   case UnqualifiedIdKind::IK_TemplateId:
9677     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9678         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9679     return nullptr;
9680 
9681   case UnqualifiedIdKind::IK_DeductionGuideName:
9682     llvm_unreachable("cannot parse qualified deduction guide name");
9683   }
9684 
9685   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9686   DeclarationName TargetName = TargetNameInfo.getName();
9687   if (!TargetName)
9688     return nullptr;
9689 
9690   // Warn about access declarations.
9691   if (UsingLoc.isInvalid()) {
9692     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9693                                  ? diag::err_access_decl
9694                                  : diag::warn_access_decl_deprecated)
9695         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9696   }
9697 
9698   if (EllipsisLoc.isInvalid()) {
9699     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9700         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9701       return nullptr;
9702   } else {
9703     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9704         !TargetNameInfo.containsUnexpandedParameterPack()) {
9705       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9706         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9707       EllipsisLoc = SourceLocation();
9708     }
9709   }
9710 
9711   NamedDecl *UD =
9712       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9713                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9714                             /*IsInstantiation*/false);
9715   if (UD)
9716     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9717 
9718   return UD;
9719 }
9720 
9721 /// Determine whether a using declaration considers the given
9722 /// declarations as "equivalent", e.g., if they are redeclarations of
9723 /// the same entity or are both typedefs of the same type.
9724 static bool
9725 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9726   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9727     return true;
9728 
9729   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9730     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9731       return Context.hasSameType(TD1->getUnderlyingType(),
9732                                  TD2->getUnderlyingType());
9733 
9734   return false;
9735 }
9736 
9737 
9738 /// Determines whether to create a using shadow decl for a particular
9739 /// decl, given the set of decls existing prior to this using lookup.
9740 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9741                                 const LookupResult &Previous,
9742                                 UsingShadowDecl *&PrevShadow) {
9743   // Diagnose finding a decl which is not from a base class of the
9744   // current class.  We do this now because there are cases where this
9745   // function will silently decide not to build a shadow decl, which
9746   // will pre-empt further diagnostics.
9747   //
9748   // We don't need to do this in C++11 because we do the check once on
9749   // the qualifier.
9750   //
9751   // FIXME: diagnose the following if we care enough:
9752   //   struct A { int foo; };
9753   //   struct B : A { using A::foo; };
9754   //   template <class T> struct C : A {};
9755   //   template <class T> struct D : C<T> { using B::foo; } // <---
9756   // This is invalid (during instantiation) in C++03 because B::foo
9757   // resolves to the using decl in B, which is not a base class of D<T>.
9758   // We can't diagnose it immediately because C<T> is an unknown
9759   // specialization.  The UsingShadowDecl in D<T> then points directly
9760   // to A::foo, which will look well-formed when we instantiate.
9761   // The right solution is to not collapse the shadow-decl chain.
9762   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9763     DeclContext *OrigDC = Orig->getDeclContext();
9764 
9765     // Handle enums and anonymous structs.
9766     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9767     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9768     while (OrigRec->isAnonymousStructOrUnion())
9769       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9770 
9771     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9772       if (OrigDC == CurContext) {
9773         Diag(Using->getLocation(),
9774              diag::err_using_decl_nested_name_specifier_is_current_class)
9775           << Using->getQualifierLoc().getSourceRange();
9776         Diag(Orig->getLocation(), diag::note_using_decl_target);
9777         Using->setInvalidDecl();
9778         return true;
9779       }
9780 
9781       Diag(Using->getQualifierLoc().getBeginLoc(),
9782            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9783         << Using->getQualifier()
9784         << cast<CXXRecordDecl>(CurContext)
9785         << Using->getQualifierLoc().getSourceRange();
9786       Diag(Orig->getLocation(), diag::note_using_decl_target);
9787       Using->setInvalidDecl();
9788       return true;
9789     }
9790   }
9791 
9792   if (Previous.empty()) return false;
9793 
9794   NamedDecl *Target = Orig;
9795   if (isa<UsingShadowDecl>(Target))
9796     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9797 
9798   // If the target happens to be one of the previous declarations, we
9799   // don't have a conflict.
9800   //
9801   // FIXME: but we might be increasing its access, in which case we
9802   // should redeclare it.
9803   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9804   bool FoundEquivalentDecl = false;
9805   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9806          I != E; ++I) {
9807     NamedDecl *D = (*I)->getUnderlyingDecl();
9808     // We can have UsingDecls in our Previous results because we use the same
9809     // LookupResult for checking whether the UsingDecl itself is a valid
9810     // redeclaration.
9811     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9812       continue;
9813 
9814     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9815       // C++ [class.mem]p19:
9816       //   If T is the name of a class, then [every named member other than
9817       //   a non-static data member] shall have a name different from T
9818       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9819           !isa<IndirectFieldDecl>(Target) &&
9820           !isa<UnresolvedUsingValueDecl>(Target) &&
9821           DiagnoseClassNameShadow(
9822               CurContext,
9823               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9824         return true;
9825     }
9826 
9827     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9828       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9829         PrevShadow = Shadow;
9830       FoundEquivalentDecl = true;
9831     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9832       // We don't conflict with an existing using shadow decl of an equivalent
9833       // declaration, but we're not a redeclaration of it.
9834       FoundEquivalentDecl = true;
9835     }
9836 
9837     if (isVisible(D))
9838       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9839   }
9840 
9841   if (FoundEquivalentDecl)
9842     return false;
9843 
9844   if (FunctionDecl *FD = Target->getAsFunction()) {
9845     NamedDecl *OldDecl = nullptr;
9846     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9847                           /*IsForUsingDecl*/ true)) {
9848     case Ovl_Overload:
9849       return false;
9850 
9851     case Ovl_NonFunction:
9852       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9853       break;
9854 
9855     // We found a decl with the exact signature.
9856     case Ovl_Match:
9857       // If we're in a record, we want to hide the target, so we
9858       // return true (without a diagnostic) to tell the caller not to
9859       // build a shadow decl.
9860       if (CurContext->isRecord())
9861         return true;
9862 
9863       // If we're not in a record, this is an error.
9864       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9865       break;
9866     }
9867 
9868     Diag(Target->getLocation(), diag::note_using_decl_target);
9869     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9870     Using->setInvalidDecl();
9871     return true;
9872   }
9873 
9874   // Target is not a function.
9875 
9876   if (isa<TagDecl>(Target)) {
9877     // No conflict between a tag and a non-tag.
9878     if (!Tag) return false;
9879 
9880     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9881     Diag(Target->getLocation(), diag::note_using_decl_target);
9882     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9883     Using->setInvalidDecl();
9884     return true;
9885   }
9886 
9887   // No conflict between a tag and a non-tag.
9888   if (!NonTag) return false;
9889 
9890   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9891   Diag(Target->getLocation(), diag::note_using_decl_target);
9892   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9893   Using->setInvalidDecl();
9894   return true;
9895 }
9896 
9897 /// Determine whether a direct base class is a virtual base class.
9898 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9899   if (!Derived->getNumVBases())
9900     return false;
9901   for (auto &B : Derived->bases())
9902     if (B.getType()->getAsCXXRecordDecl() == Base)
9903       return B.isVirtual();
9904   llvm_unreachable("not a direct base class");
9905 }
9906 
9907 /// Builds a shadow declaration corresponding to a 'using' declaration.
9908 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9909                                             UsingDecl *UD,
9910                                             NamedDecl *Orig,
9911                                             UsingShadowDecl *PrevDecl) {
9912   // If we resolved to another shadow declaration, just coalesce them.
9913   NamedDecl *Target = Orig;
9914   if (isa<UsingShadowDecl>(Target)) {
9915     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9916     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9917   }
9918 
9919   NamedDecl *NonTemplateTarget = Target;
9920   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9921     NonTemplateTarget = TargetTD->getTemplatedDecl();
9922 
9923   UsingShadowDecl *Shadow;
9924   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
9925     bool IsVirtualBase =
9926         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9927                             UD->getQualifier()->getAsRecordDecl());
9928     Shadow = ConstructorUsingShadowDecl::Create(
9929         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9930   } else {
9931     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9932                                      Target);
9933   }
9934   UD->addShadowDecl(Shadow);
9935 
9936   Shadow->setAccess(UD->getAccess());
9937   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9938     Shadow->setInvalidDecl();
9939 
9940   Shadow->setPreviousDecl(PrevDecl);
9941 
9942   if (S)
9943     PushOnScopeChains(Shadow, S);
9944   else
9945     CurContext->addDecl(Shadow);
9946 
9947 
9948   return Shadow;
9949 }
9950 
9951 /// Hides a using shadow declaration.  This is required by the current
9952 /// using-decl implementation when a resolvable using declaration in a
9953 /// class is followed by a declaration which would hide or override
9954 /// one or more of the using decl's targets; for example:
9955 ///
9956 ///   struct Base { void foo(int); };
9957 ///   struct Derived : Base {
9958 ///     using Base::foo;
9959 ///     void foo(int);
9960 ///   };
9961 ///
9962 /// The governing language is C++03 [namespace.udecl]p12:
9963 ///
9964 ///   When a using-declaration brings names from a base class into a
9965 ///   derived class scope, member functions in the derived class
9966 ///   override and/or hide member functions with the same name and
9967 ///   parameter types in a base class (rather than conflicting).
9968 ///
9969 /// There are two ways to implement this:
9970 ///   (1) optimistically create shadow decls when they're not hidden
9971 ///       by existing declarations, or
9972 ///   (2) don't create any shadow decls (or at least don't make them
9973 ///       visible) until we've fully parsed/instantiated the class.
9974 /// The problem with (1) is that we might have to retroactively remove
9975 /// a shadow decl, which requires several O(n) operations because the
9976 /// decl structures are (very reasonably) not designed for removal.
9977 /// (2) avoids this but is very fiddly and phase-dependent.
9978 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9979   if (Shadow->getDeclName().getNameKind() ==
9980         DeclarationName::CXXConversionFunctionName)
9981     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9982 
9983   // Remove it from the DeclContext...
9984   Shadow->getDeclContext()->removeDecl(Shadow);
9985 
9986   // ...and the scope, if applicable...
9987   if (S) {
9988     S->RemoveDecl(Shadow);
9989     IdResolver.RemoveDecl(Shadow);
9990   }
9991 
9992   // ...and the using decl.
9993   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9994 
9995   // TODO: complain somehow if Shadow was used.  It shouldn't
9996   // be possible for this to happen, because...?
9997 }
9998 
9999 /// Find the base specifier for a base class with the given type.
10000 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
10001                                                 QualType DesiredBase,
10002                                                 bool &AnyDependentBases) {
10003   // Check whether the named type is a direct base class.
10004   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
10005     .getUnqualifiedType();
10006   for (auto &Base : Derived->bases()) {
10007     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
10008     if (CanonicalDesiredBase == BaseType)
10009       return &Base;
10010     if (BaseType->isDependentType())
10011       AnyDependentBases = true;
10012   }
10013   return nullptr;
10014 }
10015 
10016 namespace {
10017 class UsingValidatorCCC final : public CorrectionCandidateCallback {
10018 public:
10019   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
10020                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
10021       : HasTypenameKeyword(HasTypenameKeyword),
10022         IsInstantiation(IsInstantiation), OldNNS(NNS),
10023         RequireMemberOf(RequireMemberOf) {}
10024 
10025   bool ValidateCandidate(const TypoCorrection &Candidate) override {
10026     NamedDecl *ND = Candidate.getCorrectionDecl();
10027 
10028     // Keywords are not valid here.
10029     if (!ND || isa<NamespaceDecl>(ND))
10030       return false;
10031 
10032     // Completely unqualified names are invalid for a 'using' declaration.
10033     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
10034       return false;
10035 
10036     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
10037     // reject.
10038 
10039     if (RequireMemberOf) {
10040       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
10041       if (FoundRecord && FoundRecord->isInjectedClassName()) {
10042         // No-one ever wants a using-declaration to name an injected-class-name
10043         // of a base class, unless they're declaring an inheriting constructor.
10044         ASTContext &Ctx = ND->getASTContext();
10045         if (!Ctx.getLangOpts().CPlusPlus11)
10046           return false;
10047         QualType FoundType = Ctx.getRecordType(FoundRecord);
10048 
10049         // Check that the injected-class-name is named as a member of its own
10050         // type; we don't want to suggest 'using Derived::Base;', since that
10051         // means something else.
10052         NestedNameSpecifier *Specifier =
10053             Candidate.WillReplaceSpecifier()
10054                 ? Candidate.getCorrectionSpecifier()
10055                 : OldNNS;
10056         if (!Specifier->getAsType() ||
10057             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
10058           return false;
10059 
10060         // Check that this inheriting constructor declaration actually names a
10061         // direct base class of the current class.
10062         bool AnyDependentBases = false;
10063         if (!findDirectBaseWithType(RequireMemberOf,
10064                                     Ctx.getRecordType(FoundRecord),
10065                                     AnyDependentBases) &&
10066             !AnyDependentBases)
10067           return false;
10068       } else {
10069         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
10070         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
10071           return false;
10072 
10073         // FIXME: Check that the base class member is accessible?
10074       }
10075     } else {
10076       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
10077       if (FoundRecord && FoundRecord->isInjectedClassName())
10078         return false;
10079     }
10080 
10081     if (isa<TypeDecl>(ND))
10082       return HasTypenameKeyword || !IsInstantiation;
10083 
10084     return !HasTypenameKeyword;
10085   }
10086 
10087   std::unique_ptr<CorrectionCandidateCallback> clone() override {
10088     return std::make_unique<UsingValidatorCCC>(*this);
10089   }
10090 
10091 private:
10092   bool HasTypenameKeyword;
10093   bool IsInstantiation;
10094   NestedNameSpecifier *OldNNS;
10095   CXXRecordDecl *RequireMemberOf;
10096 };
10097 } // end anonymous namespace
10098 
10099 /// Builds a using declaration.
10100 ///
10101 /// \param IsInstantiation - Whether this call arises from an
10102 ///   instantiation of an unresolved using declaration.  We treat
10103 ///   the lookup differently for these declarations.
10104 NamedDecl *Sema::BuildUsingDeclaration(
10105     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
10106     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
10107     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
10108     const ParsedAttributesView &AttrList, bool IsInstantiation) {
10109   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
10110   SourceLocation IdentLoc = NameInfo.getLoc();
10111   assert(IdentLoc.isValid() && "Invalid TargetName location.");
10112 
10113   // FIXME: We ignore attributes for now.
10114 
10115   // For an inheriting constructor declaration, the name of the using
10116   // declaration is the name of a constructor in this class, not in the
10117   // base class.
10118   DeclarationNameInfo UsingName = NameInfo;
10119   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
10120     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
10121       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10122           Context.getCanonicalType(Context.getRecordType(RD))));
10123 
10124   // Do the redeclaration lookup in the current scope.
10125   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
10126                         ForVisibleRedeclaration);
10127   Previous.setHideTags(false);
10128   if (S) {
10129     LookupName(Previous, S);
10130 
10131     // It is really dumb that we have to do this.
10132     LookupResult::Filter F = Previous.makeFilter();
10133     while (F.hasNext()) {
10134       NamedDecl *D = F.next();
10135       if (!isDeclInScope(D, CurContext, S))
10136         F.erase();
10137       // If we found a local extern declaration that's not ordinarily visible,
10138       // and this declaration is being added to a non-block scope, ignore it.
10139       // We're only checking for scope conflicts here, not also for violations
10140       // of the linkage rules.
10141       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
10142                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
10143         F.erase();
10144     }
10145     F.done();
10146   } else {
10147     assert(IsInstantiation && "no scope in non-instantiation");
10148     if (CurContext->isRecord())
10149       LookupQualifiedName(Previous, CurContext);
10150     else {
10151       // No redeclaration check is needed here; in non-member contexts we
10152       // diagnosed all possible conflicts with other using-declarations when
10153       // building the template:
10154       //
10155       // For a dependent non-type using declaration, the only valid case is
10156       // if we instantiate to a single enumerator. We check for conflicts
10157       // between shadow declarations we introduce, and we check in the template
10158       // definition for conflicts between a non-type using declaration and any
10159       // other declaration, which together covers all cases.
10160       //
10161       // A dependent typename using declaration will never successfully
10162       // instantiate, since it will always name a class member, so we reject
10163       // that in the template definition.
10164     }
10165   }
10166 
10167   // Check for invalid redeclarations.
10168   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
10169                                   SS, IdentLoc, Previous))
10170     return nullptr;
10171 
10172   // Check for bad qualifiers.
10173   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
10174                               IdentLoc))
10175     return nullptr;
10176 
10177   DeclContext *LookupContext = computeDeclContext(SS);
10178   NamedDecl *D;
10179   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10180   if (!LookupContext || EllipsisLoc.isValid()) {
10181     if (HasTypenameKeyword) {
10182       // FIXME: not all declaration name kinds are legal here
10183       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
10184                                               UsingLoc, TypenameLoc,
10185                                               QualifierLoc,
10186                                               IdentLoc, NameInfo.getName(),
10187                                               EllipsisLoc);
10188     } else {
10189       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
10190                                            QualifierLoc, NameInfo, EllipsisLoc);
10191     }
10192     D->setAccess(AS);
10193     CurContext->addDecl(D);
10194     return D;
10195   }
10196 
10197   auto Build = [&](bool Invalid) {
10198     UsingDecl *UD =
10199         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10200                           UsingName, HasTypenameKeyword);
10201     UD->setAccess(AS);
10202     CurContext->addDecl(UD);
10203     UD->setInvalidDecl(Invalid);
10204     return UD;
10205   };
10206   auto BuildInvalid = [&]{ return Build(true); };
10207   auto BuildValid = [&]{ return Build(false); };
10208 
10209   if (RequireCompleteDeclContext(SS, LookupContext))
10210     return BuildInvalid();
10211 
10212   // Look up the target name.
10213   LookupResult R(*this, NameInfo, LookupOrdinaryName);
10214 
10215   // Unlike most lookups, we don't always want to hide tag
10216   // declarations: tag names are visible through the using declaration
10217   // even if hidden by ordinary names, *except* in a dependent context
10218   // where it's important for the sanity of two-phase lookup.
10219   if (!IsInstantiation)
10220     R.setHideTags(false);
10221 
10222   // For the purposes of this lookup, we have a base object type
10223   // equal to that of the current context.
10224   if (CurContext->isRecord()) {
10225     R.setBaseObjectType(
10226                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10227   }
10228 
10229   LookupQualifiedName(R, LookupContext);
10230 
10231   // Try to correct typos if possible. If constructor name lookup finds no
10232   // results, that means the named class has no explicit constructors, and we
10233   // suppressed declaring implicit ones (probably because it's dependent or
10234   // invalid).
10235   if (R.empty() &&
10236       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10237     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10238     // it will believe that glibc provides a ::gets in cases where it does not,
10239     // and will try to pull it into namespace std with a using-declaration.
10240     // Just ignore the using-declaration in that case.
10241     auto *II = NameInfo.getName().getAsIdentifierInfo();
10242     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10243         CurContext->isStdNamespace() &&
10244         isa<TranslationUnitDecl>(LookupContext) &&
10245         getSourceManager().isInSystemHeader(UsingLoc))
10246       return nullptr;
10247     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10248                           dyn_cast<CXXRecordDecl>(CurContext));
10249     if (TypoCorrection Corrected =
10250             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
10251                         CTK_ErrorRecovery)) {
10252       // We reject candidates where DroppedSpecifier == true, hence the
10253       // literal '0' below.
10254       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10255                                 << NameInfo.getName() << LookupContext << 0
10256                                 << SS.getRange());
10257 
10258       // If we picked a correction with no attached Decl we can't do anything
10259       // useful with it, bail out.
10260       NamedDecl *ND = Corrected.getCorrectionDecl();
10261       if (!ND)
10262         return BuildInvalid();
10263 
10264       // If we corrected to an inheriting constructor, handle it as one.
10265       auto *RD = dyn_cast<CXXRecordDecl>(ND);
10266       if (RD && RD->isInjectedClassName()) {
10267         // The parent of the injected class name is the class itself.
10268         RD = cast<CXXRecordDecl>(RD->getParent());
10269 
10270         // Fix up the information we'll use to build the using declaration.
10271         if (Corrected.WillReplaceSpecifier()) {
10272           NestedNameSpecifierLocBuilder Builder;
10273           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10274                               QualifierLoc.getSourceRange());
10275           QualifierLoc = Builder.getWithLocInContext(Context);
10276         }
10277 
10278         // In this case, the name we introduce is the name of a derived class
10279         // constructor.
10280         auto *CurClass = cast<CXXRecordDecl>(CurContext);
10281         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10282             Context.getCanonicalType(Context.getRecordType(CurClass))));
10283         UsingName.setNamedTypeInfo(nullptr);
10284         for (auto *Ctor : LookupConstructors(RD))
10285           R.addDecl(Ctor);
10286         R.resolveKind();
10287       } else {
10288         // FIXME: Pick up all the declarations if we found an overloaded
10289         // function.
10290         UsingName.setName(ND->getDeclName());
10291         R.addDecl(ND);
10292       }
10293     } else {
10294       Diag(IdentLoc, diag::err_no_member)
10295         << NameInfo.getName() << LookupContext << SS.getRange();
10296       return BuildInvalid();
10297     }
10298   }
10299 
10300   if (R.isAmbiguous())
10301     return BuildInvalid();
10302 
10303   if (HasTypenameKeyword) {
10304     // If we asked for a typename and got a non-type decl, error out.
10305     if (!R.getAsSingle<TypeDecl>()) {
10306       Diag(IdentLoc, diag::err_using_typename_non_type);
10307       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10308         Diag((*I)->getUnderlyingDecl()->getLocation(),
10309              diag::note_using_decl_target);
10310       return BuildInvalid();
10311     }
10312   } else {
10313     // If we asked for a non-typename and we got a type, error out,
10314     // but only if this is an instantiation of an unresolved using
10315     // decl.  Otherwise just silently find the type name.
10316     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10317       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10318       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10319       return BuildInvalid();
10320     }
10321   }
10322 
10323   // C++14 [namespace.udecl]p6:
10324   // A using-declaration shall not name a namespace.
10325   if (R.getAsSingle<NamespaceDecl>()) {
10326     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10327       << SS.getRange();
10328     return BuildInvalid();
10329   }
10330 
10331   // C++14 [namespace.udecl]p7:
10332   // A using-declaration shall not name a scoped enumerator.
10333   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10334     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10335       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10336         << SS.getRange();
10337       return BuildInvalid();
10338     }
10339   }
10340 
10341   UsingDecl *UD = BuildValid();
10342 
10343   // Some additional rules apply to inheriting constructors.
10344   if (UsingName.getName().getNameKind() ==
10345         DeclarationName::CXXConstructorName) {
10346     // Suppress access diagnostics; the access check is instead performed at the
10347     // point of use for an inheriting constructor.
10348     R.suppressDiagnostics();
10349     if (CheckInheritingConstructorUsingDecl(UD))
10350       return UD;
10351   }
10352 
10353   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10354     UsingShadowDecl *PrevDecl = nullptr;
10355     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10356       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10357   }
10358 
10359   return UD;
10360 }
10361 
10362 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10363                                     ArrayRef<NamedDecl *> Expansions) {
10364   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10365          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10366          isa<UsingPackDecl>(InstantiatedFrom));
10367 
10368   auto *UPD =
10369       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10370   UPD->setAccess(InstantiatedFrom->getAccess());
10371   CurContext->addDecl(UPD);
10372   return UPD;
10373 }
10374 
10375 /// Additional checks for a using declaration referring to a constructor name.
10376 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10377   assert(!UD->hasTypename() && "expecting a constructor name");
10378 
10379   const Type *SourceType = UD->getQualifier()->getAsType();
10380   assert(SourceType &&
10381          "Using decl naming constructor doesn't have type in scope spec.");
10382   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10383 
10384   // Check whether the named type is a direct base class.
10385   bool AnyDependentBases = false;
10386   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10387                                       AnyDependentBases);
10388   if (!Base && !AnyDependentBases) {
10389     Diag(UD->getUsingLoc(),
10390          diag::err_using_decl_constructor_not_in_direct_base)
10391       << UD->getNameInfo().getSourceRange()
10392       << QualType(SourceType, 0) << TargetClass;
10393     UD->setInvalidDecl();
10394     return true;
10395   }
10396 
10397   if (Base)
10398     Base->setInheritConstructors();
10399 
10400   return false;
10401 }
10402 
10403 /// Checks that the given using declaration is not an invalid
10404 /// redeclaration.  Note that this is checking only for the using decl
10405 /// itself, not for any ill-formedness among the UsingShadowDecls.
10406 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10407                                        bool HasTypenameKeyword,
10408                                        const CXXScopeSpec &SS,
10409                                        SourceLocation NameLoc,
10410                                        const LookupResult &Prev) {
10411   NestedNameSpecifier *Qual = SS.getScopeRep();
10412 
10413   // C++03 [namespace.udecl]p8:
10414   // C++0x [namespace.udecl]p10:
10415   //   A using-declaration is a declaration and can therefore be used
10416   //   repeatedly where (and only where) multiple declarations are
10417   //   allowed.
10418   //
10419   // That's in non-member contexts.
10420   if (!CurContext->getRedeclContext()->isRecord()) {
10421     // A dependent qualifier outside a class can only ever resolve to an
10422     // enumeration type. Therefore it conflicts with any other non-type
10423     // declaration in the same scope.
10424     // FIXME: How should we check for dependent type-type conflicts at block
10425     // scope?
10426     if (Qual->isDependent() && !HasTypenameKeyword) {
10427       for (auto *D : Prev) {
10428         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10429           bool OldCouldBeEnumerator =
10430               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10431           Diag(NameLoc,
10432                OldCouldBeEnumerator ? diag::err_redefinition
10433                                     : diag::err_redefinition_different_kind)
10434               << Prev.getLookupName();
10435           Diag(D->getLocation(), diag::note_previous_definition);
10436           return true;
10437         }
10438       }
10439     }
10440     return false;
10441   }
10442 
10443   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10444     NamedDecl *D = *I;
10445 
10446     bool DTypename;
10447     NestedNameSpecifier *DQual;
10448     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10449       DTypename = UD->hasTypename();
10450       DQual = UD->getQualifier();
10451     } else if (UnresolvedUsingValueDecl *UD
10452                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10453       DTypename = false;
10454       DQual = UD->getQualifier();
10455     } else if (UnresolvedUsingTypenameDecl *UD
10456                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10457       DTypename = true;
10458       DQual = UD->getQualifier();
10459     } else continue;
10460 
10461     // using decls differ if one says 'typename' and the other doesn't.
10462     // FIXME: non-dependent using decls?
10463     if (HasTypenameKeyword != DTypename) continue;
10464 
10465     // using decls differ if they name different scopes (but note that
10466     // template instantiation can cause this check to trigger when it
10467     // didn't before instantiation).
10468     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10469         Context.getCanonicalNestedNameSpecifier(DQual))
10470       continue;
10471 
10472     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10473     Diag(D->getLocation(), diag::note_using_decl) << 1;
10474     return true;
10475   }
10476 
10477   return false;
10478 }
10479 
10480 
10481 /// Checks that the given nested-name qualifier used in a using decl
10482 /// in the current context is appropriately related to the current
10483 /// scope.  If an error is found, diagnoses it and returns true.
10484 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10485                                    bool HasTypename,
10486                                    const CXXScopeSpec &SS,
10487                                    const DeclarationNameInfo &NameInfo,
10488                                    SourceLocation NameLoc) {
10489   DeclContext *NamedContext = computeDeclContext(SS);
10490 
10491   if (!CurContext->isRecord()) {
10492     // C++03 [namespace.udecl]p3:
10493     // C++0x [namespace.udecl]p8:
10494     //   A using-declaration for a class member shall be a member-declaration.
10495 
10496     // If we weren't able to compute a valid scope, it might validly be a
10497     // dependent class scope or a dependent enumeration unscoped scope. If
10498     // we have a 'typename' keyword, the scope must resolve to a class type.
10499     if ((HasTypename && !NamedContext) ||
10500         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10501       auto *RD = NamedContext
10502                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10503                      : nullptr;
10504       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10505         RD = nullptr;
10506 
10507       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10508         << SS.getRange();
10509 
10510       // If we have a complete, non-dependent source type, try to suggest a
10511       // way to get the same effect.
10512       if (!RD)
10513         return true;
10514 
10515       // Find what this using-declaration was referring to.
10516       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10517       R.setHideTags(false);
10518       R.suppressDiagnostics();
10519       LookupQualifiedName(R, RD);
10520 
10521       if (R.getAsSingle<TypeDecl>()) {
10522         if (getLangOpts().CPlusPlus11) {
10523           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10524           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10525             << 0 // alias declaration
10526             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10527                                           NameInfo.getName().getAsString() +
10528                                               " = ");
10529         } else {
10530           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10531           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10532           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10533             << 1 // typedef declaration
10534             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10535             << FixItHint::CreateInsertion(
10536                    InsertLoc, " " + NameInfo.getName().getAsString());
10537         }
10538       } else if (R.getAsSingle<VarDecl>()) {
10539         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10540         // repeating the type of the static data member here.
10541         FixItHint FixIt;
10542         if (getLangOpts().CPlusPlus11) {
10543           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10544           FixIt = FixItHint::CreateReplacement(
10545               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10546         }
10547 
10548         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10549           << 2 // reference declaration
10550           << FixIt;
10551       } else if (R.getAsSingle<EnumConstantDecl>()) {
10552         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10553         // repeating the type of the enumeration here, and we can't do so if
10554         // the type is anonymous.
10555         FixItHint FixIt;
10556         if (getLangOpts().CPlusPlus11) {
10557           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10558           FixIt = FixItHint::CreateReplacement(
10559               UsingLoc,
10560               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10561         }
10562 
10563         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10564           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10565           << FixIt;
10566       }
10567       return true;
10568     }
10569 
10570     // Otherwise, this might be valid.
10571     return false;
10572   }
10573 
10574   // The current scope is a record.
10575 
10576   // If the named context is dependent, we can't decide much.
10577   if (!NamedContext) {
10578     // FIXME: in C++0x, we can diagnose if we can prove that the
10579     // nested-name-specifier does not refer to a base class, which is
10580     // still possible in some cases.
10581 
10582     // Otherwise we have to conservatively report that things might be
10583     // okay.
10584     return false;
10585   }
10586 
10587   if (!NamedContext->isRecord()) {
10588     // Ideally this would point at the last name in the specifier,
10589     // but we don't have that level of source info.
10590     Diag(SS.getRange().getBegin(),
10591          diag::err_using_decl_nested_name_specifier_is_not_class)
10592       << SS.getScopeRep() << SS.getRange();
10593     return true;
10594   }
10595 
10596   if (!NamedContext->isDependentContext() &&
10597       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10598     return true;
10599 
10600   if (getLangOpts().CPlusPlus11) {
10601     // C++11 [namespace.udecl]p3:
10602     //   In a using-declaration used as a member-declaration, the
10603     //   nested-name-specifier shall name a base class of the class
10604     //   being defined.
10605 
10606     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10607                                  cast<CXXRecordDecl>(NamedContext))) {
10608       if (CurContext == NamedContext) {
10609         Diag(NameLoc,
10610              diag::err_using_decl_nested_name_specifier_is_current_class)
10611           << SS.getRange();
10612         return true;
10613       }
10614 
10615       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10616         Diag(SS.getRange().getBegin(),
10617              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10618           << SS.getScopeRep()
10619           << cast<CXXRecordDecl>(CurContext)
10620           << SS.getRange();
10621       }
10622       return true;
10623     }
10624 
10625     return false;
10626   }
10627 
10628   // C++03 [namespace.udecl]p4:
10629   //   A using-declaration used as a member-declaration shall refer
10630   //   to a member of a base class of the class being defined [etc.].
10631 
10632   // Salient point: SS doesn't have to name a base class as long as
10633   // lookup only finds members from base classes.  Therefore we can
10634   // diagnose here only if we can prove that that can't happen,
10635   // i.e. if the class hierarchies provably don't intersect.
10636 
10637   // TODO: it would be nice if "definitely valid" results were cached
10638   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10639   // need to be repeated.
10640 
10641   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10642   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10643     Bases.insert(Base);
10644     return true;
10645   };
10646 
10647   // Collect all bases. Return false if we find a dependent base.
10648   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10649     return false;
10650 
10651   // Returns true if the base is dependent or is one of the accumulated base
10652   // classes.
10653   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10654     return !Bases.count(Base);
10655   };
10656 
10657   // Return false if the class has a dependent base or if it or one
10658   // of its bases is present in the base set of the current context.
10659   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10660       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10661     return false;
10662 
10663   Diag(SS.getRange().getBegin(),
10664        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10665     << SS.getScopeRep()
10666     << cast<CXXRecordDecl>(CurContext)
10667     << SS.getRange();
10668 
10669   return true;
10670 }
10671 
10672 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10673                                   MultiTemplateParamsArg TemplateParamLists,
10674                                   SourceLocation UsingLoc, UnqualifiedId &Name,
10675                                   const ParsedAttributesView &AttrList,
10676                                   TypeResult Type, Decl *DeclFromDeclSpec) {
10677   // Skip up to the relevant declaration scope.
10678   while (S->isTemplateParamScope())
10679     S = S->getParent();
10680   assert((S->getFlags() & Scope::DeclScope) &&
10681          "got alias-declaration outside of declaration scope");
10682 
10683   if (Type.isInvalid())
10684     return nullptr;
10685 
10686   bool Invalid = false;
10687   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10688   TypeSourceInfo *TInfo = nullptr;
10689   GetTypeFromParser(Type.get(), &TInfo);
10690 
10691   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10692     return nullptr;
10693 
10694   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10695                                       UPPC_DeclarationType)) {
10696     Invalid = true;
10697     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10698                                              TInfo->getTypeLoc().getBeginLoc());
10699   }
10700 
10701   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10702                         TemplateParamLists.size()
10703                             ? forRedeclarationInCurContext()
10704                             : ForVisibleRedeclaration);
10705   LookupName(Previous, S);
10706 
10707   // Warn about shadowing the name of a template parameter.
10708   if (Previous.isSingleResult() &&
10709       Previous.getFoundDecl()->isTemplateParameter()) {
10710     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10711     Previous.clear();
10712   }
10713 
10714   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10715          "name in alias declaration must be an identifier");
10716   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10717                                                Name.StartLocation,
10718                                                Name.Identifier, TInfo);
10719 
10720   NewTD->setAccess(AS);
10721 
10722   if (Invalid)
10723     NewTD->setInvalidDecl();
10724 
10725   ProcessDeclAttributeList(S, NewTD, AttrList);
10726   AddPragmaAttributes(S, NewTD);
10727 
10728   CheckTypedefForVariablyModifiedType(S, NewTD);
10729   Invalid |= NewTD->isInvalidDecl();
10730 
10731   bool Redeclaration = false;
10732 
10733   NamedDecl *NewND;
10734   if (TemplateParamLists.size()) {
10735     TypeAliasTemplateDecl *OldDecl = nullptr;
10736     TemplateParameterList *OldTemplateParams = nullptr;
10737 
10738     if (TemplateParamLists.size() != 1) {
10739       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10740         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10741          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10742     }
10743     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10744 
10745     // Check that we can declare a template here.
10746     if (CheckTemplateDeclScope(S, TemplateParams))
10747       return nullptr;
10748 
10749     // Only consider previous declarations in the same scope.
10750     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10751                          /*ExplicitInstantiationOrSpecialization*/false);
10752     if (!Previous.empty()) {
10753       Redeclaration = true;
10754 
10755       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10756       if (!OldDecl && !Invalid) {
10757         Diag(UsingLoc, diag::err_redefinition_different_kind)
10758           << Name.Identifier;
10759 
10760         NamedDecl *OldD = Previous.getRepresentativeDecl();
10761         if (OldD->getLocation().isValid())
10762           Diag(OldD->getLocation(), diag::note_previous_definition);
10763 
10764         Invalid = true;
10765       }
10766 
10767       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10768         if (TemplateParameterListsAreEqual(TemplateParams,
10769                                            OldDecl->getTemplateParameters(),
10770                                            /*Complain=*/true,
10771                                            TPL_TemplateMatch))
10772           OldTemplateParams =
10773               OldDecl->getMostRecentDecl()->getTemplateParameters();
10774         else
10775           Invalid = true;
10776 
10777         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10778         if (!Invalid &&
10779             !Context.hasSameType(OldTD->getUnderlyingType(),
10780                                  NewTD->getUnderlyingType())) {
10781           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10782           // but we can't reasonably accept it.
10783           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10784             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10785           if (OldTD->getLocation().isValid())
10786             Diag(OldTD->getLocation(), diag::note_previous_definition);
10787           Invalid = true;
10788         }
10789       }
10790     }
10791 
10792     // Merge any previous default template arguments into our parameters,
10793     // and check the parameter list.
10794     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10795                                    TPC_TypeAliasTemplate))
10796       return nullptr;
10797 
10798     TypeAliasTemplateDecl *NewDecl =
10799       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10800                                     Name.Identifier, TemplateParams,
10801                                     NewTD);
10802     NewTD->setDescribedAliasTemplate(NewDecl);
10803 
10804     NewDecl->setAccess(AS);
10805 
10806     if (Invalid)
10807       NewDecl->setInvalidDecl();
10808     else if (OldDecl) {
10809       NewDecl->setPreviousDecl(OldDecl);
10810       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10811     }
10812 
10813     NewND = NewDecl;
10814   } else {
10815     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10816       setTagNameForLinkagePurposes(TD, NewTD);
10817       handleTagNumbering(TD, S);
10818     }
10819     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10820     NewND = NewTD;
10821   }
10822 
10823   PushOnScopeChains(NewND, S);
10824   ActOnDocumentableDecl(NewND);
10825   return NewND;
10826 }
10827 
10828 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10829                                    SourceLocation AliasLoc,
10830                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10831                                    SourceLocation IdentLoc,
10832                                    IdentifierInfo *Ident) {
10833 
10834   // Lookup the namespace name.
10835   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10836   LookupParsedName(R, S, &SS);
10837 
10838   if (R.isAmbiguous())
10839     return nullptr;
10840 
10841   if (R.empty()) {
10842     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10843       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10844       return nullptr;
10845     }
10846   }
10847   assert(!R.isAmbiguous() && !R.empty());
10848   NamedDecl *ND = R.getRepresentativeDecl();
10849 
10850   // Check if we have a previous declaration with the same name.
10851   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10852                      ForVisibleRedeclaration);
10853   LookupName(PrevR, S);
10854 
10855   // Check we're not shadowing a template parameter.
10856   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10857     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10858     PrevR.clear();
10859   }
10860 
10861   // Filter out any other lookup result from an enclosing scope.
10862   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10863                        /*AllowInlineNamespace*/false);
10864 
10865   // Find the previous declaration and check that we can redeclare it.
10866   NamespaceAliasDecl *Prev = nullptr;
10867   if (PrevR.isSingleResult()) {
10868     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10869     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10870       // We already have an alias with the same name that points to the same
10871       // namespace; check that it matches.
10872       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10873         Prev = AD;
10874       } else if (isVisible(PrevDecl)) {
10875         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10876           << Alias;
10877         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10878           << AD->getNamespace();
10879         return nullptr;
10880       }
10881     } else if (isVisible(PrevDecl)) {
10882       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10883                             ? diag::err_redefinition
10884                             : diag::err_redefinition_different_kind;
10885       Diag(AliasLoc, DiagID) << Alias;
10886       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10887       return nullptr;
10888     }
10889   }
10890 
10891   // The use of a nested name specifier may trigger deprecation warnings.
10892   DiagnoseUseOfDecl(ND, IdentLoc);
10893 
10894   NamespaceAliasDecl *AliasDecl =
10895     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10896                                Alias, SS.getWithLocInContext(Context),
10897                                IdentLoc, ND);
10898   if (Prev)
10899     AliasDecl->setPreviousDecl(Prev);
10900 
10901   PushOnScopeChains(AliasDecl, S);
10902   return AliasDecl;
10903 }
10904 
10905 namespace {
10906 struct SpecialMemberExceptionSpecInfo
10907     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10908   SourceLocation Loc;
10909   Sema::ImplicitExceptionSpecification ExceptSpec;
10910 
10911   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10912                                  Sema::CXXSpecialMember CSM,
10913                                  Sema::InheritedConstructorInfo *ICI,
10914                                  SourceLocation Loc)
10915       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10916 
10917   bool visitBase(CXXBaseSpecifier *Base);
10918   bool visitField(FieldDecl *FD);
10919 
10920   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10921                            unsigned Quals);
10922 
10923   void visitSubobjectCall(Subobject Subobj,
10924                           Sema::SpecialMemberOverloadResult SMOR);
10925 };
10926 }
10927 
10928 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10929   auto *RT = Base->getType()->getAs<RecordType>();
10930   if (!RT)
10931     return false;
10932 
10933   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10934   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10935   if (auto *BaseCtor = SMOR.getMethod()) {
10936     visitSubobjectCall(Base, BaseCtor);
10937     return false;
10938   }
10939 
10940   visitClassSubobject(BaseClass, Base, 0);
10941   return false;
10942 }
10943 
10944 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10945   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10946     Expr *E = FD->getInClassInitializer();
10947     if (!E)
10948       // FIXME: It's a little wasteful to build and throw away a
10949       // CXXDefaultInitExpr here.
10950       // FIXME: We should have a single context note pointing at Loc, and
10951       // this location should be MD->getLocation() instead, since that's
10952       // the location where we actually use the default init expression.
10953       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10954     if (E)
10955       ExceptSpec.CalledExpr(E);
10956   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10957                             ->getAs<RecordType>()) {
10958     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10959                         FD->getType().getCVRQualifiers());
10960   }
10961   return false;
10962 }
10963 
10964 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10965                                                          Subobject Subobj,
10966                                                          unsigned Quals) {
10967   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10968   bool IsMutable = Field && Field->isMutable();
10969   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10970 }
10971 
10972 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10973     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10974   // Note, if lookup fails, it doesn't matter what exception specification we
10975   // choose because the special member will be deleted.
10976   if (CXXMethodDecl *MD = SMOR.getMethod())
10977     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10978 }
10979 
10980 namespace {
10981 /// RAII object to register a special member as being currently declared.
10982 struct ComputingExceptionSpec {
10983   Sema &S;
10984 
10985   ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
10986       : S(S) {
10987     Sema::CodeSynthesisContext Ctx;
10988     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
10989     Ctx.PointOfInstantiation = Loc;
10990     Ctx.Entity = MD;
10991     S.pushCodeSynthesisContext(Ctx);
10992   }
10993   ~ComputingExceptionSpec() {
10994     S.popCodeSynthesisContext();
10995   }
10996 };
10997 }
10998 
10999 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
11000   llvm::APSInt Result;
11001   ExprResult Converted = CheckConvertedConstantExpression(
11002       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
11003   ExplicitSpec.setExpr(Converted.get());
11004   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
11005     ExplicitSpec.setKind(Result.getBoolValue()
11006                              ? ExplicitSpecKind::ResolvedTrue
11007                              : ExplicitSpecKind::ResolvedFalse);
11008     return true;
11009   }
11010   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
11011   return false;
11012 }
11013 
11014 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
11015   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
11016   if (!ExplicitExpr->isTypeDependent())
11017     tryResolveExplicitSpecifier(ES);
11018   return ES;
11019 }
11020 
11021 static Sema::ImplicitExceptionSpecification
11022 ComputeDefaultedSpecialMemberExceptionSpec(
11023     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
11024     Sema::InheritedConstructorInfo *ICI) {
11025   ComputingExceptionSpec CES(S, MD, Loc);
11026 
11027   CXXRecordDecl *ClassDecl = MD->getParent();
11028 
11029   // C++ [except.spec]p14:
11030   //   An implicitly declared special member function (Clause 12) shall have an
11031   //   exception-specification. [...]
11032   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
11033   if (ClassDecl->isInvalidDecl())
11034     return Info.ExceptSpec;
11035 
11036   // FIXME: If this diagnostic fires, we're probably missing a check for
11037   // attempting to resolve an exception specification before it's known
11038   // at a higher level.
11039   if (S.RequireCompleteType(MD->getLocation(),
11040                             S.Context.getRecordType(ClassDecl),
11041                             diag::err_exception_spec_incomplete_type))
11042     return Info.ExceptSpec;
11043 
11044   // C++1z [except.spec]p7:
11045   //   [Look for exceptions thrown by] a constructor selected [...] to
11046   //   initialize a potentially constructed subobject,
11047   // C++1z [except.spec]p8:
11048   //   The exception specification for an implicitly-declared destructor, or a
11049   //   destructor without a noexcept-specifier, is potentially-throwing if and
11050   //   only if any of the destructors for any of its potentially constructed
11051   //   subojects is potentially throwing.
11052   // FIXME: We respect the first rule but ignore the "potentially constructed"
11053   // in the second rule to resolve a core issue (no number yet) that would have
11054   // us reject:
11055   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
11056   //   struct B : A {};
11057   //   struct C : B { void f(); };
11058   // ... due to giving B::~B() a non-throwing exception specification.
11059   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
11060                                 : Info.VisitAllBases);
11061 
11062   return Info.ExceptSpec;
11063 }
11064 
11065 namespace {
11066 /// RAII object to register a special member as being currently declared.
11067 struct DeclaringSpecialMember {
11068   Sema &S;
11069   Sema::SpecialMemberDecl D;
11070   Sema::ContextRAII SavedContext;
11071   bool WasAlreadyBeingDeclared;
11072 
11073   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
11074       : S(S), D(RD, CSM), SavedContext(S, RD) {
11075     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
11076     if (WasAlreadyBeingDeclared)
11077       // This almost never happens, but if it does, ensure that our cache
11078       // doesn't contain a stale result.
11079       S.SpecialMemberCache.clear();
11080     else {
11081       // Register a note to be produced if we encounter an error while
11082       // declaring the special member.
11083       Sema::CodeSynthesisContext Ctx;
11084       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
11085       // FIXME: We don't have a location to use here. Using the class's
11086       // location maintains the fiction that we declare all special members
11087       // with the class, but (1) it's not clear that lying about that helps our
11088       // users understand what's going on, and (2) there may be outer contexts
11089       // on the stack (some of which are relevant) and printing them exposes
11090       // our lies.
11091       Ctx.PointOfInstantiation = RD->getLocation();
11092       Ctx.Entity = RD;
11093       Ctx.SpecialMember = CSM;
11094       S.pushCodeSynthesisContext(Ctx);
11095     }
11096   }
11097   ~DeclaringSpecialMember() {
11098     if (!WasAlreadyBeingDeclared) {
11099       S.SpecialMembersBeingDeclared.erase(D);
11100       S.popCodeSynthesisContext();
11101     }
11102   }
11103 
11104   /// Are we already trying to declare this special member?
11105   bool isAlreadyBeingDeclared() const {
11106     return WasAlreadyBeingDeclared;
11107   }
11108 };
11109 }
11110 
11111 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
11112   // Look up any existing declarations, but don't trigger declaration of all
11113   // implicit special members with this name.
11114   DeclarationName Name = FD->getDeclName();
11115   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
11116                  ForExternalRedeclaration);
11117   for (auto *D : FD->getParent()->lookup(Name))
11118     if (auto *Acceptable = R.getAcceptableDecl(D))
11119       R.addDecl(Acceptable);
11120   R.resolveKind();
11121   R.suppressDiagnostics();
11122 
11123   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
11124 }
11125 
11126 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
11127                                           QualType ResultTy,
11128                                           ArrayRef<QualType> Args) {
11129   // Build an exception specification pointing back at this constructor.
11130   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
11131 
11132   if (getLangOpts().OpenCLCPlusPlus) {
11133     // OpenCL: Implicitly defaulted special member are of the generic address
11134     // space.
11135     EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
11136   }
11137 
11138   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
11139   SpecialMem->setType(QT);
11140 }
11141 
11142 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
11143                                                      CXXRecordDecl *ClassDecl) {
11144   // C++ [class.ctor]p5:
11145   //   A default constructor for a class X is a constructor of class X
11146   //   that can be called without an argument. If there is no
11147   //   user-declared constructor for class X, a default constructor is
11148   //   implicitly declared. An implicitly-declared default constructor
11149   //   is an inline public member of its class.
11150   assert(ClassDecl->needsImplicitDefaultConstructor() &&
11151          "Should not build implicit default constructor!");
11152 
11153   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
11154   if (DSM.isAlreadyBeingDeclared())
11155     return nullptr;
11156 
11157   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11158                                                      CXXDefaultConstructor,
11159                                                      false);
11160 
11161   // Create the actual constructor declaration.
11162   CanQualType ClassType
11163     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11164   SourceLocation ClassLoc = ClassDecl->getLocation();
11165   DeclarationName Name
11166     = Context.DeclarationNames.getCXXConstructorName(ClassType);
11167   DeclarationNameInfo NameInfo(Name, ClassLoc);
11168   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
11169       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
11170       /*TInfo=*/nullptr, ExplicitSpecifier(),
11171       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11172       Constexpr ? CSK_constexpr : CSK_unspecified);
11173   DefaultCon->setAccess(AS_public);
11174   DefaultCon->setDefaulted();
11175 
11176   if (getLangOpts().CUDA) {
11177     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
11178                                             DefaultCon,
11179                                             /* ConstRHS */ false,
11180                                             /* Diagnose */ false);
11181   }
11182 
11183   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
11184 
11185   // We don't need to use SpecialMemberIsTrivial here; triviality for default
11186   // constructors is easy to compute.
11187   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
11188 
11189   // Note that we have declared this constructor.
11190   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
11191 
11192   Scope *S = getScopeForContext(ClassDecl);
11193   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
11194 
11195   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
11196     SetDeclDeleted(DefaultCon, ClassLoc);
11197 
11198   if (S)
11199     PushOnScopeChains(DefaultCon, S, false);
11200   ClassDecl->addDecl(DefaultCon);
11201 
11202   return DefaultCon;
11203 }
11204 
11205 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
11206                                             CXXConstructorDecl *Constructor) {
11207   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
11208           !Constructor->doesThisDeclarationHaveABody() &&
11209           !Constructor->isDeleted()) &&
11210     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
11211   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11212     return;
11213 
11214   CXXRecordDecl *ClassDecl = Constructor->getParent();
11215   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
11216 
11217   SynthesizedFunctionScope Scope(*this, Constructor);
11218 
11219   // The exception specification is needed because we are defining the
11220   // function.
11221   ResolveExceptionSpec(CurrentLocation,
11222                        Constructor->getType()->castAs<FunctionProtoType>());
11223   MarkVTableUsed(CurrentLocation, ClassDecl);
11224 
11225   // Add a context note for diagnostics produced after this point.
11226   Scope.addContextNote(CurrentLocation);
11227 
11228   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11229     Constructor->setInvalidDecl();
11230     return;
11231   }
11232 
11233   SourceLocation Loc = Constructor->getEndLoc().isValid()
11234                            ? Constructor->getEndLoc()
11235                            : Constructor->getLocation();
11236   Constructor->setBody(new (Context) CompoundStmt(Loc));
11237   Constructor->markUsed(Context);
11238 
11239   if (ASTMutationListener *L = getASTMutationListener()) {
11240     L->CompletedImplicitDefinition(Constructor);
11241   }
11242 
11243   DiagnoseUninitializedFields(*this, Constructor);
11244 }
11245 
11246 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
11247   // Perform any delayed checks on exception specifications.
11248   CheckDelayedMemberExceptionSpecs();
11249 }
11250 
11251 /// Find or create the fake constructor we synthesize to model constructing an
11252 /// object of a derived class via a constructor of a base class.
11253 CXXConstructorDecl *
11254 Sema::findInheritingConstructor(SourceLocation Loc,
11255                                 CXXConstructorDecl *BaseCtor,
11256                                 ConstructorUsingShadowDecl *Shadow) {
11257   CXXRecordDecl *Derived = Shadow->getParent();
11258   SourceLocation UsingLoc = Shadow->getLocation();
11259 
11260   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11261   // For now we use the name of the base class constructor as a member of the
11262   // derived class to indicate a (fake) inherited constructor name.
11263   DeclarationName Name = BaseCtor->getDeclName();
11264 
11265   // Check to see if we already have a fake constructor for this inherited
11266   // constructor call.
11267   for (NamedDecl *Ctor : Derived->lookup(Name))
11268     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11269                                ->getInheritedConstructor()
11270                                .getConstructor(),
11271                            BaseCtor))
11272       return cast<CXXConstructorDecl>(Ctor);
11273 
11274   DeclarationNameInfo NameInfo(Name, UsingLoc);
11275   TypeSourceInfo *TInfo =
11276       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11277   FunctionProtoTypeLoc ProtoLoc =
11278       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11279 
11280   // Check the inherited constructor is valid and find the list of base classes
11281   // from which it was inherited.
11282   InheritedConstructorInfo ICI(*this, Loc, Shadow);
11283 
11284   bool Constexpr =
11285       BaseCtor->isConstexpr() &&
11286       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11287                                         false, BaseCtor, &ICI);
11288 
11289   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11290       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11291       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
11292       /*isImplicitlyDeclared=*/true,
11293       Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
11294       InheritedConstructor(Shadow, BaseCtor));
11295   if (Shadow->isInvalidDecl())
11296     DerivedCtor->setInvalidDecl();
11297 
11298   // Build an unevaluated exception specification for this fake constructor.
11299   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11300   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11301   EPI.ExceptionSpec.Type = EST_Unevaluated;
11302   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11303   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11304                                                FPT->getParamTypes(), EPI));
11305 
11306   // Build the parameter declarations.
11307   SmallVector<ParmVarDecl *, 16> ParamDecls;
11308   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11309     TypeSourceInfo *TInfo =
11310         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11311     ParmVarDecl *PD = ParmVarDecl::Create(
11312         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11313         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
11314     PD->setScopeInfo(0, I);
11315     PD->setImplicit();
11316     // Ensure attributes are propagated onto parameters (this matters for
11317     // format, pass_object_size, ...).
11318     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11319     ParamDecls.push_back(PD);
11320     ProtoLoc.setParam(I, PD);
11321   }
11322 
11323   // Set up the new constructor.
11324   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11325   DerivedCtor->setAccess(BaseCtor->getAccess());
11326   DerivedCtor->setParams(ParamDecls);
11327   Derived->addDecl(DerivedCtor);
11328 
11329   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11330     SetDeclDeleted(DerivedCtor, UsingLoc);
11331 
11332   return DerivedCtor;
11333 }
11334 
11335 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11336   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11337                                Ctor->getInheritedConstructor().getShadowDecl());
11338   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11339                             /*Diagnose*/true);
11340 }
11341 
11342 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11343                                        CXXConstructorDecl *Constructor) {
11344   CXXRecordDecl *ClassDecl = Constructor->getParent();
11345   assert(Constructor->getInheritedConstructor() &&
11346          !Constructor->doesThisDeclarationHaveABody() &&
11347          !Constructor->isDeleted());
11348   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11349     return;
11350 
11351   // Initializations are performed "as if by a defaulted default constructor",
11352   // so enter the appropriate scope.
11353   SynthesizedFunctionScope Scope(*this, Constructor);
11354 
11355   // The exception specification is needed because we are defining the
11356   // function.
11357   ResolveExceptionSpec(CurrentLocation,
11358                        Constructor->getType()->castAs<FunctionProtoType>());
11359   MarkVTableUsed(CurrentLocation, ClassDecl);
11360 
11361   // Add a context note for diagnostics produced after this point.
11362   Scope.addContextNote(CurrentLocation);
11363 
11364   ConstructorUsingShadowDecl *Shadow =
11365       Constructor->getInheritedConstructor().getShadowDecl();
11366   CXXConstructorDecl *InheritedCtor =
11367       Constructor->getInheritedConstructor().getConstructor();
11368 
11369   // [class.inhctor.init]p1:
11370   //   initialization proceeds as if a defaulted default constructor is used to
11371   //   initialize the D object and each base class subobject from which the
11372   //   constructor was inherited
11373 
11374   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11375   CXXRecordDecl *RD = Shadow->getParent();
11376   SourceLocation InitLoc = Shadow->getLocation();
11377 
11378   // Build explicit initializers for all base classes from which the
11379   // constructor was inherited.
11380   SmallVector<CXXCtorInitializer*, 8> Inits;
11381   for (bool VBase : {false, true}) {
11382     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11383       if (B.isVirtual() != VBase)
11384         continue;
11385 
11386       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11387       if (!BaseRD)
11388         continue;
11389 
11390       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11391       if (!BaseCtor.first)
11392         continue;
11393 
11394       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11395       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11396           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11397 
11398       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11399       Inits.push_back(new (Context) CXXCtorInitializer(
11400           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11401           SourceLocation()));
11402     }
11403   }
11404 
11405   // We now proceed as if for a defaulted default constructor, with the relevant
11406   // initializers replaced.
11407 
11408   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11409     Constructor->setInvalidDecl();
11410     return;
11411   }
11412 
11413   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11414   Constructor->markUsed(Context);
11415 
11416   if (ASTMutationListener *L = getASTMutationListener()) {
11417     L->CompletedImplicitDefinition(Constructor);
11418   }
11419 
11420   DiagnoseUninitializedFields(*this, Constructor);
11421 }
11422 
11423 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11424   // C++ [class.dtor]p2:
11425   //   If a class has no user-declared destructor, a destructor is
11426   //   declared implicitly. An implicitly-declared destructor is an
11427   //   inline public member of its class.
11428   assert(ClassDecl->needsImplicitDestructor());
11429 
11430   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11431   if (DSM.isAlreadyBeingDeclared())
11432     return nullptr;
11433 
11434   // Create the actual destructor declaration.
11435   CanQualType ClassType
11436     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11437   SourceLocation ClassLoc = ClassDecl->getLocation();
11438   DeclarationName Name
11439     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11440   DeclarationNameInfo NameInfo(Name, ClassLoc);
11441   CXXDestructorDecl *Destructor
11442       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11443                                   QualType(), nullptr, /*isInline=*/true,
11444                                   /*isImplicitlyDeclared=*/true);
11445   Destructor->setAccess(AS_public);
11446   Destructor->setDefaulted();
11447 
11448   if (getLangOpts().CUDA) {
11449     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11450                                             Destructor,
11451                                             /* ConstRHS */ false,
11452                                             /* Diagnose */ false);
11453   }
11454 
11455   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
11456 
11457   // We don't need to use SpecialMemberIsTrivial here; triviality for
11458   // destructors is easy to compute.
11459   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11460   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11461                                 ClassDecl->hasTrivialDestructorForCall());
11462 
11463   // Note that we have declared this destructor.
11464   ++getASTContext().NumImplicitDestructorsDeclared;
11465 
11466   Scope *S = getScopeForContext(ClassDecl);
11467   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11468 
11469   // We can't check whether an implicit destructor is deleted before we complete
11470   // the definition of the class, because its validity depends on the alignment
11471   // of the class. We'll check this from ActOnFields once the class is complete.
11472   if (ClassDecl->isCompleteDefinition() &&
11473       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11474     SetDeclDeleted(Destructor, ClassLoc);
11475 
11476   // Introduce this destructor into its scope.
11477   if (S)
11478     PushOnScopeChains(Destructor, S, false);
11479   ClassDecl->addDecl(Destructor);
11480 
11481   return Destructor;
11482 }
11483 
11484 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11485                                     CXXDestructorDecl *Destructor) {
11486   assert((Destructor->isDefaulted() &&
11487           !Destructor->doesThisDeclarationHaveABody() &&
11488           !Destructor->isDeleted()) &&
11489          "DefineImplicitDestructor - call it for implicit default dtor");
11490   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11491     return;
11492 
11493   CXXRecordDecl *ClassDecl = Destructor->getParent();
11494   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11495 
11496   SynthesizedFunctionScope Scope(*this, Destructor);
11497 
11498   // The exception specification is needed because we are defining the
11499   // function.
11500   ResolveExceptionSpec(CurrentLocation,
11501                        Destructor->getType()->castAs<FunctionProtoType>());
11502   MarkVTableUsed(CurrentLocation, ClassDecl);
11503 
11504   // Add a context note for diagnostics produced after this point.
11505   Scope.addContextNote(CurrentLocation);
11506 
11507   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11508                                          Destructor->getParent());
11509 
11510   if (CheckDestructor(Destructor)) {
11511     Destructor->setInvalidDecl();
11512     return;
11513   }
11514 
11515   SourceLocation Loc = Destructor->getEndLoc().isValid()
11516                            ? Destructor->getEndLoc()
11517                            : Destructor->getLocation();
11518   Destructor->setBody(new (Context) CompoundStmt(Loc));
11519   Destructor->markUsed(Context);
11520 
11521   if (ASTMutationListener *L = getASTMutationListener()) {
11522     L->CompletedImplicitDefinition(Destructor);
11523   }
11524 }
11525 
11526 /// Perform any semantic analysis which needs to be delayed until all
11527 /// pending class member declarations have been parsed.
11528 void Sema::ActOnFinishCXXMemberDecls() {
11529   // If the context is an invalid C++ class, just suppress these checks.
11530   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11531     if (Record->isInvalidDecl()) {
11532       DelayedOverridingExceptionSpecChecks.clear();
11533       DelayedEquivalentExceptionSpecChecks.clear();
11534       return;
11535     }
11536     checkForMultipleExportedDefaultConstructors(*this, Record);
11537   }
11538 }
11539 
11540 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11541   referenceDLLExportedClassMethods();
11542 
11543   if (!DelayedDllExportMemberFunctions.empty()) {
11544     SmallVector<CXXMethodDecl*, 4> WorkList;
11545     std::swap(DelayedDllExportMemberFunctions, WorkList);
11546     for (CXXMethodDecl *M : WorkList) {
11547       DefineImplicitSpecialMember(*this, M, M->getLocation());
11548 
11549       // Pass the method to the consumer to get emitted. This is not necessary
11550       // for explicit instantiation definitions, as they will get emitted
11551       // anyway.
11552       if (M->getParent()->getTemplateSpecializationKind() !=
11553           TSK_ExplicitInstantiationDefinition)
11554         ActOnFinishInlineFunctionDef(M);
11555     }
11556   }
11557 }
11558 
11559 void Sema::referenceDLLExportedClassMethods() {
11560   if (!DelayedDllExportClasses.empty()) {
11561     // Calling ReferenceDllExportedMembers might cause the current function to
11562     // be called again, so use a local copy of DelayedDllExportClasses.
11563     SmallVector<CXXRecordDecl *, 4> WorkList;
11564     std::swap(DelayedDllExportClasses, WorkList);
11565     for (CXXRecordDecl *Class : WorkList)
11566       ReferenceDllExportedMembers(*this, Class);
11567   }
11568 }
11569 
11570 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11571   assert(getLangOpts().CPlusPlus11 &&
11572          "adjusting dtor exception specs was introduced in c++11");
11573 
11574   if (Destructor->isDependentContext())
11575     return;
11576 
11577   // C++11 [class.dtor]p3:
11578   //   A declaration of a destructor that does not have an exception-
11579   //   specification is implicitly considered to have the same exception-
11580   //   specification as an implicit declaration.
11581   const FunctionProtoType *DtorType = Destructor->getType()->
11582                                         getAs<FunctionProtoType>();
11583   if (DtorType->hasExceptionSpec())
11584     return;
11585 
11586   // Replace the destructor's type, building off the existing one. Fortunately,
11587   // the only thing of interest in the destructor type is its extended info.
11588   // The return and arguments are fixed.
11589   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11590   EPI.ExceptionSpec.Type = EST_Unevaluated;
11591   EPI.ExceptionSpec.SourceDecl = Destructor;
11592   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11593 
11594   // FIXME: If the destructor has a body that could throw, and the newly created
11595   // spec doesn't allow exceptions, we should emit a warning, because this
11596   // change in behavior can break conforming C++03 programs at runtime.
11597   // However, we don't have a body or an exception specification yet, so it
11598   // needs to be done somewhere else.
11599 }
11600 
11601 namespace {
11602 /// An abstract base class for all helper classes used in building the
11603 //  copy/move operators. These classes serve as factory functions and help us
11604 //  avoid using the same Expr* in the AST twice.
11605 class ExprBuilder {
11606   ExprBuilder(const ExprBuilder&) = delete;
11607   ExprBuilder &operator=(const ExprBuilder&) = delete;
11608 
11609 protected:
11610   static Expr *assertNotNull(Expr *E) {
11611     assert(E && "Expression construction must not fail.");
11612     return E;
11613   }
11614 
11615 public:
11616   ExprBuilder() {}
11617   virtual ~ExprBuilder() {}
11618 
11619   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11620 };
11621 
11622 class RefBuilder: public ExprBuilder {
11623   VarDecl *Var;
11624   QualType VarType;
11625 
11626 public:
11627   Expr *build(Sema &S, SourceLocation Loc) const override {
11628     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
11629   }
11630 
11631   RefBuilder(VarDecl *Var, QualType VarType)
11632       : Var(Var), VarType(VarType) {}
11633 };
11634 
11635 class ThisBuilder: public ExprBuilder {
11636 public:
11637   Expr *build(Sema &S, SourceLocation Loc) const override {
11638     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11639   }
11640 };
11641 
11642 class CastBuilder: public ExprBuilder {
11643   const ExprBuilder &Builder;
11644   QualType Type;
11645   ExprValueKind Kind;
11646   const CXXCastPath &Path;
11647 
11648 public:
11649   Expr *build(Sema &S, SourceLocation Loc) const override {
11650     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11651                                              CK_UncheckedDerivedToBase, Kind,
11652                                              &Path).get());
11653   }
11654 
11655   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11656               const CXXCastPath &Path)
11657       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11658 };
11659 
11660 class DerefBuilder: public ExprBuilder {
11661   const ExprBuilder &Builder;
11662 
11663 public:
11664   Expr *build(Sema &S, SourceLocation Loc) const override {
11665     return assertNotNull(
11666         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11667   }
11668 
11669   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11670 };
11671 
11672 class MemberBuilder: public ExprBuilder {
11673   const ExprBuilder &Builder;
11674   QualType Type;
11675   CXXScopeSpec SS;
11676   bool IsArrow;
11677   LookupResult &MemberLookup;
11678 
11679 public:
11680   Expr *build(Sema &S, SourceLocation Loc) const override {
11681     return assertNotNull(S.BuildMemberReferenceExpr(
11682         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11683         nullptr, MemberLookup, nullptr, nullptr).get());
11684   }
11685 
11686   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11687                 LookupResult &MemberLookup)
11688       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11689         MemberLookup(MemberLookup) {}
11690 };
11691 
11692 class MoveCastBuilder: public ExprBuilder {
11693   const ExprBuilder &Builder;
11694 
11695 public:
11696   Expr *build(Sema &S, SourceLocation Loc) const override {
11697     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11698   }
11699 
11700   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11701 };
11702 
11703 class LvalueConvBuilder: public ExprBuilder {
11704   const ExprBuilder &Builder;
11705 
11706 public:
11707   Expr *build(Sema &S, SourceLocation Loc) const override {
11708     return assertNotNull(
11709         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11710   }
11711 
11712   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11713 };
11714 
11715 class SubscriptBuilder: public ExprBuilder {
11716   const ExprBuilder &Base;
11717   const ExprBuilder &Index;
11718 
11719 public:
11720   Expr *build(Sema &S, SourceLocation Loc) const override {
11721     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11722         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11723   }
11724 
11725   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11726       : Base(Base), Index(Index) {}
11727 };
11728 
11729 } // end anonymous namespace
11730 
11731 /// When generating a defaulted copy or move assignment operator, if a field
11732 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11733 /// do so. This optimization only applies for arrays of scalars, and for arrays
11734 /// of class type where the selected copy/move-assignment operator is trivial.
11735 static StmtResult
11736 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11737                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11738   // Compute the size of the memory buffer to be copied.
11739   QualType SizeType = S.Context.getSizeType();
11740   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11741                    S.Context.getTypeSizeInChars(T).getQuantity());
11742 
11743   // Take the address of the field references for "from" and "to". We
11744   // directly construct UnaryOperators here because semantic analysis
11745   // does not permit us to take the address of an xvalue.
11746   Expr *From = FromB.build(S, Loc);
11747   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11748                          S.Context.getPointerType(From->getType()),
11749                          VK_RValue, OK_Ordinary, Loc, false);
11750   Expr *To = ToB.build(S, Loc);
11751   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11752                        S.Context.getPointerType(To->getType()),
11753                        VK_RValue, OK_Ordinary, Loc, false);
11754 
11755   const Type *E = T->getBaseElementTypeUnsafe();
11756   bool NeedsCollectableMemCpy =
11757     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11758 
11759   // Create a reference to the __builtin_objc_memmove_collectable function
11760   StringRef MemCpyName = NeedsCollectableMemCpy ?
11761     "__builtin_objc_memmove_collectable" :
11762     "__builtin_memcpy";
11763   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11764                  Sema::LookupOrdinaryName);
11765   S.LookupName(R, S.TUScope, true);
11766 
11767   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11768   if (!MemCpy)
11769     // Something went horribly wrong earlier, and we will have complained
11770     // about it.
11771     return StmtError();
11772 
11773   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11774                                             VK_RValue, Loc, nullptr);
11775   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11776 
11777   Expr *CallArgs[] = {
11778     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11779   };
11780   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11781                                     Loc, CallArgs, Loc);
11782 
11783   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11784   return Call.getAs<Stmt>();
11785 }
11786 
11787 /// Builds a statement that copies/moves the given entity from \p From to
11788 /// \c To.
11789 ///
11790 /// This routine is used to copy/move the members of a class with an
11791 /// implicitly-declared copy/move assignment operator. When the entities being
11792 /// copied are arrays, this routine builds for loops to copy them.
11793 ///
11794 /// \param S The Sema object used for type-checking.
11795 ///
11796 /// \param Loc The location where the implicit copy/move is being generated.
11797 ///
11798 /// \param T The type of the expressions being copied/moved. Both expressions
11799 /// must have this type.
11800 ///
11801 /// \param To The expression we are copying/moving to.
11802 ///
11803 /// \param From The expression we are copying/moving from.
11804 ///
11805 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11806 /// Otherwise, it's a non-static member subobject.
11807 ///
11808 /// \param Copying Whether we're copying or moving.
11809 ///
11810 /// \param Depth Internal parameter recording the depth of the recursion.
11811 ///
11812 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11813 /// if a memcpy should be used instead.
11814 static StmtResult
11815 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11816                                  const ExprBuilder &To, const ExprBuilder &From,
11817                                  bool CopyingBaseSubobject, bool Copying,
11818                                  unsigned Depth = 0) {
11819   // C++11 [class.copy]p28:
11820   //   Each subobject is assigned in the manner appropriate to its type:
11821   //
11822   //     - if the subobject is of class type, as if by a call to operator= with
11823   //       the subobject as the object expression and the corresponding
11824   //       subobject of x as a single function argument (as if by explicit
11825   //       qualification; that is, ignoring any possible virtual overriding
11826   //       functions in more derived classes);
11827   //
11828   // C++03 [class.copy]p13:
11829   //     - if the subobject is of class type, the copy assignment operator for
11830   //       the class is used (as if by explicit qualification; that is,
11831   //       ignoring any possible virtual overriding functions in more derived
11832   //       classes);
11833   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11834     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11835 
11836     // Look for operator=.
11837     DeclarationName Name
11838       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11839     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11840     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11841 
11842     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11843     // operator.
11844     if (!S.getLangOpts().CPlusPlus11) {
11845       LookupResult::Filter F = OpLookup.makeFilter();
11846       while (F.hasNext()) {
11847         NamedDecl *D = F.next();
11848         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11849           if (Method->isCopyAssignmentOperator() ||
11850               (!Copying && Method->isMoveAssignmentOperator()))
11851             continue;
11852 
11853         F.erase();
11854       }
11855       F.done();
11856     }
11857 
11858     // Suppress the protected check (C++ [class.protected]) for each of the
11859     // assignment operators we found. This strange dance is required when
11860     // we're assigning via a base classes's copy-assignment operator. To
11861     // ensure that we're getting the right base class subobject (without
11862     // ambiguities), we need to cast "this" to that subobject type; to
11863     // ensure that we don't go through the virtual call mechanism, we need
11864     // to qualify the operator= name with the base class (see below). However,
11865     // this means that if the base class has a protected copy assignment
11866     // operator, the protected member access check will fail. So, we
11867     // rewrite "protected" access to "public" access in this case, since we
11868     // know by construction that we're calling from a derived class.
11869     if (CopyingBaseSubobject) {
11870       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11871            L != LEnd; ++L) {
11872         if (L.getAccess() == AS_protected)
11873           L.setAccess(AS_public);
11874       }
11875     }
11876 
11877     // Create the nested-name-specifier that will be used to qualify the
11878     // reference to operator=; this is required to suppress the virtual
11879     // call mechanism.
11880     CXXScopeSpec SS;
11881     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11882     SS.MakeTrivial(S.Context,
11883                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11884                                                CanonicalT),
11885                    Loc);
11886 
11887     // Create the reference to operator=.
11888     ExprResult OpEqualRef
11889       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
11890                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11891                                    /*FirstQualifierInScope=*/nullptr,
11892                                    OpLookup,
11893                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11894                                    /*SuppressQualifierCheck=*/true);
11895     if (OpEqualRef.isInvalid())
11896       return StmtError();
11897 
11898     // Build the call to the assignment operator.
11899 
11900     Expr *FromInst = From.build(S, Loc);
11901     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11902                                                   OpEqualRef.getAs<Expr>(),
11903                                                   Loc, FromInst, Loc);
11904     if (Call.isInvalid())
11905       return StmtError();
11906 
11907     // If we built a call to a trivial 'operator=' while copying an array,
11908     // bail out. We'll replace the whole shebang with a memcpy.
11909     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11910     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11911       return StmtResult((Stmt*)nullptr);
11912 
11913     // Convert to an expression-statement, and clean up any produced
11914     // temporaries.
11915     return S.ActOnExprStmt(Call);
11916   }
11917 
11918   //     - if the subobject is of scalar type, the built-in assignment
11919   //       operator is used.
11920   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11921   if (!ArrayTy) {
11922     ExprResult Assignment = S.CreateBuiltinBinOp(
11923         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11924     if (Assignment.isInvalid())
11925       return StmtError();
11926     return S.ActOnExprStmt(Assignment);
11927   }
11928 
11929   //     - if the subobject is an array, each element is assigned, in the
11930   //       manner appropriate to the element type;
11931 
11932   // Construct a loop over the array bounds, e.g.,
11933   //
11934   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11935   //
11936   // that will copy each of the array elements.
11937   QualType SizeType = S.Context.getSizeType();
11938 
11939   // Create the iteration variable.
11940   IdentifierInfo *IterationVarName = nullptr;
11941   {
11942     SmallString<8> Str;
11943     llvm::raw_svector_ostream OS(Str);
11944     OS << "__i" << Depth;
11945     IterationVarName = &S.Context.Idents.get(OS.str());
11946   }
11947   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11948                                           IterationVarName, SizeType,
11949                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11950                                           SC_None);
11951 
11952   // Initialize the iteration variable to zero.
11953   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11954   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11955 
11956   // Creates a reference to the iteration variable.
11957   RefBuilder IterationVarRef(IterationVar, SizeType);
11958   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11959 
11960   // Create the DeclStmt that holds the iteration variable.
11961   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11962 
11963   // Subscript the "from" and "to" expressions with the iteration variable.
11964   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11965   MoveCastBuilder FromIndexMove(FromIndexCopy);
11966   const ExprBuilder *FromIndex;
11967   if (Copying)
11968     FromIndex = &FromIndexCopy;
11969   else
11970     FromIndex = &FromIndexMove;
11971 
11972   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11973 
11974   // Build the copy/move for an individual element of the array.
11975   StmtResult Copy =
11976     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11977                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11978                                      Copying, Depth + 1);
11979   // Bail out if copying fails or if we determined that we should use memcpy.
11980   if (Copy.isInvalid() || !Copy.get())
11981     return Copy;
11982 
11983   // Create the comparison against the array bound.
11984   llvm::APInt Upper
11985     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11986   Expr *Comparison
11987     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11988                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11989                                      BO_NE, S.Context.BoolTy,
11990                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11991 
11992   // Create the pre-increment of the iteration variable. We can determine
11993   // whether the increment will overflow based on the value of the array
11994   // bound.
11995   Expr *Increment = new (S.Context)
11996       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11997                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11998 
11999   // Construct the loop that copies all elements of this array.
12000   return S.ActOnForStmt(
12001       Loc, Loc, InitStmt,
12002       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
12003       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
12004 }
12005 
12006 static StmtResult
12007 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
12008                       const ExprBuilder &To, const ExprBuilder &From,
12009                       bool CopyingBaseSubobject, bool Copying) {
12010   // Maybe we should use a memcpy?
12011   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
12012       T.isTriviallyCopyableType(S.Context))
12013     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
12014 
12015   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
12016                                                      CopyingBaseSubobject,
12017                                                      Copying, 0));
12018 
12019   // If we ended up picking a trivial assignment operator for an array of a
12020   // non-trivially-copyable class type, just emit a memcpy.
12021   if (!Result.isInvalid() && !Result.get())
12022     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
12023 
12024   return Result;
12025 }
12026 
12027 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
12028   // Note: The following rules are largely analoguous to the copy
12029   // constructor rules. Note that virtual bases are not taken into account
12030   // for determining the argument type of the operator. Note also that
12031   // operators taking an object instead of a reference are allowed.
12032   assert(ClassDecl->needsImplicitCopyAssignment());
12033 
12034   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
12035   if (DSM.isAlreadyBeingDeclared())
12036     return nullptr;
12037 
12038   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12039   if (Context.getLangOpts().OpenCLCPlusPlus)
12040     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12041   QualType RetType = Context.getLValueReferenceType(ArgType);
12042   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
12043   if (Const)
12044     ArgType = ArgType.withConst();
12045 
12046   ArgType = Context.getLValueReferenceType(ArgType);
12047 
12048   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12049                                                      CXXCopyAssignment,
12050                                                      Const);
12051 
12052   //   An implicitly-declared copy assignment operator is an inline public
12053   //   member of its class.
12054   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12055   SourceLocation ClassLoc = ClassDecl->getLocation();
12056   DeclarationNameInfo NameInfo(Name, ClassLoc);
12057   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
12058       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12059       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12060       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
12061       SourceLocation());
12062   CopyAssignment->setAccess(AS_public);
12063   CopyAssignment->setDefaulted();
12064   CopyAssignment->setImplicit();
12065 
12066   if (getLangOpts().CUDA) {
12067     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
12068                                             CopyAssignment,
12069                                             /* ConstRHS */ Const,
12070                                             /* Diagnose */ false);
12071   }
12072 
12073   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
12074 
12075   // Add the parameter to the operator.
12076   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
12077                                                ClassLoc, ClassLoc,
12078                                                /*Id=*/nullptr, ArgType,
12079                                                /*TInfo=*/nullptr, SC_None,
12080                                                nullptr);
12081   CopyAssignment->setParams(FromParam);
12082 
12083   CopyAssignment->setTrivial(
12084     ClassDecl->needsOverloadResolutionForCopyAssignment()
12085       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
12086       : ClassDecl->hasTrivialCopyAssignment());
12087 
12088   // Note that we have added this copy-assignment operator.
12089   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
12090 
12091   Scope *S = getScopeForContext(ClassDecl);
12092   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
12093 
12094   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
12095     SetDeclDeleted(CopyAssignment, ClassLoc);
12096 
12097   if (S)
12098     PushOnScopeChains(CopyAssignment, S, false);
12099   ClassDecl->addDecl(CopyAssignment);
12100 
12101   return CopyAssignment;
12102 }
12103 
12104 /// Diagnose an implicit copy operation for a class which is odr-used, but
12105 /// which is deprecated because the class has a user-declared copy constructor,
12106 /// copy assignment operator, or destructor.
12107 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
12108   assert(CopyOp->isImplicit());
12109 
12110   CXXRecordDecl *RD = CopyOp->getParent();
12111   CXXMethodDecl *UserDeclaredOperation = nullptr;
12112 
12113   // In Microsoft mode, assignment operations don't affect constructors and
12114   // vice versa.
12115   if (RD->hasUserDeclaredDestructor()) {
12116     UserDeclaredOperation = RD->getDestructor();
12117   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
12118              RD->hasUserDeclaredCopyConstructor() &&
12119              !S.getLangOpts().MSVCCompat) {
12120     // Find any user-declared copy constructor.
12121     for (auto *I : RD->ctors()) {
12122       if (I->isCopyConstructor()) {
12123         UserDeclaredOperation = I;
12124         break;
12125       }
12126     }
12127     assert(UserDeclaredOperation);
12128   } else if (isa<CXXConstructorDecl>(CopyOp) &&
12129              RD->hasUserDeclaredCopyAssignment() &&
12130              !S.getLangOpts().MSVCCompat) {
12131     // Find any user-declared move assignment operator.
12132     for (auto *I : RD->methods()) {
12133       if (I->isCopyAssignmentOperator()) {
12134         UserDeclaredOperation = I;
12135         break;
12136       }
12137     }
12138     assert(UserDeclaredOperation);
12139   }
12140 
12141   if (UserDeclaredOperation) {
12142     S.Diag(UserDeclaredOperation->getLocation(),
12143          diag::warn_deprecated_copy_operation)
12144       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
12145       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
12146   }
12147 }
12148 
12149 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
12150                                         CXXMethodDecl *CopyAssignOperator) {
12151   assert((CopyAssignOperator->isDefaulted() &&
12152           CopyAssignOperator->isOverloadedOperator() &&
12153           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
12154           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
12155           !CopyAssignOperator->isDeleted()) &&
12156          "DefineImplicitCopyAssignment called for wrong function");
12157   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
12158     return;
12159 
12160   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
12161   if (ClassDecl->isInvalidDecl()) {
12162     CopyAssignOperator->setInvalidDecl();
12163     return;
12164   }
12165 
12166   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
12167 
12168   // The exception specification is needed because we are defining the
12169   // function.
12170   ResolveExceptionSpec(CurrentLocation,
12171                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
12172 
12173   // Add a context note for diagnostics produced after this point.
12174   Scope.addContextNote(CurrentLocation);
12175 
12176   // C++11 [class.copy]p18:
12177   //   The [definition of an implicitly declared copy assignment operator] is
12178   //   deprecated if the class has a user-declared copy constructor or a
12179   //   user-declared destructor.
12180   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
12181     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
12182 
12183   // C++0x [class.copy]p30:
12184   //   The implicitly-defined or explicitly-defaulted copy assignment operator
12185   //   for a non-union class X performs memberwise copy assignment of its
12186   //   subobjects. The direct base classes of X are assigned first, in the
12187   //   order of their declaration in the base-specifier-list, and then the
12188   //   immediate non-static data members of X are assigned, in the order in
12189   //   which they were declared in the class definition.
12190 
12191   // The statements that form the synthesized function body.
12192   SmallVector<Stmt*, 8> Statements;
12193 
12194   // The parameter for the "other" object, which we are copying from.
12195   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
12196   Qualifiers OtherQuals = Other->getType().getQualifiers();
12197   QualType OtherRefType = Other->getType();
12198   if (const LValueReferenceType *OtherRef
12199                                 = OtherRefType->getAs<LValueReferenceType>()) {
12200     OtherRefType = OtherRef->getPointeeType();
12201     OtherQuals = OtherRefType.getQualifiers();
12202   }
12203 
12204   // Our location for everything implicitly-generated.
12205   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
12206                            ? CopyAssignOperator->getEndLoc()
12207                            : CopyAssignOperator->getLocation();
12208 
12209   // Builds a DeclRefExpr for the "other" object.
12210   RefBuilder OtherRef(Other, OtherRefType);
12211 
12212   // Builds the "this" pointer.
12213   ThisBuilder This;
12214 
12215   // Assign base classes.
12216   bool Invalid = false;
12217   for (auto &Base : ClassDecl->bases()) {
12218     // Form the assignment:
12219     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
12220     QualType BaseType = Base.getType().getUnqualifiedType();
12221     if (!BaseType->isRecordType()) {
12222       Invalid = true;
12223       continue;
12224     }
12225 
12226     CXXCastPath BasePath;
12227     BasePath.push_back(&Base);
12228 
12229     // Construct the "from" expression, which is an implicit cast to the
12230     // appropriately-qualified base type.
12231     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
12232                      VK_LValue, BasePath);
12233 
12234     // Dereference "this".
12235     DerefBuilder DerefThis(This);
12236     CastBuilder To(DerefThis,
12237                    Context.getQualifiedType(
12238                        BaseType, CopyAssignOperator->getMethodQualifiers()),
12239                    VK_LValue, BasePath);
12240 
12241     // Build the copy.
12242     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12243                                             To, From,
12244                                             /*CopyingBaseSubobject=*/true,
12245                                             /*Copying=*/true);
12246     if (Copy.isInvalid()) {
12247       CopyAssignOperator->setInvalidDecl();
12248       return;
12249     }
12250 
12251     // Success! Record the copy.
12252     Statements.push_back(Copy.getAs<Expr>());
12253   }
12254 
12255   // Assign non-static members.
12256   for (auto *Field : ClassDecl->fields()) {
12257     // FIXME: We should form some kind of AST representation for the implied
12258     // memcpy in a union copy operation.
12259     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12260       continue;
12261 
12262     if (Field->isInvalidDecl()) {
12263       Invalid = true;
12264       continue;
12265     }
12266 
12267     // Check for members of reference type; we can't copy those.
12268     if (Field->getType()->isReferenceType()) {
12269       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12270         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12271       Diag(Field->getLocation(), diag::note_declared_at);
12272       Invalid = true;
12273       continue;
12274     }
12275 
12276     // Check for members of const-qualified, non-class type.
12277     QualType BaseType = Context.getBaseElementType(Field->getType());
12278     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12279       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12280         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12281       Diag(Field->getLocation(), diag::note_declared_at);
12282       Invalid = true;
12283       continue;
12284     }
12285 
12286     // Suppress assigning zero-width bitfields.
12287     if (Field->isZeroLengthBitField(Context))
12288       continue;
12289 
12290     QualType FieldType = Field->getType().getNonReferenceType();
12291     if (FieldType->isIncompleteArrayType()) {
12292       assert(ClassDecl->hasFlexibleArrayMember() &&
12293              "Incomplete array type is not valid");
12294       continue;
12295     }
12296 
12297     // Build references to the field in the object we're copying from and to.
12298     CXXScopeSpec SS; // Intentionally empty
12299     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12300                               LookupMemberName);
12301     MemberLookup.addDecl(Field);
12302     MemberLookup.resolveKind();
12303 
12304     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12305 
12306     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12307 
12308     // Build the copy of this field.
12309     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12310                                             To, From,
12311                                             /*CopyingBaseSubobject=*/false,
12312                                             /*Copying=*/true);
12313     if (Copy.isInvalid()) {
12314       CopyAssignOperator->setInvalidDecl();
12315       return;
12316     }
12317 
12318     // Success! Record the copy.
12319     Statements.push_back(Copy.getAs<Stmt>());
12320   }
12321 
12322   if (!Invalid) {
12323     // Add a "return *this;"
12324     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12325 
12326     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12327     if (Return.isInvalid())
12328       Invalid = true;
12329     else
12330       Statements.push_back(Return.getAs<Stmt>());
12331   }
12332 
12333   if (Invalid) {
12334     CopyAssignOperator->setInvalidDecl();
12335     return;
12336   }
12337 
12338   StmtResult Body;
12339   {
12340     CompoundScopeRAII CompoundScope(*this);
12341     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12342                              /*isStmtExpr=*/false);
12343     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12344   }
12345   CopyAssignOperator->setBody(Body.getAs<Stmt>());
12346   CopyAssignOperator->markUsed(Context);
12347 
12348   if (ASTMutationListener *L = getASTMutationListener()) {
12349     L->CompletedImplicitDefinition(CopyAssignOperator);
12350   }
12351 }
12352 
12353 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12354   assert(ClassDecl->needsImplicitMoveAssignment());
12355 
12356   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12357   if (DSM.isAlreadyBeingDeclared())
12358     return nullptr;
12359 
12360   // Note: The following rules are largely analoguous to the move
12361   // constructor rules.
12362 
12363   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12364   if (Context.getLangOpts().OpenCLCPlusPlus)
12365     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12366   QualType RetType = Context.getLValueReferenceType(ArgType);
12367   ArgType = Context.getRValueReferenceType(ArgType);
12368 
12369   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12370                                                      CXXMoveAssignment,
12371                                                      false);
12372 
12373   //   An implicitly-declared move assignment operator is an inline public
12374   //   member of its class.
12375   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12376   SourceLocation ClassLoc = ClassDecl->getLocation();
12377   DeclarationNameInfo NameInfo(Name, ClassLoc);
12378   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
12379       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12380       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12381       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
12382       SourceLocation());
12383   MoveAssignment->setAccess(AS_public);
12384   MoveAssignment->setDefaulted();
12385   MoveAssignment->setImplicit();
12386 
12387   if (getLangOpts().CUDA) {
12388     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12389                                             MoveAssignment,
12390                                             /* ConstRHS */ false,
12391                                             /* Diagnose */ false);
12392   }
12393 
12394   // Build an exception specification pointing back at this member.
12395   FunctionProtoType::ExtProtoInfo EPI =
12396       getImplicitMethodEPI(*this, MoveAssignment);
12397   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12398 
12399   // Add the parameter to the operator.
12400   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12401                                                ClassLoc, ClassLoc,
12402                                                /*Id=*/nullptr, ArgType,
12403                                                /*TInfo=*/nullptr, SC_None,
12404                                                nullptr);
12405   MoveAssignment->setParams(FromParam);
12406 
12407   MoveAssignment->setTrivial(
12408     ClassDecl->needsOverloadResolutionForMoveAssignment()
12409       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12410       : ClassDecl->hasTrivialMoveAssignment());
12411 
12412   // Note that we have added this copy-assignment operator.
12413   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
12414 
12415   Scope *S = getScopeForContext(ClassDecl);
12416   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12417 
12418   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12419     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12420     SetDeclDeleted(MoveAssignment, ClassLoc);
12421   }
12422 
12423   if (S)
12424     PushOnScopeChains(MoveAssignment, S, false);
12425   ClassDecl->addDecl(MoveAssignment);
12426 
12427   return MoveAssignment;
12428 }
12429 
12430 /// Check if we're implicitly defining a move assignment operator for a class
12431 /// with virtual bases. Such a move assignment might move-assign the virtual
12432 /// base multiple times.
12433 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12434                                                SourceLocation CurrentLocation) {
12435   assert(!Class->isDependentContext() && "should not define dependent move");
12436 
12437   // Only a virtual base could get implicitly move-assigned multiple times.
12438   // Only a non-trivial move assignment can observe this. We only want to
12439   // diagnose if we implicitly define an assignment operator that assigns
12440   // two base classes, both of which move-assign the same virtual base.
12441   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12442       Class->getNumBases() < 2)
12443     return;
12444 
12445   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12446   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12447   VBaseMap VBases;
12448 
12449   for (auto &BI : Class->bases()) {
12450     Worklist.push_back(&BI);
12451     while (!Worklist.empty()) {
12452       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12453       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12454 
12455       // If the base has no non-trivial move assignment operators,
12456       // we don't care about moves from it.
12457       if (!Base->hasNonTrivialMoveAssignment())
12458         continue;
12459 
12460       // If there's nothing virtual here, skip it.
12461       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12462         continue;
12463 
12464       // If we're not actually going to call a move assignment for this base,
12465       // or the selected move assignment is trivial, skip it.
12466       Sema::SpecialMemberOverloadResult SMOR =
12467         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12468                               /*ConstArg*/false, /*VolatileArg*/false,
12469                               /*RValueThis*/true, /*ConstThis*/false,
12470                               /*VolatileThis*/false);
12471       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12472           !SMOR.getMethod()->isMoveAssignmentOperator())
12473         continue;
12474 
12475       if (BaseSpec->isVirtual()) {
12476         // We're going to move-assign this virtual base, and its move
12477         // assignment operator is not trivial. If this can happen for
12478         // multiple distinct direct bases of Class, diagnose it. (If it
12479         // only happens in one base, we'll diagnose it when synthesizing
12480         // that base class's move assignment operator.)
12481         CXXBaseSpecifier *&Existing =
12482             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12483                 .first->second;
12484         if (Existing && Existing != &BI) {
12485           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12486             << Class << Base;
12487           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12488               << (Base->getCanonicalDecl() ==
12489                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12490               << Base << Existing->getType() << Existing->getSourceRange();
12491           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12492               << (Base->getCanonicalDecl() ==
12493                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12494               << Base << BI.getType() << BaseSpec->getSourceRange();
12495 
12496           // Only diagnose each vbase once.
12497           Existing = nullptr;
12498         }
12499       } else {
12500         // Only walk over bases that have defaulted move assignment operators.
12501         // We assume that any user-provided move assignment operator handles
12502         // the multiple-moves-of-vbase case itself somehow.
12503         if (!SMOR.getMethod()->isDefaulted())
12504           continue;
12505 
12506         // We're going to move the base classes of Base. Add them to the list.
12507         for (auto &BI : Base->bases())
12508           Worklist.push_back(&BI);
12509       }
12510     }
12511   }
12512 }
12513 
12514 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12515                                         CXXMethodDecl *MoveAssignOperator) {
12516   assert((MoveAssignOperator->isDefaulted() &&
12517           MoveAssignOperator->isOverloadedOperator() &&
12518           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12519           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12520           !MoveAssignOperator->isDeleted()) &&
12521          "DefineImplicitMoveAssignment called for wrong function");
12522   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12523     return;
12524 
12525   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12526   if (ClassDecl->isInvalidDecl()) {
12527     MoveAssignOperator->setInvalidDecl();
12528     return;
12529   }
12530 
12531   // C++0x [class.copy]p28:
12532   //   The implicitly-defined or move assignment operator for a non-union class
12533   //   X performs memberwise move assignment of its subobjects. The direct base
12534   //   classes of X are assigned first, in the order of their declaration in the
12535   //   base-specifier-list, and then the immediate non-static data members of X
12536   //   are assigned, in the order in which they were declared in the class
12537   //   definition.
12538 
12539   // Issue a warning if our implicit move assignment operator will move
12540   // from a virtual base more than once.
12541   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12542 
12543   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12544 
12545   // The exception specification is needed because we are defining the
12546   // function.
12547   ResolveExceptionSpec(CurrentLocation,
12548                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12549 
12550   // Add a context note for diagnostics produced after this point.
12551   Scope.addContextNote(CurrentLocation);
12552 
12553   // The statements that form the synthesized function body.
12554   SmallVector<Stmt*, 8> Statements;
12555 
12556   // The parameter for the "other" object, which we are move from.
12557   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12558   QualType OtherRefType = Other->getType()->
12559       getAs<RValueReferenceType>()->getPointeeType();
12560 
12561   // Our location for everything implicitly-generated.
12562   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12563                            ? MoveAssignOperator->getEndLoc()
12564                            : MoveAssignOperator->getLocation();
12565 
12566   // Builds a reference to the "other" object.
12567   RefBuilder OtherRef(Other, OtherRefType);
12568   // Cast to rvalue.
12569   MoveCastBuilder MoveOther(OtherRef);
12570 
12571   // Builds the "this" pointer.
12572   ThisBuilder This;
12573 
12574   // Assign base classes.
12575   bool Invalid = false;
12576   for (auto &Base : ClassDecl->bases()) {
12577     // C++11 [class.copy]p28:
12578     //   It is unspecified whether subobjects representing virtual base classes
12579     //   are assigned more than once by the implicitly-defined copy assignment
12580     //   operator.
12581     // FIXME: Do not assign to a vbase that will be assigned by some other base
12582     // class. For a move-assignment, this can result in the vbase being moved
12583     // multiple times.
12584 
12585     // Form the assignment:
12586     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12587     QualType BaseType = Base.getType().getUnqualifiedType();
12588     if (!BaseType->isRecordType()) {
12589       Invalid = true;
12590       continue;
12591     }
12592 
12593     CXXCastPath BasePath;
12594     BasePath.push_back(&Base);
12595 
12596     // Construct the "from" expression, which is an implicit cast to the
12597     // appropriately-qualified base type.
12598     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12599 
12600     // Dereference "this".
12601     DerefBuilder DerefThis(This);
12602 
12603     // Implicitly cast "this" to the appropriately-qualified base type.
12604     CastBuilder To(DerefThis,
12605                    Context.getQualifiedType(
12606                        BaseType, MoveAssignOperator->getMethodQualifiers()),
12607                    VK_LValue, BasePath);
12608 
12609     // Build the move.
12610     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12611                                             To, From,
12612                                             /*CopyingBaseSubobject=*/true,
12613                                             /*Copying=*/false);
12614     if (Move.isInvalid()) {
12615       MoveAssignOperator->setInvalidDecl();
12616       return;
12617     }
12618 
12619     // Success! Record the move.
12620     Statements.push_back(Move.getAs<Expr>());
12621   }
12622 
12623   // Assign non-static members.
12624   for (auto *Field : ClassDecl->fields()) {
12625     // FIXME: We should form some kind of AST representation for the implied
12626     // memcpy in a union copy operation.
12627     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12628       continue;
12629 
12630     if (Field->isInvalidDecl()) {
12631       Invalid = true;
12632       continue;
12633     }
12634 
12635     // Check for members of reference type; we can't move those.
12636     if (Field->getType()->isReferenceType()) {
12637       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12638         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12639       Diag(Field->getLocation(), diag::note_declared_at);
12640       Invalid = true;
12641       continue;
12642     }
12643 
12644     // Check for members of const-qualified, non-class type.
12645     QualType BaseType = Context.getBaseElementType(Field->getType());
12646     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12647       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12648         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12649       Diag(Field->getLocation(), diag::note_declared_at);
12650       Invalid = true;
12651       continue;
12652     }
12653 
12654     // Suppress assigning zero-width bitfields.
12655     if (Field->isZeroLengthBitField(Context))
12656       continue;
12657 
12658     QualType FieldType = Field->getType().getNonReferenceType();
12659     if (FieldType->isIncompleteArrayType()) {
12660       assert(ClassDecl->hasFlexibleArrayMember() &&
12661              "Incomplete array type is not valid");
12662       continue;
12663     }
12664 
12665     // Build references to the field in the object we're copying from and to.
12666     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12667                               LookupMemberName);
12668     MemberLookup.addDecl(Field);
12669     MemberLookup.resolveKind();
12670     MemberBuilder From(MoveOther, OtherRefType,
12671                        /*IsArrow=*/false, MemberLookup);
12672     MemberBuilder To(This, getCurrentThisType(),
12673                      /*IsArrow=*/true, MemberLookup);
12674 
12675     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12676         "Member reference with rvalue base must be rvalue except for reference "
12677         "members, which aren't allowed for move assignment.");
12678 
12679     // Build the move of this field.
12680     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12681                                             To, From,
12682                                             /*CopyingBaseSubobject=*/false,
12683                                             /*Copying=*/false);
12684     if (Move.isInvalid()) {
12685       MoveAssignOperator->setInvalidDecl();
12686       return;
12687     }
12688 
12689     // Success! Record the copy.
12690     Statements.push_back(Move.getAs<Stmt>());
12691   }
12692 
12693   if (!Invalid) {
12694     // Add a "return *this;"
12695     ExprResult ThisObj =
12696         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12697 
12698     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12699     if (Return.isInvalid())
12700       Invalid = true;
12701     else
12702       Statements.push_back(Return.getAs<Stmt>());
12703   }
12704 
12705   if (Invalid) {
12706     MoveAssignOperator->setInvalidDecl();
12707     return;
12708   }
12709 
12710   StmtResult Body;
12711   {
12712     CompoundScopeRAII CompoundScope(*this);
12713     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12714                              /*isStmtExpr=*/false);
12715     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12716   }
12717   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12718   MoveAssignOperator->markUsed(Context);
12719 
12720   if (ASTMutationListener *L = getASTMutationListener()) {
12721     L->CompletedImplicitDefinition(MoveAssignOperator);
12722   }
12723 }
12724 
12725 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12726                                                     CXXRecordDecl *ClassDecl) {
12727   // C++ [class.copy]p4:
12728   //   If the class definition does not explicitly declare a copy
12729   //   constructor, one is declared implicitly.
12730   assert(ClassDecl->needsImplicitCopyConstructor());
12731 
12732   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12733   if (DSM.isAlreadyBeingDeclared())
12734     return nullptr;
12735 
12736   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12737   QualType ArgType = ClassType;
12738   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12739   if (Const)
12740     ArgType = ArgType.withConst();
12741 
12742   if (Context.getLangOpts().OpenCLCPlusPlus)
12743     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12744 
12745   ArgType = Context.getLValueReferenceType(ArgType);
12746 
12747   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12748                                                      CXXCopyConstructor,
12749                                                      Const);
12750 
12751   DeclarationName Name
12752     = Context.DeclarationNames.getCXXConstructorName(
12753                                            Context.getCanonicalType(ClassType));
12754   SourceLocation ClassLoc = ClassDecl->getLocation();
12755   DeclarationNameInfo NameInfo(Name, ClassLoc);
12756 
12757   //   An implicitly-declared copy constructor is an inline public
12758   //   member of its class.
12759   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12760       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12761       ExplicitSpecifier(),
12762       /*isInline=*/true,
12763       /*isImplicitlyDeclared=*/true,
12764       Constexpr ? CSK_constexpr : CSK_unspecified);
12765   CopyConstructor->setAccess(AS_public);
12766   CopyConstructor->setDefaulted();
12767 
12768   if (getLangOpts().CUDA) {
12769     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12770                                             CopyConstructor,
12771                                             /* ConstRHS */ Const,
12772                                             /* Diagnose */ false);
12773   }
12774 
12775   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
12776 
12777   // Add the parameter to the constructor.
12778   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12779                                                ClassLoc, ClassLoc,
12780                                                /*IdentifierInfo=*/nullptr,
12781                                                ArgType, /*TInfo=*/nullptr,
12782                                                SC_None, nullptr);
12783   CopyConstructor->setParams(FromParam);
12784 
12785   CopyConstructor->setTrivial(
12786       ClassDecl->needsOverloadResolutionForCopyConstructor()
12787           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12788           : ClassDecl->hasTrivialCopyConstructor());
12789 
12790   CopyConstructor->setTrivialForCall(
12791       ClassDecl->hasAttr<TrivialABIAttr>() ||
12792       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12793            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12794              TAH_ConsiderTrivialABI)
12795            : ClassDecl->hasTrivialCopyConstructorForCall()));
12796 
12797   // Note that we have declared this constructor.
12798   ++getASTContext().NumImplicitCopyConstructorsDeclared;
12799 
12800   Scope *S = getScopeForContext(ClassDecl);
12801   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12802 
12803   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12804     ClassDecl->setImplicitCopyConstructorIsDeleted();
12805     SetDeclDeleted(CopyConstructor, ClassLoc);
12806   }
12807 
12808   if (S)
12809     PushOnScopeChains(CopyConstructor, S, false);
12810   ClassDecl->addDecl(CopyConstructor);
12811 
12812   return CopyConstructor;
12813 }
12814 
12815 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12816                                          CXXConstructorDecl *CopyConstructor) {
12817   assert((CopyConstructor->isDefaulted() &&
12818           CopyConstructor->isCopyConstructor() &&
12819           !CopyConstructor->doesThisDeclarationHaveABody() &&
12820           !CopyConstructor->isDeleted()) &&
12821          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12822   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12823     return;
12824 
12825   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12826   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12827 
12828   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12829 
12830   // The exception specification is needed because we are defining the
12831   // function.
12832   ResolveExceptionSpec(CurrentLocation,
12833                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12834   MarkVTableUsed(CurrentLocation, ClassDecl);
12835 
12836   // Add a context note for diagnostics produced after this point.
12837   Scope.addContextNote(CurrentLocation);
12838 
12839   // C++11 [class.copy]p7:
12840   //   The [definition of an implicitly declared copy constructor] is
12841   //   deprecated if the class has a user-declared copy assignment operator
12842   //   or a user-declared destructor.
12843   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12844     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12845 
12846   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12847     CopyConstructor->setInvalidDecl();
12848   }  else {
12849     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12850                              ? CopyConstructor->getEndLoc()
12851                              : CopyConstructor->getLocation();
12852     Sema::CompoundScopeRAII CompoundScope(*this);
12853     CopyConstructor->setBody(
12854         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12855     CopyConstructor->markUsed(Context);
12856   }
12857 
12858   if (ASTMutationListener *L = getASTMutationListener()) {
12859     L->CompletedImplicitDefinition(CopyConstructor);
12860   }
12861 }
12862 
12863 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12864                                                     CXXRecordDecl *ClassDecl) {
12865   assert(ClassDecl->needsImplicitMoveConstructor());
12866 
12867   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12868   if (DSM.isAlreadyBeingDeclared())
12869     return nullptr;
12870 
12871   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12872 
12873   QualType ArgType = ClassType;
12874   if (Context.getLangOpts().OpenCLCPlusPlus)
12875     ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
12876   ArgType = Context.getRValueReferenceType(ArgType);
12877 
12878   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12879                                                      CXXMoveConstructor,
12880                                                      false);
12881 
12882   DeclarationName Name
12883     = Context.DeclarationNames.getCXXConstructorName(
12884                                            Context.getCanonicalType(ClassType));
12885   SourceLocation ClassLoc = ClassDecl->getLocation();
12886   DeclarationNameInfo NameInfo(Name, ClassLoc);
12887 
12888   // C++11 [class.copy]p11:
12889   //   An implicitly-declared copy/move constructor is an inline public
12890   //   member of its class.
12891   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12892       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12893       ExplicitSpecifier(),
12894       /*isInline=*/true,
12895       /*isImplicitlyDeclared=*/true,
12896       Constexpr ? CSK_constexpr : CSK_unspecified);
12897   MoveConstructor->setAccess(AS_public);
12898   MoveConstructor->setDefaulted();
12899 
12900   if (getLangOpts().CUDA) {
12901     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12902                                             MoveConstructor,
12903                                             /* ConstRHS */ false,
12904                                             /* Diagnose */ false);
12905   }
12906 
12907   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
12908 
12909   // Add the parameter to the constructor.
12910   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12911                                                ClassLoc, ClassLoc,
12912                                                /*IdentifierInfo=*/nullptr,
12913                                                ArgType, /*TInfo=*/nullptr,
12914                                                SC_None, nullptr);
12915   MoveConstructor->setParams(FromParam);
12916 
12917   MoveConstructor->setTrivial(
12918       ClassDecl->needsOverloadResolutionForMoveConstructor()
12919           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12920           : ClassDecl->hasTrivialMoveConstructor());
12921 
12922   MoveConstructor->setTrivialForCall(
12923       ClassDecl->hasAttr<TrivialABIAttr>() ||
12924       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12925            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12926                                     TAH_ConsiderTrivialABI)
12927            : ClassDecl->hasTrivialMoveConstructorForCall()));
12928 
12929   // Note that we have declared this constructor.
12930   ++getASTContext().NumImplicitMoveConstructorsDeclared;
12931 
12932   Scope *S = getScopeForContext(ClassDecl);
12933   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12934 
12935   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12936     ClassDecl->setImplicitMoveConstructorIsDeleted();
12937     SetDeclDeleted(MoveConstructor, ClassLoc);
12938   }
12939 
12940   if (S)
12941     PushOnScopeChains(MoveConstructor, S, false);
12942   ClassDecl->addDecl(MoveConstructor);
12943 
12944   return MoveConstructor;
12945 }
12946 
12947 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12948                                          CXXConstructorDecl *MoveConstructor) {
12949   assert((MoveConstructor->isDefaulted() &&
12950           MoveConstructor->isMoveConstructor() &&
12951           !MoveConstructor->doesThisDeclarationHaveABody() &&
12952           !MoveConstructor->isDeleted()) &&
12953          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12954   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12955     return;
12956 
12957   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12958   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12959 
12960   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12961 
12962   // The exception specification is needed because we are defining the
12963   // function.
12964   ResolveExceptionSpec(CurrentLocation,
12965                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12966   MarkVTableUsed(CurrentLocation, ClassDecl);
12967 
12968   // Add a context note for diagnostics produced after this point.
12969   Scope.addContextNote(CurrentLocation);
12970 
12971   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12972     MoveConstructor->setInvalidDecl();
12973   } else {
12974     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12975                              ? MoveConstructor->getEndLoc()
12976                              : MoveConstructor->getLocation();
12977     Sema::CompoundScopeRAII CompoundScope(*this);
12978     MoveConstructor->setBody(ActOnCompoundStmt(
12979         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12980     MoveConstructor->markUsed(Context);
12981   }
12982 
12983   if (ASTMutationListener *L = getASTMutationListener()) {
12984     L->CompletedImplicitDefinition(MoveConstructor);
12985   }
12986 }
12987 
12988 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12989   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12990 }
12991 
12992 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12993                             SourceLocation CurrentLocation,
12994                             CXXConversionDecl *Conv) {
12995   SynthesizedFunctionScope Scope(*this, Conv);
12996   assert(!Conv->getReturnType()->isUndeducedType());
12997 
12998   CXXRecordDecl *Lambda = Conv->getParent();
12999   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
13000   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
13001 
13002   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
13003     CallOp = InstantiateFunctionDeclaration(
13004         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
13005     if (!CallOp)
13006       return;
13007 
13008     Invoker = InstantiateFunctionDeclaration(
13009         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
13010     if (!Invoker)
13011       return;
13012   }
13013 
13014   if (CallOp->isInvalidDecl())
13015     return;
13016 
13017   // Mark the call operator referenced (and add to pending instantiations
13018   // if necessary).
13019   // For both the conversion and static-invoker template specializations
13020   // we construct their body's in this function, so no need to add them
13021   // to the PendingInstantiations.
13022   MarkFunctionReferenced(CurrentLocation, CallOp);
13023 
13024   // Fill in the __invoke function with a dummy implementation. IR generation
13025   // will fill in the actual details. Update its type in case it contained
13026   // an 'auto'.
13027   Invoker->markUsed(Context);
13028   Invoker->setReferenced();
13029   Invoker->setType(Conv->getReturnType()->getPointeeType());
13030   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
13031 
13032   // Construct the body of the conversion function { return __invoke; }.
13033   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
13034                                        VK_LValue, Conv->getLocation());
13035   assert(FunctionRef && "Can't refer to __invoke function?");
13036   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
13037   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
13038                                      Conv->getLocation()));
13039   Conv->markUsed(Context);
13040   Conv->setReferenced();
13041 
13042   if (ASTMutationListener *L = getASTMutationListener()) {
13043     L->CompletedImplicitDefinition(Conv);
13044     L->CompletedImplicitDefinition(Invoker);
13045   }
13046 }
13047 
13048 
13049 
13050 void Sema::DefineImplicitLambdaToBlockPointerConversion(
13051        SourceLocation CurrentLocation,
13052        CXXConversionDecl *Conv)
13053 {
13054   assert(!Conv->getParent()->isGenericLambda());
13055 
13056   SynthesizedFunctionScope Scope(*this, Conv);
13057 
13058   // Copy-initialize the lambda object as needed to capture it.
13059   Expr *This = ActOnCXXThis(CurrentLocation).get();
13060   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
13061 
13062   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
13063                                                         Conv->getLocation(),
13064                                                         Conv, DerefThis);
13065 
13066   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
13067   // behavior.  Note that only the general conversion function does this
13068   // (since it's unusable otherwise); in the case where we inline the
13069   // block literal, it has block literal lifetime semantics.
13070   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
13071     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
13072                                           CK_CopyAndAutoreleaseBlockObject,
13073                                           BuildBlock.get(), nullptr, VK_RValue);
13074 
13075   if (BuildBlock.isInvalid()) {
13076     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
13077     Conv->setInvalidDecl();
13078     return;
13079   }
13080 
13081   // Create the return statement that returns the block from the conversion
13082   // function.
13083   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
13084   if (Return.isInvalid()) {
13085     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
13086     Conv->setInvalidDecl();
13087     return;
13088   }
13089 
13090   // Set the body of the conversion function.
13091   Stmt *ReturnS = Return.get();
13092   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
13093                                      Conv->getLocation()));
13094   Conv->markUsed(Context);
13095 
13096   // We're done; notify the mutation listener, if any.
13097   if (ASTMutationListener *L = getASTMutationListener()) {
13098     L->CompletedImplicitDefinition(Conv);
13099   }
13100 }
13101 
13102 /// Determine whether the given list arguments contains exactly one
13103 /// "real" (non-default) argument.
13104 static bool hasOneRealArgument(MultiExprArg Args) {
13105   switch (Args.size()) {
13106   case 0:
13107     return false;
13108 
13109   default:
13110     if (!Args[1]->isDefaultArgument())
13111       return false;
13112 
13113     LLVM_FALLTHROUGH;
13114   case 1:
13115     return !Args[0]->isDefaultArgument();
13116   }
13117 
13118   return false;
13119 }
13120 
13121 ExprResult
13122 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13123                             NamedDecl *FoundDecl,
13124                             CXXConstructorDecl *Constructor,
13125                             MultiExprArg ExprArgs,
13126                             bool HadMultipleCandidates,
13127                             bool IsListInitialization,
13128                             bool IsStdInitListInitialization,
13129                             bool RequiresZeroInit,
13130                             unsigned ConstructKind,
13131                             SourceRange ParenRange) {
13132   bool Elidable = false;
13133 
13134   // C++0x [class.copy]p34:
13135   //   When certain criteria are met, an implementation is allowed to
13136   //   omit the copy/move construction of a class object, even if the
13137   //   copy/move constructor and/or destructor for the object have
13138   //   side effects. [...]
13139   //     - when a temporary class object that has not been bound to a
13140   //       reference (12.2) would be copied/moved to a class object
13141   //       with the same cv-unqualified type, the copy/move operation
13142   //       can be omitted by constructing the temporary object
13143   //       directly into the target of the omitted copy/move
13144   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
13145       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
13146     Expr *SubExpr = ExprArgs[0];
13147     Elidable = SubExpr->isTemporaryObject(
13148         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
13149   }
13150 
13151   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
13152                                FoundDecl, Constructor,
13153                                Elidable, ExprArgs, HadMultipleCandidates,
13154                                IsListInitialization,
13155                                IsStdInitListInitialization, RequiresZeroInit,
13156                                ConstructKind, ParenRange);
13157 }
13158 
13159 ExprResult
13160 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13161                             NamedDecl *FoundDecl,
13162                             CXXConstructorDecl *Constructor,
13163                             bool Elidable,
13164                             MultiExprArg ExprArgs,
13165                             bool HadMultipleCandidates,
13166                             bool IsListInitialization,
13167                             bool IsStdInitListInitialization,
13168                             bool RequiresZeroInit,
13169                             unsigned ConstructKind,
13170                             SourceRange ParenRange) {
13171   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
13172     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
13173     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
13174       return ExprError();
13175   }
13176 
13177   return BuildCXXConstructExpr(
13178       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
13179       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
13180       RequiresZeroInit, ConstructKind, ParenRange);
13181 }
13182 
13183 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
13184 /// including handling of its default argument expressions.
13185 ExprResult
13186 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13187                             CXXConstructorDecl *Constructor,
13188                             bool Elidable,
13189                             MultiExprArg ExprArgs,
13190                             bool HadMultipleCandidates,
13191                             bool IsListInitialization,
13192                             bool IsStdInitListInitialization,
13193                             bool RequiresZeroInit,
13194                             unsigned ConstructKind,
13195                             SourceRange ParenRange) {
13196   assert(declaresSameEntity(
13197              Constructor->getParent(),
13198              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
13199          "given constructor for wrong type");
13200   MarkFunctionReferenced(ConstructLoc, Constructor);
13201   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
13202     return ExprError();
13203 
13204   return CXXConstructExpr::Create(
13205       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
13206       ExprArgs, HadMultipleCandidates, IsListInitialization,
13207       IsStdInitListInitialization, RequiresZeroInit,
13208       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
13209       ParenRange);
13210 }
13211 
13212 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
13213   assert(Field->hasInClassInitializer());
13214 
13215   // If we already have the in-class initializer nothing needs to be done.
13216   if (Field->getInClassInitializer())
13217     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13218 
13219   // If we might have already tried and failed to instantiate, don't try again.
13220   if (Field->isInvalidDecl())
13221     return ExprError();
13222 
13223   // Maybe we haven't instantiated the in-class initializer. Go check the
13224   // pattern FieldDecl to see if it has one.
13225   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
13226 
13227   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
13228     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
13229     DeclContext::lookup_result Lookup =
13230         ClassPattern->lookup(Field->getDeclName());
13231 
13232     // Lookup can return at most two results: the pattern for the field, or the
13233     // injected class name of the parent record. No other member can have the
13234     // same name as the field.
13235     // In modules mode, lookup can return multiple results (coming from
13236     // different modules).
13237     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
13238            "more than two lookup results for field name");
13239     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
13240     if (!Pattern) {
13241       assert(isa<CXXRecordDecl>(Lookup[0]) &&
13242              "cannot have other non-field member with same name");
13243       for (auto L : Lookup)
13244         if (isa<FieldDecl>(L)) {
13245           Pattern = cast<FieldDecl>(L);
13246           break;
13247         }
13248       assert(Pattern && "We must have set the Pattern!");
13249     }
13250 
13251     if (!Pattern->hasInClassInitializer() ||
13252         InstantiateInClassInitializer(Loc, Field, Pattern,
13253                                       getTemplateInstantiationArgs(Field))) {
13254       // Don't diagnose this again.
13255       Field->setInvalidDecl();
13256       return ExprError();
13257     }
13258     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13259   }
13260 
13261   // DR1351:
13262   //   If the brace-or-equal-initializer of a non-static data member
13263   //   invokes a defaulted default constructor of its class or of an
13264   //   enclosing class in a potentially evaluated subexpression, the
13265   //   program is ill-formed.
13266   //
13267   // This resolution is unworkable: the exception specification of the
13268   // default constructor can be needed in an unevaluated context, in
13269   // particular, in the operand of a noexcept-expression, and we can be
13270   // unable to compute an exception specification for an enclosed class.
13271   //
13272   // Any attempt to resolve the exception specification of a defaulted default
13273   // constructor before the initializer is lexically complete will ultimately
13274   // come here at which point we can diagnose it.
13275   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13276   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13277       << OutermostClass << Field;
13278   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13279   // Recover by marking the field invalid, unless we're in a SFINAE context.
13280   if (!isSFINAEContext())
13281     Field->setInvalidDecl();
13282   return ExprError();
13283 }
13284 
13285 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13286   if (VD->isInvalidDecl()) return;
13287 
13288   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13289   if (ClassDecl->isInvalidDecl()) return;
13290   if (ClassDecl->hasIrrelevantDestructor()) return;
13291   if (ClassDecl->isDependentContext()) return;
13292 
13293   if (VD->isNoDestroy(getASTContext()))
13294     return;
13295 
13296   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13297 
13298   // If this is an array, we'll require the destructor during initialization, so
13299   // we can skip over this. We still want to emit exit-time destructor warnings
13300   // though.
13301   if (!VD->getType()->isArrayType()) {
13302     MarkFunctionReferenced(VD->getLocation(), Destructor);
13303     CheckDestructorAccess(VD->getLocation(), Destructor,
13304                           PDiag(diag::err_access_dtor_var)
13305                               << VD->getDeclName() << VD->getType());
13306     DiagnoseUseOfDecl(Destructor, VD->getLocation());
13307   }
13308 
13309   if (Destructor->isTrivial()) return;
13310   if (!VD->hasGlobalStorage()) return;
13311 
13312   // Emit warning for non-trivial dtor in global scope (a real global,
13313   // class-static, function-static).
13314   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13315 
13316   // TODO: this should be re-enabled for static locals by !CXAAtExit
13317   if (!VD->isStaticLocal())
13318     Diag(VD->getLocation(), diag::warn_global_destructor);
13319 }
13320 
13321 /// Given a constructor and the set of arguments provided for the
13322 /// constructor, convert the arguments and add any required default arguments
13323 /// to form a proper call to this constructor.
13324 ///
13325 /// \returns true if an error occurred, false otherwise.
13326 bool
13327 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13328                               MultiExprArg ArgsPtr,
13329                               SourceLocation Loc,
13330                               SmallVectorImpl<Expr*> &ConvertedArgs,
13331                               bool AllowExplicit,
13332                               bool IsListInitialization) {
13333   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13334   unsigned NumArgs = ArgsPtr.size();
13335   Expr **Args = ArgsPtr.data();
13336 
13337   const FunctionProtoType *Proto
13338     = Constructor->getType()->getAs<FunctionProtoType>();
13339   assert(Proto && "Constructor without a prototype?");
13340   unsigned NumParams = Proto->getNumParams();
13341 
13342   // If too few arguments are available, we'll fill in the rest with defaults.
13343   if (NumArgs < NumParams)
13344     ConvertedArgs.reserve(NumParams);
13345   else
13346     ConvertedArgs.reserve(NumArgs);
13347 
13348   VariadicCallType CallType =
13349     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13350   SmallVector<Expr *, 8> AllArgs;
13351   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13352                                         Proto, 0,
13353                                         llvm::makeArrayRef(Args, NumArgs),
13354                                         AllArgs,
13355                                         CallType, AllowExplicit,
13356                                         IsListInitialization);
13357   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13358 
13359   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13360 
13361   CheckConstructorCall(Constructor,
13362                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13363                        Proto, Loc);
13364 
13365   return Invalid;
13366 }
13367 
13368 static inline bool
13369 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13370                                        const FunctionDecl *FnDecl) {
13371   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13372   if (isa<NamespaceDecl>(DC)) {
13373     return SemaRef.Diag(FnDecl->getLocation(),
13374                         diag::err_operator_new_delete_declared_in_namespace)
13375       << FnDecl->getDeclName();
13376   }
13377 
13378   if (isa<TranslationUnitDecl>(DC) &&
13379       FnDecl->getStorageClass() == SC_Static) {
13380     return SemaRef.Diag(FnDecl->getLocation(),
13381                         diag::err_operator_new_delete_declared_static)
13382       << FnDecl->getDeclName();
13383   }
13384 
13385   return false;
13386 }
13387 
13388 static QualType
13389 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13390   QualType QTy = PtrTy->getPointeeType();
13391   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13392   return SemaRef.Context.getPointerType(QTy);
13393 }
13394 
13395 static inline bool
13396 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13397                             CanQualType ExpectedResultType,
13398                             CanQualType ExpectedFirstParamType,
13399                             unsigned DependentParamTypeDiag,
13400                             unsigned InvalidParamTypeDiag) {
13401   QualType ResultType =
13402       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13403 
13404   // Check that the result type is not dependent.
13405   if (ResultType->isDependentType())
13406     return SemaRef.Diag(FnDecl->getLocation(),
13407                         diag::err_operator_new_delete_dependent_result_type)
13408     << FnDecl->getDeclName() << ExpectedResultType;
13409 
13410   // The operator is valid on any address space for OpenCL.
13411   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13412     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13413       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13414     }
13415   }
13416 
13417   // Check that the result type is what we expect.
13418   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13419     return SemaRef.Diag(FnDecl->getLocation(),
13420                         diag::err_operator_new_delete_invalid_result_type)
13421     << FnDecl->getDeclName() << ExpectedResultType;
13422 
13423   // A function template must have at least 2 parameters.
13424   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13425     return SemaRef.Diag(FnDecl->getLocation(),
13426                       diag::err_operator_new_delete_template_too_few_parameters)
13427         << FnDecl->getDeclName();
13428 
13429   // The function decl must have at least 1 parameter.
13430   if (FnDecl->getNumParams() == 0)
13431     return SemaRef.Diag(FnDecl->getLocation(),
13432                         diag::err_operator_new_delete_too_few_parameters)
13433       << FnDecl->getDeclName();
13434 
13435   // Check the first parameter type is not dependent.
13436   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13437   if (FirstParamType->isDependentType())
13438     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13439       << FnDecl->getDeclName() << ExpectedFirstParamType;
13440 
13441   // Check that the first parameter type is what we expect.
13442   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13443     // The operator is valid on any address space for OpenCL.
13444     if (auto *PtrTy =
13445             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13446       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13447     }
13448   }
13449   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13450       ExpectedFirstParamType)
13451     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13452     << FnDecl->getDeclName() << ExpectedFirstParamType;
13453 
13454   return false;
13455 }
13456 
13457 static bool
13458 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13459   // C++ [basic.stc.dynamic.allocation]p1:
13460   //   A program is ill-formed if an allocation function is declared in a
13461   //   namespace scope other than global scope or declared static in global
13462   //   scope.
13463   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13464     return true;
13465 
13466   CanQualType SizeTy =
13467     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13468 
13469   // C++ [basic.stc.dynamic.allocation]p1:
13470   //  The return type shall be void*. The first parameter shall have type
13471   //  std::size_t.
13472   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13473                                   SizeTy,
13474                                   diag::err_operator_new_dependent_param_type,
13475                                   diag::err_operator_new_param_type))
13476     return true;
13477 
13478   // C++ [basic.stc.dynamic.allocation]p1:
13479   //  The first parameter shall not have an associated default argument.
13480   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13481     return SemaRef.Diag(FnDecl->getLocation(),
13482                         diag::err_operator_new_default_arg)
13483       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13484 
13485   return false;
13486 }
13487 
13488 static bool
13489 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13490   // C++ [basic.stc.dynamic.deallocation]p1:
13491   //   A program is ill-formed if deallocation functions are declared in a
13492   //   namespace scope other than global scope or declared static in global
13493   //   scope.
13494   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13495     return true;
13496 
13497   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13498 
13499   // C++ P0722:
13500   //   Within a class C, the first parameter of a destroying operator delete
13501   //   shall be of type C *. The first parameter of any other deallocation
13502   //   function shall be of type void *.
13503   CanQualType ExpectedFirstParamType =
13504       MD && MD->isDestroyingOperatorDelete()
13505           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13506                 SemaRef.Context.getRecordType(MD->getParent())))
13507           : SemaRef.Context.VoidPtrTy;
13508 
13509   // C++ [basic.stc.dynamic.deallocation]p2:
13510   //   Each deallocation function shall return void
13511   if (CheckOperatorNewDeleteTypes(
13512           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13513           diag::err_operator_delete_dependent_param_type,
13514           diag::err_operator_delete_param_type))
13515     return true;
13516 
13517   // C++ P0722:
13518   //   A destroying operator delete shall be a usual deallocation function.
13519   if (MD && !MD->getParent()->isDependentContext() &&
13520       MD->isDestroyingOperatorDelete() &&
13521       !SemaRef.isUsualDeallocationFunction(MD)) {
13522     SemaRef.Diag(MD->getLocation(),
13523                  diag::err_destroying_operator_delete_not_usual);
13524     return true;
13525   }
13526 
13527   return false;
13528 }
13529 
13530 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13531 /// of this overloaded operator is well-formed. If so, returns false;
13532 /// otherwise, emits appropriate diagnostics and returns true.
13533 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13534   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13535          "Expected an overloaded operator declaration");
13536 
13537   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13538 
13539   // C++ [over.oper]p5:
13540   //   The allocation and deallocation functions, operator new,
13541   //   operator new[], operator delete and operator delete[], are
13542   //   described completely in 3.7.3. The attributes and restrictions
13543   //   found in the rest of this subclause do not apply to them unless
13544   //   explicitly stated in 3.7.3.
13545   if (Op == OO_Delete || Op == OO_Array_Delete)
13546     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13547 
13548   if (Op == OO_New || Op == OO_Array_New)
13549     return CheckOperatorNewDeclaration(*this, FnDecl);
13550 
13551   // C++ [over.oper]p6:
13552   //   An operator function shall either be a non-static member
13553   //   function or be a non-member function and have at least one
13554   //   parameter whose type is a class, a reference to a class, an
13555   //   enumeration, or a reference to an enumeration.
13556   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13557     if (MethodDecl->isStatic())
13558       return Diag(FnDecl->getLocation(),
13559                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13560   } else {
13561     bool ClassOrEnumParam = false;
13562     for (auto Param : FnDecl->parameters()) {
13563       QualType ParamType = Param->getType().getNonReferenceType();
13564       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13565           ParamType->isEnumeralType()) {
13566         ClassOrEnumParam = true;
13567         break;
13568       }
13569     }
13570 
13571     if (!ClassOrEnumParam)
13572       return Diag(FnDecl->getLocation(),
13573                   diag::err_operator_overload_needs_class_or_enum)
13574         << FnDecl->getDeclName();
13575   }
13576 
13577   // C++ [over.oper]p8:
13578   //   An operator function cannot have default arguments (8.3.6),
13579   //   except where explicitly stated below.
13580   //
13581   // Only the function-call operator allows default arguments
13582   // (C++ [over.call]p1).
13583   if (Op != OO_Call) {
13584     for (auto Param : FnDecl->parameters()) {
13585       if (Param->hasDefaultArg())
13586         return Diag(Param->getLocation(),
13587                     diag::err_operator_overload_default_arg)
13588           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13589     }
13590   }
13591 
13592   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13593     { false, false, false }
13594 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13595     , { Unary, Binary, MemberOnly }
13596 #include "clang/Basic/OperatorKinds.def"
13597   };
13598 
13599   bool CanBeUnaryOperator = OperatorUses[Op][0];
13600   bool CanBeBinaryOperator = OperatorUses[Op][1];
13601   bool MustBeMemberOperator = OperatorUses[Op][2];
13602 
13603   // C++ [over.oper]p8:
13604   //   [...] Operator functions cannot have more or fewer parameters
13605   //   than the number required for the corresponding operator, as
13606   //   described in the rest of this subclause.
13607   unsigned NumParams = FnDecl->getNumParams()
13608                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13609   if (Op != OO_Call &&
13610       ((NumParams == 1 && !CanBeUnaryOperator) ||
13611        (NumParams == 2 && !CanBeBinaryOperator) ||
13612        (NumParams < 1) || (NumParams > 2))) {
13613     // We have the wrong number of parameters.
13614     unsigned ErrorKind;
13615     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13616       ErrorKind = 2;  // 2 -> unary or binary.
13617     } else if (CanBeUnaryOperator) {
13618       ErrorKind = 0;  // 0 -> unary
13619     } else {
13620       assert(CanBeBinaryOperator &&
13621              "All non-call overloaded operators are unary or binary!");
13622       ErrorKind = 1;  // 1 -> binary
13623     }
13624 
13625     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13626       << FnDecl->getDeclName() << NumParams << ErrorKind;
13627   }
13628 
13629   // Overloaded operators other than operator() cannot be variadic.
13630   if (Op != OO_Call &&
13631       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13632     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13633       << FnDecl->getDeclName();
13634   }
13635 
13636   // Some operators must be non-static member functions.
13637   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13638     return Diag(FnDecl->getLocation(),
13639                 diag::err_operator_overload_must_be_member)
13640       << FnDecl->getDeclName();
13641   }
13642 
13643   // C++ [over.inc]p1:
13644   //   The user-defined function called operator++ implements the
13645   //   prefix and postfix ++ operator. If this function is a member
13646   //   function with no parameters, or a non-member function with one
13647   //   parameter of class or enumeration type, it defines the prefix
13648   //   increment operator ++ for objects of that type. If the function
13649   //   is a member function with one parameter (which shall be of type
13650   //   int) or a non-member function with two parameters (the second
13651   //   of which shall be of type int), it defines the postfix
13652   //   increment operator ++ for objects of that type.
13653   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13654     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13655     QualType ParamType = LastParam->getType();
13656 
13657     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13658         !ParamType->isDependentType())
13659       return Diag(LastParam->getLocation(),
13660                   diag::err_operator_overload_post_incdec_must_be_int)
13661         << LastParam->getType() << (Op == OO_MinusMinus);
13662   }
13663 
13664   return false;
13665 }
13666 
13667 static bool
13668 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13669                                           FunctionTemplateDecl *TpDecl) {
13670   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13671 
13672   // Must have one or two template parameters.
13673   if (TemplateParams->size() == 1) {
13674     NonTypeTemplateParmDecl *PmDecl =
13675         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13676 
13677     // The template parameter must be a char parameter pack.
13678     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13679         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13680       return false;
13681 
13682   } else if (TemplateParams->size() == 2) {
13683     TemplateTypeParmDecl *PmType =
13684         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13685     NonTypeTemplateParmDecl *PmArgs =
13686         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13687 
13688     // The second template parameter must be a parameter pack with the
13689     // first template parameter as its type.
13690     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13691         PmArgs->isTemplateParameterPack()) {
13692       const TemplateTypeParmType *TArgs =
13693           PmArgs->getType()->getAs<TemplateTypeParmType>();
13694       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13695           TArgs->getIndex() == PmType->getIndex()) {
13696         if (!SemaRef.inTemplateInstantiation())
13697           SemaRef.Diag(TpDecl->getLocation(),
13698                        diag::ext_string_literal_operator_template);
13699         return false;
13700       }
13701     }
13702   }
13703 
13704   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13705                diag::err_literal_operator_template)
13706       << TpDecl->getTemplateParameters()->getSourceRange();
13707   return true;
13708 }
13709 
13710 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13711 /// of this literal operator function is well-formed. If so, returns
13712 /// false; otherwise, emits appropriate diagnostics and returns true.
13713 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13714   if (isa<CXXMethodDecl>(FnDecl)) {
13715     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13716       << FnDecl->getDeclName();
13717     return true;
13718   }
13719 
13720   if (FnDecl->isExternC()) {
13721     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13722     if (const LinkageSpecDecl *LSD =
13723             FnDecl->getDeclContext()->getExternCContext())
13724       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13725     return true;
13726   }
13727 
13728   // This might be the definition of a literal operator template.
13729   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13730 
13731   // This might be a specialization of a literal operator template.
13732   if (!TpDecl)
13733     TpDecl = FnDecl->getPrimaryTemplate();
13734 
13735   // template <char...> type operator "" name() and
13736   // template <class T, T...> type operator "" name() are the only valid
13737   // template signatures, and the only valid signatures with no parameters.
13738   if (TpDecl) {
13739     if (FnDecl->param_size() != 0) {
13740       Diag(FnDecl->getLocation(),
13741            diag::err_literal_operator_template_with_params);
13742       return true;
13743     }
13744 
13745     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13746       return true;
13747 
13748   } else if (FnDecl->param_size() == 1) {
13749     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13750 
13751     QualType ParamType = Param->getType().getUnqualifiedType();
13752 
13753     // Only unsigned long long int, long double, any character type, and const
13754     // char * are allowed as the only parameters.
13755     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13756         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13757         Context.hasSameType(ParamType, Context.CharTy) ||
13758         Context.hasSameType(ParamType, Context.WideCharTy) ||
13759         Context.hasSameType(ParamType, Context.Char8Ty) ||
13760         Context.hasSameType(ParamType, Context.Char16Ty) ||
13761         Context.hasSameType(ParamType, Context.Char32Ty)) {
13762     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13763       QualType InnerType = Ptr->getPointeeType();
13764 
13765       // Pointer parameter must be a const char *.
13766       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13767                                 Context.CharTy) &&
13768             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13769         Diag(Param->getSourceRange().getBegin(),
13770              diag::err_literal_operator_param)
13771             << ParamType << "'const char *'" << Param->getSourceRange();
13772         return true;
13773       }
13774 
13775     } else if (ParamType->isRealFloatingType()) {
13776       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13777           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13778       return true;
13779 
13780     } else if (ParamType->isIntegerType()) {
13781       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13782           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13783       return true;
13784 
13785     } else {
13786       Diag(Param->getSourceRange().getBegin(),
13787            diag::err_literal_operator_invalid_param)
13788           << ParamType << Param->getSourceRange();
13789       return true;
13790     }
13791 
13792   } else if (FnDecl->param_size() == 2) {
13793     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13794 
13795     // First, verify that the first parameter is correct.
13796 
13797     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13798 
13799     // Two parameter function must have a pointer to const as a
13800     // first parameter; let's strip those qualifiers.
13801     const PointerType *PT = FirstParamType->getAs<PointerType>();
13802 
13803     if (!PT) {
13804       Diag((*Param)->getSourceRange().getBegin(),
13805            diag::err_literal_operator_param)
13806           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13807       return true;
13808     }
13809 
13810     QualType PointeeType = PT->getPointeeType();
13811     // First parameter must be const
13812     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13813       Diag((*Param)->getSourceRange().getBegin(),
13814            diag::err_literal_operator_param)
13815           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13816       return true;
13817     }
13818 
13819     QualType InnerType = PointeeType.getUnqualifiedType();
13820     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13821     // const char32_t* are allowed as the first parameter to a two-parameter
13822     // function
13823     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13824           Context.hasSameType(InnerType, Context.WideCharTy) ||
13825           Context.hasSameType(InnerType, Context.Char8Ty) ||
13826           Context.hasSameType(InnerType, Context.Char16Ty) ||
13827           Context.hasSameType(InnerType, Context.Char32Ty))) {
13828       Diag((*Param)->getSourceRange().getBegin(),
13829            diag::err_literal_operator_param)
13830           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13831       return true;
13832     }
13833 
13834     // Move on to the second and final parameter.
13835     ++Param;
13836 
13837     // The second parameter must be a std::size_t.
13838     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13839     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13840       Diag((*Param)->getSourceRange().getBegin(),
13841            diag::err_literal_operator_param)
13842           << SecondParamType << Context.getSizeType()
13843           << (*Param)->getSourceRange();
13844       return true;
13845     }
13846   } else {
13847     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13848     return true;
13849   }
13850 
13851   // Parameters are good.
13852 
13853   // A parameter-declaration-clause containing a default argument is not
13854   // equivalent to any of the permitted forms.
13855   for (auto Param : FnDecl->parameters()) {
13856     if (Param->hasDefaultArg()) {
13857       Diag(Param->getDefaultArgRange().getBegin(),
13858            diag::err_literal_operator_default_argument)
13859         << Param->getDefaultArgRange();
13860       break;
13861     }
13862   }
13863 
13864   StringRef LiteralName
13865     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13866   if (LiteralName[0] != '_' &&
13867       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13868     // C++11 [usrlit.suffix]p1:
13869     //   Literal suffix identifiers that do not start with an underscore
13870     //   are reserved for future standardization.
13871     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13872       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13873   }
13874 
13875   return false;
13876 }
13877 
13878 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13879 /// linkage specification, including the language and (if present)
13880 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13881 /// language string literal. LBraceLoc, if valid, provides the location of
13882 /// the '{' brace. Otherwise, this linkage specification does not
13883 /// have any braces.
13884 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13885                                            Expr *LangStr,
13886                                            SourceLocation LBraceLoc) {
13887   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13888   if (!Lit->isAscii()) {
13889     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13890       << LangStr->getSourceRange();
13891     return nullptr;
13892   }
13893 
13894   StringRef Lang = Lit->getString();
13895   LinkageSpecDecl::LanguageIDs Language;
13896   if (Lang == "C")
13897     Language = LinkageSpecDecl::lang_c;
13898   else if (Lang == "C++")
13899     Language = LinkageSpecDecl::lang_cxx;
13900   else {
13901     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13902       << LangStr->getSourceRange();
13903     return nullptr;
13904   }
13905 
13906   // FIXME: Add all the various semantics of linkage specifications
13907 
13908   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13909                                                LangStr->getExprLoc(), Language,
13910                                                LBraceLoc.isValid());
13911   CurContext->addDecl(D);
13912   PushDeclContext(S, D);
13913   return D;
13914 }
13915 
13916 /// ActOnFinishLinkageSpecification - Complete the definition of
13917 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13918 /// valid, it's the position of the closing '}' brace in a linkage
13919 /// specification that uses braces.
13920 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13921                                             Decl *LinkageSpec,
13922                                             SourceLocation RBraceLoc) {
13923   if (RBraceLoc.isValid()) {
13924     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13925     LSDecl->setRBraceLoc(RBraceLoc);
13926   }
13927   PopDeclContext();
13928   return LinkageSpec;
13929 }
13930 
13931 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13932                                   const ParsedAttributesView &AttrList,
13933                                   SourceLocation SemiLoc) {
13934   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13935   // Attribute declarations appertain to empty declaration so we handle
13936   // them here.
13937   ProcessDeclAttributeList(S, ED, AttrList);
13938 
13939   CurContext->addDecl(ED);
13940   return ED;
13941 }
13942 
13943 /// Perform semantic analysis for the variable declaration that
13944 /// occurs within a C++ catch clause, returning the newly-created
13945 /// variable.
13946 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13947                                          TypeSourceInfo *TInfo,
13948                                          SourceLocation StartLoc,
13949                                          SourceLocation Loc,
13950                                          IdentifierInfo *Name) {
13951   bool Invalid = false;
13952   QualType ExDeclType = TInfo->getType();
13953 
13954   // Arrays and functions decay.
13955   if (ExDeclType->isArrayType())
13956     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13957   else if (ExDeclType->isFunctionType())
13958     ExDeclType = Context.getPointerType(ExDeclType);
13959 
13960   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13961   // The exception-declaration shall not denote a pointer or reference to an
13962   // incomplete type, other than [cv] void*.
13963   // N2844 forbids rvalue references.
13964   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13965     Diag(Loc, diag::err_catch_rvalue_ref);
13966     Invalid = true;
13967   }
13968 
13969   if (ExDeclType->isVariablyModifiedType()) {
13970     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13971     Invalid = true;
13972   }
13973 
13974   QualType BaseType = ExDeclType;
13975   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13976   unsigned DK = diag::err_catch_incomplete;
13977   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13978     BaseType = Ptr->getPointeeType();
13979     Mode = 1;
13980     DK = diag::err_catch_incomplete_ptr;
13981   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13982     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13983     BaseType = Ref->getPointeeType();
13984     Mode = 2;
13985     DK = diag::err_catch_incomplete_ref;
13986   }
13987   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13988       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13989     Invalid = true;
13990 
13991   if (!Invalid && !ExDeclType->isDependentType() &&
13992       RequireNonAbstractType(Loc, ExDeclType,
13993                              diag::err_abstract_type_in_decl,
13994                              AbstractVariableType))
13995     Invalid = true;
13996 
13997   // Only the non-fragile NeXT runtime currently supports C++ catches
13998   // of ObjC types, and no runtime supports catching ObjC types by value.
13999   if (!Invalid && getLangOpts().ObjC) {
14000     QualType T = ExDeclType;
14001     if (const ReferenceType *RT = T->getAs<ReferenceType>())
14002       T = RT->getPointeeType();
14003 
14004     if (T->isObjCObjectType()) {
14005       Diag(Loc, diag::err_objc_object_catch);
14006       Invalid = true;
14007     } else if (T->isObjCObjectPointerType()) {
14008       // FIXME: should this be a test for macosx-fragile specifically?
14009       if (getLangOpts().ObjCRuntime.isFragile())
14010         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
14011     }
14012   }
14013 
14014   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
14015                                     ExDeclType, TInfo, SC_None);
14016   ExDecl->setExceptionVariable(true);
14017 
14018   // In ARC, infer 'retaining' for variables of retainable type.
14019   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
14020     Invalid = true;
14021 
14022   if (!Invalid && !ExDeclType->isDependentType()) {
14023     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
14024       // Insulate this from anything else we might currently be parsing.
14025       EnterExpressionEvaluationContext scope(
14026           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14027 
14028       // C++ [except.handle]p16:
14029       //   The object declared in an exception-declaration or, if the
14030       //   exception-declaration does not specify a name, a temporary (12.2) is
14031       //   copy-initialized (8.5) from the exception object. [...]
14032       //   The object is destroyed when the handler exits, after the destruction
14033       //   of any automatic objects initialized within the handler.
14034       //
14035       // We just pretend to initialize the object with itself, then make sure
14036       // it can be destroyed later.
14037       QualType initType = Context.getExceptionObjectType(ExDeclType);
14038 
14039       InitializedEntity entity =
14040         InitializedEntity::InitializeVariable(ExDecl);
14041       InitializationKind initKind =
14042         InitializationKind::CreateCopy(Loc, SourceLocation());
14043 
14044       Expr *opaqueValue =
14045         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
14046       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
14047       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
14048       if (result.isInvalid())
14049         Invalid = true;
14050       else {
14051         // If the constructor used was non-trivial, set this as the
14052         // "initializer".
14053         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
14054         if (!construct->getConstructor()->isTrivial()) {
14055           Expr *init = MaybeCreateExprWithCleanups(construct);
14056           ExDecl->setInit(init);
14057         }
14058 
14059         // And make sure it's destructable.
14060         FinalizeVarWithDestructor(ExDecl, recordType);
14061       }
14062     }
14063   }
14064 
14065   if (Invalid)
14066     ExDecl->setInvalidDecl();
14067 
14068   return ExDecl;
14069 }
14070 
14071 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
14072 /// handler.
14073 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
14074   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14075   bool Invalid = D.isInvalidType();
14076 
14077   // Check for unexpanded parameter packs.
14078   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14079                                       UPPC_ExceptionType)) {
14080     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
14081                                              D.getIdentifierLoc());
14082     Invalid = true;
14083   }
14084 
14085   IdentifierInfo *II = D.getIdentifier();
14086   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
14087                                              LookupOrdinaryName,
14088                                              ForVisibleRedeclaration)) {
14089     // The scope should be freshly made just for us. There is just no way
14090     // it contains any previous declaration, except for function parameters in
14091     // a function-try-block's catch statement.
14092     assert(!S->isDeclScope(PrevDecl));
14093     if (isDeclInScope(PrevDecl, CurContext, S)) {
14094       Diag(D.getIdentifierLoc(), diag::err_redefinition)
14095         << D.getIdentifier();
14096       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14097       Invalid = true;
14098     } else if (PrevDecl->isTemplateParameter())
14099       // Maybe we will complain about the shadowed template parameter.
14100       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14101   }
14102 
14103   if (D.getCXXScopeSpec().isSet() && !Invalid) {
14104     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
14105       << D.getCXXScopeSpec().getRange();
14106     Invalid = true;
14107   }
14108 
14109   VarDecl *ExDecl = BuildExceptionDeclaration(
14110       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
14111   if (Invalid)
14112     ExDecl->setInvalidDecl();
14113 
14114   // Add the exception declaration into this scope.
14115   if (II)
14116     PushOnScopeChains(ExDecl, S);
14117   else
14118     CurContext->addDecl(ExDecl);
14119 
14120   ProcessDeclAttributes(S, ExDecl, D);
14121   return ExDecl;
14122 }
14123 
14124 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
14125                                          Expr *AssertExpr,
14126                                          Expr *AssertMessageExpr,
14127                                          SourceLocation RParenLoc) {
14128   StringLiteral *AssertMessage =
14129       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
14130 
14131   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
14132     return nullptr;
14133 
14134   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
14135                                       AssertMessage, RParenLoc, false);
14136 }
14137 
14138 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
14139                                          Expr *AssertExpr,
14140                                          StringLiteral *AssertMessage,
14141                                          SourceLocation RParenLoc,
14142                                          bool Failed) {
14143   assert(AssertExpr != nullptr && "Expected non-null condition");
14144   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
14145       !Failed) {
14146     // In a static_assert-declaration, the constant-expression shall be a
14147     // constant expression that can be contextually converted to bool.
14148     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
14149     if (Converted.isInvalid())
14150       Failed = true;
14151 
14152     llvm::APSInt Cond;
14153     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
14154           diag::err_static_assert_expression_is_not_constant,
14155           /*AllowFold=*/false).isInvalid())
14156       Failed = true;
14157 
14158     if (!Failed && !Cond) {
14159       SmallString<256> MsgBuffer;
14160       llvm::raw_svector_ostream Msg(MsgBuffer);
14161       if (AssertMessage)
14162         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
14163 
14164       Expr *InnerCond = nullptr;
14165       std::string InnerCondDescription;
14166       std::tie(InnerCond, InnerCondDescription) =
14167         findFailedBooleanCondition(Converted.get());
14168       if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
14169                     && !isa<IntegerLiteral>(InnerCond)) {
14170         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
14171           << InnerCondDescription << !AssertMessage
14172           << Msg.str() << InnerCond->getSourceRange();
14173       } else {
14174         Diag(StaticAssertLoc, diag::err_static_assert_failed)
14175           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
14176       }
14177       Failed = true;
14178     }
14179   }
14180 
14181   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
14182                                                   /*DiscardedValue*/false,
14183                                                   /*IsConstexpr*/true);
14184   if (FullAssertExpr.isInvalid())
14185     Failed = true;
14186   else
14187     AssertExpr = FullAssertExpr.get();
14188 
14189   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
14190                                         AssertExpr, AssertMessage, RParenLoc,
14191                                         Failed);
14192 
14193   CurContext->addDecl(Decl);
14194   return Decl;
14195 }
14196 
14197 /// Perform semantic analysis of the given friend type declaration.
14198 ///
14199 /// \returns A friend declaration that.
14200 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
14201                                       SourceLocation FriendLoc,
14202                                       TypeSourceInfo *TSInfo) {
14203   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
14204 
14205   QualType T = TSInfo->getType();
14206   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
14207 
14208   // C++03 [class.friend]p2:
14209   //   An elaborated-type-specifier shall be used in a friend declaration
14210   //   for a class.*
14211   //
14212   //   * The class-key of the elaborated-type-specifier is required.
14213   if (!CodeSynthesisContexts.empty()) {
14214     // Do not complain about the form of friend template types during any kind
14215     // of code synthesis. For template instantiation, we will have complained
14216     // when the template was defined.
14217   } else {
14218     if (!T->isElaboratedTypeSpecifier()) {
14219       // If we evaluated the type to a record type, suggest putting
14220       // a tag in front.
14221       if (const RecordType *RT = T->getAs<RecordType>()) {
14222         RecordDecl *RD = RT->getDecl();
14223 
14224         SmallString<16> InsertionText(" ");
14225         InsertionText += RD->getKindName();
14226 
14227         Diag(TypeRange.getBegin(),
14228              getLangOpts().CPlusPlus11 ?
14229                diag::warn_cxx98_compat_unelaborated_friend_type :
14230                diag::ext_unelaborated_friend_type)
14231           << (unsigned) RD->getTagKind()
14232           << T
14233           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
14234                                         InsertionText);
14235       } else {
14236         Diag(FriendLoc,
14237              getLangOpts().CPlusPlus11 ?
14238                diag::warn_cxx98_compat_nonclass_type_friend :
14239                diag::ext_nonclass_type_friend)
14240           << T
14241           << TypeRange;
14242       }
14243     } else if (T->getAs<EnumType>()) {
14244       Diag(FriendLoc,
14245            getLangOpts().CPlusPlus11 ?
14246              diag::warn_cxx98_compat_enum_friend :
14247              diag::ext_enum_friend)
14248         << T
14249         << TypeRange;
14250     }
14251 
14252     // C++11 [class.friend]p3:
14253     //   A friend declaration that does not declare a function shall have one
14254     //   of the following forms:
14255     //     friend elaborated-type-specifier ;
14256     //     friend simple-type-specifier ;
14257     //     friend typename-specifier ;
14258     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14259       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14260   }
14261 
14262   //   If the type specifier in a friend declaration designates a (possibly
14263   //   cv-qualified) class type, that class is declared as a friend; otherwise,
14264   //   the friend declaration is ignored.
14265   return FriendDecl::Create(Context, CurContext,
14266                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14267                             FriendLoc);
14268 }
14269 
14270 /// Handle a friend tag declaration where the scope specifier was
14271 /// templated.
14272 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
14273                                     unsigned TagSpec, SourceLocation TagLoc,
14274                                     CXXScopeSpec &SS, IdentifierInfo *Name,
14275                                     SourceLocation NameLoc,
14276                                     const ParsedAttributesView &Attr,
14277                                     MultiTemplateParamsArg TempParamLists) {
14278   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14279 
14280   bool IsMemberSpecialization = false;
14281   bool Invalid = false;
14282 
14283   if (TemplateParameterList *TemplateParams =
14284           MatchTemplateParametersToScopeSpecifier(
14285               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14286               IsMemberSpecialization, Invalid)) {
14287     if (TemplateParams->size() > 0) {
14288       // This is a declaration of a class template.
14289       if (Invalid)
14290         return nullptr;
14291 
14292       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14293                                 NameLoc, Attr, TemplateParams, AS_public,
14294                                 /*ModulePrivateLoc=*/SourceLocation(),
14295                                 FriendLoc, TempParamLists.size() - 1,
14296                                 TempParamLists.data()).get();
14297     } else {
14298       // The "template<>" header is extraneous.
14299       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14300         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14301       IsMemberSpecialization = true;
14302     }
14303   }
14304 
14305   if (Invalid) return nullptr;
14306 
14307   bool isAllExplicitSpecializations = true;
14308   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14309     if (TempParamLists[I]->size()) {
14310       isAllExplicitSpecializations = false;
14311       break;
14312     }
14313   }
14314 
14315   // FIXME: don't ignore attributes.
14316 
14317   // If it's explicit specializations all the way down, just forget
14318   // about the template header and build an appropriate non-templated
14319   // friend.  TODO: for source fidelity, remember the headers.
14320   if (isAllExplicitSpecializations) {
14321     if (SS.isEmpty()) {
14322       bool Owned = false;
14323       bool IsDependent = false;
14324       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14325                       Attr, AS_public,
14326                       /*ModulePrivateLoc=*/SourceLocation(),
14327                       MultiTemplateParamsArg(), Owned, IsDependent,
14328                       /*ScopedEnumKWLoc=*/SourceLocation(),
14329                       /*ScopedEnumUsesClassTag=*/false,
14330                       /*UnderlyingType=*/TypeResult(),
14331                       /*IsTypeSpecifier=*/false,
14332                       /*IsTemplateParamOrArg=*/false);
14333     }
14334 
14335     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14336     ElaboratedTypeKeyword Keyword
14337       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14338     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14339                                    *Name, NameLoc);
14340     if (T.isNull())
14341       return nullptr;
14342 
14343     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14344     if (isa<DependentNameType>(T)) {
14345       DependentNameTypeLoc TL =
14346           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14347       TL.setElaboratedKeywordLoc(TagLoc);
14348       TL.setQualifierLoc(QualifierLoc);
14349       TL.setNameLoc(NameLoc);
14350     } else {
14351       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14352       TL.setElaboratedKeywordLoc(TagLoc);
14353       TL.setQualifierLoc(QualifierLoc);
14354       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14355     }
14356 
14357     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14358                                             TSI, FriendLoc, TempParamLists);
14359     Friend->setAccess(AS_public);
14360     CurContext->addDecl(Friend);
14361     return Friend;
14362   }
14363 
14364   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14365 
14366 
14367 
14368   // Handle the case of a templated-scope friend class.  e.g.
14369   //   template <class T> class A<T>::B;
14370   // FIXME: we don't support these right now.
14371   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14372     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14373   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14374   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14375   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14376   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14377   TL.setElaboratedKeywordLoc(TagLoc);
14378   TL.setQualifierLoc(SS.getWithLocInContext(Context));
14379   TL.setNameLoc(NameLoc);
14380 
14381   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14382                                           TSI, FriendLoc, TempParamLists);
14383   Friend->setAccess(AS_public);
14384   Friend->setUnsupportedFriend(true);
14385   CurContext->addDecl(Friend);
14386   return Friend;
14387 }
14388 
14389 /// Handle a friend type declaration.  This works in tandem with
14390 /// ActOnTag.
14391 ///
14392 /// Notes on friend class templates:
14393 ///
14394 /// We generally treat friend class declarations as if they were
14395 /// declaring a class.  So, for example, the elaborated type specifier
14396 /// in a friend declaration is required to obey the restrictions of a
14397 /// class-head (i.e. no typedefs in the scope chain), template
14398 /// parameters are required to match up with simple template-ids, &c.
14399 /// However, unlike when declaring a template specialization, it's
14400 /// okay to refer to a template specialization without an empty
14401 /// template parameter declaration, e.g.
14402 ///   friend class A<T>::B<unsigned>;
14403 /// We permit this as a special case; if there are any template
14404 /// parameters present at all, require proper matching, i.e.
14405 ///   template <> template \<class T> friend class A<int>::B;
14406 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14407                                 MultiTemplateParamsArg TempParams) {
14408   SourceLocation Loc = DS.getBeginLoc();
14409 
14410   assert(DS.isFriendSpecified());
14411   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14412 
14413   // C++ [class.friend]p3:
14414   // A friend declaration that does not declare a function shall have one of
14415   // the following forms:
14416   //     friend elaborated-type-specifier ;
14417   //     friend simple-type-specifier ;
14418   //     friend typename-specifier ;
14419   //
14420   // Any declaration with a type qualifier does not have that form. (It's
14421   // legal to specify a qualified type as a friend, you just can't write the
14422   // keywords.)
14423   if (DS.getTypeQualifiers()) {
14424     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14425       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14426     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14427       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14428     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14429       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14430     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14431       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14432     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14433       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14434   }
14435 
14436   // Try to convert the decl specifier to a type.  This works for
14437   // friend templates because ActOnTag never produces a ClassTemplateDecl
14438   // for a TUK_Friend.
14439   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14440   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14441   QualType T = TSI->getType();
14442   if (TheDeclarator.isInvalidType())
14443     return nullptr;
14444 
14445   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14446     return nullptr;
14447 
14448   // This is definitely an error in C++98.  It's probably meant to
14449   // be forbidden in C++0x, too, but the specification is just
14450   // poorly written.
14451   //
14452   // The problem is with declarations like the following:
14453   //   template <T> friend A<T>::foo;
14454   // where deciding whether a class C is a friend or not now hinges
14455   // on whether there exists an instantiation of A that causes
14456   // 'foo' to equal C.  There are restrictions on class-heads
14457   // (which we declare (by fiat) elaborated friend declarations to
14458   // be) that makes this tractable.
14459   //
14460   // FIXME: handle "template <> friend class A<T>;", which
14461   // is possibly well-formed?  Who even knows?
14462   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14463     Diag(Loc, diag::err_tagless_friend_type_template)
14464       << DS.getSourceRange();
14465     return nullptr;
14466   }
14467 
14468   // C++98 [class.friend]p1: A friend of a class is a function
14469   //   or class that is not a member of the class . . .
14470   // This is fixed in DR77, which just barely didn't make the C++03
14471   // deadline.  It's also a very silly restriction that seriously
14472   // affects inner classes and which nobody else seems to implement;
14473   // thus we never diagnose it, not even in -pedantic.
14474   //
14475   // But note that we could warn about it: it's always useless to
14476   // friend one of your own members (it's not, however, worthless to
14477   // friend a member of an arbitrary specialization of your template).
14478 
14479   Decl *D;
14480   if (!TempParams.empty())
14481     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14482                                    TempParams,
14483                                    TSI,
14484                                    DS.getFriendSpecLoc());
14485   else
14486     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14487 
14488   if (!D)
14489     return nullptr;
14490 
14491   D->setAccess(AS_public);
14492   CurContext->addDecl(D);
14493 
14494   return D;
14495 }
14496 
14497 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14498                                         MultiTemplateParamsArg TemplateParams) {
14499   const DeclSpec &DS = D.getDeclSpec();
14500 
14501   assert(DS.isFriendSpecified());
14502   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14503 
14504   SourceLocation Loc = D.getIdentifierLoc();
14505   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14506 
14507   // C++ [class.friend]p1
14508   //   A friend of a class is a function or class....
14509   // Note that this sees through typedefs, which is intended.
14510   // It *doesn't* see through dependent types, which is correct
14511   // according to [temp.arg.type]p3:
14512   //   If a declaration acquires a function type through a
14513   //   type dependent on a template-parameter and this causes
14514   //   a declaration that does not use the syntactic form of a
14515   //   function declarator to have a function type, the program
14516   //   is ill-formed.
14517   if (!TInfo->getType()->isFunctionType()) {
14518     Diag(Loc, diag::err_unexpected_friend);
14519 
14520     // It might be worthwhile to try to recover by creating an
14521     // appropriate declaration.
14522     return nullptr;
14523   }
14524 
14525   // C++ [namespace.memdef]p3
14526   //  - If a friend declaration in a non-local class first declares a
14527   //    class or function, the friend class or function is a member
14528   //    of the innermost enclosing namespace.
14529   //  - The name of the friend is not found by simple name lookup
14530   //    until a matching declaration is provided in that namespace
14531   //    scope (either before or after the class declaration granting
14532   //    friendship).
14533   //  - If a friend function is called, its name may be found by the
14534   //    name lookup that considers functions from namespaces and
14535   //    classes associated with the types of the function arguments.
14536   //  - When looking for a prior declaration of a class or a function
14537   //    declared as a friend, scopes outside the innermost enclosing
14538   //    namespace scope are not considered.
14539 
14540   CXXScopeSpec &SS = D.getCXXScopeSpec();
14541   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14542   assert(NameInfo.getName());
14543 
14544   // Check for unexpanded parameter packs.
14545   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14546       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14547       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14548     return nullptr;
14549 
14550   // The context we found the declaration in, or in which we should
14551   // create the declaration.
14552   DeclContext *DC;
14553   Scope *DCScope = S;
14554   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14555                         ForExternalRedeclaration);
14556 
14557   // There are five cases here.
14558   //   - There's no scope specifier and we're in a local class. Only look
14559   //     for functions declared in the immediately-enclosing block scope.
14560   // We recover from invalid scope qualifiers as if they just weren't there.
14561   FunctionDecl *FunctionContainingLocalClass = nullptr;
14562   if ((SS.isInvalid() || !SS.isSet()) &&
14563       (FunctionContainingLocalClass =
14564            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14565     // C++11 [class.friend]p11:
14566     //   If a friend declaration appears in a local class and the name
14567     //   specified is an unqualified name, a prior declaration is
14568     //   looked up without considering scopes that are outside the
14569     //   innermost enclosing non-class scope. For a friend function
14570     //   declaration, if there is no prior declaration, the program is
14571     //   ill-formed.
14572 
14573     // Find the innermost enclosing non-class scope. This is the block
14574     // scope containing the local class definition (or for a nested class,
14575     // the outer local class).
14576     DCScope = S->getFnParent();
14577 
14578     // Look up the function name in the scope.
14579     Previous.clear(LookupLocalFriendName);
14580     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14581 
14582     if (!Previous.empty()) {
14583       // All possible previous declarations must have the same context:
14584       // either they were declared at block scope or they are members of
14585       // one of the enclosing local classes.
14586       DC = Previous.getRepresentativeDecl()->getDeclContext();
14587     } else {
14588       // This is ill-formed, but provide the context that we would have
14589       // declared the function in, if we were permitted to, for error recovery.
14590       DC = FunctionContainingLocalClass;
14591     }
14592     adjustContextForLocalExternDecl(DC);
14593 
14594     // C++ [class.friend]p6:
14595     //   A function can be defined in a friend declaration of a class if and
14596     //   only if the class is a non-local class (9.8), the function name is
14597     //   unqualified, and the function has namespace scope.
14598     if (D.isFunctionDefinition()) {
14599       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14600     }
14601 
14602   //   - There's no scope specifier, in which case we just go to the
14603   //     appropriate scope and look for a function or function template
14604   //     there as appropriate.
14605   } else if (SS.isInvalid() || !SS.isSet()) {
14606     // C++11 [namespace.memdef]p3:
14607     //   If the name in a friend declaration is neither qualified nor
14608     //   a template-id and the declaration is a function or an
14609     //   elaborated-type-specifier, the lookup to determine whether
14610     //   the entity has been previously declared shall not consider
14611     //   any scopes outside the innermost enclosing namespace.
14612     bool isTemplateId =
14613         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14614 
14615     // Find the appropriate context according to the above.
14616     DC = CurContext;
14617 
14618     // Skip class contexts.  If someone can cite chapter and verse
14619     // for this behavior, that would be nice --- it's what GCC and
14620     // EDG do, and it seems like a reasonable intent, but the spec
14621     // really only says that checks for unqualified existing
14622     // declarations should stop at the nearest enclosing namespace,
14623     // not that they should only consider the nearest enclosing
14624     // namespace.
14625     while (DC->isRecord())
14626       DC = DC->getParent();
14627 
14628     DeclContext *LookupDC = DC;
14629     while (LookupDC->isTransparentContext())
14630       LookupDC = LookupDC->getParent();
14631 
14632     while (true) {
14633       LookupQualifiedName(Previous, LookupDC);
14634 
14635       if (!Previous.empty()) {
14636         DC = LookupDC;
14637         break;
14638       }
14639 
14640       if (isTemplateId) {
14641         if (isa<TranslationUnitDecl>(LookupDC)) break;
14642       } else {
14643         if (LookupDC->isFileContext()) break;
14644       }
14645       LookupDC = LookupDC->getParent();
14646     }
14647 
14648     DCScope = getScopeForDeclContext(S, DC);
14649 
14650   //   - There's a non-dependent scope specifier, in which case we
14651   //     compute it and do a previous lookup there for a function
14652   //     or function template.
14653   } else if (!SS.getScopeRep()->isDependent()) {
14654     DC = computeDeclContext(SS);
14655     if (!DC) return nullptr;
14656 
14657     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14658 
14659     LookupQualifiedName(Previous, DC);
14660 
14661     // C++ [class.friend]p1: A friend of a class is a function or
14662     //   class that is not a member of the class . . .
14663     if (DC->Equals(CurContext))
14664       Diag(DS.getFriendSpecLoc(),
14665            getLangOpts().CPlusPlus11 ?
14666              diag::warn_cxx98_compat_friend_is_member :
14667              diag::err_friend_is_member);
14668 
14669     if (D.isFunctionDefinition()) {
14670       // C++ [class.friend]p6:
14671       //   A function can be defined in a friend declaration of a class if and
14672       //   only if the class is a non-local class (9.8), the function name is
14673       //   unqualified, and the function has namespace scope.
14674       //
14675       // FIXME: We should only do this if the scope specifier names the
14676       // innermost enclosing namespace; otherwise the fixit changes the
14677       // meaning of the code.
14678       SemaDiagnosticBuilder DB
14679         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14680 
14681       DB << SS.getScopeRep();
14682       if (DC->isFileContext())
14683         DB << FixItHint::CreateRemoval(SS.getRange());
14684       SS.clear();
14685     }
14686 
14687   //   - There's a scope specifier that does not match any template
14688   //     parameter lists, in which case we use some arbitrary context,
14689   //     create a method or method template, and wait for instantiation.
14690   //   - There's a scope specifier that does match some template
14691   //     parameter lists, which we don't handle right now.
14692   } else {
14693     if (D.isFunctionDefinition()) {
14694       // C++ [class.friend]p6:
14695       //   A function can be defined in a friend declaration of a class if and
14696       //   only if the class is a non-local class (9.8), the function name is
14697       //   unqualified, and the function has namespace scope.
14698       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14699         << SS.getScopeRep();
14700     }
14701 
14702     DC = CurContext;
14703     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14704   }
14705 
14706   if (!DC->isRecord()) {
14707     int DiagArg = -1;
14708     switch (D.getName().getKind()) {
14709     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14710     case UnqualifiedIdKind::IK_ConstructorName:
14711       DiagArg = 0;
14712       break;
14713     case UnqualifiedIdKind::IK_DestructorName:
14714       DiagArg = 1;
14715       break;
14716     case UnqualifiedIdKind::IK_ConversionFunctionId:
14717       DiagArg = 2;
14718       break;
14719     case UnqualifiedIdKind::IK_DeductionGuideName:
14720       DiagArg = 3;
14721       break;
14722     case UnqualifiedIdKind::IK_Identifier:
14723     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14724     case UnqualifiedIdKind::IK_LiteralOperatorId:
14725     case UnqualifiedIdKind::IK_OperatorFunctionId:
14726     case UnqualifiedIdKind::IK_TemplateId:
14727       break;
14728     }
14729     // This implies that it has to be an operator or function.
14730     if (DiagArg >= 0) {
14731       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14732       return nullptr;
14733     }
14734   }
14735 
14736   // FIXME: This is an egregious hack to cope with cases where the scope stack
14737   // does not contain the declaration context, i.e., in an out-of-line
14738   // definition of a class.
14739   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14740   if (!DCScope) {
14741     FakeDCScope.setEntity(DC);
14742     DCScope = &FakeDCScope;
14743   }
14744 
14745   bool AddToScope = true;
14746   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14747                                           TemplateParams, AddToScope);
14748   if (!ND) return nullptr;
14749 
14750   assert(ND->getLexicalDeclContext() == CurContext);
14751 
14752   // If we performed typo correction, we might have added a scope specifier
14753   // and changed the decl context.
14754   DC = ND->getDeclContext();
14755 
14756   // Add the function declaration to the appropriate lookup tables,
14757   // adjusting the redeclarations list as necessary.  We don't
14758   // want to do this yet if the friending class is dependent.
14759   //
14760   // Also update the scope-based lookup if the target context's
14761   // lookup context is in lexical scope.
14762   if (!CurContext->isDependentContext()) {
14763     DC = DC->getRedeclContext();
14764     DC->makeDeclVisibleInContext(ND);
14765     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14766       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14767   }
14768 
14769   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14770                                        D.getIdentifierLoc(), ND,
14771                                        DS.getFriendSpecLoc());
14772   FrD->setAccess(AS_public);
14773   CurContext->addDecl(FrD);
14774 
14775   if (ND->isInvalidDecl()) {
14776     FrD->setInvalidDecl();
14777   } else {
14778     if (DC->isRecord()) CheckFriendAccess(ND);
14779 
14780     FunctionDecl *FD;
14781     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14782       FD = FTD->getTemplatedDecl();
14783     else
14784       FD = cast<FunctionDecl>(ND);
14785 
14786     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14787     // default argument expression, that declaration shall be a definition
14788     // and shall be the only declaration of the function or function
14789     // template in the translation unit.
14790     if (functionDeclHasDefaultArgument(FD)) {
14791       // We can't look at FD->getPreviousDecl() because it may not have been set
14792       // if we're in a dependent context. If the function is known to be a
14793       // redeclaration, we will have narrowed Previous down to the right decl.
14794       if (D.isRedeclaration()) {
14795         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14796         Diag(Previous.getRepresentativeDecl()->getLocation(),
14797              diag::note_previous_declaration);
14798       } else if (!D.isFunctionDefinition())
14799         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14800     }
14801 
14802     // Mark templated-scope function declarations as unsupported.
14803     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14804       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14805         << SS.getScopeRep() << SS.getRange()
14806         << cast<CXXRecordDecl>(CurContext);
14807       FrD->setUnsupportedFriend(true);
14808     }
14809   }
14810 
14811   return ND;
14812 }
14813 
14814 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14815   AdjustDeclIfTemplate(Dcl);
14816 
14817   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14818   if (!Fn) {
14819     Diag(DelLoc, diag::err_deleted_non_function);
14820     return;
14821   }
14822 
14823   // Deleted function does not have a body.
14824   Fn->setWillHaveBody(false);
14825 
14826   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14827     // Don't consider the implicit declaration we generate for explicit
14828     // specializations. FIXME: Do not generate these implicit declarations.
14829     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14830          Prev->getPreviousDecl()) &&
14831         !Prev->isDefined()) {
14832       Diag(DelLoc, diag::err_deleted_decl_not_first);
14833       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14834            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14835                               : diag::note_previous_declaration);
14836     }
14837     // If the declaration wasn't the first, we delete the function anyway for
14838     // recovery.
14839     Fn = Fn->getCanonicalDecl();
14840   }
14841 
14842   // dllimport/dllexport cannot be deleted.
14843   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14844     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14845     Fn->setInvalidDecl();
14846   }
14847 
14848   if (Fn->isDeleted())
14849     return;
14850 
14851   // See if we're deleting a function which is already known to override a
14852   // non-deleted virtual function.
14853   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14854     bool IssuedDiagnostic = false;
14855     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14856       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14857         if (!IssuedDiagnostic) {
14858           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14859           IssuedDiagnostic = true;
14860         }
14861         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14862       }
14863     }
14864     // If this function was implicitly deleted because it was defaulted,
14865     // explain why it was deleted.
14866     if (IssuedDiagnostic && MD->isDefaulted())
14867       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14868                                 /*Diagnose*/true);
14869   }
14870 
14871   // C++11 [basic.start.main]p3:
14872   //   A program that defines main as deleted [...] is ill-formed.
14873   if (Fn->isMain())
14874     Diag(DelLoc, diag::err_deleted_main);
14875 
14876   // C++11 [dcl.fct.def.delete]p4:
14877   //  A deleted function is implicitly inline.
14878   Fn->setImplicitlyInline();
14879   Fn->setDeletedAsWritten();
14880 }
14881 
14882 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14883   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14884 
14885   if (MD) {
14886     if (MD->getParent()->isDependentType()) {
14887       MD->setDefaulted();
14888       MD->setExplicitlyDefaulted();
14889       return;
14890     }
14891 
14892     CXXSpecialMember Member = getSpecialMember(MD);
14893     if (Member == CXXInvalid) {
14894       if (!MD->isInvalidDecl())
14895         Diag(DefaultLoc, diag::err_default_special_members);
14896       return;
14897     }
14898 
14899     MD->setDefaulted();
14900     MD->setExplicitlyDefaulted();
14901 
14902     // Unset that we will have a body for this function. We might not,
14903     // if it turns out to be trivial, and we don't need this marking now
14904     // that we've marked it as defaulted.
14905     MD->setWillHaveBody(false);
14906 
14907     // If this definition appears within the record, do the checking when
14908     // the record is complete.
14909     const FunctionDecl *Primary = MD;
14910     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14911       // Ask the template instantiation pattern that actually had the
14912       // '= default' on it.
14913       Primary = Pattern;
14914 
14915     // If the method was defaulted on its first declaration, we will have
14916     // already performed the checking in CheckCompletedCXXClass. Such a
14917     // declaration doesn't trigger an implicit definition.
14918     if (Primary->getCanonicalDecl()->isDefaulted())
14919       return;
14920 
14921     CheckExplicitlyDefaultedSpecialMember(MD);
14922 
14923     if (!MD->isInvalidDecl())
14924       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14925   } else {
14926     Diag(DefaultLoc, diag::err_default_special_members);
14927   }
14928 }
14929 
14930 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14931   for (Stmt *SubStmt : S->children()) {
14932     if (!SubStmt)
14933       continue;
14934     if (isa<ReturnStmt>(SubStmt))
14935       Self.Diag(SubStmt->getBeginLoc(),
14936                 diag::err_return_in_constructor_handler);
14937     if (!isa<Expr>(SubStmt))
14938       SearchForReturnInStmt(Self, SubStmt);
14939   }
14940 }
14941 
14942 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14943   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14944     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14945     SearchForReturnInStmt(*this, Handler);
14946   }
14947 }
14948 
14949 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14950                                              const CXXMethodDecl *Old) {
14951   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14952   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14953 
14954   if (OldFT->hasExtParameterInfos()) {
14955     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14956       // A parameter of the overriding method should be annotated with noescape
14957       // if the corresponding parameter of the overridden method is annotated.
14958       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14959           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14960         Diag(New->getParamDecl(I)->getLocation(),
14961              diag::warn_overriding_method_missing_noescape);
14962         Diag(Old->getParamDecl(I)->getLocation(),
14963              diag::note_overridden_marked_noescape);
14964       }
14965   }
14966 
14967   // Virtual overrides must have the same code_seg.
14968   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14969   const auto *NewCSA = New->getAttr<CodeSegAttr>();
14970   if ((NewCSA || OldCSA) &&
14971       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14972     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14973     Diag(Old->getLocation(), diag::note_previous_declaration);
14974     return true;
14975   }
14976 
14977   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14978 
14979   // If the calling conventions match, everything is fine
14980   if (NewCC == OldCC)
14981     return false;
14982 
14983   // If the calling conventions mismatch because the new function is static,
14984   // suppress the calling convention mismatch error; the error about static
14985   // function override (err_static_overrides_virtual from
14986   // Sema::CheckFunctionDeclaration) is more clear.
14987   if (New->getStorageClass() == SC_Static)
14988     return false;
14989 
14990   Diag(New->getLocation(),
14991        diag::err_conflicting_overriding_cc_attributes)
14992     << New->getDeclName() << New->getType() << Old->getType();
14993   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14994   return true;
14995 }
14996 
14997 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14998                                              const CXXMethodDecl *Old) {
14999   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
15000   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
15001 
15002   if (Context.hasSameType(NewTy, OldTy) ||
15003       NewTy->isDependentType() || OldTy->isDependentType())
15004     return false;
15005 
15006   // Check if the return types are covariant
15007   QualType NewClassTy, OldClassTy;
15008 
15009   /// Both types must be pointers or references to classes.
15010   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
15011     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
15012       NewClassTy = NewPT->getPointeeType();
15013       OldClassTy = OldPT->getPointeeType();
15014     }
15015   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
15016     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
15017       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
15018         NewClassTy = NewRT->getPointeeType();
15019         OldClassTy = OldRT->getPointeeType();
15020       }
15021     }
15022   }
15023 
15024   // The return types aren't either both pointers or references to a class type.
15025   if (NewClassTy.isNull()) {
15026     Diag(New->getLocation(),
15027          diag::err_different_return_type_for_overriding_virtual_function)
15028         << New->getDeclName() << NewTy << OldTy
15029         << New->getReturnTypeSourceRange();
15030     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15031         << Old->getReturnTypeSourceRange();
15032 
15033     return true;
15034   }
15035 
15036   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
15037     // C++14 [class.virtual]p8:
15038     //   If the class type in the covariant return type of D::f differs from
15039     //   that of B::f, the class type in the return type of D::f shall be
15040     //   complete at the point of declaration of D::f or shall be the class
15041     //   type D.
15042     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
15043       if (!RT->isBeingDefined() &&
15044           RequireCompleteType(New->getLocation(), NewClassTy,
15045                               diag::err_covariant_return_incomplete,
15046                               New->getDeclName()))
15047         return true;
15048     }
15049 
15050     // Check if the new class derives from the old class.
15051     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
15052       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
15053           << New->getDeclName() << NewTy << OldTy
15054           << New->getReturnTypeSourceRange();
15055       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15056           << Old->getReturnTypeSourceRange();
15057       return true;
15058     }
15059 
15060     // Check if we the conversion from derived to base is valid.
15061     if (CheckDerivedToBaseConversion(
15062             NewClassTy, OldClassTy,
15063             diag::err_covariant_return_inaccessible_base,
15064             diag::err_covariant_return_ambiguous_derived_to_base_conv,
15065             New->getLocation(), New->getReturnTypeSourceRange(),
15066             New->getDeclName(), nullptr)) {
15067       // FIXME: this note won't trigger for delayed access control
15068       // diagnostics, and it's impossible to get an undelayed error
15069       // here from access control during the original parse because
15070       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
15071       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15072           << Old->getReturnTypeSourceRange();
15073       return true;
15074     }
15075   }
15076 
15077   // The qualifiers of the return types must be the same.
15078   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
15079     Diag(New->getLocation(),
15080          diag::err_covariant_return_type_different_qualifications)
15081         << New->getDeclName() << NewTy << OldTy
15082         << New->getReturnTypeSourceRange();
15083     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15084         << Old->getReturnTypeSourceRange();
15085     return true;
15086   }
15087 
15088 
15089   // The new class type must have the same or less qualifiers as the old type.
15090   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
15091     Diag(New->getLocation(),
15092          diag::err_covariant_return_type_class_type_more_qualified)
15093         << New->getDeclName() << NewTy << OldTy
15094         << New->getReturnTypeSourceRange();
15095     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15096         << Old->getReturnTypeSourceRange();
15097     return true;
15098   }
15099 
15100   return false;
15101 }
15102 
15103 /// Mark the given method pure.
15104 ///
15105 /// \param Method the method to be marked pure.
15106 ///
15107 /// \param InitRange the source range that covers the "0" initializer.
15108 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
15109   SourceLocation EndLoc = InitRange.getEnd();
15110   if (EndLoc.isValid())
15111     Method->setRangeEnd(EndLoc);
15112 
15113   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
15114     Method->setPure();
15115     return false;
15116   }
15117 
15118   if (!Method->isInvalidDecl())
15119     Diag(Method->getLocation(), diag::err_non_virtual_pure)
15120       << Method->getDeclName() << InitRange;
15121   return true;
15122 }
15123 
15124 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
15125   if (D->getFriendObjectKind())
15126     Diag(D->getLocation(), diag::err_pure_friend);
15127   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
15128     CheckPureMethod(M, ZeroLoc);
15129   else
15130     Diag(D->getLocation(), diag::err_illegal_initializer);
15131 }
15132 
15133 /// Determine whether the given declaration is a global variable or
15134 /// static data member.
15135 static bool isNonlocalVariable(const Decl *D) {
15136   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
15137     return Var->hasGlobalStorage();
15138 
15139   return false;
15140 }
15141 
15142 /// Invoked when we are about to parse an initializer for the declaration
15143 /// 'Dcl'.
15144 ///
15145 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
15146 /// static data member of class X, names should be looked up in the scope of
15147 /// class X. If the declaration had a scope specifier, a scope will have
15148 /// been created and passed in for this purpose. Otherwise, S will be null.
15149 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
15150   // If there is no declaration, there was an error parsing it.
15151   if (!D || D->isInvalidDecl())
15152     return;
15153 
15154   // We will always have a nested name specifier here, but this declaration
15155   // might not be out of line if the specifier names the current namespace:
15156   //   extern int n;
15157   //   int ::n = 0;
15158   if (S && D->isOutOfLine())
15159     EnterDeclaratorContext(S, D->getDeclContext());
15160 
15161   // If we are parsing the initializer for a static data member, push a
15162   // new expression evaluation context that is associated with this static
15163   // data member.
15164   if (isNonlocalVariable(D))
15165     PushExpressionEvaluationContext(
15166         ExpressionEvaluationContext::PotentiallyEvaluated, D);
15167 }
15168 
15169 /// Invoked after we are finished parsing an initializer for the declaration D.
15170 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
15171   // If there is no declaration, there was an error parsing it.
15172   if (!D || D->isInvalidDecl())
15173     return;
15174 
15175   if (isNonlocalVariable(D))
15176     PopExpressionEvaluationContext();
15177 
15178   if (S && D->isOutOfLine())
15179     ExitDeclaratorContext(S);
15180 }
15181 
15182 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
15183 /// C++ if/switch/while/for statement.
15184 /// e.g: "if (int x = f()) {...}"
15185 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
15186   // C++ 6.4p2:
15187   // The declarator shall not specify a function or an array.
15188   // The type-specifier-seq shall not contain typedef and shall not declare a
15189   // new class or enumeration.
15190   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
15191          "Parser allowed 'typedef' as storage class of condition decl.");
15192 
15193   Decl *Dcl = ActOnDeclarator(S, D);
15194   if (!Dcl)
15195     return true;
15196 
15197   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
15198     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
15199       << D.getSourceRange();
15200     return true;
15201   }
15202 
15203   return Dcl;
15204 }
15205 
15206 void Sema::LoadExternalVTableUses() {
15207   if (!ExternalSource)
15208     return;
15209 
15210   SmallVector<ExternalVTableUse, 4> VTables;
15211   ExternalSource->ReadUsedVTables(VTables);
15212   SmallVector<VTableUse, 4> NewUses;
15213   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
15214     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
15215       = VTablesUsed.find(VTables[I].Record);
15216     // Even if a definition wasn't required before, it may be required now.
15217     if (Pos != VTablesUsed.end()) {
15218       if (!Pos->second && VTables[I].DefinitionRequired)
15219         Pos->second = true;
15220       continue;
15221     }
15222 
15223     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
15224     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
15225   }
15226 
15227   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
15228 }
15229 
15230 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
15231                           bool DefinitionRequired) {
15232   // Ignore any vtable uses in unevaluated operands or for classes that do
15233   // not have a vtable.
15234   if (!Class->isDynamicClass() || Class->isDependentContext() ||
15235       CurContext->isDependentContext() || isUnevaluatedContext())
15236     return;
15237   // Do not mark as used if compiling for the device outside of the target
15238   // region.
15239   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15240       !isInOpenMPDeclareTargetContext() &&
15241       !isInOpenMPTargetExecutionDirective()) {
15242     if (!DefinitionRequired)
15243       MarkVirtualMembersReferenced(Loc, Class);
15244     return;
15245   }
15246 
15247   // Try to insert this class into the map.
15248   LoadExternalVTableUses();
15249   Class = Class->getCanonicalDecl();
15250   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15251     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15252   if (!Pos.second) {
15253     // If we already had an entry, check to see if we are promoting this vtable
15254     // to require a definition. If so, we need to reappend to the VTableUses
15255     // list, since we may have already processed the first entry.
15256     if (DefinitionRequired && !Pos.first->second) {
15257       Pos.first->second = true;
15258     } else {
15259       // Otherwise, we can early exit.
15260       return;
15261     }
15262   } else {
15263     // The Microsoft ABI requires that we perform the destructor body
15264     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15265     // the deleting destructor is emitted with the vtable, not with the
15266     // destructor definition as in the Itanium ABI.
15267     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15268       CXXDestructorDecl *DD = Class->getDestructor();
15269       if (DD && DD->isVirtual() && !DD->isDeleted()) {
15270         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15271           // If this is an out-of-line declaration, marking it referenced will
15272           // not do anything. Manually call CheckDestructor to look up operator
15273           // delete().
15274           ContextRAII SavedContext(*this, DD);
15275           CheckDestructor(DD);
15276         } else {
15277           MarkFunctionReferenced(Loc, Class->getDestructor());
15278         }
15279       }
15280     }
15281   }
15282 
15283   // Local classes need to have their virtual members marked
15284   // immediately. For all other classes, we mark their virtual members
15285   // at the end of the translation unit.
15286   if (Class->isLocalClass())
15287     MarkVirtualMembersReferenced(Loc, Class);
15288   else
15289     VTableUses.push_back(std::make_pair(Class, Loc));
15290 }
15291 
15292 bool Sema::DefineUsedVTables() {
15293   LoadExternalVTableUses();
15294   if (VTableUses.empty())
15295     return false;
15296 
15297   // Note: The VTableUses vector could grow as a result of marking
15298   // the members of a class as "used", so we check the size each
15299   // time through the loop and prefer indices (which are stable) to
15300   // iterators (which are not).
15301   bool DefinedAnything = false;
15302   for (unsigned I = 0; I != VTableUses.size(); ++I) {
15303     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15304     if (!Class)
15305       continue;
15306     TemplateSpecializationKind ClassTSK =
15307         Class->getTemplateSpecializationKind();
15308 
15309     SourceLocation Loc = VTableUses[I].second;
15310 
15311     bool DefineVTable = true;
15312 
15313     // If this class has a key function, but that key function is
15314     // defined in another translation unit, we don't need to emit the
15315     // vtable even though we're using it.
15316     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15317     if (KeyFunction && !KeyFunction->hasBody()) {
15318       // The key function is in another translation unit.
15319       DefineVTable = false;
15320       TemplateSpecializationKind TSK =
15321           KeyFunction->getTemplateSpecializationKind();
15322       assert(TSK != TSK_ExplicitInstantiationDefinition &&
15323              TSK != TSK_ImplicitInstantiation &&
15324              "Instantiations don't have key functions");
15325       (void)TSK;
15326     } else if (!KeyFunction) {
15327       // If we have a class with no key function that is the subject
15328       // of an explicit instantiation declaration, suppress the
15329       // vtable; it will live with the explicit instantiation
15330       // definition.
15331       bool IsExplicitInstantiationDeclaration =
15332           ClassTSK == TSK_ExplicitInstantiationDeclaration;
15333       for (auto R : Class->redecls()) {
15334         TemplateSpecializationKind TSK
15335           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15336         if (TSK == TSK_ExplicitInstantiationDeclaration)
15337           IsExplicitInstantiationDeclaration = true;
15338         else if (TSK == TSK_ExplicitInstantiationDefinition) {
15339           IsExplicitInstantiationDeclaration = false;
15340           break;
15341         }
15342       }
15343 
15344       if (IsExplicitInstantiationDeclaration)
15345         DefineVTable = false;
15346     }
15347 
15348     // The exception specifications for all virtual members may be needed even
15349     // if we are not providing an authoritative form of the vtable in this TU.
15350     // We may choose to emit it available_externally anyway.
15351     if (!DefineVTable) {
15352       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15353       continue;
15354     }
15355 
15356     // Mark all of the virtual members of this class as referenced, so
15357     // that we can build a vtable. Then, tell the AST consumer that a
15358     // vtable for this class is required.
15359     DefinedAnything = true;
15360     MarkVirtualMembersReferenced(Loc, Class);
15361     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15362     if (VTablesUsed[Canonical])
15363       Consumer.HandleVTable(Class);
15364 
15365     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15366     // no key function or the key function is inlined. Don't warn in C++ ABIs
15367     // that lack key functions, since the user won't be able to make one.
15368     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15369         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15370       const FunctionDecl *KeyFunctionDef = nullptr;
15371       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15372                            KeyFunctionDef->isInlined())) {
15373         Diag(Class->getLocation(),
15374              ClassTSK == TSK_ExplicitInstantiationDefinition
15375                  ? diag::warn_weak_template_vtable
15376                  : diag::warn_weak_vtable)
15377             << Class;
15378       }
15379     }
15380   }
15381   VTableUses.clear();
15382 
15383   return DefinedAnything;
15384 }
15385 
15386 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15387                                                  const CXXRecordDecl *RD) {
15388   for (const auto *I : RD->methods())
15389     if (I->isVirtual() && !I->isPure())
15390       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15391 }
15392 
15393 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15394                                         const CXXRecordDecl *RD,
15395                                         bool ConstexprOnly) {
15396   // Mark all functions which will appear in RD's vtable as used.
15397   CXXFinalOverriderMap FinalOverriders;
15398   RD->getFinalOverriders(FinalOverriders);
15399   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15400                                             E = FinalOverriders.end();
15401        I != E; ++I) {
15402     for (OverridingMethods::const_iterator OI = I->second.begin(),
15403                                            OE = I->second.end();
15404          OI != OE; ++OI) {
15405       assert(OI->second.size() > 0 && "no final overrider");
15406       CXXMethodDecl *Overrider = OI->second.front().Method;
15407 
15408       // C++ [basic.def.odr]p2:
15409       //   [...] A virtual member function is used if it is not pure. [...]
15410       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
15411         MarkFunctionReferenced(Loc, Overrider);
15412     }
15413   }
15414 
15415   // Only classes that have virtual bases need a VTT.
15416   if (RD->getNumVBases() == 0)
15417     return;
15418 
15419   for (const auto &I : RD->bases()) {
15420     const CXXRecordDecl *Base =
15421         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15422     if (Base->getNumVBases() == 0)
15423       continue;
15424     MarkVirtualMembersReferenced(Loc, Base);
15425   }
15426 }
15427 
15428 /// SetIvarInitializers - This routine builds initialization ASTs for the
15429 /// Objective-C implementation whose ivars need be initialized.
15430 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15431   if (!getLangOpts().CPlusPlus)
15432     return;
15433   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15434     SmallVector<ObjCIvarDecl*, 8> ivars;
15435     CollectIvarsToConstructOrDestruct(OID, ivars);
15436     if (ivars.empty())
15437       return;
15438     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15439     for (unsigned i = 0; i < ivars.size(); i++) {
15440       FieldDecl *Field = ivars[i];
15441       if (Field->isInvalidDecl())
15442         continue;
15443 
15444       CXXCtorInitializer *Member;
15445       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15446       InitializationKind InitKind =
15447         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15448 
15449       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15450       ExprResult MemberInit =
15451         InitSeq.Perform(*this, InitEntity, InitKind, None);
15452       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15453       // Note, MemberInit could actually come back empty if no initialization
15454       // is required (e.g., because it would call a trivial default constructor)
15455       if (!MemberInit.get() || MemberInit.isInvalid())
15456         continue;
15457 
15458       Member =
15459         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15460                                          SourceLocation(),
15461                                          MemberInit.getAs<Expr>(),
15462                                          SourceLocation());
15463       AllToInit.push_back(Member);
15464 
15465       // Be sure that the destructor is accessible and is marked as referenced.
15466       if (const RecordType *RecordTy =
15467               Context.getBaseElementType(Field->getType())
15468                   ->getAs<RecordType>()) {
15469         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15470         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15471           MarkFunctionReferenced(Field->getLocation(), Destructor);
15472           CheckDestructorAccess(Field->getLocation(), Destructor,
15473                             PDiag(diag::err_access_dtor_ivar)
15474                               << Context.getBaseElementType(Field->getType()));
15475         }
15476       }
15477     }
15478     ObjCImplementation->setIvarInitializers(Context,
15479                                             AllToInit.data(), AllToInit.size());
15480   }
15481 }
15482 
15483 static
15484 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15485                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15486                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15487                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15488                            Sema &S) {
15489   if (Ctor->isInvalidDecl())
15490     return;
15491 
15492   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15493 
15494   // Target may not be determinable yet, for instance if this is a dependent
15495   // call in an uninstantiated template.
15496   if (Target) {
15497     const FunctionDecl *FNTarget = nullptr;
15498     (void)Target->hasBody(FNTarget);
15499     Target = const_cast<CXXConstructorDecl*>(
15500       cast_or_null<CXXConstructorDecl>(FNTarget));
15501   }
15502 
15503   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15504                      // Avoid dereferencing a null pointer here.
15505                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15506 
15507   if (!Current.insert(Canonical).second)
15508     return;
15509 
15510   // We know that beyond here, we aren't chaining into a cycle.
15511   if (!Target || !Target->isDelegatingConstructor() ||
15512       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15513     Valid.insert(Current.begin(), Current.end());
15514     Current.clear();
15515   // We've hit a cycle.
15516   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15517              Current.count(TCanonical)) {
15518     // If we haven't diagnosed this cycle yet, do so now.
15519     if (!Invalid.count(TCanonical)) {
15520       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15521              diag::warn_delegating_ctor_cycle)
15522         << Ctor;
15523 
15524       // Don't add a note for a function delegating directly to itself.
15525       if (TCanonical != Canonical)
15526         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15527 
15528       CXXConstructorDecl *C = Target;
15529       while (C->getCanonicalDecl() != Canonical) {
15530         const FunctionDecl *FNTarget = nullptr;
15531         (void)C->getTargetConstructor()->hasBody(FNTarget);
15532         assert(FNTarget && "Ctor cycle through bodiless function");
15533 
15534         C = const_cast<CXXConstructorDecl*>(
15535           cast<CXXConstructorDecl>(FNTarget));
15536         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15537       }
15538     }
15539 
15540     Invalid.insert(Current.begin(), Current.end());
15541     Current.clear();
15542   } else {
15543     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15544   }
15545 }
15546 
15547 
15548 void Sema::CheckDelegatingCtorCycles() {
15549   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15550 
15551   for (DelegatingCtorDeclsType::iterator
15552          I = DelegatingCtorDecls.begin(ExternalSource),
15553          E = DelegatingCtorDecls.end();
15554        I != E; ++I)
15555     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15556 
15557   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15558     (*CI)->setInvalidDecl();
15559 }
15560 
15561 namespace {
15562   /// AST visitor that finds references to the 'this' expression.
15563   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15564     Sema &S;
15565 
15566   public:
15567     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15568 
15569     bool VisitCXXThisExpr(CXXThisExpr *E) {
15570       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15571         << E->isImplicit();
15572       return false;
15573     }
15574   };
15575 }
15576 
15577 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15578   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15579   if (!TSInfo)
15580     return false;
15581 
15582   TypeLoc TL = TSInfo->getTypeLoc();
15583   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15584   if (!ProtoTL)
15585     return false;
15586 
15587   // C++11 [expr.prim.general]p3:
15588   //   [The expression this] shall not appear before the optional
15589   //   cv-qualifier-seq and it shall not appear within the declaration of a
15590   //   static member function (although its type and value category are defined
15591   //   within a static member function as they are within a non-static member
15592   //   function). [ Note: this is because declaration matching does not occur
15593   //  until the complete declarator is known. - end note ]
15594   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15595   FindCXXThisExpr Finder(*this);
15596 
15597   // If the return type came after the cv-qualifier-seq, check it now.
15598   if (Proto->hasTrailingReturn() &&
15599       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15600     return true;
15601 
15602   // Check the exception specification.
15603   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15604     return true;
15605 
15606   return checkThisInStaticMemberFunctionAttributes(Method);
15607 }
15608 
15609 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15610   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15611   if (!TSInfo)
15612     return false;
15613 
15614   TypeLoc TL = TSInfo->getTypeLoc();
15615   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15616   if (!ProtoTL)
15617     return false;
15618 
15619   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15620   FindCXXThisExpr Finder(*this);
15621 
15622   switch (Proto->getExceptionSpecType()) {
15623   case EST_Unparsed:
15624   case EST_Uninstantiated:
15625   case EST_Unevaluated:
15626   case EST_BasicNoexcept:
15627   case EST_NoThrow:
15628   case EST_DynamicNone:
15629   case EST_MSAny:
15630   case EST_None:
15631     break;
15632 
15633   case EST_DependentNoexcept:
15634   case EST_NoexceptFalse:
15635   case EST_NoexceptTrue:
15636     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15637       return true;
15638     LLVM_FALLTHROUGH;
15639 
15640   case EST_Dynamic:
15641     for (const auto &E : Proto->exceptions()) {
15642       if (!Finder.TraverseType(E))
15643         return true;
15644     }
15645     break;
15646   }
15647 
15648   return false;
15649 }
15650 
15651 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15652   FindCXXThisExpr Finder(*this);
15653 
15654   // Check attributes.
15655   for (const auto *A : Method->attrs()) {
15656     // FIXME: This should be emitted by tblgen.
15657     Expr *Arg = nullptr;
15658     ArrayRef<Expr *> Args;
15659     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15660       Arg = G->getArg();
15661     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15662       Arg = G->getArg();
15663     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15664       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15665     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15666       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15667     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15668       Arg = ETLF->getSuccessValue();
15669       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15670     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15671       Arg = STLF->getSuccessValue();
15672       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15673     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15674       Arg = LR->getArg();
15675     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15676       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15677     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15678       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15679     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15680       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15681     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15682       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15683     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15684       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15685 
15686     if (Arg && !Finder.TraverseStmt(Arg))
15687       return true;
15688 
15689     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15690       if (!Finder.TraverseStmt(Args[I]))
15691         return true;
15692     }
15693   }
15694 
15695   return false;
15696 }
15697 
15698 void Sema::checkExceptionSpecification(
15699     bool IsTopLevel, ExceptionSpecificationType EST,
15700     ArrayRef<ParsedType> DynamicExceptions,
15701     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15702     SmallVectorImpl<QualType> &Exceptions,
15703     FunctionProtoType::ExceptionSpecInfo &ESI) {
15704   Exceptions.clear();
15705   ESI.Type = EST;
15706   if (EST == EST_Dynamic) {
15707     Exceptions.reserve(DynamicExceptions.size());
15708     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15709       // FIXME: Preserve type source info.
15710       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15711 
15712       if (IsTopLevel) {
15713         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15714         collectUnexpandedParameterPacks(ET, Unexpanded);
15715         if (!Unexpanded.empty()) {
15716           DiagnoseUnexpandedParameterPacks(
15717               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15718               Unexpanded);
15719           continue;
15720         }
15721       }
15722 
15723       // Check that the type is valid for an exception spec, and
15724       // drop it if not.
15725       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15726         Exceptions.push_back(ET);
15727     }
15728     ESI.Exceptions = Exceptions;
15729     return;
15730   }
15731 
15732   if (isComputedNoexcept(EST)) {
15733     assert((NoexceptExpr->isTypeDependent() ||
15734             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15735             Context.BoolTy) &&
15736            "Parser should have made sure that the expression is boolean");
15737     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15738       ESI.Type = EST_BasicNoexcept;
15739       return;
15740     }
15741 
15742     ESI.NoexceptExpr = NoexceptExpr;
15743     return;
15744   }
15745 }
15746 
15747 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15748              ExceptionSpecificationType EST,
15749              SourceRange SpecificationRange,
15750              ArrayRef<ParsedType> DynamicExceptions,
15751              ArrayRef<SourceRange> DynamicExceptionRanges,
15752              Expr *NoexceptExpr) {
15753   if (!MethodD)
15754     return;
15755 
15756   // Dig out the method we're referring to.
15757   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15758     MethodD = FunTmpl->getTemplatedDecl();
15759 
15760   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15761   if (!Method)
15762     return;
15763 
15764   // Check the exception specification.
15765   llvm::SmallVector<QualType, 4> Exceptions;
15766   FunctionProtoType::ExceptionSpecInfo ESI;
15767   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15768                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15769                               ESI);
15770 
15771   // Update the exception specification on the function type.
15772   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15773 
15774   if (Method->isStatic())
15775     checkThisInStaticMemberFunctionExceptionSpec(Method);
15776 
15777   if (Method->isVirtual()) {
15778     // Check overrides, which we previously had to delay.
15779     for (const CXXMethodDecl *O : Method->overridden_methods())
15780       CheckOverridingFunctionExceptionSpec(Method, O);
15781   }
15782 }
15783 
15784 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15785 ///
15786 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15787                                        SourceLocation DeclStart, Declarator &D,
15788                                        Expr *BitWidth,
15789                                        InClassInitStyle InitStyle,
15790                                        AccessSpecifier AS,
15791                                        const ParsedAttr &MSPropertyAttr) {
15792   IdentifierInfo *II = D.getIdentifier();
15793   if (!II) {
15794     Diag(DeclStart, diag::err_anonymous_property);
15795     return nullptr;
15796   }
15797   SourceLocation Loc = D.getIdentifierLoc();
15798 
15799   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15800   QualType T = TInfo->getType();
15801   if (getLangOpts().CPlusPlus) {
15802     CheckExtraCXXDefaultArguments(D);
15803 
15804     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15805                                         UPPC_DataMemberType)) {
15806       D.setInvalidType();
15807       T = Context.IntTy;
15808       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15809     }
15810   }
15811 
15812   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15813 
15814   if (D.getDeclSpec().isInlineSpecified())
15815     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15816         << getLangOpts().CPlusPlus17;
15817   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15818     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15819          diag::err_invalid_thread)
15820       << DeclSpec::getSpecifierName(TSCS);
15821 
15822   // Check to see if this name was declared as a member previously
15823   NamedDecl *PrevDecl = nullptr;
15824   LookupResult Previous(*this, II, Loc, LookupMemberName,
15825                         ForVisibleRedeclaration);
15826   LookupName(Previous, S);
15827   switch (Previous.getResultKind()) {
15828   case LookupResult::Found:
15829   case LookupResult::FoundUnresolvedValue:
15830     PrevDecl = Previous.getAsSingle<NamedDecl>();
15831     break;
15832 
15833   case LookupResult::FoundOverloaded:
15834     PrevDecl = Previous.getRepresentativeDecl();
15835     break;
15836 
15837   case LookupResult::NotFound:
15838   case LookupResult::NotFoundInCurrentInstantiation:
15839   case LookupResult::Ambiguous:
15840     break;
15841   }
15842 
15843   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15844     // Maybe we will complain about the shadowed template parameter.
15845     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15846     // Just pretend that we didn't see the previous declaration.
15847     PrevDecl = nullptr;
15848   }
15849 
15850   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15851     PrevDecl = nullptr;
15852 
15853   SourceLocation TSSL = D.getBeginLoc();
15854   MSPropertyDecl *NewPD =
15855       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15856                              MSPropertyAttr.getPropertyDataGetter(),
15857                              MSPropertyAttr.getPropertyDataSetter());
15858   ProcessDeclAttributes(TUScope, NewPD, D);
15859   NewPD->setAccess(AS);
15860 
15861   if (NewPD->isInvalidDecl())
15862     Record->setInvalidDecl();
15863 
15864   if (D.getDeclSpec().isModulePrivateSpecified())
15865     NewPD->setModulePrivate();
15866 
15867   if (NewPD->isInvalidDecl() && PrevDecl) {
15868     // Don't introduce NewFD into scope; there's already something
15869     // with the same name in the same scope.
15870   } else if (II) {
15871     PushOnScopeChains(NewPD, S);
15872   } else
15873     Record->addDecl(NewPD);
15874 
15875   return NewPD;
15876 }
15877