1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for C++ declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ComparisonCategories.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/LiteralSupport.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/CXXFieldCollector.h"
32 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/Initialization.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/ParsedTemplate.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaInternal.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include <map>
44 #include <set>
45 
46 using namespace clang;
47 
48 //===----------------------------------------------------------------------===//
49 // CheckDefaultArgumentVisitor
50 //===----------------------------------------------------------------------===//
51 
52 namespace {
53   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54   /// the default argument of a parameter to determine whether it
55   /// contains any ill-formed subexpressions. For example, this will
56   /// diagnose the use of local variables or parameters within the
57   /// default argument expression.
58   class CheckDefaultArgumentVisitor
59     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
60     Expr *DefaultArg;
61     Sema *S;
62 
63   public:
64     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
65       : DefaultArg(defarg), S(s) {}
66 
67     bool VisitExpr(Expr *Node);
68     bool VisitDeclRefExpr(DeclRefExpr *DRE);
69     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
70     bool VisitLambdaExpr(LambdaExpr *Lambda);
71     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
72   };
73 
74   /// VisitExpr - Visit all of the children of this expression.
75   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76     bool IsInvalid = false;
77     for (Stmt *SubStmt : Node->children())
78       IsInvalid |= Visit(SubStmt);
79     return IsInvalid;
80   }
81 
82   /// VisitDeclRefExpr - Visit a reference to a declaration, to
83   /// determine whether this declaration can be used in the default
84   /// argument expression.
85   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
86     NamedDecl *Decl = DRE->getDecl();
87     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88       // C++ [dcl.fct.default]p9
89       //   Default arguments are evaluated each time the function is
90       //   called. The order of evaluation of function arguments is
91       //   unspecified. Consequently, parameters of a function shall not
92       //   be used in default argument expressions, even if they are not
93       //   evaluated. Parameters of a function declared before a default
94       //   argument expression are in scope and can hide namespace and
95       //   class member names.
96       return S->Diag(DRE->getBeginLoc(),
97                      diag::err_param_default_argument_references_param)
98              << Param->getDeclName() << DefaultArg->getSourceRange();
99     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
100       // C++ [dcl.fct.default]p7
101       //   Local variables shall not be used in default argument
102       //   expressions.
103       if (VDecl->isLocalVarDecl())
104         return S->Diag(DRE->getBeginLoc(),
105                        diag::err_param_default_argument_references_local)
106                << VDecl->getDeclName() << DefaultArg->getSourceRange();
107     }
108 
109     return false;
110   }
111 
112   /// VisitCXXThisExpr - Visit a C++ "this" expression.
113   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114     // C++ [dcl.fct.default]p8:
115     //   The keyword this shall not be used in a default argument of a
116     //   member function.
117     return S->Diag(ThisE->getBeginLoc(),
118                    diag::err_param_default_argument_references_this)
119            << ThisE->getSourceRange();
120   }
121 
122   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123     bool Invalid = false;
124     for (PseudoObjectExpr::semantics_iterator
125            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126       Expr *E = *i;
127 
128       // Look through bindings.
129       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130         E = OVE->getSourceExpr();
131         assert(E && "pseudo-object binding without source expression?");
132       }
133 
134       Invalid |= Visit(E);
135     }
136     return Invalid;
137   }
138 
139   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140     // C++11 [expr.lambda.prim]p13:
141     //   A lambda-expression appearing in a default argument shall not
142     //   implicitly or explicitly capture any entity.
143     if (Lambda->capture_begin() == Lambda->capture_end())
144       return false;
145 
146     return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
147   }
148 }
149 
150 void
151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152                                                  const CXXMethodDecl *Method) {
153   // If we have an MSAny spec already, don't bother.
154   if (!Method || ComputedEST == EST_MSAny)
155     return;
156 
157   const FunctionProtoType *Proto
158     = Method->getType()->getAs<FunctionProtoType>();
159   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160   if (!Proto)
161     return;
162 
163   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164 
165   // If we have a throw-all spec at this point, ignore the function.
166   if (ComputedEST == EST_None)
167     return;
168 
169   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
170     EST = EST_BasicNoexcept;
171 
172   switch (EST) {
173   case EST_Unparsed:
174   case EST_Uninstantiated:
175   case EST_Unevaluated:
176     llvm_unreachable("should not see unresolved exception specs here");
177 
178   // If this function can throw any exceptions, make a note of that.
179   case EST_MSAny:
180   case EST_None:
181     // FIXME: Whichever we see last of MSAny and None determines our result.
182     // We should make a consistent, order-independent choice here.
183     ClearExceptions();
184     ComputedEST = EST;
185     return;
186   case EST_NoexceptFalse:
187     ClearExceptions();
188     ComputedEST = EST_None;
189     return;
190   // FIXME: If the call to this decl is using any of its default arguments, we
191   // need to search them for potentially-throwing calls.
192   // If this function has a basic noexcept, it doesn't affect the outcome.
193   case EST_BasicNoexcept:
194   case EST_NoexceptTrue:
195     return;
196   // If we're still at noexcept(true) and there's a throw() callee,
197   // change to that specification.
198   case EST_DynamicNone:
199     if (ComputedEST == EST_BasicNoexcept)
200       ComputedEST = EST_DynamicNone;
201     return;
202   case EST_DependentNoexcept:
203     llvm_unreachable(
204         "should not generate implicit declarations for dependent cases");
205   case EST_Dynamic:
206     break;
207   }
208   assert(EST == EST_Dynamic && "EST case not considered earlier.");
209   assert(ComputedEST != EST_None &&
210          "Shouldn't collect exceptions when throw-all is guaranteed.");
211   ComputedEST = EST_Dynamic;
212   // Record the exceptions in this function's exception specification.
213   for (const auto &E : Proto->exceptions())
214     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
215       Exceptions.push_back(E);
216 }
217 
218 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
219   if (!E || ComputedEST == EST_MSAny)
220     return;
221 
222   // FIXME:
223   //
224   // C++0x [except.spec]p14:
225   //   [An] implicit exception-specification specifies the type-id T if and
226   // only if T is allowed by the exception-specification of a function directly
227   // invoked by f's implicit definition; f shall allow all exceptions if any
228   // function it directly invokes allows all exceptions, and f shall allow no
229   // exceptions if every function it directly invokes allows no exceptions.
230   //
231   // Note in particular that if an implicit exception-specification is generated
232   // for a function containing a throw-expression, that specification can still
233   // be noexcept(true).
234   //
235   // Note also that 'directly invoked' is not defined in the standard, and there
236   // is no indication that we should only consider potentially-evaluated calls.
237   //
238   // Ultimately we should implement the intent of the standard: the exception
239   // specification should be the set of exceptions which can be thrown by the
240   // implicit definition. For now, we assume that any non-nothrow expression can
241   // throw any exception.
242 
243   if (Self->canThrow(E))
244     ComputedEST = EST_None;
245 }
246 
247 bool
248 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
249                               SourceLocation EqualLoc) {
250   if (RequireCompleteType(Param->getLocation(), Param->getType(),
251                           diag::err_typecheck_decl_incomplete_type)) {
252     Param->setInvalidDecl();
253     return true;
254   }
255 
256   // C++ [dcl.fct.default]p5
257   //   A default argument expression is implicitly converted (clause
258   //   4) to the parameter type. The default argument expression has
259   //   the same semantic constraints as the initializer expression in
260   //   a declaration of a variable of the parameter type, using the
261   //   copy-initialization semantics (8.5).
262   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
263                                                                     Param);
264   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
265                                                            EqualLoc);
266   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
267   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
268   if (Result.isInvalid())
269     return true;
270   Arg = Result.getAs<Expr>();
271 
272   CheckCompletedExpr(Arg, EqualLoc);
273   Arg = MaybeCreateExprWithCleanups(Arg);
274 
275   // Okay: add the default argument to the parameter
276   Param->setDefaultArg(Arg);
277 
278   // We have already instantiated this parameter; provide each of the
279   // instantiations with the uninstantiated default argument.
280   UnparsedDefaultArgInstantiationsMap::iterator InstPos
281     = UnparsedDefaultArgInstantiations.find(Param);
282   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
283     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
284       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
285 
286     // We're done tracking this parameter's instantiations.
287     UnparsedDefaultArgInstantiations.erase(InstPos);
288   }
289 
290   return false;
291 }
292 
293 /// ActOnParamDefaultArgument - Check whether the default argument
294 /// provided for a function parameter is well-formed. If so, attach it
295 /// to the parameter declaration.
296 void
297 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
298                                 Expr *DefaultArg) {
299   if (!param || !DefaultArg)
300     return;
301 
302   ParmVarDecl *Param = cast<ParmVarDecl>(param);
303   UnparsedDefaultArgLocs.erase(Param);
304 
305   // Default arguments are only permitted in C++
306   if (!getLangOpts().CPlusPlus) {
307     Diag(EqualLoc, diag::err_param_default_argument)
308       << DefaultArg->getSourceRange();
309     Param->setInvalidDecl();
310     return;
311   }
312 
313   // Check for unexpanded parameter packs.
314   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
315     Param->setInvalidDecl();
316     return;
317   }
318 
319   // C++11 [dcl.fct.default]p3
320   //   A default argument expression [...] shall not be specified for a
321   //   parameter pack.
322   if (Param->isParameterPack()) {
323     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
324         << DefaultArg->getSourceRange();
325     return;
326   }
327 
328   // Check that the default argument is well-formed
329   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
330   if (DefaultArgChecker.Visit(DefaultArg)) {
331     Param->setInvalidDecl();
332     return;
333   }
334 
335   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
336 }
337 
338 /// ActOnParamUnparsedDefaultArgument - We've seen a default
339 /// argument for a function parameter, but we can't parse it yet
340 /// because we're inside a class definition. Note that this default
341 /// argument will be parsed later.
342 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
343                                              SourceLocation EqualLoc,
344                                              SourceLocation ArgLoc) {
345   if (!param)
346     return;
347 
348   ParmVarDecl *Param = cast<ParmVarDecl>(param);
349   Param->setUnparsedDefaultArg();
350   UnparsedDefaultArgLocs[Param] = ArgLoc;
351 }
352 
353 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
354 /// the default argument for the parameter param failed.
355 void Sema::ActOnParamDefaultArgumentError(Decl *param,
356                                           SourceLocation EqualLoc) {
357   if (!param)
358     return;
359 
360   ParmVarDecl *Param = cast<ParmVarDecl>(param);
361   Param->setInvalidDecl();
362   UnparsedDefaultArgLocs.erase(Param);
363   Param->setDefaultArg(new(Context)
364                        OpaqueValueExpr(EqualLoc,
365                                        Param->getType().getNonReferenceType(),
366                                        VK_RValue));
367 }
368 
369 /// CheckExtraCXXDefaultArguments - Check for any extra default
370 /// arguments in the declarator, which is not a function declaration
371 /// or definition and therefore is not permitted to have default
372 /// arguments. This routine should be invoked for every declarator
373 /// that is not a function declaration or definition.
374 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
375   // C++ [dcl.fct.default]p3
376   //   A default argument expression shall be specified only in the
377   //   parameter-declaration-clause of a function declaration or in a
378   //   template-parameter (14.1). It shall not be specified for a
379   //   parameter pack. If it is specified in a
380   //   parameter-declaration-clause, it shall not occur within a
381   //   declarator or abstract-declarator of a parameter-declaration.
382   bool MightBeFunction = D.isFunctionDeclarationContext();
383   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
384     DeclaratorChunk &chunk = D.getTypeObject(i);
385     if (chunk.Kind == DeclaratorChunk::Function) {
386       if (MightBeFunction) {
387         // This is a function declaration. It can have default arguments, but
388         // keep looking in case its return type is a function type with default
389         // arguments.
390         MightBeFunction = false;
391         continue;
392       }
393       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
394            ++argIdx) {
395         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
396         if (Param->hasUnparsedDefaultArg()) {
397           std::unique_ptr<CachedTokens> Toks =
398               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
399           SourceRange SR;
400           if (Toks->size() > 1)
401             SR = SourceRange((*Toks)[1].getLocation(),
402                              Toks->back().getLocation());
403           else
404             SR = UnparsedDefaultArgLocs[Param];
405           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
406             << SR;
407         } else if (Param->getDefaultArg()) {
408           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
409             << Param->getDefaultArg()->getSourceRange();
410           Param->setDefaultArg(nullptr);
411         }
412       }
413     } else if (chunk.Kind != DeclaratorChunk::Paren) {
414       MightBeFunction = false;
415     }
416   }
417 }
418 
419 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
420   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
421     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
422     if (!PVD->hasDefaultArg())
423       return false;
424     if (!PVD->hasInheritedDefaultArg())
425       return true;
426   }
427   return false;
428 }
429 
430 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
431 /// function, once we already know that they have the same
432 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
433 /// error, false otherwise.
434 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
435                                 Scope *S) {
436   bool Invalid = false;
437 
438   // The declaration context corresponding to the scope is the semantic
439   // parent, unless this is a local function declaration, in which case
440   // it is that surrounding function.
441   DeclContext *ScopeDC = New->isLocalExternDecl()
442                              ? New->getLexicalDeclContext()
443                              : New->getDeclContext();
444 
445   // Find the previous declaration for the purpose of default arguments.
446   FunctionDecl *PrevForDefaultArgs = Old;
447   for (/**/; PrevForDefaultArgs;
448        // Don't bother looking back past the latest decl if this is a local
449        // extern declaration; nothing else could work.
450        PrevForDefaultArgs = New->isLocalExternDecl()
451                                 ? nullptr
452                                 : PrevForDefaultArgs->getPreviousDecl()) {
453     // Ignore hidden declarations.
454     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
455       continue;
456 
457     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
458         !New->isCXXClassMember()) {
459       // Ignore default arguments of old decl if they are not in
460       // the same scope and this is not an out-of-line definition of
461       // a member function.
462       continue;
463     }
464 
465     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
466       // If only one of these is a local function declaration, then they are
467       // declared in different scopes, even though isDeclInScope may think
468       // they're in the same scope. (If both are local, the scope check is
469       // sufficient, and if neither is local, then they are in the same scope.)
470       continue;
471     }
472 
473     // We found the right previous declaration.
474     break;
475   }
476 
477   // C++ [dcl.fct.default]p4:
478   //   For non-template functions, default arguments can be added in
479   //   later declarations of a function in the same
480   //   scope. Declarations in different scopes have completely
481   //   distinct sets of default arguments. That is, declarations in
482   //   inner scopes do not acquire default arguments from
483   //   declarations in outer scopes, and vice versa. In a given
484   //   function declaration, all parameters subsequent to a
485   //   parameter with a default argument shall have default
486   //   arguments supplied in this or previous declarations. A
487   //   default argument shall not be redefined by a later
488   //   declaration (not even to the same value).
489   //
490   // C++ [dcl.fct.default]p6:
491   //   Except for member functions of class templates, the default arguments
492   //   in a member function definition that appears outside of the class
493   //   definition are added to the set of default arguments provided by the
494   //   member function declaration in the class definition.
495   for (unsigned p = 0, NumParams = PrevForDefaultArgs
496                                        ? PrevForDefaultArgs->getNumParams()
497                                        : 0;
498        p < NumParams; ++p) {
499     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
500     ParmVarDecl *NewParam = New->getParamDecl(p);
501 
502     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
503     bool NewParamHasDfl = NewParam->hasDefaultArg();
504 
505     if (OldParamHasDfl && NewParamHasDfl) {
506       unsigned DiagDefaultParamID =
507         diag::err_param_default_argument_redefinition;
508 
509       // MSVC accepts that default parameters be redefined for member functions
510       // of template class. The new default parameter's value is ignored.
511       Invalid = true;
512       if (getLangOpts().MicrosoftExt) {
513         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
514         if (MD && MD->getParent()->getDescribedClassTemplate()) {
515           // Merge the old default argument into the new parameter.
516           NewParam->setHasInheritedDefaultArg();
517           if (OldParam->hasUninstantiatedDefaultArg())
518             NewParam->setUninstantiatedDefaultArg(
519                                       OldParam->getUninstantiatedDefaultArg());
520           else
521             NewParam->setDefaultArg(OldParam->getInit());
522           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
523           Invalid = false;
524         }
525       }
526 
527       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
528       // hint here. Alternatively, we could walk the type-source information
529       // for NewParam to find the last source location in the type... but it
530       // isn't worth the effort right now. This is the kind of test case that
531       // is hard to get right:
532       //   int f(int);
533       //   void g(int (*fp)(int) = f);
534       //   void g(int (*fp)(int) = &f);
535       Diag(NewParam->getLocation(), DiagDefaultParamID)
536         << NewParam->getDefaultArgRange();
537 
538       // Look for the function declaration where the default argument was
539       // actually written, which may be a declaration prior to Old.
540       for (auto Older = PrevForDefaultArgs;
541            OldParam->hasInheritedDefaultArg(); /**/) {
542         Older = Older->getPreviousDecl();
543         OldParam = Older->getParamDecl(p);
544       }
545 
546       Diag(OldParam->getLocation(), diag::note_previous_definition)
547         << OldParam->getDefaultArgRange();
548     } else if (OldParamHasDfl) {
549       // Merge the old default argument into the new parameter unless the new
550       // function is a friend declaration in a template class. In the latter
551       // case the default arguments will be inherited when the friend
552       // declaration will be instantiated.
553       if (New->getFriendObjectKind() == Decl::FOK_None ||
554           !New->getLexicalDeclContext()->isDependentContext()) {
555         // It's important to use getInit() here;  getDefaultArg()
556         // strips off any top-level ExprWithCleanups.
557         NewParam->setHasInheritedDefaultArg();
558         if (OldParam->hasUnparsedDefaultArg())
559           NewParam->setUnparsedDefaultArg();
560         else if (OldParam->hasUninstantiatedDefaultArg())
561           NewParam->setUninstantiatedDefaultArg(
562                                        OldParam->getUninstantiatedDefaultArg());
563         else
564           NewParam->setDefaultArg(OldParam->getInit());
565       }
566     } else if (NewParamHasDfl) {
567       if (New->getDescribedFunctionTemplate()) {
568         // Paragraph 4, quoted above, only applies to non-template functions.
569         Diag(NewParam->getLocation(),
570              diag::err_param_default_argument_template_redecl)
571           << NewParam->getDefaultArgRange();
572         Diag(PrevForDefaultArgs->getLocation(),
573              diag::note_template_prev_declaration)
574             << false;
575       } else if (New->getTemplateSpecializationKind()
576                    != TSK_ImplicitInstantiation &&
577                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
578         // C++ [temp.expr.spec]p21:
579         //   Default function arguments shall not be specified in a declaration
580         //   or a definition for one of the following explicit specializations:
581         //     - the explicit specialization of a function template;
582         //     - the explicit specialization of a member function template;
583         //     - the explicit specialization of a member function of a class
584         //       template where the class template specialization to which the
585         //       member function specialization belongs is implicitly
586         //       instantiated.
587         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
588           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
589           << New->getDeclName()
590           << NewParam->getDefaultArgRange();
591       } else if (New->getDeclContext()->isDependentContext()) {
592         // C++ [dcl.fct.default]p6 (DR217):
593         //   Default arguments for a member function of a class template shall
594         //   be specified on the initial declaration of the member function
595         //   within the class template.
596         //
597         // Reading the tea leaves a bit in DR217 and its reference to DR205
598         // leads me to the conclusion that one cannot add default function
599         // arguments for an out-of-line definition of a member function of a
600         // dependent type.
601         int WhichKind = 2;
602         if (CXXRecordDecl *Record
603               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
604           if (Record->getDescribedClassTemplate())
605             WhichKind = 0;
606           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
607             WhichKind = 1;
608           else
609             WhichKind = 2;
610         }
611 
612         Diag(NewParam->getLocation(),
613              diag::err_param_default_argument_member_template_redecl)
614           << WhichKind
615           << NewParam->getDefaultArgRange();
616       }
617     }
618   }
619 
620   // DR1344: If a default argument is added outside a class definition and that
621   // default argument makes the function a special member function, the program
622   // is ill-formed. This can only happen for constructors.
623   if (isa<CXXConstructorDecl>(New) &&
624       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
625     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
626                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
627     if (NewSM != OldSM) {
628       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
629       assert(NewParam->hasDefaultArg());
630       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
631         << NewParam->getDefaultArgRange() << NewSM;
632       Diag(Old->getLocation(), diag::note_previous_declaration);
633     }
634   }
635 
636   const FunctionDecl *Def;
637   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
638   // template has a constexpr specifier then all its declarations shall
639   // contain the constexpr specifier.
640   if (New->isConstexpr() != Old->isConstexpr()) {
641     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
642       << New << New->isConstexpr();
643     Diag(Old->getLocation(), diag::note_previous_declaration);
644     Invalid = true;
645   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
646              Old->isDefined(Def) &&
647              // If a friend function is inlined but does not have 'inline'
648              // specifier, it is a definition. Do not report attribute conflict
649              // in this case, redefinition will be diagnosed later.
650              (New->isInlineSpecified() ||
651               New->getFriendObjectKind() == Decl::FOK_None)) {
652     // C++11 [dcl.fcn.spec]p4:
653     //   If the definition of a function appears in a translation unit before its
654     //   first declaration as inline, the program is ill-formed.
655     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
656     Diag(Def->getLocation(), diag::note_previous_definition);
657     Invalid = true;
658   }
659 
660   // FIXME: It's not clear what should happen if multiple declarations of a
661   // deduction guide have different explicitness. For now at least we simply
662   // reject any case where the explicitness changes.
663   auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
664   if (NewGuide && NewGuide->isExplicitSpecified() !=
665                       cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
666     Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
667       << NewGuide->isExplicitSpecified();
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++1z [dcl.dcl]/8:
720   //   The decl-specifier-seq shall contain only the type-specifier auto
721   //   and cv-qualifiers.
722   auto &DS = D.getDeclSpec();
723   {
724     SmallVector<StringRef, 8> BadSpecifiers;
725     SmallVector<SourceLocation, 8> BadSpecifierLocs;
726     if (auto SCS = DS.getStorageClassSpec()) {
727       BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
728       BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
729     }
730     if (auto TSCS = DS.getThreadStorageClassSpec()) {
731       BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
732       BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
733     }
734     if (DS.isConstexprSpecified()) {
735       BadSpecifiers.push_back("constexpr");
736       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
737     }
738     if (DS.isInlineSpecified()) {
739       BadSpecifiers.push_back("inline");
740       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
741     }
742     if (!BadSpecifiers.empty()) {
743       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
744       Err << (int)BadSpecifiers.size()
745           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
746       // Don't add FixItHints to remove the specifiers; we do still respect
747       // them when building the underlying variable.
748       for (auto Loc : BadSpecifierLocs)
749         Err << SourceRange(Loc, Loc);
750     }
751     // We can't recover from it being declared as a typedef.
752     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
753       return nullptr;
754   }
755 
756   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
757   QualType R = TInfo->getType();
758 
759   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
760                                       UPPC_DeclarationType))
761     D.setInvalidType();
762 
763   // The syntax only allows a single ref-qualifier prior to the decomposition
764   // declarator. No other declarator chunks are permitted. Also check the type
765   // specifier here.
766   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
767       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
768       (D.getNumTypeObjects() == 1 &&
769        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
770     Diag(Decomp.getLSquareLoc(),
771          (D.hasGroupingParens() ||
772           (D.getNumTypeObjects() &&
773            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
774              ? diag::err_decomp_decl_parens
775              : diag::err_decomp_decl_type)
776         << R;
777 
778     // In most cases, there's no actual problem with an explicitly-specified
779     // type, but a function type won't work here, and ActOnVariableDeclarator
780     // shouldn't be called for such a type.
781     if (R->isFunctionType())
782       D.setInvalidType();
783   }
784 
785   // Build the BindingDecls.
786   SmallVector<BindingDecl*, 8> Bindings;
787 
788   // Build the BindingDecls.
789   for (auto &B : D.getDecompositionDeclarator().bindings()) {
790     // Check for name conflicts.
791     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
792     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
793                           ForVisibleRedeclaration);
794     LookupName(Previous, S,
795                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
796 
797     // It's not permitted to shadow a template parameter name.
798     if (Previous.isSingleResult() &&
799         Previous.getFoundDecl()->isTemplateParameter()) {
800       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
801                                       Previous.getFoundDecl());
802       Previous.clear();
803     }
804 
805     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
806                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
807     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
808                          /*AllowInlineNamespace*/false);
809     if (!Previous.empty()) {
810       auto *Old = Previous.getRepresentativeDecl();
811       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
812       Diag(Old->getLocation(), diag::note_previous_definition);
813     }
814 
815     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
816     PushOnScopeChains(BD, S, true);
817     Bindings.push_back(BD);
818     ParsingInitForAutoVars.insert(BD);
819   }
820 
821   // There are no prior lookup results for the variable itself, because it
822   // is unnamed.
823   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
824                                Decomp.getLSquareLoc());
825   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
826                         ForVisibleRedeclaration);
827 
828   // Build the variable that holds the non-decomposed object.
829   bool AddToScope = true;
830   NamedDecl *New =
831       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
832                               MultiTemplateParamsArg(), AddToScope, Bindings);
833   if (AddToScope) {
834     S->AddDecl(New);
835     CurContext->addHiddenDecl(New);
836   }
837 
838   if (isInOpenMPDeclareTargetContext())
839     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
840 
841   return New;
842 }
843 
844 static bool checkSimpleDecomposition(
845     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
846     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
847     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
848   if ((int64_t)Bindings.size() != NumElems) {
849     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
850         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
851         << (NumElems < Bindings.size());
852     return true;
853   }
854 
855   unsigned I = 0;
856   for (auto *B : Bindings) {
857     SourceLocation Loc = B->getLocation();
858     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
859     if (E.isInvalid())
860       return true;
861     E = GetInit(Loc, E.get(), I++);
862     if (E.isInvalid())
863       return true;
864     B->setBinding(ElemType, E.get());
865   }
866 
867   return false;
868 }
869 
870 static bool checkArrayLikeDecomposition(Sema &S,
871                                         ArrayRef<BindingDecl *> Bindings,
872                                         ValueDecl *Src, QualType DecompType,
873                                         const llvm::APSInt &NumElems,
874                                         QualType ElemType) {
875   return checkSimpleDecomposition(
876       S, Bindings, Src, DecompType, NumElems, ElemType,
877       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
878         ExprResult E = S.ActOnIntegerConstant(Loc, I);
879         if (E.isInvalid())
880           return ExprError();
881         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
882       });
883 }
884 
885 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
886                                     ValueDecl *Src, QualType DecompType,
887                                     const ConstantArrayType *CAT) {
888   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
889                                      llvm::APSInt(CAT->getSize()),
890                                      CAT->getElementType());
891 }
892 
893 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
894                                      ValueDecl *Src, QualType DecompType,
895                                      const VectorType *VT) {
896   return checkArrayLikeDecomposition(
897       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
898       S.Context.getQualifiedType(VT->getElementType(),
899                                  DecompType.getQualifiers()));
900 }
901 
902 static bool checkComplexDecomposition(Sema &S,
903                                       ArrayRef<BindingDecl *> Bindings,
904                                       ValueDecl *Src, QualType DecompType,
905                                       const ComplexType *CT) {
906   return checkSimpleDecomposition(
907       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
908       S.Context.getQualifiedType(CT->getElementType(),
909                                  DecompType.getQualifiers()),
910       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
911         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
912       });
913 }
914 
915 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
916                                      TemplateArgumentListInfo &Args) {
917   SmallString<128> SS;
918   llvm::raw_svector_ostream OS(SS);
919   bool First = true;
920   for (auto &Arg : Args.arguments()) {
921     if (!First)
922       OS << ", ";
923     Arg.getArgument().print(PrintingPolicy, OS);
924     First = false;
925   }
926   return OS.str();
927 }
928 
929 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
930                                      SourceLocation Loc, StringRef Trait,
931                                      TemplateArgumentListInfo &Args,
932                                      unsigned DiagID) {
933   auto DiagnoseMissing = [&] {
934     if (DiagID)
935       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
936                                                Args);
937     return true;
938   };
939 
940   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
941   NamespaceDecl *Std = S.getStdNamespace();
942   if (!Std)
943     return DiagnoseMissing();
944 
945   // Look up the trait itself, within namespace std. We can diagnose various
946   // problems with this lookup even if we've been asked to not diagnose a
947   // missing specialization, because this can only fail if the user has been
948   // declaring their own names in namespace std or we don't support the
949   // standard library implementation in use.
950   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
951                       Loc, Sema::LookupOrdinaryName);
952   if (!S.LookupQualifiedName(Result, Std))
953     return DiagnoseMissing();
954   if (Result.isAmbiguous())
955     return true;
956 
957   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
958   if (!TraitTD) {
959     Result.suppressDiagnostics();
960     NamedDecl *Found = *Result.begin();
961     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
962     S.Diag(Found->getLocation(), diag::note_declared_at);
963     return true;
964   }
965 
966   // Build the template-id.
967   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
968   if (TraitTy.isNull())
969     return true;
970   if (!S.isCompleteType(Loc, TraitTy)) {
971     if (DiagID)
972       S.RequireCompleteType(
973           Loc, TraitTy, DiagID,
974           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
975     return true;
976   }
977 
978   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
979   assert(RD && "specialization of class template is not a class?");
980 
981   // Look up the member of the trait type.
982   S.LookupQualifiedName(TraitMemberLookup, RD);
983   return TraitMemberLookup.isAmbiguous();
984 }
985 
986 static TemplateArgumentLoc
987 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
988                                    uint64_t I) {
989   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
990   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
991 }
992 
993 static TemplateArgumentLoc
994 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
995   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
996 }
997 
998 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
999 
1000 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1001                                llvm::APSInt &Size) {
1002   EnterExpressionEvaluationContext ContextRAII(
1003       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1004 
1005   DeclarationName Value = S.PP.getIdentifierInfo("value");
1006   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1007 
1008   // Form template argument list for tuple_size<T>.
1009   TemplateArgumentListInfo Args(Loc, Loc);
1010   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1011 
1012   // If there's no tuple_size specialization, it's not tuple-like.
1013   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1014     return IsTupleLike::NotTupleLike;
1015 
1016   // If we get this far, we've committed to the tuple interpretation, but
1017   // we can still fail if there actually isn't a usable ::value.
1018 
1019   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1020     LookupResult &R;
1021     TemplateArgumentListInfo &Args;
1022     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1023         : R(R), Args(Args) {}
1024     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1025       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1026           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1027     }
1028   } Diagnoser(R, Args);
1029 
1030   if (R.empty()) {
1031     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1032     return IsTupleLike::Error;
1033   }
1034 
1035   ExprResult E =
1036       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1037   if (E.isInvalid())
1038     return IsTupleLike::Error;
1039 
1040   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1041   if (E.isInvalid())
1042     return IsTupleLike::Error;
1043 
1044   return IsTupleLike::TupleLike;
1045 }
1046 
1047 /// \return std::tuple_element<I, T>::type.
1048 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1049                                         unsigned I, QualType T) {
1050   // Form template argument list for tuple_element<I, T>.
1051   TemplateArgumentListInfo Args(Loc, Loc);
1052   Args.addArgument(
1053       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1054   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1055 
1056   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1057   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1058   if (lookupStdTypeTraitMember(
1059           S, R, Loc, "tuple_element", Args,
1060           diag::err_decomp_decl_std_tuple_element_not_specialized))
1061     return QualType();
1062 
1063   auto *TD = R.getAsSingle<TypeDecl>();
1064   if (!TD) {
1065     R.suppressDiagnostics();
1066     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1067       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1068     if (!R.empty())
1069       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1070     return QualType();
1071   }
1072 
1073   return S.Context.getTypeDeclType(TD);
1074 }
1075 
1076 namespace {
1077 struct BindingDiagnosticTrap {
1078   Sema &S;
1079   DiagnosticErrorTrap Trap;
1080   BindingDecl *BD;
1081 
1082   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1083       : S(S), Trap(S.Diags), BD(BD) {}
1084   ~BindingDiagnosticTrap() {
1085     if (Trap.hasErrorOccurred())
1086       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1087   }
1088 };
1089 }
1090 
1091 static bool checkTupleLikeDecomposition(Sema &S,
1092                                         ArrayRef<BindingDecl *> Bindings,
1093                                         VarDecl *Src, QualType DecompType,
1094                                         const llvm::APSInt &TupleSize) {
1095   if ((int64_t)Bindings.size() != TupleSize) {
1096     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1097         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1098         << (TupleSize < Bindings.size());
1099     return true;
1100   }
1101 
1102   if (Bindings.empty())
1103     return false;
1104 
1105   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1106 
1107   // [dcl.decomp]p3:
1108   //   The unqualified-id get is looked up in the scope of E by class member
1109   //   access lookup ...
1110   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1111   bool UseMemberGet = false;
1112   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1113     if (auto *RD = DecompType->getAsCXXRecordDecl())
1114       S.LookupQualifiedName(MemberGet, RD);
1115     if (MemberGet.isAmbiguous())
1116       return true;
1117     //   ... and if that finds at least one declaration that is a function
1118     //   template whose first template parameter is a non-type parameter ...
1119     for (NamedDecl *D : MemberGet) {
1120       if (FunctionTemplateDecl *FTD =
1121               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1122         TemplateParameterList *TPL = FTD->getTemplateParameters();
1123         if (TPL->size() != 0 &&
1124             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1125           //   ... the initializer is e.get<i>().
1126           UseMemberGet = true;
1127           break;
1128         }
1129       }
1130     }
1131   }
1132 
1133   unsigned I = 0;
1134   for (auto *B : Bindings) {
1135     BindingDiagnosticTrap Trap(S, B);
1136     SourceLocation Loc = B->getLocation();
1137 
1138     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1139     if (E.isInvalid())
1140       return true;
1141 
1142     //   e is an lvalue if the type of the entity is an lvalue reference and
1143     //   an xvalue otherwise
1144     if (!Src->getType()->isLValueReferenceType())
1145       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1146                                    E.get(), nullptr, VK_XValue);
1147 
1148     TemplateArgumentListInfo Args(Loc, Loc);
1149     Args.addArgument(
1150         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1151 
1152     if (UseMemberGet) {
1153       //   if [lookup of member get] finds at least one declaration, the
1154       //   initializer is e.get<i-1>().
1155       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1156                                      CXXScopeSpec(), SourceLocation(), nullptr,
1157                                      MemberGet, &Args, nullptr);
1158       if (E.isInvalid())
1159         return true;
1160 
1161       E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1162     } else {
1163       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1164       //   in the associated namespaces.
1165       Expr *Get = UnresolvedLookupExpr::Create(
1166           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1167           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1168           UnresolvedSetIterator(), UnresolvedSetIterator());
1169 
1170       Expr *Arg = E.get();
1171       E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1172     }
1173     if (E.isInvalid())
1174       return true;
1175     Expr *Init = E.get();
1176 
1177     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1178     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1179     if (T.isNull())
1180       return true;
1181 
1182     //   each vi is a variable of type "reference to T" initialized with the
1183     //   initializer, where the reference is an lvalue reference if the
1184     //   initializer is an lvalue and an rvalue reference otherwise
1185     QualType RefType =
1186         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1187     if (RefType.isNull())
1188       return true;
1189     auto *RefVD = VarDecl::Create(
1190         S.Context, Src->getDeclContext(), Loc, Loc,
1191         B->getDeclName().getAsIdentifierInfo(), RefType,
1192         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1193     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1194     RefVD->setTSCSpec(Src->getTSCSpec());
1195     RefVD->setImplicit();
1196     if (Src->isInlineSpecified())
1197       RefVD->setInlineSpecified();
1198     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1199 
1200     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1201     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1202     InitializationSequence Seq(S, Entity, Kind, Init);
1203     E = Seq.Perform(S, Entity, Kind, Init);
1204     if (E.isInvalid())
1205       return true;
1206     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1207     if (E.isInvalid())
1208       return true;
1209     RefVD->setInit(E.get());
1210     RefVD->checkInitIsICE();
1211 
1212     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1213                                    DeclarationNameInfo(B->getDeclName(), Loc),
1214                                    RefVD);
1215     if (E.isInvalid())
1216       return true;
1217 
1218     B->setBinding(T, E.get());
1219     I++;
1220   }
1221 
1222   return false;
1223 }
1224 
1225 /// Find the base class to decompose in a built-in decomposition of a class type.
1226 /// This base class search is, unfortunately, not quite like any other that we
1227 /// perform anywhere else in C++.
1228 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1229                                                 const CXXRecordDecl *RD,
1230                                                 CXXCastPath &BasePath) {
1231   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1232                           CXXBasePath &Path) {
1233     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1234   };
1235 
1236   const CXXRecordDecl *ClassWithFields = nullptr;
1237   AccessSpecifier AS = AS_public;
1238   if (RD->hasDirectFields())
1239     // [dcl.decomp]p4:
1240     //   Otherwise, all of E's non-static data members shall be public direct
1241     //   members of E ...
1242     ClassWithFields = RD;
1243   else {
1244     //   ... or of ...
1245     CXXBasePaths Paths;
1246     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1247     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1248       // If no classes have fields, just decompose RD itself. (This will work
1249       // if and only if zero bindings were provided.)
1250       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1251     }
1252 
1253     CXXBasePath *BestPath = nullptr;
1254     for (auto &P : Paths) {
1255       if (!BestPath)
1256         BestPath = &P;
1257       else if (!S.Context.hasSameType(P.back().Base->getType(),
1258                                       BestPath->back().Base->getType())) {
1259         //   ... the same ...
1260         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1261           << false << RD << BestPath->back().Base->getType()
1262           << P.back().Base->getType();
1263         return DeclAccessPair();
1264       } else if (P.Access < BestPath->Access) {
1265         BestPath = &P;
1266       }
1267     }
1268 
1269     //   ... unambiguous ...
1270     QualType BaseType = BestPath->back().Base->getType();
1271     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1272       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1273         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1274       return DeclAccessPair();
1275     }
1276 
1277     //   ... [accessible, implied by other rules] base class of E.
1278     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1279                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1280     AS = BestPath->Access;
1281 
1282     ClassWithFields = BaseType->getAsCXXRecordDecl();
1283     S.BuildBasePathArray(Paths, BasePath);
1284   }
1285 
1286   // The above search did not check whether the selected class itself has base
1287   // classes with fields, so check that now.
1288   CXXBasePaths Paths;
1289   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1290     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1291       << (ClassWithFields == RD) << RD << ClassWithFields
1292       << Paths.front().back().Base->getType();
1293     return DeclAccessPair();
1294   }
1295 
1296   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1297 }
1298 
1299 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1300                                      ValueDecl *Src, QualType DecompType,
1301                                      const CXXRecordDecl *OrigRD) {
1302   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1303                             diag::err_incomplete_type))
1304     return true;
1305 
1306   CXXCastPath BasePath;
1307   DeclAccessPair BasePair =
1308       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1309   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1310   if (!RD)
1311     return true;
1312   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1313                                                  DecompType.getQualifiers());
1314 
1315   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1316     unsigned NumFields =
1317         std::count_if(RD->field_begin(), RD->field_end(),
1318                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1319     assert(Bindings.size() != NumFields);
1320     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1321         << DecompType << (unsigned)Bindings.size() << NumFields
1322         << (NumFields < Bindings.size());
1323     return true;
1324   };
1325 
1326   //   all of E's non-static data members shall be [...] well-formed
1327   //   when named as e.name in the context of the structured binding,
1328   //   E shall not have an anonymous union member, ...
1329   unsigned I = 0;
1330   for (auto *FD : RD->fields()) {
1331     if (FD->isUnnamedBitfield())
1332       continue;
1333 
1334     if (FD->isAnonymousStructOrUnion()) {
1335       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1336         << DecompType << FD->getType()->isUnionType();
1337       S.Diag(FD->getLocation(), diag::note_declared_at);
1338       return true;
1339     }
1340 
1341     // We have a real field to bind.
1342     if (I >= Bindings.size())
1343       return DiagnoseBadNumberOfBindings();
1344     auto *B = Bindings[I++];
1345     SourceLocation Loc = B->getLocation();
1346 
1347     // The field must be accessible in the context of the structured binding.
1348     // We already checked that the base class is accessible.
1349     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1350     // const_cast here.
1351     S.CheckStructuredBindingMemberAccess(
1352         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1353         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1354                                      BasePair.getAccess(), FD->getAccess())));
1355 
1356     // Initialize the binding to Src.FD.
1357     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1358     if (E.isInvalid())
1359       return true;
1360     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1361                             VK_LValue, &BasePath);
1362     if (E.isInvalid())
1363       return true;
1364     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1365                                   CXXScopeSpec(), FD,
1366                                   DeclAccessPair::make(FD, FD->getAccess()),
1367                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1368     if (E.isInvalid())
1369       return true;
1370 
1371     // If the type of the member is T, the referenced type is cv T, where cv is
1372     // the cv-qualification of the decomposition expression.
1373     //
1374     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1375     // 'const' to the type of the field.
1376     Qualifiers Q = DecompType.getQualifiers();
1377     if (FD->isMutable())
1378       Q.removeConst();
1379     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1380   }
1381 
1382   if (I != Bindings.size())
1383     return DiagnoseBadNumberOfBindings();
1384 
1385   return false;
1386 }
1387 
1388 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1389   QualType DecompType = DD->getType();
1390 
1391   // If the type of the decomposition is dependent, then so is the type of
1392   // each binding.
1393   if (DecompType->isDependentType()) {
1394     for (auto *B : DD->bindings())
1395       B->setType(Context.DependentTy);
1396     return;
1397   }
1398 
1399   DecompType = DecompType.getNonReferenceType();
1400   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1401 
1402   // C++1z [dcl.decomp]/2:
1403   //   If E is an array type [...]
1404   // As an extension, we also support decomposition of built-in complex and
1405   // vector types.
1406   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1407     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1408       DD->setInvalidDecl();
1409     return;
1410   }
1411   if (auto *VT = DecompType->getAs<VectorType>()) {
1412     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1413       DD->setInvalidDecl();
1414     return;
1415   }
1416   if (auto *CT = DecompType->getAs<ComplexType>()) {
1417     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1418       DD->setInvalidDecl();
1419     return;
1420   }
1421 
1422   // C++1z [dcl.decomp]/3:
1423   //   if the expression std::tuple_size<E>::value is a well-formed integral
1424   //   constant expression, [...]
1425   llvm::APSInt TupleSize(32);
1426   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1427   case IsTupleLike::Error:
1428     DD->setInvalidDecl();
1429     return;
1430 
1431   case IsTupleLike::TupleLike:
1432     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1433       DD->setInvalidDecl();
1434     return;
1435 
1436   case IsTupleLike::NotTupleLike:
1437     break;
1438   }
1439 
1440   // C++1z [dcl.dcl]/8:
1441   //   [E shall be of array or non-union class type]
1442   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1443   if (!RD || RD->isUnion()) {
1444     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1445         << DD << !RD << DecompType;
1446     DD->setInvalidDecl();
1447     return;
1448   }
1449 
1450   // C++1z [dcl.decomp]/4:
1451   //   all of E's non-static data members shall be [...] direct members of
1452   //   E or of the same unambiguous public base class of E, ...
1453   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1454     DD->setInvalidDecl();
1455 }
1456 
1457 /// Merge the exception specifications of two variable declarations.
1458 ///
1459 /// This is called when there's a redeclaration of a VarDecl. The function
1460 /// checks if the redeclaration might have an exception specification and
1461 /// validates compatibility and merges the specs if necessary.
1462 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1463   // Shortcut if exceptions are disabled.
1464   if (!getLangOpts().CXXExceptions)
1465     return;
1466 
1467   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1468          "Should only be called if types are otherwise the same.");
1469 
1470   QualType NewType = New->getType();
1471   QualType OldType = Old->getType();
1472 
1473   // We're only interested in pointers and references to functions, as well
1474   // as pointers to member functions.
1475   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1476     NewType = R->getPointeeType();
1477     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1478   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1479     NewType = P->getPointeeType();
1480     OldType = OldType->getAs<PointerType>()->getPointeeType();
1481   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1482     NewType = M->getPointeeType();
1483     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1484   }
1485 
1486   if (!NewType->isFunctionProtoType())
1487     return;
1488 
1489   // There's lots of special cases for functions. For function pointers, system
1490   // libraries are hopefully not as broken so that we don't need these
1491   // workarounds.
1492   if (CheckEquivalentExceptionSpec(
1493         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1494         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1495     New->setInvalidDecl();
1496   }
1497 }
1498 
1499 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1500 /// function declaration are well-formed according to C++
1501 /// [dcl.fct.default].
1502 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1503   unsigned NumParams = FD->getNumParams();
1504   unsigned p;
1505 
1506   // Find first parameter with a default argument
1507   for (p = 0; p < NumParams; ++p) {
1508     ParmVarDecl *Param = FD->getParamDecl(p);
1509     if (Param->hasDefaultArg())
1510       break;
1511   }
1512 
1513   // C++11 [dcl.fct.default]p4:
1514   //   In a given function declaration, each parameter subsequent to a parameter
1515   //   with a default argument shall have a default argument supplied in this or
1516   //   a previous declaration or shall be a function parameter pack. A default
1517   //   argument shall not be redefined by a later declaration (not even to the
1518   //   same value).
1519   unsigned LastMissingDefaultArg = 0;
1520   for (; p < NumParams; ++p) {
1521     ParmVarDecl *Param = FD->getParamDecl(p);
1522     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1523       if (Param->isInvalidDecl())
1524         /* We already complained about this parameter. */;
1525       else if (Param->getIdentifier())
1526         Diag(Param->getLocation(),
1527              diag::err_param_default_argument_missing_name)
1528           << Param->getIdentifier();
1529       else
1530         Diag(Param->getLocation(),
1531              diag::err_param_default_argument_missing);
1532 
1533       LastMissingDefaultArg = p;
1534     }
1535   }
1536 
1537   if (LastMissingDefaultArg > 0) {
1538     // Some default arguments were missing. Clear out all of the
1539     // default arguments up to (and including) the last missing
1540     // default argument, so that we leave the function parameters
1541     // in a semantically valid state.
1542     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1543       ParmVarDecl *Param = FD->getParamDecl(p);
1544       if (Param->hasDefaultArg()) {
1545         Param->setDefaultArg(nullptr);
1546       }
1547     }
1548   }
1549 }
1550 
1551 // CheckConstexprParameterTypes - Check whether a function's parameter types
1552 // are all literal types. If so, return true. If not, produce a suitable
1553 // diagnostic and return false.
1554 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1555                                          const FunctionDecl *FD) {
1556   unsigned ArgIndex = 0;
1557   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1558   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1559                                               e = FT->param_type_end();
1560        i != e; ++i, ++ArgIndex) {
1561     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1562     SourceLocation ParamLoc = PD->getLocation();
1563     if (!(*i)->isDependentType() &&
1564         SemaRef.RequireLiteralType(ParamLoc, *i,
1565                                    diag::err_constexpr_non_literal_param,
1566                                    ArgIndex+1, PD->getSourceRange(),
1567                                    isa<CXXConstructorDecl>(FD)))
1568       return false;
1569   }
1570   return true;
1571 }
1572 
1573 /// Get diagnostic %select index for tag kind for
1574 /// record diagnostic message.
1575 /// WARNING: Indexes apply to particular diagnostics only!
1576 ///
1577 /// \returns diagnostic %select index.
1578 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1579   switch (Tag) {
1580   case TTK_Struct: return 0;
1581   case TTK_Interface: return 1;
1582   case TTK_Class:  return 2;
1583   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1584   }
1585 }
1586 
1587 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1588 // the requirements of a constexpr function definition or a constexpr
1589 // constructor definition. If so, return true. If not, produce appropriate
1590 // diagnostics and return false.
1591 //
1592 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1593 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1594   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1595   if (MD && MD->isInstance()) {
1596     // C++11 [dcl.constexpr]p4:
1597     //  The definition of a constexpr constructor shall satisfy the following
1598     //  constraints:
1599     //  - the class shall not have any virtual base classes;
1600     const CXXRecordDecl *RD = MD->getParent();
1601     if (RD->getNumVBases()) {
1602       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1603         << isa<CXXConstructorDecl>(NewFD)
1604         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1605       for (const auto &I : RD->vbases())
1606         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1607             << I.getSourceRange();
1608       return false;
1609     }
1610   }
1611 
1612   if (!isa<CXXConstructorDecl>(NewFD)) {
1613     // C++11 [dcl.constexpr]p3:
1614     //  The definition of a constexpr function shall satisfy the following
1615     //  constraints:
1616     // - it shall not be virtual;
1617     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1618     if (Method && Method->isVirtual()) {
1619       Method = Method->getCanonicalDecl();
1620       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1621 
1622       // If it's not obvious why this function is virtual, find an overridden
1623       // function which uses the 'virtual' keyword.
1624       const CXXMethodDecl *WrittenVirtual = Method;
1625       while (!WrittenVirtual->isVirtualAsWritten())
1626         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1627       if (WrittenVirtual != Method)
1628         Diag(WrittenVirtual->getLocation(),
1629              diag::note_overridden_virtual_function);
1630       return false;
1631     }
1632 
1633     // - its return type shall be a literal type;
1634     QualType RT = NewFD->getReturnType();
1635     if (!RT->isDependentType() &&
1636         RequireLiteralType(NewFD->getLocation(), RT,
1637                            diag::err_constexpr_non_literal_return))
1638       return false;
1639   }
1640 
1641   // - each of its parameter types shall be a literal type;
1642   if (!CheckConstexprParameterTypes(*this, NewFD))
1643     return false;
1644 
1645   return true;
1646 }
1647 
1648 /// Check the given declaration statement is legal within a constexpr function
1649 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1650 ///
1651 /// \return true if the body is OK (maybe only as an extension), false if we
1652 ///         have diagnosed a problem.
1653 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1654                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1655   // C++11 [dcl.constexpr]p3 and p4:
1656   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1657   //  contain only
1658   for (const auto *DclIt : DS->decls()) {
1659     switch (DclIt->getKind()) {
1660     case Decl::StaticAssert:
1661     case Decl::Using:
1662     case Decl::UsingShadow:
1663     case Decl::UsingDirective:
1664     case Decl::UnresolvedUsingTypename:
1665     case Decl::UnresolvedUsingValue:
1666       //   - static_assert-declarations
1667       //   - using-declarations,
1668       //   - using-directives,
1669       continue;
1670 
1671     case Decl::Typedef:
1672     case Decl::TypeAlias: {
1673       //   - typedef declarations and alias-declarations that do not define
1674       //     classes or enumerations,
1675       const auto *TN = cast<TypedefNameDecl>(DclIt);
1676       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1677         // Don't allow variably-modified types in constexpr functions.
1678         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1679         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1680           << TL.getSourceRange() << TL.getType()
1681           << isa<CXXConstructorDecl>(Dcl);
1682         return false;
1683       }
1684       continue;
1685     }
1686 
1687     case Decl::Enum:
1688     case Decl::CXXRecord:
1689       // C++1y allows types to be defined, not just declared.
1690       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1691         SemaRef.Diag(DS->getBeginLoc(),
1692                      SemaRef.getLangOpts().CPlusPlus14
1693                          ? diag::warn_cxx11_compat_constexpr_type_definition
1694                          : diag::ext_constexpr_type_definition)
1695             << isa<CXXConstructorDecl>(Dcl);
1696       continue;
1697 
1698     case Decl::EnumConstant:
1699     case Decl::IndirectField:
1700     case Decl::ParmVar:
1701       // These can only appear with other declarations which are banned in
1702       // C++11 and permitted in C++1y, so ignore them.
1703       continue;
1704 
1705     case Decl::Var:
1706     case Decl::Decomposition: {
1707       // C++1y [dcl.constexpr]p3 allows anything except:
1708       //   a definition of a variable of non-literal type or of static or
1709       //   thread storage duration or for which no initialization is performed.
1710       const auto *VD = cast<VarDecl>(DclIt);
1711       if (VD->isThisDeclarationADefinition()) {
1712         if (VD->isStaticLocal()) {
1713           SemaRef.Diag(VD->getLocation(),
1714                        diag::err_constexpr_local_var_static)
1715             << isa<CXXConstructorDecl>(Dcl)
1716             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1717           return false;
1718         }
1719         if (!VD->getType()->isDependentType() &&
1720             SemaRef.RequireLiteralType(
1721               VD->getLocation(), VD->getType(),
1722               diag::err_constexpr_local_var_non_literal_type,
1723               isa<CXXConstructorDecl>(Dcl)))
1724           return false;
1725         if (!VD->getType()->isDependentType() &&
1726             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1727           SemaRef.Diag(VD->getLocation(),
1728                        diag::err_constexpr_local_var_no_init)
1729             << isa<CXXConstructorDecl>(Dcl);
1730           return false;
1731         }
1732       }
1733       SemaRef.Diag(VD->getLocation(),
1734                    SemaRef.getLangOpts().CPlusPlus14
1735                     ? diag::warn_cxx11_compat_constexpr_local_var
1736                     : diag::ext_constexpr_local_var)
1737         << isa<CXXConstructorDecl>(Dcl);
1738       continue;
1739     }
1740 
1741     case Decl::NamespaceAlias:
1742     case Decl::Function:
1743       // These are disallowed in C++11 and permitted in C++1y. Allow them
1744       // everywhere as an extension.
1745       if (!Cxx1yLoc.isValid())
1746         Cxx1yLoc = DS->getBeginLoc();
1747       continue;
1748 
1749     default:
1750       SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1751           << isa<CXXConstructorDecl>(Dcl);
1752       return false;
1753     }
1754   }
1755 
1756   return true;
1757 }
1758 
1759 /// Check that the given field is initialized within a constexpr constructor.
1760 ///
1761 /// \param Dcl The constexpr constructor being checked.
1762 /// \param Field The field being checked. This may be a member of an anonymous
1763 ///        struct or union nested within the class being checked.
1764 /// \param Inits All declarations, including anonymous struct/union members and
1765 ///        indirect members, for which any initialization was provided.
1766 /// \param Diagnosed Set to true if an error is produced.
1767 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1768                                           const FunctionDecl *Dcl,
1769                                           FieldDecl *Field,
1770                                           llvm::SmallSet<Decl*, 16> &Inits,
1771                                           bool &Diagnosed) {
1772   if (Field->isInvalidDecl())
1773     return;
1774 
1775   if (Field->isUnnamedBitfield())
1776     return;
1777 
1778   // Anonymous unions with no variant members and empty anonymous structs do not
1779   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1780   // indirect fields don't need initializing.
1781   if (Field->isAnonymousStructOrUnion() &&
1782       (Field->getType()->isUnionType()
1783            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1784            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1785     return;
1786 
1787   if (!Inits.count(Field)) {
1788     if (!Diagnosed) {
1789       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1790       Diagnosed = true;
1791     }
1792     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1793   } else if (Field->isAnonymousStructOrUnion()) {
1794     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1795     for (auto *I : RD->fields())
1796       // If an anonymous union contains an anonymous struct of which any member
1797       // is initialized, all members must be initialized.
1798       if (!RD->isUnion() || Inits.count(I))
1799         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1800   }
1801 }
1802 
1803 /// Check the provided statement is allowed in a constexpr function
1804 /// definition.
1805 static bool
1806 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1807                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1808                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc) {
1809   // - its function-body shall be [...] a compound-statement that contains only
1810   switch (S->getStmtClass()) {
1811   case Stmt::NullStmtClass:
1812     //   - null statements,
1813     return true;
1814 
1815   case Stmt::DeclStmtClass:
1816     //   - static_assert-declarations
1817     //   - using-declarations,
1818     //   - using-directives,
1819     //   - typedef declarations and alias-declarations that do not define
1820     //     classes or enumerations,
1821     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1822       return false;
1823     return true;
1824 
1825   case Stmt::ReturnStmtClass:
1826     //   - and exactly one return statement;
1827     if (isa<CXXConstructorDecl>(Dcl)) {
1828       // C++1y allows return statements in constexpr constructors.
1829       if (!Cxx1yLoc.isValid())
1830         Cxx1yLoc = S->getBeginLoc();
1831       return true;
1832     }
1833 
1834     ReturnStmts.push_back(S->getBeginLoc());
1835     return true;
1836 
1837   case Stmt::CompoundStmtClass: {
1838     // C++1y allows compound-statements.
1839     if (!Cxx1yLoc.isValid())
1840       Cxx1yLoc = S->getBeginLoc();
1841 
1842     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1843     for (auto *BodyIt : CompStmt->body()) {
1844       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1845                                       Cxx1yLoc, Cxx2aLoc))
1846         return false;
1847     }
1848     return true;
1849   }
1850 
1851   case Stmt::AttributedStmtClass:
1852     if (!Cxx1yLoc.isValid())
1853       Cxx1yLoc = S->getBeginLoc();
1854     return true;
1855 
1856   case Stmt::IfStmtClass: {
1857     // C++1y allows if-statements.
1858     if (!Cxx1yLoc.isValid())
1859       Cxx1yLoc = S->getBeginLoc();
1860 
1861     IfStmt *If = cast<IfStmt>(S);
1862     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1863                                     Cxx1yLoc, Cxx2aLoc))
1864       return false;
1865     if (If->getElse() &&
1866         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1867                                     Cxx1yLoc, Cxx2aLoc))
1868       return false;
1869     return true;
1870   }
1871 
1872   case Stmt::WhileStmtClass:
1873   case Stmt::DoStmtClass:
1874   case Stmt::ForStmtClass:
1875   case Stmt::CXXForRangeStmtClass:
1876   case Stmt::ContinueStmtClass:
1877     // C++1y allows all of these. We don't allow them as extensions in C++11,
1878     // because they don't make sense without variable mutation.
1879     if (!SemaRef.getLangOpts().CPlusPlus14)
1880       break;
1881     if (!Cxx1yLoc.isValid())
1882       Cxx1yLoc = S->getBeginLoc();
1883     for (Stmt *SubStmt : S->children())
1884       if (SubStmt &&
1885           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1886                                       Cxx1yLoc, Cxx2aLoc))
1887         return false;
1888     return true;
1889 
1890   case Stmt::SwitchStmtClass:
1891   case Stmt::CaseStmtClass:
1892   case Stmt::DefaultStmtClass:
1893   case Stmt::BreakStmtClass:
1894     // C++1y allows switch-statements, and since they don't need variable
1895     // mutation, we can reasonably allow them in C++11 as an extension.
1896     if (!Cxx1yLoc.isValid())
1897       Cxx1yLoc = S->getBeginLoc();
1898     for (Stmt *SubStmt : S->children())
1899       if (SubStmt &&
1900           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1901                                       Cxx1yLoc, Cxx2aLoc))
1902         return false;
1903     return true;
1904 
1905   case Stmt::CXXTryStmtClass:
1906     if (Cxx2aLoc.isInvalid())
1907       Cxx2aLoc = S->getBeginLoc();
1908     for (Stmt *SubStmt : S->children()) {
1909       if (SubStmt &&
1910           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1911                                       Cxx1yLoc, Cxx2aLoc))
1912         return false;
1913     }
1914     return true;
1915 
1916   case Stmt::CXXCatchStmtClass:
1917     // Do not bother checking the language mode (already covered by the
1918     // try block check).
1919     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
1920                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
1921                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc))
1922       return false;
1923     return true;
1924 
1925   default:
1926     if (!isa<Expr>(S))
1927       break;
1928 
1929     // C++1y allows expression-statements.
1930     if (!Cxx1yLoc.isValid())
1931       Cxx1yLoc = S->getBeginLoc();
1932     return true;
1933   }
1934 
1935   SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1936       << isa<CXXConstructorDecl>(Dcl);
1937   return false;
1938 }
1939 
1940 /// Check the body for the given constexpr function declaration only contains
1941 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1942 ///
1943 /// \return true if the body is OK, false if we have diagnosed a problem.
1944 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1945   SmallVector<SourceLocation, 4> ReturnStmts;
1946 
1947   if (isa<CXXTryStmt>(Body)) {
1948     // C++11 [dcl.constexpr]p3:
1949     //  The definition of a constexpr function shall satisfy the following
1950     //  constraints: [...]
1951     // - its function-body shall be = delete, = default, or a
1952     //   compound-statement
1953     //
1954     // C++11 [dcl.constexpr]p4:
1955     //  In the definition of a constexpr constructor, [...]
1956     // - its function-body shall not be a function-try-block;
1957     //
1958     // This restriction is lifted in C++2a, as long as inner statements also
1959     // apply the general constexpr rules.
1960     Diag(Body->getBeginLoc(),
1961          !getLangOpts().CPlusPlus2a
1962              ? diag::ext_constexpr_function_try_block_cxx2a
1963              : diag::warn_cxx17_compat_constexpr_function_try_block)
1964         << isa<CXXConstructorDecl>(Dcl);
1965   }
1966 
1967   // - its function-body shall be [...] a compound-statement that contains only
1968   //   [... list of cases ...]
1969   //
1970   // Note that walking the children here is enough to properly check for
1971   // CompoundStmt and CXXTryStmt body.
1972   SourceLocation Cxx1yLoc, Cxx2aLoc;
1973   for (Stmt *SubStmt : Body->children()) {
1974     if (SubStmt &&
1975         !CheckConstexprFunctionStmt(*this, Dcl, SubStmt, ReturnStmts,
1976                                     Cxx1yLoc, Cxx2aLoc))
1977       return false;
1978   }
1979 
1980   if (Cxx2aLoc.isValid())
1981     Diag(Cxx2aLoc,
1982          getLangOpts().CPlusPlus2a
1983            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
1984            : diag::ext_constexpr_body_invalid_stmt_cxx2a)
1985       << isa<CXXConstructorDecl>(Dcl);
1986   if (Cxx1yLoc.isValid())
1987     Diag(Cxx1yLoc,
1988          getLangOpts().CPlusPlus14
1989            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1990            : diag::ext_constexpr_body_invalid_stmt)
1991       << isa<CXXConstructorDecl>(Dcl);
1992 
1993   if (const CXXConstructorDecl *Constructor
1994         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1995     const CXXRecordDecl *RD = Constructor->getParent();
1996     // DR1359:
1997     // - every non-variant non-static data member and base class sub-object
1998     //   shall be initialized;
1999     // DR1460:
2000     // - if the class is a union having variant members, exactly one of them
2001     //   shall be initialized;
2002     if (RD->isUnion()) {
2003       if (Constructor->getNumCtorInitializers() == 0 &&
2004           RD->hasVariantMembers()) {
2005         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
2006         return false;
2007       }
2008     } else if (!Constructor->isDependentContext() &&
2009                !Constructor->isDelegatingConstructor()) {
2010       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2011 
2012       // Skip detailed checking if we have enough initializers, and we would
2013       // allow at most one initializer per member.
2014       bool AnyAnonStructUnionMembers = false;
2015       unsigned Fields = 0;
2016       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2017            E = RD->field_end(); I != E; ++I, ++Fields) {
2018         if (I->isAnonymousStructOrUnion()) {
2019           AnyAnonStructUnionMembers = true;
2020           break;
2021         }
2022       }
2023       // DR1460:
2024       // - if the class is a union-like class, but is not a union, for each of
2025       //   its anonymous union members having variant members, exactly one of
2026       //   them shall be initialized;
2027       if (AnyAnonStructUnionMembers ||
2028           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2029         // Check initialization of non-static data members. Base classes are
2030         // always initialized so do not need to be checked. Dependent bases
2031         // might not have initializers in the member initializer list.
2032         llvm::SmallSet<Decl*, 16> Inits;
2033         for (const auto *I: Constructor->inits()) {
2034           if (FieldDecl *FD = I->getMember())
2035             Inits.insert(FD);
2036           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2037             Inits.insert(ID->chain_begin(), ID->chain_end());
2038         }
2039 
2040         bool Diagnosed = false;
2041         for (auto *I : RD->fields())
2042           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2043         if (Diagnosed)
2044           return false;
2045       }
2046     }
2047   } else {
2048     if (ReturnStmts.empty()) {
2049       // C++1y doesn't require constexpr functions to contain a 'return'
2050       // statement. We still do, unless the return type might be void, because
2051       // otherwise if there's no return statement, the function cannot
2052       // be used in a core constant expression.
2053       bool OK = getLangOpts().CPlusPlus14 &&
2054                 (Dcl->getReturnType()->isVoidType() ||
2055                  Dcl->getReturnType()->isDependentType());
2056       Diag(Dcl->getLocation(),
2057            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2058               : diag::err_constexpr_body_no_return);
2059       if (!OK)
2060         return false;
2061     } else if (ReturnStmts.size() > 1) {
2062       Diag(ReturnStmts.back(),
2063            getLangOpts().CPlusPlus14
2064              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2065              : diag::ext_constexpr_body_multiple_return);
2066       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2067         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2068     }
2069   }
2070 
2071   // C++11 [dcl.constexpr]p5:
2072   //   if no function argument values exist such that the function invocation
2073   //   substitution would produce a constant expression, the program is
2074   //   ill-formed; no diagnostic required.
2075   // C++11 [dcl.constexpr]p3:
2076   //   - every constructor call and implicit conversion used in initializing the
2077   //     return value shall be one of those allowed in a constant expression.
2078   // C++11 [dcl.constexpr]p4:
2079   //   - every constructor involved in initializing non-static data members and
2080   //     base class sub-objects shall be a constexpr constructor.
2081   SmallVector<PartialDiagnosticAt, 8> Diags;
2082   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2083     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2084       << isa<CXXConstructorDecl>(Dcl);
2085     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2086       Diag(Diags[I].first, Diags[I].second);
2087     // Don't return false here: we allow this for compatibility in
2088     // system headers.
2089   }
2090 
2091   return true;
2092 }
2093 
2094 /// Get the class that is directly named by the current context. This is the
2095 /// class for which an unqualified-id in this scope could name a constructor
2096 /// or destructor.
2097 ///
2098 /// If the scope specifier denotes a class, this will be that class.
2099 /// If the scope specifier is empty, this will be the class whose
2100 /// member-specification we are currently within. Otherwise, there
2101 /// is no such class.
2102 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2103   assert(getLangOpts().CPlusPlus && "No class names in C!");
2104 
2105   if (SS && SS->isInvalid())
2106     return nullptr;
2107 
2108   if (SS && SS->isNotEmpty()) {
2109     DeclContext *DC = computeDeclContext(*SS, true);
2110     return dyn_cast_or_null<CXXRecordDecl>(DC);
2111   }
2112 
2113   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2114 }
2115 
2116 /// isCurrentClassName - Determine whether the identifier II is the
2117 /// name of the class type currently being defined. In the case of
2118 /// nested classes, this will only return true if II is the name of
2119 /// the innermost class.
2120 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2121                               const CXXScopeSpec *SS) {
2122   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2123   return CurDecl && &II == CurDecl->getIdentifier();
2124 }
2125 
2126 /// Determine whether the identifier II is a typo for the name of
2127 /// the class type currently being defined. If so, update it to the identifier
2128 /// that should have been used.
2129 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2130   assert(getLangOpts().CPlusPlus && "No class names in C!");
2131 
2132   if (!getLangOpts().SpellChecking)
2133     return false;
2134 
2135   CXXRecordDecl *CurDecl;
2136   if (SS && SS->isSet() && !SS->isInvalid()) {
2137     DeclContext *DC = computeDeclContext(*SS, true);
2138     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2139   } else
2140     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2141 
2142   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2143       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2144           < II->getLength()) {
2145     II = CurDecl->getIdentifier();
2146     return true;
2147   }
2148 
2149   return false;
2150 }
2151 
2152 /// Determine whether the given class is a base class of the given
2153 /// class, including looking at dependent bases.
2154 static bool findCircularInheritance(const CXXRecordDecl *Class,
2155                                     const CXXRecordDecl *Current) {
2156   SmallVector<const CXXRecordDecl*, 8> Queue;
2157 
2158   Class = Class->getCanonicalDecl();
2159   while (true) {
2160     for (const auto &I : Current->bases()) {
2161       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2162       if (!Base)
2163         continue;
2164 
2165       Base = Base->getDefinition();
2166       if (!Base)
2167         continue;
2168 
2169       if (Base->getCanonicalDecl() == Class)
2170         return true;
2171 
2172       Queue.push_back(Base);
2173     }
2174 
2175     if (Queue.empty())
2176       return false;
2177 
2178     Current = Queue.pop_back_val();
2179   }
2180 
2181   return false;
2182 }
2183 
2184 /// Check the validity of a C++ base class specifier.
2185 ///
2186 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2187 /// and returns NULL otherwise.
2188 CXXBaseSpecifier *
2189 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2190                          SourceRange SpecifierRange,
2191                          bool Virtual, AccessSpecifier Access,
2192                          TypeSourceInfo *TInfo,
2193                          SourceLocation EllipsisLoc) {
2194   QualType BaseType = TInfo->getType();
2195 
2196   // C++ [class.union]p1:
2197   //   A union shall not have base classes.
2198   if (Class->isUnion()) {
2199     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2200       << SpecifierRange;
2201     return nullptr;
2202   }
2203 
2204   if (EllipsisLoc.isValid() &&
2205       !TInfo->getType()->containsUnexpandedParameterPack()) {
2206     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2207       << TInfo->getTypeLoc().getSourceRange();
2208     EllipsisLoc = SourceLocation();
2209   }
2210 
2211   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2212 
2213   if (BaseType->isDependentType()) {
2214     // Make sure that we don't have circular inheritance among our dependent
2215     // bases. For non-dependent bases, the check for completeness below handles
2216     // this.
2217     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2218       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2219           ((BaseDecl = BaseDecl->getDefinition()) &&
2220            findCircularInheritance(Class, BaseDecl))) {
2221         Diag(BaseLoc, diag::err_circular_inheritance)
2222           << BaseType << Context.getTypeDeclType(Class);
2223 
2224         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2225           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2226             << BaseType;
2227 
2228         return nullptr;
2229       }
2230     }
2231 
2232     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2233                                           Class->getTagKind() == TTK_Class,
2234                                           Access, TInfo, EllipsisLoc);
2235   }
2236 
2237   // Base specifiers must be record types.
2238   if (!BaseType->isRecordType()) {
2239     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2240     return nullptr;
2241   }
2242 
2243   // C++ [class.union]p1:
2244   //   A union shall not be used as a base class.
2245   if (BaseType->isUnionType()) {
2246     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2247     return nullptr;
2248   }
2249 
2250   // For the MS ABI, propagate DLL attributes to base class templates.
2251   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2252     if (Attr *ClassAttr = getDLLAttr(Class)) {
2253       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2254               BaseType->getAsCXXRecordDecl())) {
2255         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2256                                             BaseLoc);
2257       }
2258     }
2259   }
2260 
2261   // C++ [class.derived]p2:
2262   //   The class-name in a base-specifier shall not be an incompletely
2263   //   defined class.
2264   if (RequireCompleteType(BaseLoc, BaseType,
2265                           diag::err_incomplete_base_class, SpecifierRange)) {
2266     Class->setInvalidDecl();
2267     return nullptr;
2268   }
2269 
2270   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2271   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2272   assert(BaseDecl && "Record type has no declaration");
2273   BaseDecl = BaseDecl->getDefinition();
2274   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2275   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2276   assert(CXXBaseDecl && "Base type is not a C++ type");
2277 
2278   // Microsoft docs say:
2279   // "If a base-class has a code_seg attribute, derived classes must have the
2280   // same attribute."
2281   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2282   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2283   if ((DerivedCSA || BaseCSA) &&
2284       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2285     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2286     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2287       << CXXBaseDecl;
2288     return nullptr;
2289   }
2290 
2291   // A class which contains a flexible array member is not suitable for use as a
2292   // base class:
2293   //   - If the layout determines that a base comes before another base,
2294   //     the flexible array member would index into the subsequent base.
2295   //   - If the layout determines that base comes before the derived class,
2296   //     the flexible array member would index into the derived class.
2297   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2298     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2299       << CXXBaseDecl->getDeclName();
2300     return nullptr;
2301   }
2302 
2303   // C++ [class]p3:
2304   //   If a class is marked final and it appears as a base-type-specifier in
2305   //   base-clause, the program is ill-formed.
2306   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2307     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2308       << CXXBaseDecl->getDeclName()
2309       << FA->isSpelledAsSealed();
2310     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2311         << CXXBaseDecl->getDeclName() << FA->getRange();
2312     return nullptr;
2313   }
2314 
2315   if (BaseDecl->isInvalidDecl())
2316     Class->setInvalidDecl();
2317 
2318   // Create the base specifier.
2319   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2320                                         Class->getTagKind() == TTK_Class,
2321                                         Access, TInfo, EllipsisLoc);
2322 }
2323 
2324 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2325 /// one entry in the base class list of a class specifier, for
2326 /// example:
2327 ///    class foo : public bar, virtual private baz {
2328 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2329 BaseResult
2330 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2331                          ParsedAttributes &Attributes,
2332                          bool Virtual, AccessSpecifier Access,
2333                          ParsedType basetype, SourceLocation BaseLoc,
2334                          SourceLocation EllipsisLoc) {
2335   if (!classdecl)
2336     return true;
2337 
2338   AdjustDeclIfTemplate(classdecl);
2339   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2340   if (!Class)
2341     return true;
2342 
2343   // We haven't yet attached the base specifiers.
2344   Class->setIsParsingBaseSpecifiers();
2345 
2346   // We do not support any C++11 attributes on base-specifiers yet.
2347   // Diagnose any attributes we see.
2348   for (const ParsedAttr &AL : Attributes) {
2349     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2350       continue;
2351     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2352                           ? (unsigned)diag::warn_unknown_attribute_ignored
2353                           : (unsigned)diag::err_base_specifier_attribute)
2354         << AL.getName();
2355   }
2356 
2357   TypeSourceInfo *TInfo = nullptr;
2358   GetTypeFromParser(basetype, &TInfo);
2359 
2360   if (EllipsisLoc.isInvalid() &&
2361       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2362                                       UPPC_BaseType))
2363     return true;
2364 
2365   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2366                                                       Virtual, Access, TInfo,
2367                                                       EllipsisLoc))
2368     return BaseSpec;
2369   else
2370     Class->setInvalidDecl();
2371 
2372   return true;
2373 }
2374 
2375 /// Use small set to collect indirect bases.  As this is only used
2376 /// locally, there's no need to abstract the small size parameter.
2377 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2378 
2379 /// Recursively add the bases of Type.  Don't add Type itself.
2380 static void
2381 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2382                   const QualType &Type)
2383 {
2384   // Even though the incoming type is a base, it might not be
2385   // a class -- it could be a template parm, for instance.
2386   if (auto Rec = Type->getAs<RecordType>()) {
2387     auto Decl = Rec->getAsCXXRecordDecl();
2388 
2389     // Iterate over its bases.
2390     for (const auto &BaseSpec : Decl->bases()) {
2391       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2392         .getUnqualifiedType();
2393       if (Set.insert(Base).second)
2394         // If we've not already seen it, recurse.
2395         NoteIndirectBases(Context, Set, Base);
2396     }
2397   }
2398 }
2399 
2400 /// Performs the actual work of attaching the given base class
2401 /// specifiers to a C++ class.
2402 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2403                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2404  if (Bases.empty())
2405     return false;
2406 
2407   // Used to keep track of which base types we have already seen, so
2408   // that we can properly diagnose redundant direct base types. Note
2409   // that the key is always the unqualified canonical type of the base
2410   // class.
2411   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2412 
2413   // Used to track indirect bases so we can see if a direct base is
2414   // ambiguous.
2415   IndirectBaseSet IndirectBaseTypes;
2416 
2417   // Copy non-redundant base specifiers into permanent storage.
2418   unsigned NumGoodBases = 0;
2419   bool Invalid = false;
2420   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2421     QualType NewBaseType
2422       = Context.getCanonicalType(Bases[idx]->getType());
2423     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2424 
2425     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2426     if (KnownBase) {
2427       // C++ [class.mi]p3:
2428       //   A class shall not be specified as a direct base class of a
2429       //   derived class more than once.
2430       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2431           << KnownBase->getType() << Bases[idx]->getSourceRange();
2432 
2433       // Delete the duplicate base class specifier; we're going to
2434       // overwrite its pointer later.
2435       Context.Deallocate(Bases[idx]);
2436 
2437       Invalid = true;
2438     } else {
2439       // Okay, add this new base class.
2440       KnownBase = Bases[idx];
2441       Bases[NumGoodBases++] = Bases[idx];
2442 
2443       // Note this base's direct & indirect bases, if there could be ambiguity.
2444       if (Bases.size() > 1)
2445         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2446 
2447       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2448         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2449         if (Class->isInterface() &&
2450               (!RD->isInterfaceLike() ||
2451                KnownBase->getAccessSpecifier() != AS_public)) {
2452           // The Microsoft extension __interface does not permit bases that
2453           // are not themselves public interfaces.
2454           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2455               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2456               << RD->getSourceRange();
2457           Invalid = true;
2458         }
2459         if (RD->hasAttr<WeakAttr>())
2460           Class->addAttr(WeakAttr::CreateImplicit(Context));
2461       }
2462     }
2463   }
2464 
2465   // Attach the remaining base class specifiers to the derived class.
2466   Class->setBases(Bases.data(), NumGoodBases);
2467 
2468   // Check that the only base classes that are duplicate are virtual.
2469   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2470     // Check whether this direct base is inaccessible due to ambiguity.
2471     QualType BaseType = Bases[idx]->getType();
2472 
2473     // Skip all dependent types in templates being used as base specifiers.
2474     // Checks below assume that the base specifier is a CXXRecord.
2475     if (BaseType->isDependentType())
2476       continue;
2477 
2478     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2479       .getUnqualifiedType();
2480 
2481     if (IndirectBaseTypes.count(CanonicalBase)) {
2482       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2483                          /*DetectVirtual=*/true);
2484       bool found
2485         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2486       assert(found);
2487       (void)found;
2488 
2489       if (Paths.isAmbiguous(CanonicalBase))
2490         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2491             << BaseType << getAmbiguousPathsDisplayString(Paths)
2492             << Bases[idx]->getSourceRange();
2493       else
2494         assert(Bases[idx]->isVirtual());
2495     }
2496 
2497     // Delete the base class specifier, since its data has been copied
2498     // into the CXXRecordDecl.
2499     Context.Deallocate(Bases[idx]);
2500   }
2501 
2502   return Invalid;
2503 }
2504 
2505 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2506 /// class, after checking whether there are any duplicate base
2507 /// classes.
2508 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2509                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2510   if (!ClassDecl || Bases.empty())
2511     return;
2512 
2513   AdjustDeclIfTemplate(ClassDecl);
2514   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2515 }
2516 
2517 /// Determine whether the type \p Derived is a C++ class that is
2518 /// derived from the type \p Base.
2519 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2520   if (!getLangOpts().CPlusPlus)
2521     return false;
2522 
2523   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2524   if (!DerivedRD)
2525     return false;
2526 
2527   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2528   if (!BaseRD)
2529     return false;
2530 
2531   // If either the base or the derived type is invalid, don't try to
2532   // check whether one is derived from the other.
2533   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2534     return false;
2535 
2536   // FIXME: In a modules build, do we need the entire path to be visible for us
2537   // to be able to use the inheritance relationship?
2538   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2539     return false;
2540 
2541   return DerivedRD->isDerivedFrom(BaseRD);
2542 }
2543 
2544 /// Determine whether the type \p Derived is a C++ class that is
2545 /// derived from the type \p Base.
2546 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2547                          CXXBasePaths &Paths) {
2548   if (!getLangOpts().CPlusPlus)
2549     return false;
2550 
2551   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2552   if (!DerivedRD)
2553     return false;
2554 
2555   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2556   if (!BaseRD)
2557     return false;
2558 
2559   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2560     return false;
2561 
2562   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2563 }
2564 
2565 static void BuildBasePathArray(const CXXBasePath &Path,
2566                                CXXCastPath &BasePathArray) {
2567   // We first go backward and check if we have a virtual base.
2568   // FIXME: It would be better if CXXBasePath had the base specifier for
2569   // the nearest virtual base.
2570   unsigned Start = 0;
2571   for (unsigned I = Path.size(); I != 0; --I) {
2572     if (Path[I - 1].Base->isVirtual()) {
2573       Start = I - 1;
2574       break;
2575     }
2576   }
2577 
2578   // Now add all bases.
2579   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2580     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2581 }
2582 
2583 
2584 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2585                               CXXCastPath &BasePathArray) {
2586   assert(BasePathArray.empty() && "Base path array must be empty!");
2587   assert(Paths.isRecordingPaths() && "Must record paths!");
2588   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2589 }
2590 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2591 /// conversion (where Derived and Base are class types) is
2592 /// well-formed, meaning that the conversion is unambiguous (and
2593 /// that all of the base classes are accessible). Returns true
2594 /// and emits a diagnostic if the code is ill-formed, returns false
2595 /// otherwise. Loc is the location where this routine should point to
2596 /// if there is an error, and Range is the source range to highlight
2597 /// if there is an error.
2598 ///
2599 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2600 /// diagnostic for the respective type of error will be suppressed, but the
2601 /// check for ill-formed code will still be performed.
2602 bool
2603 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2604                                    unsigned InaccessibleBaseID,
2605                                    unsigned AmbigiousBaseConvID,
2606                                    SourceLocation Loc, SourceRange Range,
2607                                    DeclarationName Name,
2608                                    CXXCastPath *BasePath,
2609                                    bool IgnoreAccess) {
2610   // First, determine whether the path from Derived to Base is
2611   // ambiguous. This is slightly more expensive than checking whether
2612   // the Derived to Base conversion exists, because here we need to
2613   // explore multiple paths to determine if there is an ambiguity.
2614   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2615                      /*DetectVirtual=*/false);
2616   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2617   if (!DerivationOkay)
2618     return true;
2619 
2620   const CXXBasePath *Path = nullptr;
2621   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2622     Path = &Paths.front();
2623 
2624   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2625   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2626   // user to access such bases.
2627   if (!Path && getLangOpts().MSVCCompat) {
2628     for (const CXXBasePath &PossiblePath : Paths) {
2629       if (PossiblePath.size() == 1) {
2630         Path = &PossiblePath;
2631         if (AmbigiousBaseConvID)
2632           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2633               << Base << Derived << Range;
2634         break;
2635       }
2636     }
2637   }
2638 
2639   if (Path) {
2640     if (!IgnoreAccess) {
2641       // Check that the base class can be accessed.
2642       switch (
2643           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2644       case AR_inaccessible:
2645         return true;
2646       case AR_accessible:
2647       case AR_dependent:
2648       case AR_delayed:
2649         break;
2650       }
2651     }
2652 
2653     // Build a base path if necessary.
2654     if (BasePath)
2655       ::BuildBasePathArray(*Path, *BasePath);
2656     return false;
2657   }
2658 
2659   if (AmbigiousBaseConvID) {
2660     // We know that the derived-to-base conversion is ambiguous, and
2661     // we're going to produce a diagnostic. Perform the derived-to-base
2662     // search just one more time to compute all of the possible paths so
2663     // that we can print them out. This is more expensive than any of
2664     // the previous derived-to-base checks we've done, but at this point
2665     // performance isn't as much of an issue.
2666     Paths.clear();
2667     Paths.setRecordingPaths(true);
2668     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2669     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2670     (void)StillOkay;
2671 
2672     // Build up a textual representation of the ambiguous paths, e.g.,
2673     // D -> B -> A, that will be used to illustrate the ambiguous
2674     // conversions in the diagnostic. We only print one of the paths
2675     // to each base class subobject.
2676     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2677 
2678     Diag(Loc, AmbigiousBaseConvID)
2679     << Derived << Base << PathDisplayStr << Range << Name;
2680   }
2681   return true;
2682 }
2683 
2684 bool
2685 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2686                                    SourceLocation Loc, SourceRange Range,
2687                                    CXXCastPath *BasePath,
2688                                    bool IgnoreAccess) {
2689   return CheckDerivedToBaseConversion(
2690       Derived, Base, diag::err_upcast_to_inaccessible_base,
2691       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2692       BasePath, IgnoreAccess);
2693 }
2694 
2695 
2696 /// Builds a string representing ambiguous paths from a
2697 /// specific derived class to different subobjects of the same base
2698 /// class.
2699 ///
2700 /// This function builds a string that can be used in error messages
2701 /// to show the different paths that one can take through the
2702 /// inheritance hierarchy to go from the derived class to different
2703 /// subobjects of a base class. The result looks something like this:
2704 /// @code
2705 /// struct D -> struct B -> struct A
2706 /// struct D -> struct C -> struct A
2707 /// @endcode
2708 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2709   std::string PathDisplayStr;
2710   std::set<unsigned> DisplayedPaths;
2711   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2712        Path != Paths.end(); ++Path) {
2713     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2714       // We haven't displayed a path to this particular base
2715       // class subobject yet.
2716       PathDisplayStr += "\n    ";
2717       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2718       for (CXXBasePath::const_iterator Element = Path->begin();
2719            Element != Path->end(); ++Element)
2720         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2721     }
2722   }
2723 
2724   return PathDisplayStr;
2725 }
2726 
2727 //===----------------------------------------------------------------------===//
2728 // C++ class member Handling
2729 //===----------------------------------------------------------------------===//
2730 
2731 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2732 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2733                                 SourceLocation ColonLoc,
2734                                 const ParsedAttributesView &Attrs) {
2735   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2736   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2737                                                   ASLoc, ColonLoc);
2738   CurContext->addHiddenDecl(ASDecl);
2739   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2740 }
2741 
2742 /// CheckOverrideControl - Check C++11 override control semantics.
2743 void Sema::CheckOverrideControl(NamedDecl *D) {
2744   if (D->isInvalidDecl())
2745     return;
2746 
2747   // We only care about "override" and "final" declarations.
2748   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2749     return;
2750 
2751   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2752 
2753   // We can't check dependent instance methods.
2754   if (MD && MD->isInstance() &&
2755       (MD->getParent()->hasAnyDependentBases() ||
2756        MD->getType()->isDependentType()))
2757     return;
2758 
2759   if (MD && !MD->isVirtual()) {
2760     // If we have a non-virtual method, check if if hides a virtual method.
2761     // (In that case, it's most likely the method has the wrong type.)
2762     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2763     FindHiddenVirtualMethods(MD, OverloadedMethods);
2764 
2765     if (!OverloadedMethods.empty()) {
2766       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2767         Diag(OA->getLocation(),
2768              diag::override_keyword_hides_virtual_member_function)
2769           << "override" << (OverloadedMethods.size() > 1);
2770       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2771         Diag(FA->getLocation(),
2772              diag::override_keyword_hides_virtual_member_function)
2773           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2774           << (OverloadedMethods.size() > 1);
2775       }
2776       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2777       MD->setInvalidDecl();
2778       return;
2779     }
2780     // Fall through into the general case diagnostic.
2781     // FIXME: We might want to attempt typo correction here.
2782   }
2783 
2784   if (!MD || !MD->isVirtual()) {
2785     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2786       Diag(OA->getLocation(),
2787            diag::override_keyword_only_allowed_on_virtual_member_functions)
2788         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2789       D->dropAttr<OverrideAttr>();
2790     }
2791     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2792       Diag(FA->getLocation(),
2793            diag::override_keyword_only_allowed_on_virtual_member_functions)
2794         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2795         << FixItHint::CreateRemoval(FA->getLocation());
2796       D->dropAttr<FinalAttr>();
2797     }
2798     return;
2799   }
2800 
2801   // C++11 [class.virtual]p5:
2802   //   If a function is marked with the virt-specifier override and
2803   //   does not override a member function of a base class, the program is
2804   //   ill-formed.
2805   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2806   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2807     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2808       << MD->getDeclName();
2809 }
2810 
2811 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2812   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2813     return;
2814   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2815   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2816     return;
2817 
2818   SourceLocation Loc = MD->getLocation();
2819   SourceLocation SpellingLoc = Loc;
2820   if (getSourceManager().isMacroArgExpansion(Loc))
2821     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2822   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2823   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2824       return;
2825 
2826   if (MD->size_overridden_methods() > 0) {
2827     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2828                           ? diag::warn_destructor_marked_not_override_overriding
2829                           : diag::warn_function_marked_not_override_overriding;
2830     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2831     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2832     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2833   }
2834 }
2835 
2836 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2837 /// function overrides a virtual member function marked 'final', according to
2838 /// C++11 [class.virtual]p4.
2839 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2840                                                   const CXXMethodDecl *Old) {
2841   FinalAttr *FA = Old->getAttr<FinalAttr>();
2842   if (!FA)
2843     return false;
2844 
2845   Diag(New->getLocation(), diag::err_final_function_overridden)
2846     << New->getDeclName()
2847     << FA->isSpelledAsSealed();
2848   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2849   return true;
2850 }
2851 
2852 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2853   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2854   // FIXME: Destruction of ObjC lifetime types has side-effects.
2855   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2856     return !RD->isCompleteDefinition() ||
2857            !RD->hasTrivialDefaultConstructor() ||
2858            !RD->hasTrivialDestructor();
2859   return false;
2860 }
2861 
2862 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
2863   ParsedAttributesView::const_iterator Itr =
2864       llvm::find_if(list, [](const ParsedAttr &AL) {
2865         return AL.isDeclspecPropertyAttribute();
2866       });
2867   if (Itr != list.end())
2868     return &*Itr;
2869   return nullptr;
2870 }
2871 
2872 // Check if there is a field shadowing.
2873 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2874                                       DeclarationName FieldName,
2875                                       const CXXRecordDecl *RD,
2876                                       bool DeclIsField) {
2877   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2878     return;
2879 
2880   // To record a shadowed field in a base
2881   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2882   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2883                            CXXBasePath &Path) {
2884     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2885     // Record an ambiguous path directly
2886     if (Bases.find(Base) != Bases.end())
2887       return true;
2888     for (const auto Field : Base->lookup(FieldName)) {
2889       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2890           Field->getAccess() != AS_private) {
2891         assert(Field->getAccess() != AS_none);
2892         assert(Bases.find(Base) == Bases.end());
2893         Bases[Base] = Field;
2894         return true;
2895       }
2896     }
2897     return false;
2898   };
2899 
2900   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2901                      /*DetectVirtual=*/true);
2902   if (!RD->lookupInBases(FieldShadowed, Paths))
2903     return;
2904 
2905   for (const auto &P : Paths) {
2906     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2907     auto It = Bases.find(Base);
2908     // Skip duplicated bases
2909     if (It == Bases.end())
2910       continue;
2911     auto BaseField = It->second;
2912     assert(BaseField->getAccess() != AS_private);
2913     if (AS_none !=
2914         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2915       Diag(Loc, diag::warn_shadow_field)
2916         << FieldName << RD << Base << DeclIsField;
2917       Diag(BaseField->getLocation(), diag::note_shadow_field);
2918       Bases.erase(It);
2919     }
2920   }
2921 }
2922 
2923 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2924 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2925 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2926 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2927 /// present (but parsing it has been deferred).
2928 NamedDecl *
2929 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2930                                MultiTemplateParamsArg TemplateParameterLists,
2931                                Expr *BW, const VirtSpecifiers &VS,
2932                                InClassInitStyle InitStyle) {
2933   const DeclSpec &DS = D.getDeclSpec();
2934   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2935   DeclarationName Name = NameInfo.getName();
2936   SourceLocation Loc = NameInfo.getLoc();
2937 
2938   // For anonymous bitfields, the location should point to the type.
2939   if (Loc.isInvalid())
2940     Loc = D.getBeginLoc();
2941 
2942   Expr *BitWidth = static_cast<Expr*>(BW);
2943 
2944   assert(isa<CXXRecordDecl>(CurContext));
2945   assert(!DS.isFriendSpecified());
2946 
2947   bool isFunc = D.isDeclarationOfFunction();
2948   const ParsedAttr *MSPropertyAttr =
2949       getMSPropertyAttr(D.getDeclSpec().getAttributes());
2950 
2951   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2952     // The Microsoft extension __interface only permits public member functions
2953     // and prohibits constructors, destructors, operators, non-public member
2954     // functions, static methods and data members.
2955     unsigned InvalidDecl;
2956     bool ShowDeclName = true;
2957     if (!isFunc &&
2958         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2959       InvalidDecl = 0;
2960     else if (!isFunc)
2961       InvalidDecl = 1;
2962     else if (AS != AS_public)
2963       InvalidDecl = 2;
2964     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2965       InvalidDecl = 3;
2966     else switch (Name.getNameKind()) {
2967       case DeclarationName::CXXConstructorName:
2968         InvalidDecl = 4;
2969         ShowDeclName = false;
2970         break;
2971 
2972       case DeclarationName::CXXDestructorName:
2973         InvalidDecl = 5;
2974         ShowDeclName = false;
2975         break;
2976 
2977       case DeclarationName::CXXOperatorName:
2978       case DeclarationName::CXXConversionFunctionName:
2979         InvalidDecl = 6;
2980         break;
2981 
2982       default:
2983         InvalidDecl = 0;
2984         break;
2985     }
2986 
2987     if (InvalidDecl) {
2988       if (ShowDeclName)
2989         Diag(Loc, diag::err_invalid_member_in_interface)
2990           << (InvalidDecl-1) << Name;
2991       else
2992         Diag(Loc, diag::err_invalid_member_in_interface)
2993           << (InvalidDecl-1) << "";
2994       return nullptr;
2995     }
2996   }
2997 
2998   // C++ 9.2p6: A member shall not be declared to have automatic storage
2999   // duration (auto, register) or with the extern storage-class-specifier.
3000   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3001   // data members and cannot be applied to names declared const or static,
3002   // and cannot be applied to reference members.
3003   switch (DS.getStorageClassSpec()) {
3004   case DeclSpec::SCS_unspecified:
3005   case DeclSpec::SCS_typedef:
3006   case DeclSpec::SCS_static:
3007     break;
3008   case DeclSpec::SCS_mutable:
3009     if (isFunc) {
3010       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3011 
3012       // FIXME: It would be nicer if the keyword was ignored only for this
3013       // declarator. Otherwise we could get follow-up errors.
3014       D.getMutableDeclSpec().ClearStorageClassSpecs();
3015     }
3016     break;
3017   default:
3018     Diag(DS.getStorageClassSpecLoc(),
3019          diag::err_storageclass_invalid_for_member);
3020     D.getMutableDeclSpec().ClearStorageClassSpecs();
3021     break;
3022   }
3023 
3024   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3025                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3026                       !isFunc);
3027 
3028   if (DS.isConstexprSpecified() && isInstField) {
3029     SemaDiagnosticBuilder B =
3030         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3031     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3032     if (InitStyle == ICIS_NoInit) {
3033       B << 0 << 0;
3034       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3035         B << FixItHint::CreateRemoval(ConstexprLoc);
3036       else {
3037         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3038         D.getMutableDeclSpec().ClearConstexprSpec();
3039         const char *PrevSpec;
3040         unsigned DiagID;
3041         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3042             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3043         (void)Failed;
3044         assert(!Failed && "Making a constexpr member const shouldn't fail");
3045       }
3046     } else {
3047       B << 1;
3048       const char *PrevSpec;
3049       unsigned DiagID;
3050       if (D.getMutableDeclSpec().SetStorageClassSpec(
3051           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3052           Context.getPrintingPolicy())) {
3053         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3054                "This is the only DeclSpec that should fail to be applied");
3055         B << 1;
3056       } else {
3057         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3058         isInstField = false;
3059       }
3060     }
3061   }
3062 
3063   NamedDecl *Member;
3064   if (isInstField) {
3065     CXXScopeSpec &SS = D.getCXXScopeSpec();
3066 
3067     // Data members must have identifiers for names.
3068     if (!Name.isIdentifier()) {
3069       Diag(Loc, diag::err_bad_variable_name)
3070         << Name;
3071       return nullptr;
3072     }
3073 
3074     IdentifierInfo *II = Name.getAsIdentifierInfo();
3075 
3076     // Member field could not be with "template" keyword.
3077     // So TemplateParameterLists should be empty in this case.
3078     if (TemplateParameterLists.size()) {
3079       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3080       if (TemplateParams->size()) {
3081         // There is no such thing as a member field template.
3082         Diag(D.getIdentifierLoc(), diag::err_template_member)
3083             << II
3084             << SourceRange(TemplateParams->getTemplateLoc(),
3085                 TemplateParams->getRAngleLoc());
3086       } else {
3087         // There is an extraneous 'template<>' for this member.
3088         Diag(TemplateParams->getTemplateLoc(),
3089             diag::err_template_member_noparams)
3090             << II
3091             << SourceRange(TemplateParams->getTemplateLoc(),
3092                 TemplateParams->getRAngleLoc());
3093       }
3094       return nullptr;
3095     }
3096 
3097     if (SS.isSet() && !SS.isInvalid()) {
3098       // The user provided a superfluous scope specifier inside a class
3099       // definition:
3100       //
3101       // class X {
3102       //   int X::member;
3103       // };
3104       if (DeclContext *DC = computeDeclContext(SS, false))
3105         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3106                                      D.getName().getKind() ==
3107                                          UnqualifiedIdKind::IK_TemplateId);
3108       else
3109         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3110           << Name << SS.getRange();
3111 
3112       SS.clear();
3113     }
3114 
3115     if (MSPropertyAttr) {
3116       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3117                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3118       if (!Member)
3119         return nullptr;
3120       isInstField = false;
3121     } else {
3122       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3123                                 BitWidth, InitStyle, AS);
3124       if (!Member)
3125         return nullptr;
3126     }
3127 
3128     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3129   } else {
3130     Member = HandleDeclarator(S, D, TemplateParameterLists);
3131     if (!Member)
3132       return nullptr;
3133 
3134     // Non-instance-fields can't have a bitfield.
3135     if (BitWidth) {
3136       if (Member->isInvalidDecl()) {
3137         // don't emit another diagnostic.
3138       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3139         // C++ 9.6p3: A bit-field shall not be a static member.
3140         // "static member 'A' cannot be a bit-field"
3141         Diag(Loc, diag::err_static_not_bitfield)
3142           << Name << BitWidth->getSourceRange();
3143       } else if (isa<TypedefDecl>(Member)) {
3144         // "typedef member 'x' cannot be a bit-field"
3145         Diag(Loc, diag::err_typedef_not_bitfield)
3146           << Name << BitWidth->getSourceRange();
3147       } else {
3148         // A function typedef ("typedef int f(); f a;").
3149         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3150         Diag(Loc, diag::err_not_integral_type_bitfield)
3151           << Name << cast<ValueDecl>(Member)->getType()
3152           << BitWidth->getSourceRange();
3153       }
3154 
3155       BitWidth = nullptr;
3156       Member->setInvalidDecl();
3157     }
3158 
3159     NamedDecl *NonTemplateMember = Member;
3160     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3161       NonTemplateMember = FunTmpl->getTemplatedDecl();
3162     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3163       NonTemplateMember = VarTmpl->getTemplatedDecl();
3164 
3165     Member->setAccess(AS);
3166 
3167     // If we have declared a member function template or static data member
3168     // template, set the access of the templated declaration as well.
3169     if (NonTemplateMember != Member)
3170       NonTemplateMember->setAccess(AS);
3171 
3172     // C++ [temp.deduct.guide]p3:
3173     //   A deduction guide [...] for a member class template [shall be
3174     //   declared] with the same access [as the template].
3175     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3176       auto *TD = DG->getDeducedTemplate();
3177       // Access specifiers are only meaningful if both the template and the
3178       // deduction guide are from the same scope.
3179       if (AS != TD->getAccess() &&
3180           TD->getDeclContext()->getRedeclContext()->Equals(
3181               DG->getDeclContext()->getRedeclContext())) {
3182         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3183         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3184             << TD->getAccess();
3185         const AccessSpecDecl *LastAccessSpec = nullptr;
3186         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3187           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3188             LastAccessSpec = AccessSpec;
3189         }
3190         assert(LastAccessSpec && "differing access with no access specifier");
3191         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3192             << AS;
3193       }
3194     }
3195   }
3196 
3197   if (VS.isOverrideSpecified())
3198     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3199   if (VS.isFinalSpecified())
3200     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3201                                             VS.isFinalSpelledSealed()));
3202 
3203   if (VS.getLastLocation().isValid()) {
3204     // Update the end location of a method that has a virt-specifiers.
3205     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3206       MD->setRangeEnd(VS.getLastLocation());
3207   }
3208 
3209   CheckOverrideControl(Member);
3210 
3211   assert((Name || isInstField) && "No identifier for non-field ?");
3212 
3213   if (isInstField) {
3214     FieldDecl *FD = cast<FieldDecl>(Member);
3215     FieldCollector->Add(FD);
3216 
3217     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3218       // Remember all explicit private FieldDecls that have a name, no side
3219       // effects and are not part of a dependent type declaration.
3220       if (!FD->isImplicit() && FD->getDeclName() &&
3221           FD->getAccess() == AS_private &&
3222           !FD->hasAttr<UnusedAttr>() &&
3223           !FD->getParent()->isDependentContext() &&
3224           !InitializationHasSideEffects(*FD))
3225         UnusedPrivateFields.insert(FD);
3226     }
3227   }
3228 
3229   return Member;
3230 }
3231 
3232 namespace {
3233   class UninitializedFieldVisitor
3234       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3235     Sema &S;
3236     // List of Decls to generate a warning on.  Also remove Decls that become
3237     // initialized.
3238     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3239     // List of base classes of the record.  Classes are removed after their
3240     // initializers.
3241     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3242     // Vector of decls to be removed from the Decl set prior to visiting the
3243     // nodes.  These Decls may have been initialized in the prior initializer.
3244     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3245     // If non-null, add a note to the warning pointing back to the constructor.
3246     const CXXConstructorDecl *Constructor;
3247     // Variables to hold state when processing an initializer list.  When
3248     // InitList is true, special case initialization of FieldDecls matching
3249     // InitListFieldDecl.
3250     bool InitList;
3251     FieldDecl *InitListFieldDecl;
3252     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3253 
3254   public:
3255     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3256     UninitializedFieldVisitor(Sema &S,
3257                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3258                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3259       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3260         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3261 
3262     // Returns true if the use of ME is not an uninitialized use.
3263     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3264                                          bool CheckReferenceOnly) {
3265       llvm::SmallVector<FieldDecl*, 4> Fields;
3266       bool ReferenceField = false;
3267       while (ME) {
3268         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3269         if (!FD)
3270           return false;
3271         Fields.push_back(FD);
3272         if (FD->getType()->isReferenceType())
3273           ReferenceField = true;
3274         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3275       }
3276 
3277       // Binding a reference to an uninitialized field is not an
3278       // uninitialized use.
3279       if (CheckReferenceOnly && !ReferenceField)
3280         return true;
3281 
3282       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3283       // Discard the first field since it is the field decl that is being
3284       // initialized.
3285       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3286         UsedFieldIndex.push_back((*I)->getFieldIndex());
3287       }
3288 
3289       for (auto UsedIter = UsedFieldIndex.begin(),
3290                 UsedEnd = UsedFieldIndex.end(),
3291                 OrigIter = InitFieldIndex.begin(),
3292                 OrigEnd = InitFieldIndex.end();
3293            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3294         if (*UsedIter < *OrigIter)
3295           return true;
3296         if (*UsedIter > *OrigIter)
3297           break;
3298       }
3299 
3300       return false;
3301     }
3302 
3303     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3304                           bool AddressOf) {
3305       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3306         return;
3307 
3308       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3309       // or union.
3310       MemberExpr *FieldME = ME;
3311 
3312       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3313 
3314       Expr *Base = ME;
3315       while (MemberExpr *SubME =
3316                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3317 
3318         if (isa<VarDecl>(SubME->getMemberDecl()))
3319           return;
3320 
3321         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3322           if (!FD->isAnonymousStructOrUnion())
3323             FieldME = SubME;
3324 
3325         if (!FieldME->getType().isPODType(S.Context))
3326           AllPODFields = false;
3327 
3328         Base = SubME->getBase();
3329       }
3330 
3331       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3332         return;
3333 
3334       if (AddressOf && AllPODFields)
3335         return;
3336 
3337       ValueDecl* FoundVD = FieldME->getMemberDecl();
3338 
3339       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3340         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3341           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3342         }
3343 
3344         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3345           QualType T = BaseCast->getType();
3346           if (T->isPointerType() &&
3347               BaseClasses.count(T->getPointeeType())) {
3348             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3349                 << T->getPointeeType() << FoundVD;
3350           }
3351         }
3352       }
3353 
3354       if (!Decls.count(FoundVD))
3355         return;
3356 
3357       const bool IsReference = FoundVD->getType()->isReferenceType();
3358 
3359       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3360         // Special checking for initializer lists.
3361         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3362           return;
3363         }
3364       } else {
3365         // Prevent double warnings on use of unbounded references.
3366         if (CheckReferenceOnly && !IsReference)
3367           return;
3368       }
3369 
3370       unsigned diag = IsReference
3371           ? diag::warn_reference_field_is_uninit
3372           : diag::warn_field_is_uninit;
3373       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3374       if (Constructor)
3375         S.Diag(Constructor->getLocation(),
3376                diag::note_uninit_in_this_constructor)
3377           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3378 
3379     }
3380 
3381     void HandleValue(Expr *E, bool AddressOf) {
3382       E = E->IgnoreParens();
3383 
3384       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3385         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3386                          AddressOf /*AddressOf*/);
3387         return;
3388       }
3389 
3390       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3391         Visit(CO->getCond());
3392         HandleValue(CO->getTrueExpr(), AddressOf);
3393         HandleValue(CO->getFalseExpr(), AddressOf);
3394         return;
3395       }
3396 
3397       if (BinaryConditionalOperator *BCO =
3398               dyn_cast<BinaryConditionalOperator>(E)) {
3399         Visit(BCO->getCond());
3400         HandleValue(BCO->getFalseExpr(), AddressOf);
3401         return;
3402       }
3403 
3404       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3405         HandleValue(OVE->getSourceExpr(), AddressOf);
3406         return;
3407       }
3408 
3409       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3410         switch (BO->getOpcode()) {
3411         default:
3412           break;
3413         case(BO_PtrMemD):
3414         case(BO_PtrMemI):
3415           HandleValue(BO->getLHS(), AddressOf);
3416           Visit(BO->getRHS());
3417           return;
3418         case(BO_Comma):
3419           Visit(BO->getLHS());
3420           HandleValue(BO->getRHS(), AddressOf);
3421           return;
3422         }
3423       }
3424 
3425       Visit(E);
3426     }
3427 
3428     void CheckInitListExpr(InitListExpr *ILE) {
3429       InitFieldIndex.push_back(0);
3430       for (auto Child : ILE->children()) {
3431         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3432           CheckInitListExpr(SubList);
3433         } else {
3434           Visit(Child);
3435         }
3436         ++InitFieldIndex.back();
3437       }
3438       InitFieldIndex.pop_back();
3439     }
3440 
3441     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3442                           FieldDecl *Field, const Type *BaseClass) {
3443       // Remove Decls that may have been initialized in the previous
3444       // initializer.
3445       for (ValueDecl* VD : DeclsToRemove)
3446         Decls.erase(VD);
3447       DeclsToRemove.clear();
3448 
3449       Constructor = FieldConstructor;
3450       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3451 
3452       if (ILE && Field) {
3453         InitList = true;
3454         InitListFieldDecl = Field;
3455         InitFieldIndex.clear();
3456         CheckInitListExpr(ILE);
3457       } else {
3458         InitList = false;
3459         Visit(E);
3460       }
3461 
3462       if (Field)
3463         Decls.erase(Field);
3464       if (BaseClass)
3465         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3466     }
3467 
3468     void VisitMemberExpr(MemberExpr *ME) {
3469       // All uses of unbounded reference fields will warn.
3470       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3471     }
3472 
3473     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3474       if (E->getCastKind() == CK_LValueToRValue) {
3475         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3476         return;
3477       }
3478 
3479       Inherited::VisitImplicitCastExpr(E);
3480     }
3481 
3482     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3483       if (E->getConstructor()->isCopyConstructor()) {
3484         Expr *ArgExpr = E->getArg(0);
3485         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3486           if (ILE->getNumInits() == 1)
3487             ArgExpr = ILE->getInit(0);
3488         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3489           if (ICE->getCastKind() == CK_NoOp)
3490             ArgExpr = ICE->getSubExpr();
3491         HandleValue(ArgExpr, false /*AddressOf*/);
3492         return;
3493       }
3494       Inherited::VisitCXXConstructExpr(E);
3495     }
3496 
3497     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3498       Expr *Callee = E->getCallee();
3499       if (isa<MemberExpr>(Callee)) {
3500         HandleValue(Callee, false /*AddressOf*/);
3501         for (auto Arg : E->arguments())
3502           Visit(Arg);
3503         return;
3504       }
3505 
3506       Inherited::VisitCXXMemberCallExpr(E);
3507     }
3508 
3509     void VisitCallExpr(CallExpr *E) {
3510       // Treat std::move as a use.
3511       if (E->isCallToStdMove()) {
3512         HandleValue(E->getArg(0), /*AddressOf=*/false);
3513         return;
3514       }
3515 
3516       Inherited::VisitCallExpr(E);
3517     }
3518 
3519     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3520       Expr *Callee = E->getCallee();
3521 
3522       if (isa<UnresolvedLookupExpr>(Callee))
3523         return Inherited::VisitCXXOperatorCallExpr(E);
3524 
3525       Visit(Callee);
3526       for (auto Arg : E->arguments())
3527         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3528     }
3529 
3530     void VisitBinaryOperator(BinaryOperator *E) {
3531       // If a field assignment is detected, remove the field from the
3532       // uninitiailized field set.
3533       if (E->getOpcode() == BO_Assign)
3534         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3535           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3536             if (!FD->getType()->isReferenceType())
3537               DeclsToRemove.push_back(FD);
3538 
3539       if (E->isCompoundAssignmentOp()) {
3540         HandleValue(E->getLHS(), false /*AddressOf*/);
3541         Visit(E->getRHS());
3542         return;
3543       }
3544 
3545       Inherited::VisitBinaryOperator(E);
3546     }
3547 
3548     void VisitUnaryOperator(UnaryOperator *E) {
3549       if (E->isIncrementDecrementOp()) {
3550         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3551         return;
3552       }
3553       if (E->getOpcode() == UO_AddrOf) {
3554         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3555           HandleValue(ME->getBase(), true /*AddressOf*/);
3556           return;
3557         }
3558       }
3559 
3560       Inherited::VisitUnaryOperator(E);
3561     }
3562   };
3563 
3564   // Diagnose value-uses of fields to initialize themselves, e.g.
3565   //   foo(foo)
3566   // where foo is not also a parameter to the constructor.
3567   // Also diagnose across field uninitialized use such as
3568   //   x(y), y(x)
3569   // TODO: implement -Wuninitialized and fold this into that framework.
3570   static void DiagnoseUninitializedFields(
3571       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3572 
3573     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3574                                            Constructor->getLocation())) {
3575       return;
3576     }
3577 
3578     if (Constructor->isInvalidDecl())
3579       return;
3580 
3581     const CXXRecordDecl *RD = Constructor->getParent();
3582 
3583     if (RD->getDescribedClassTemplate())
3584       return;
3585 
3586     // Holds fields that are uninitialized.
3587     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3588 
3589     // At the beginning, all fields are uninitialized.
3590     for (auto *I : RD->decls()) {
3591       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3592         UninitializedFields.insert(FD);
3593       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3594         UninitializedFields.insert(IFD->getAnonField());
3595       }
3596     }
3597 
3598     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3599     for (auto I : RD->bases())
3600       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3601 
3602     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3603       return;
3604 
3605     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3606                                                    UninitializedFields,
3607                                                    UninitializedBaseClasses);
3608 
3609     for (const auto *FieldInit : Constructor->inits()) {
3610       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3611         break;
3612 
3613       Expr *InitExpr = FieldInit->getInit();
3614       if (!InitExpr)
3615         continue;
3616 
3617       if (CXXDefaultInitExpr *Default =
3618               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3619         InitExpr = Default->getExpr();
3620         if (!InitExpr)
3621           continue;
3622         // In class initializers will point to the constructor.
3623         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3624                                               FieldInit->getAnyMember(),
3625                                               FieldInit->getBaseClass());
3626       } else {
3627         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3628                                               FieldInit->getAnyMember(),
3629                                               FieldInit->getBaseClass());
3630       }
3631     }
3632   }
3633 } // namespace
3634 
3635 /// Enter a new C++ default initializer scope. After calling this, the
3636 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3637 /// parsing or instantiating the initializer failed.
3638 void Sema::ActOnStartCXXInClassMemberInitializer() {
3639   // Create a synthetic function scope to represent the call to the constructor
3640   // that notionally surrounds a use of this initializer.
3641   PushFunctionScope();
3642 }
3643 
3644 /// This is invoked after parsing an in-class initializer for a
3645 /// non-static C++ class member, and after instantiating an in-class initializer
3646 /// in a class template. Such actions are deferred until the class is complete.
3647 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3648                                                   SourceLocation InitLoc,
3649                                                   Expr *InitExpr) {
3650   // Pop the notional constructor scope we created earlier.
3651   PopFunctionScopeInfo(nullptr, D);
3652 
3653   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3654   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3655          "must set init style when field is created");
3656 
3657   if (!InitExpr) {
3658     D->setInvalidDecl();
3659     if (FD)
3660       FD->removeInClassInitializer();
3661     return;
3662   }
3663 
3664   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3665     FD->setInvalidDecl();
3666     FD->removeInClassInitializer();
3667     return;
3668   }
3669 
3670   ExprResult Init = InitExpr;
3671   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3672     InitializedEntity Entity =
3673         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3674     InitializationKind Kind =
3675         FD->getInClassInitStyle() == ICIS_ListInit
3676             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3677                                                    InitExpr->getBeginLoc(),
3678                                                    InitExpr->getEndLoc())
3679             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3680     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3681     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3682     if (Init.isInvalid()) {
3683       FD->setInvalidDecl();
3684       return;
3685     }
3686   }
3687 
3688   // C++11 [class.base.init]p7:
3689   //   The initialization of each base and member constitutes a
3690   //   full-expression.
3691   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3692   if (Init.isInvalid()) {
3693     FD->setInvalidDecl();
3694     return;
3695   }
3696 
3697   InitExpr = Init.get();
3698 
3699   FD->setInClassInitializer(InitExpr);
3700 }
3701 
3702 /// Find the direct and/or virtual base specifiers that
3703 /// correspond to the given base type, for use in base initialization
3704 /// within a constructor.
3705 static bool FindBaseInitializer(Sema &SemaRef,
3706                                 CXXRecordDecl *ClassDecl,
3707                                 QualType BaseType,
3708                                 const CXXBaseSpecifier *&DirectBaseSpec,
3709                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3710   // First, check for a direct base class.
3711   DirectBaseSpec = nullptr;
3712   for (const auto &Base : ClassDecl->bases()) {
3713     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3714       // We found a direct base of this type. That's what we're
3715       // initializing.
3716       DirectBaseSpec = &Base;
3717       break;
3718     }
3719   }
3720 
3721   // Check for a virtual base class.
3722   // FIXME: We might be able to short-circuit this if we know in advance that
3723   // there are no virtual bases.
3724   VirtualBaseSpec = nullptr;
3725   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3726     // We haven't found a base yet; search the class hierarchy for a
3727     // virtual base class.
3728     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3729                        /*DetectVirtual=*/false);
3730     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3731                               SemaRef.Context.getTypeDeclType(ClassDecl),
3732                               BaseType, Paths)) {
3733       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3734            Path != Paths.end(); ++Path) {
3735         if (Path->back().Base->isVirtual()) {
3736           VirtualBaseSpec = Path->back().Base;
3737           break;
3738         }
3739       }
3740     }
3741   }
3742 
3743   return DirectBaseSpec || VirtualBaseSpec;
3744 }
3745 
3746 /// Handle a C++ member initializer using braced-init-list syntax.
3747 MemInitResult
3748 Sema::ActOnMemInitializer(Decl *ConstructorD,
3749                           Scope *S,
3750                           CXXScopeSpec &SS,
3751                           IdentifierInfo *MemberOrBase,
3752                           ParsedType TemplateTypeTy,
3753                           const DeclSpec &DS,
3754                           SourceLocation IdLoc,
3755                           Expr *InitList,
3756                           SourceLocation EllipsisLoc) {
3757   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3758                              DS, IdLoc, InitList,
3759                              EllipsisLoc);
3760 }
3761 
3762 /// Handle a C++ member initializer using parentheses syntax.
3763 MemInitResult
3764 Sema::ActOnMemInitializer(Decl *ConstructorD,
3765                           Scope *S,
3766                           CXXScopeSpec &SS,
3767                           IdentifierInfo *MemberOrBase,
3768                           ParsedType TemplateTypeTy,
3769                           const DeclSpec &DS,
3770                           SourceLocation IdLoc,
3771                           SourceLocation LParenLoc,
3772                           ArrayRef<Expr *> Args,
3773                           SourceLocation RParenLoc,
3774                           SourceLocation EllipsisLoc) {
3775   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3776   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3777                              DS, IdLoc, List, EllipsisLoc);
3778 }
3779 
3780 namespace {
3781 
3782 // Callback to only accept typo corrections that can be a valid C++ member
3783 // intializer: either a non-static field member or a base class.
3784 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
3785 public:
3786   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3787       : ClassDecl(ClassDecl) {}
3788 
3789   bool ValidateCandidate(const TypoCorrection &candidate) override {
3790     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3791       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3792         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3793       return isa<TypeDecl>(ND);
3794     }
3795     return false;
3796   }
3797 
3798   std::unique_ptr<CorrectionCandidateCallback> clone() override {
3799     return llvm::make_unique<MemInitializerValidatorCCC>(*this);
3800   }
3801 
3802 private:
3803   CXXRecordDecl *ClassDecl;
3804 };
3805 
3806 }
3807 
3808 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3809                                              CXXScopeSpec &SS,
3810                                              ParsedType TemplateTypeTy,
3811                                              IdentifierInfo *MemberOrBase) {
3812   if (SS.getScopeRep() || TemplateTypeTy)
3813     return nullptr;
3814   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3815   if (Result.empty())
3816     return nullptr;
3817   ValueDecl *Member;
3818   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3819       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3820     return Member;
3821   return nullptr;
3822 }
3823 
3824 /// Handle a C++ member initializer.
3825 MemInitResult
3826 Sema::BuildMemInitializer(Decl *ConstructorD,
3827                           Scope *S,
3828                           CXXScopeSpec &SS,
3829                           IdentifierInfo *MemberOrBase,
3830                           ParsedType TemplateTypeTy,
3831                           const DeclSpec &DS,
3832                           SourceLocation IdLoc,
3833                           Expr *Init,
3834                           SourceLocation EllipsisLoc) {
3835   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3836   if (!Res.isUsable())
3837     return true;
3838   Init = Res.get();
3839 
3840   if (!ConstructorD)
3841     return true;
3842 
3843   AdjustDeclIfTemplate(ConstructorD);
3844 
3845   CXXConstructorDecl *Constructor
3846     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3847   if (!Constructor) {
3848     // The user wrote a constructor initializer on a function that is
3849     // not a C++ constructor. Ignore the error for now, because we may
3850     // have more member initializers coming; we'll diagnose it just
3851     // once in ActOnMemInitializers.
3852     return true;
3853   }
3854 
3855   CXXRecordDecl *ClassDecl = Constructor->getParent();
3856 
3857   // C++ [class.base.init]p2:
3858   //   Names in a mem-initializer-id are looked up in the scope of the
3859   //   constructor's class and, if not found in that scope, are looked
3860   //   up in the scope containing the constructor's definition.
3861   //   [Note: if the constructor's class contains a member with the
3862   //   same name as a direct or virtual base class of the class, a
3863   //   mem-initializer-id naming the member or base class and composed
3864   //   of a single identifier refers to the class member. A
3865   //   mem-initializer-id for the hidden base class may be specified
3866   //   using a qualified name. ]
3867 
3868   // Look for a member, first.
3869   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
3870           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
3871     if (EllipsisLoc.isValid())
3872       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3873           << MemberOrBase
3874           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3875 
3876     return BuildMemberInitializer(Member, Init, IdLoc);
3877   }
3878   // It didn't name a member, so see if it names a class.
3879   QualType BaseType;
3880   TypeSourceInfo *TInfo = nullptr;
3881 
3882   if (TemplateTypeTy) {
3883     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3884   } else if (DS.getTypeSpecType() == TST_decltype) {
3885     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3886   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3887     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3888     return true;
3889   } else {
3890     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3891     LookupParsedName(R, S, &SS);
3892 
3893     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3894     if (!TyD) {
3895       if (R.isAmbiguous()) return true;
3896 
3897       // We don't want access-control diagnostics here.
3898       R.suppressDiagnostics();
3899 
3900       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3901         bool NotUnknownSpecialization = false;
3902         DeclContext *DC = computeDeclContext(SS, false);
3903         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3904           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3905 
3906         if (!NotUnknownSpecialization) {
3907           // When the scope specifier can refer to a member of an unknown
3908           // specialization, we take it as a type name.
3909           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3910                                        SS.getWithLocInContext(Context),
3911                                        *MemberOrBase, IdLoc);
3912           if (BaseType.isNull())
3913             return true;
3914 
3915           TInfo = Context.CreateTypeSourceInfo(BaseType);
3916           DependentNameTypeLoc TL =
3917               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3918           if (!TL.isNull()) {
3919             TL.setNameLoc(IdLoc);
3920             TL.setElaboratedKeywordLoc(SourceLocation());
3921             TL.setQualifierLoc(SS.getWithLocInContext(Context));
3922           }
3923 
3924           R.clear();
3925           R.setLookupName(MemberOrBase);
3926         }
3927       }
3928 
3929       // If no results were found, try to correct typos.
3930       TypoCorrection Corr;
3931       MemInitializerValidatorCCC CCC(ClassDecl);
3932       if (R.empty() && BaseType.isNull() &&
3933           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3934                               CCC, CTK_ErrorRecovery, ClassDecl))) {
3935         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3936           // We have found a non-static data member with a similar
3937           // name to what was typed; complain and initialize that
3938           // member.
3939           diagnoseTypo(Corr,
3940                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3941                          << MemberOrBase << true);
3942           return BuildMemberInitializer(Member, Init, IdLoc);
3943         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3944           const CXXBaseSpecifier *DirectBaseSpec;
3945           const CXXBaseSpecifier *VirtualBaseSpec;
3946           if (FindBaseInitializer(*this, ClassDecl,
3947                                   Context.getTypeDeclType(Type),
3948                                   DirectBaseSpec, VirtualBaseSpec)) {
3949             // We have found a direct or virtual base class with a
3950             // similar name to what was typed; complain and initialize
3951             // that base class.
3952             diagnoseTypo(Corr,
3953                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3954                            << MemberOrBase << false,
3955                          PDiag() /*Suppress note, we provide our own.*/);
3956 
3957             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3958                                                               : VirtualBaseSpec;
3959             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
3960                 << BaseSpec->getType() << BaseSpec->getSourceRange();
3961 
3962             TyD = Type;
3963           }
3964         }
3965       }
3966 
3967       if (!TyD && BaseType.isNull()) {
3968         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3969           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3970         return true;
3971       }
3972     }
3973 
3974     if (BaseType.isNull()) {
3975       BaseType = Context.getTypeDeclType(TyD);
3976       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3977       if (SS.isSet()) {
3978         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3979                                              BaseType);
3980         TInfo = Context.CreateTypeSourceInfo(BaseType);
3981         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3982         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3983         TL.setElaboratedKeywordLoc(SourceLocation());
3984         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3985       }
3986     }
3987   }
3988 
3989   if (!TInfo)
3990     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3991 
3992   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3993 }
3994 
3995 MemInitResult
3996 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3997                              SourceLocation IdLoc) {
3998   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3999   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4000   assert((DirectMember || IndirectMember) &&
4001          "Member must be a FieldDecl or IndirectFieldDecl");
4002 
4003   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4004     return true;
4005 
4006   if (Member->isInvalidDecl())
4007     return true;
4008 
4009   MultiExprArg Args;
4010   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4011     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4012   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4013     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4014   } else {
4015     // Template instantiation doesn't reconstruct ParenListExprs for us.
4016     Args = Init;
4017   }
4018 
4019   SourceRange InitRange = Init->getSourceRange();
4020 
4021   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4022     // Can't check initialization for a member of dependent type or when
4023     // any of the arguments are type-dependent expressions.
4024     DiscardCleanupsInEvaluationContext();
4025   } else {
4026     bool InitList = false;
4027     if (isa<InitListExpr>(Init)) {
4028       InitList = true;
4029       Args = Init;
4030     }
4031 
4032     // Initialize the member.
4033     InitializedEntity MemberEntity =
4034       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4035                    : InitializedEntity::InitializeMember(IndirectMember,
4036                                                          nullptr);
4037     InitializationKind Kind =
4038         InitList ? InitializationKind::CreateDirectList(
4039                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4040                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4041                                                     InitRange.getEnd());
4042 
4043     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4044     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4045                                             nullptr);
4046     if (MemberInit.isInvalid())
4047       return true;
4048 
4049     // C++11 [class.base.init]p7:
4050     //   The initialization of each base and member constitutes a
4051     //   full-expression.
4052     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4053                                      /*DiscardedValue*/ false);
4054     if (MemberInit.isInvalid())
4055       return true;
4056 
4057     Init = MemberInit.get();
4058   }
4059 
4060   if (DirectMember) {
4061     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4062                                             InitRange.getBegin(), Init,
4063                                             InitRange.getEnd());
4064   } else {
4065     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4066                                             InitRange.getBegin(), Init,
4067                                             InitRange.getEnd());
4068   }
4069 }
4070 
4071 MemInitResult
4072 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4073                                  CXXRecordDecl *ClassDecl) {
4074   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4075   if (!LangOpts.CPlusPlus11)
4076     return Diag(NameLoc, diag::err_delegating_ctor)
4077       << TInfo->getTypeLoc().getLocalSourceRange();
4078   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4079 
4080   bool InitList = true;
4081   MultiExprArg Args = Init;
4082   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4083     InitList = false;
4084     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4085   }
4086 
4087   SourceRange InitRange = Init->getSourceRange();
4088   // Initialize the object.
4089   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4090                                      QualType(ClassDecl->getTypeForDecl(), 0));
4091   InitializationKind Kind =
4092       InitList ? InitializationKind::CreateDirectList(
4093                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4094                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4095                                                   InitRange.getEnd());
4096   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4097   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4098                                               Args, nullptr);
4099   if (DelegationInit.isInvalid())
4100     return true;
4101 
4102   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4103          "Delegating constructor with no target?");
4104 
4105   // C++11 [class.base.init]p7:
4106   //   The initialization of each base and member constitutes a
4107   //   full-expression.
4108   DelegationInit = ActOnFinishFullExpr(
4109       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4110   if (DelegationInit.isInvalid())
4111     return true;
4112 
4113   // If we are in a dependent context, template instantiation will
4114   // perform this type-checking again. Just save the arguments that we
4115   // received in a ParenListExpr.
4116   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4117   // of the information that we have about the base
4118   // initializer. However, deconstructing the ASTs is a dicey process,
4119   // and this approach is far more likely to get the corner cases right.
4120   if (CurContext->isDependentContext())
4121     DelegationInit = Init;
4122 
4123   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4124                                           DelegationInit.getAs<Expr>(),
4125                                           InitRange.getEnd());
4126 }
4127 
4128 MemInitResult
4129 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4130                            Expr *Init, CXXRecordDecl *ClassDecl,
4131                            SourceLocation EllipsisLoc) {
4132   SourceLocation BaseLoc
4133     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4134 
4135   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4136     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4137              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4138 
4139   // C++ [class.base.init]p2:
4140   //   [...] Unless the mem-initializer-id names a nonstatic data
4141   //   member of the constructor's class or a direct or virtual base
4142   //   of that class, the mem-initializer is ill-formed. A
4143   //   mem-initializer-list can initialize a base class using any
4144   //   name that denotes that base class type.
4145   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4146 
4147   SourceRange InitRange = Init->getSourceRange();
4148   if (EllipsisLoc.isValid()) {
4149     // This is a pack expansion.
4150     if (!BaseType->containsUnexpandedParameterPack())  {
4151       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4152         << SourceRange(BaseLoc, InitRange.getEnd());
4153 
4154       EllipsisLoc = SourceLocation();
4155     }
4156   } else {
4157     // Check for any unexpanded parameter packs.
4158     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4159       return true;
4160 
4161     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4162       return true;
4163   }
4164 
4165   // Check for direct and virtual base classes.
4166   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4167   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4168   if (!Dependent) {
4169     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4170                                        BaseType))
4171       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4172 
4173     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4174                         VirtualBaseSpec);
4175 
4176     // C++ [base.class.init]p2:
4177     // Unless the mem-initializer-id names a nonstatic data member of the
4178     // constructor's class or a direct or virtual base of that class, the
4179     // mem-initializer is ill-formed.
4180     if (!DirectBaseSpec && !VirtualBaseSpec) {
4181       // If the class has any dependent bases, then it's possible that
4182       // one of those types will resolve to the same type as
4183       // BaseType. Therefore, just treat this as a dependent base
4184       // class initialization.  FIXME: Should we try to check the
4185       // initialization anyway? It seems odd.
4186       if (ClassDecl->hasAnyDependentBases())
4187         Dependent = true;
4188       else
4189         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4190           << BaseType << Context.getTypeDeclType(ClassDecl)
4191           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4192     }
4193   }
4194 
4195   if (Dependent) {
4196     DiscardCleanupsInEvaluationContext();
4197 
4198     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4199                                             /*IsVirtual=*/false,
4200                                             InitRange.getBegin(), Init,
4201                                             InitRange.getEnd(), EllipsisLoc);
4202   }
4203 
4204   // C++ [base.class.init]p2:
4205   //   If a mem-initializer-id is ambiguous because it designates both
4206   //   a direct non-virtual base class and an inherited virtual base
4207   //   class, the mem-initializer is ill-formed.
4208   if (DirectBaseSpec && VirtualBaseSpec)
4209     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4210       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4211 
4212   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4213   if (!BaseSpec)
4214     BaseSpec = VirtualBaseSpec;
4215 
4216   // Initialize the base.
4217   bool InitList = true;
4218   MultiExprArg Args = Init;
4219   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4220     InitList = false;
4221     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4222   }
4223 
4224   InitializedEntity BaseEntity =
4225     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4226   InitializationKind Kind =
4227       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4228                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4229                                                   InitRange.getEnd());
4230   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4231   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4232   if (BaseInit.isInvalid())
4233     return true;
4234 
4235   // C++11 [class.base.init]p7:
4236   //   The initialization of each base and member constitutes a
4237   //   full-expression.
4238   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4239                                  /*DiscardedValue*/ false);
4240   if (BaseInit.isInvalid())
4241     return true;
4242 
4243   // If we are in a dependent context, template instantiation will
4244   // perform this type-checking again. Just save the arguments that we
4245   // received in a ParenListExpr.
4246   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4247   // of the information that we have about the base
4248   // initializer. However, deconstructing the ASTs is a dicey process,
4249   // and this approach is far more likely to get the corner cases right.
4250   if (CurContext->isDependentContext())
4251     BaseInit = Init;
4252 
4253   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4254                                           BaseSpec->isVirtual(),
4255                                           InitRange.getBegin(),
4256                                           BaseInit.getAs<Expr>(),
4257                                           InitRange.getEnd(), EllipsisLoc);
4258 }
4259 
4260 // Create a static_cast\<T&&>(expr).
4261 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4262   if (T.isNull()) T = E->getType();
4263   QualType TargetType = SemaRef.BuildReferenceType(
4264       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4265   SourceLocation ExprLoc = E->getBeginLoc();
4266   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4267       TargetType, ExprLoc);
4268 
4269   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4270                                    SourceRange(ExprLoc, ExprLoc),
4271                                    E->getSourceRange()).get();
4272 }
4273 
4274 /// ImplicitInitializerKind - How an implicit base or member initializer should
4275 /// initialize its base or member.
4276 enum ImplicitInitializerKind {
4277   IIK_Default,
4278   IIK_Copy,
4279   IIK_Move,
4280   IIK_Inherit
4281 };
4282 
4283 static bool
4284 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4285                              ImplicitInitializerKind ImplicitInitKind,
4286                              CXXBaseSpecifier *BaseSpec,
4287                              bool IsInheritedVirtualBase,
4288                              CXXCtorInitializer *&CXXBaseInit) {
4289   InitializedEntity InitEntity
4290     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4291                                         IsInheritedVirtualBase);
4292 
4293   ExprResult BaseInit;
4294 
4295   switch (ImplicitInitKind) {
4296   case IIK_Inherit:
4297   case IIK_Default: {
4298     InitializationKind InitKind
4299       = InitializationKind::CreateDefault(Constructor->getLocation());
4300     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4301     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4302     break;
4303   }
4304 
4305   case IIK_Move:
4306   case IIK_Copy: {
4307     bool Moving = ImplicitInitKind == IIK_Move;
4308     ParmVarDecl *Param = Constructor->getParamDecl(0);
4309     QualType ParamType = Param->getType().getNonReferenceType();
4310 
4311     Expr *CopyCtorArg =
4312       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4313                           SourceLocation(), Param, false,
4314                           Constructor->getLocation(), ParamType,
4315                           VK_LValue, nullptr);
4316 
4317     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4318 
4319     // Cast to the base class to avoid ambiguities.
4320     QualType ArgTy =
4321       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4322                                        ParamType.getQualifiers());
4323 
4324     if (Moving) {
4325       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4326     }
4327 
4328     CXXCastPath BasePath;
4329     BasePath.push_back(BaseSpec);
4330     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4331                                             CK_UncheckedDerivedToBase,
4332                                             Moving ? VK_XValue : VK_LValue,
4333                                             &BasePath).get();
4334 
4335     InitializationKind InitKind
4336       = InitializationKind::CreateDirect(Constructor->getLocation(),
4337                                          SourceLocation(), SourceLocation());
4338     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4339     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4340     break;
4341   }
4342   }
4343 
4344   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4345   if (BaseInit.isInvalid())
4346     return true;
4347 
4348   CXXBaseInit =
4349     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4350                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4351                                                         SourceLocation()),
4352                                              BaseSpec->isVirtual(),
4353                                              SourceLocation(),
4354                                              BaseInit.getAs<Expr>(),
4355                                              SourceLocation(),
4356                                              SourceLocation());
4357 
4358   return false;
4359 }
4360 
4361 static bool RefersToRValueRef(Expr *MemRef) {
4362   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4363   return Referenced->getType()->isRValueReferenceType();
4364 }
4365 
4366 static bool
4367 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4368                                ImplicitInitializerKind ImplicitInitKind,
4369                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4370                                CXXCtorInitializer *&CXXMemberInit) {
4371   if (Field->isInvalidDecl())
4372     return true;
4373 
4374   SourceLocation Loc = Constructor->getLocation();
4375 
4376   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4377     bool Moving = ImplicitInitKind == IIK_Move;
4378     ParmVarDecl *Param = Constructor->getParamDecl(0);
4379     QualType ParamType = Param->getType().getNonReferenceType();
4380 
4381     // Suppress copying zero-width bitfields.
4382     if (Field->isZeroLengthBitField(SemaRef.Context))
4383       return false;
4384 
4385     Expr *MemberExprBase =
4386       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4387                           SourceLocation(), Param, false,
4388                           Loc, ParamType, VK_LValue, nullptr);
4389 
4390     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4391 
4392     if (Moving) {
4393       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4394     }
4395 
4396     // Build a reference to this field within the parameter.
4397     CXXScopeSpec SS;
4398     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4399                               Sema::LookupMemberName);
4400     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4401                                   : cast<ValueDecl>(Field), AS_public);
4402     MemberLookup.resolveKind();
4403     ExprResult CtorArg
4404       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4405                                          ParamType, Loc,
4406                                          /*IsArrow=*/false,
4407                                          SS,
4408                                          /*TemplateKWLoc=*/SourceLocation(),
4409                                          /*FirstQualifierInScope=*/nullptr,
4410                                          MemberLookup,
4411                                          /*TemplateArgs=*/nullptr,
4412                                          /*S*/nullptr);
4413     if (CtorArg.isInvalid())
4414       return true;
4415 
4416     // C++11 [class.copy]p15:
4417     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4418     //     with static_cast<T&&>(x.m);
4419     if (RefersToRValueRef(CtorArg.get())) {
4420       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4421     }
4422 
4423     InitializedEntity Entity =
4424         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4425                                                        /*Implicit*/ true)
4426                  : InitializedEntity::InitializeMember(Field, nullptr,
4427                                                        /*Implicit*/ true);
4428 
4429     // Direct-initialize to use the copy constructor.
4430     InitializationKind InitKind =
4431       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4432 
4433     Expr *CtorArgE = CtorArg.getAs<Expr>();
4434     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4435     ExprResult MemberInit =
4436         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4437     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4438     if (MemberInit.isInvalid())
4439       return true;
4440 
4441     if (Indirect)
4442       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4443           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4444     else
4445       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4446           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4447     return false;
4448   }
4449 
4450   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4451          "Unhandled implicit init kind!");
4452 
4453   QualType FieldBaseElementType =
4454     SemaRef.Context.getBaseElementType(Field->getType());
4455 
4456   if (FieldBaseElementType->isRecordType()) {
4457     InitializedEntity InitEntity =
4458         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4459                                                        /*Implicit*/ true)
4460                  : InitializedEntity::InitializeMember(Field, nullptr,
4461                                                        /*Implicit*/ true);
4462     InitializationKind InitKind =
4463       InitializationKind::CreateDefault(Loc);
4464 
4465     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4466     ExprResult MemberInit =
4467       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4468 
4469     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4470     if (MemberInit.isInvalid())
4471       return true;
4472 
4473     if (Indirect)
4474       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4475                                                                Indirect, Loc,
4476                                                                Loc,
4477                                                                MemberInit.get(),
4478                                                                Loc);
4479     else
4480       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4481                                                                Field, Loc, Loc,
4482                                                                MemberInit.get(),
4483                                                                Loc);
4484     return false;
4485   }
4486 
4487   if (!Field->getParent()->isUnion()) {
4488     if (FieldBaseElementType->isReferenceType()) {
4489       SemaRef.Diag(Constructor->getLocation(),
4490                    diag::err_uninitialized_member_in_ctor)
4491       << (int)Constructor->isImplicit()
4492       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4493       << 0 << Field->getDeclName();
4494       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4495       return true;
4496     }
4497 
4498     if (FieldBaseElementType.isConstQualified()) {
4499       SemaRef.Diag(Constructor->getLocation(),
4500                    diag::err_uninitialized_member_in_ctor)
4501       << (int)Constructor->isImplicit()
4502       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4503       << 1 << Field->getDeclName();
4504       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4505       return true;
4506     }
4507   }
4508 
4509   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4510     // ARC and Weak:
4511     //   Default-initialize Objective-C pointers to NULL.
4512     CXXMemberInit
4513       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4514                                                  Loc, Loc,
4515                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4516                                                  Loc);
4517     return false;
4518   }
4519 
4520   // Nothing to initialize.
4521   CXXMemberInit = nullptr;
4522   return false;
4523 }
4524 
4525 namespace {
4526 struct BaseAndFieldInfo {
4527   Sema &S;
4528   CXXConstructorDecl *Ctor;
4529   bool AnyErrorsInInits;
4530   ImplicitInitializerKind IIK;
4531   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4532   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4533   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4534 
4535   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4536     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4537     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4538     if (Ctor->getInheritedConstructor())
4539       IIK = IIK_Inherit;
4540     else if (Generated && Ctor->isCopyConstructor())
4541       IIK = IIK_Copy;
4542     else if (Generated && Ctor->isMoveConstructor())
4543       IIK = IIK_Move;
4544     else
4545       IIK = IIK_Default;
4546   }
4547 
4548   bool isImplicitCopyOrMove() const {
4549     switch (IIK) {
4550     case IIK_Copy:
4551     case IIK_Move:
4552       return true;
4553 
4554     case IIK_Default:
4555     case IIK_Inherit:
4556       return false;
4557     }
4558 
4559     llvm_unreachable("Invalid ImplicitInitializerKind!");
4560   }
4561 
4562   bool addFieldInitializer(CXXCtorInitializer *Init) {
4563     AllToInit.push_back(Init);
4564 
4565     // Check whether this initializer makes the field "used".
4566     if (Init->getInit()->HasSideEffects(S.Context))
4567       S.UnusedPrivateFields.remove(Init->getAnyMember());
4568 
4569     return false;
4570   }
4571 
4572   bool isInactiveUnionMember(FieldDecl *Field) {
4573     RecordDecl *Record = Field->getParent();
4574     if (!Record->isUnion())
4575       return false;
4576 
4577     if (FieldDecl *Active =
4578             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4579       return Active != Field->getCanonicalDecl();
4580 
4581     // In an implicit copy or move constructor, ignore any in-class initializer.
4582     if (isImplicitCopyOrMove())
4583       return true;
4584 
4585     // If there's no explicit initialization, the field is active only if it
4586     // has an in-class initializer...
4587     if (Field->hasInClassInitializer())
4588       return false;
4589     // ... or it's an anonymous struct or union whose class has an in-class
4590     // initializer.
4591     if (!Field->isAnonymousStructOrUnion())
4592       return true;
4593     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4594     return !FieldRD->hasInClassInitializer();
4595   }
4596 
4597   /// Determine whether the given field is, or is within, a union member
4598   /// that is inactive (because there was an initializer given for a different
4599   /// member of the union, or because the union was not initialized at all).
4600   bool isWithinInactiveUnionMember(FieldDecl *Field,
4601                                    IndirectFieldDecl *Indirect) {
4602     if (!Indirect)
4603       return isInactiveUnionMember(Field);
4604 
4605     for (auto *C : Indirect->chain()) {
4606       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4607       if (Field && isInactiveUnionMember(Field))
4608         return true;
4609     }
4610     return false;
4611   }
4612 };
4613 }
4614 
4615 /// Determine whether the given type is an incomplete or zero-lenfgth
4616 /// array type.
4617 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4618   if (T->isIncompleteArrayType())
4619     return true;
4620 
4621   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4622     if (!ArrayT->getSize())
4623       return true;
4624 
4625     T = ArrayT->getElementType();
4626   }
4627 
4628   return false;
4629 }
4630 
4631 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4632                                     FieldDecl *Field,
4633                                     IndirectFieldDecl *Indirect = nullptr) {
4634   if (Field->isInvalidDecl())
4635     return false;
4636 
4637   // Overwhelmingly common case: we have a direct initializer for this field.
4638   if (CXXCtorInitializer *Init =
4639           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4640     return Info.addFieldInitializer(Init);
4641 
4642   // C++11 [class.base.init]p8:
4643   //   if the entity is a non-static data member that has a
4644   //   brace-or-equal-initializer and either
4645   //   -- the constructor's class is a union and no other variant member of that
4646   //      union is designated by a mem-initializer-id or
4647   //   -- the constructor's class is not a union, and, if the entity is a member
4648   //      of an anonymous union, no other member of that union is designated by
4649   //      a mem-initializer-id,
4650   //   the entity is initialized as specified in [dcl.init].
4651   //
4652   // We also apply the same rules to handle anonymous structs within anonymous
4653   // unions.
4654   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4655     return false;
4656 
4657   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4658     ExprResult DIE =
4659         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4660     if (DIE.isInvalid())
4661       return true;
4662 
4663     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4664     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4665 
4666     CXXCtorInitializer *Init;
4667     if (Indirect)
4668       Init = new (SemaRef.Context)
4669           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4670                              SourceLocation(), DIE.get(), SourceLocation());
4671     else
4672       Init = new (SemaRef.Context)
4673           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4674                              SourceLocation(), DIE.get(), SourceLocation());
4675     return Info.addFieldInitializer(Init);
4676   }
4677 
4678   // Don't initialize incomplete or zero-length arrays.
4679   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4680     return false;
4681 
4682   // Don't try to build an implicit initializer if there were semantic
4683   // errors in any of the initializers (and therefore we might be
4684   // missing some that the user actually wrote).
4685   if (Info.AnyErrorsInInits)
4686     return false;
4687 
4688   CXXCtorInitializer *Init = nullptr;
4689   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4690                                      Indirect, Init))
4691     return true;
4692 
4693   if (!Init)
4694     return false;
4695 
4696   return Info.addFieldInitializer(Init);
4697 }
4698 
4699 bool
4700 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4701                                CXXCtorInitializer *Initializer) {
4702   assert(Initializer->isDelegatingInitializer());
4703   Constructor->setNumCtorInitializers(1);
4704   CXXCtorInitializer **initializer =
4705     new (Context) CXXCtorInitializer*[1];
4706   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4707   Constructor->setCtorInitializers(initializer);
4708 
4709   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4710     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4711     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4712   }
4713 
4714   DelegatingCtorDecls.push_back(Constructor);
4715 
4716   DiagnoseUninitializedFields(*this, Constructor);
4717 
4718   return false;
4719 }
4720 
4721 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4722                                ArrayRef<CXXCtorInitializer *> Initializers) {
4723   if (Constructor->isDependentContext()) {
4724     // Just store the initializers as written, they will be checked during
4725     // instantiation.
4726     if (!Initializers.empty()) {
4727       Constructor->setNumCtorInitializers(Initializers.size());
4728       CXXCtorInitializer **baseOrMemberInitializers =
4729         new (Context) CXXCtorInitializer*[Initializers.size()];
4730       memcpy(baseOrMemberInitializers, Initializers.data(),
4731              Initializers.size() * sizeof(CXXCtorInitializer*));
4732       Constructor->setCtorInitializers(baseOrMemberInitializers);
4733     }
4734 
4735     // Let template instantiation know whether we had errors.
4736     if (AnyErrors)
4737       Constructor->setInvalidDecl();
4738 
4739     return false;
4740   }
4741 
4742   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4743 
4744   // We need to build the initializer AST according to order of construction
4745   // and not what user specified in the Initializers list.
4746   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4747   if (!ClassDecl)
4748     return true;
4749 
4750   bool HadError = false;
4751 
4752   for (unsigned i = 0; i < Initializers.size(); i++) {
4753     CXXCtorInitializer *Member = Initializers[i];
4754 
4755     if (Member->isBaseInitializer())
4756       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4757     else {
4758       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4759 
4760       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4761         for (auto *C : F->chain()) {
4762           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4763           if (FD && FD->getParent()->isUnion())
4764             Info.ActiveUnionMember.insert(std::make_pair(
4765                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4766         }
4767       } else if (FieldDecl *FD = Member->getMember()) {
4768         if (FD->getParent()->isUnion())
4769           Info.ActiveUnionMember.insert(std::make_pair(
4770               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4771       }
4772     }
4773   }
4774 
4775   // Keep track of the direct virtual bases.
4776   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4777   for (auto &I : ClassDecl->bases()) {
4778     if (I.isVirtual())
4779       DirectVBases.insert(&I);
4780   }
4781 
4782   // Push virtual bases before others.
4783   for (auto &VBase : ClassDecl->vbases()) {
4784     if (CXXCtorInitializer *Value
4785         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4786       // [class.base.init]p7, per DR257:
4787       //   A mem-initializer where the mem-initializer-id names a virtual base
4788       //   class is ignored during execution of a constructor of any class that
4789       //   is not the most derived class.
4790       if (ClassDecl->isAbstract()) {
4791         // FIXME: Provide a fixit to remove the base specifier. This requires
4792         // tracking the location of the associated comma for a base specifier.
4793         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4794           << VBase.getType() << ClassDecl;
4795         DiagnoseAbstractType(ClassDecl);
4796       }
4797 
4798       Info.AllToInit.push_back(Value);
4799     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4800       // [class.base.init]p8, per DR257:
4801       //   If a given [...] base class is not named by a mem-initializer-id
4802       //   [...] and the entity is not a virtual base class of an abstract
4803       //   class, then [...] the entity is default-initialized.
4804       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4805       CXXCtorInitializer *CXXBaseInit;
4806       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4807                                        &VBase, IsInheritedVirtualBase,
4808                                        CXXBaseInit)) {
4809         HadError = true;
4810         continue;
4811       }
4812 
4813       Info.AllToInit.push_back(CXXBaseInit);
4814     }
4815   }
4816 
4817   // Non-virtual bases.
4818   for (auto &Base : ClassDecl->bases()) {
4819     // Virtuals are in the virtual base list and already constructed.
4820     if (Base.isVirtual())
4821       continue;
4822 
4823     if (CXXCtorInitializer *Value
4824           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4825       Info.AllToInit.push_back(Value);
4826     } else if (!AnyErrors) {
4827       CXXCtorInitializer *CXXBaseInit;
4828       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4829                                        &Base, /*IsInheritedVirtualBase=*/false,
4830                                        CXXBaseInit)) {
4831         HadError = true;
4832         continue;
4833       }
4834 
4835       Info.AllToInit.push_back(CXXBaseInit);
4836     }
4837   }
4838 
4839   // Fields.
4840   for (auto *Mem : ClassDecl->decls()) {
4841     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4842       // C++ [class.bit]p2:
4843       //   A declaration for a bit-field that omits the identifier declares an
4844       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4845       //   initialized.
4846       if (F->isUnnamedBitfield())
4847         continue;
4848 
4849       // If we're not generating the implicit copy/move constructor, then we'll
4850       // handle anonymous struct/union fields based on their individual
4851       // indirect fields.
4852       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4853         continue;
4854 
4855       if (CollectFieldInitializer(*this, Info, F))
4856         HadError = true;
4857       continue;
4858     }
4859 
4860     // Beyond this point, we only consider default initialization.
4861     if (Info.isImplicitCopyOrMove())
4862       continue;
4863 
4864     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4865       if (F->getType()->isIncompleteArrayType()) {
4866         assert(ClassDecl->hasFlexibleArrayMember() &&
4867                "Incomplete array type is not valid");
4868         continue;
4869       }
4870 
4871       // Initialize each field of an anonymous struct individually.
4872       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4873         HadError = true;
4874 
4875       continue;
4876     }
4877   }
4878 
4879   unsigned NumInitializers = Info.AllToInit.size();
4880   if (NumInitializers > 0) {
4881     Constructor->setNumCtorInitializers(NumInitializers);
4882     CXXCtorInitializer **baseOrMemberInitializers =
4883       new (Context) CXXCtorInitializer*[NumInitializers];
4884     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4885            NumInitializers * sizeof(CXXCtorInitializer*));
4886     Constructor->setCtorInitializers(baseOrMemberInitializers);
4887 
4888     // Constructors implicitly reference the base and member
4889     // destructors.
4890     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4891                                            Constructor->getParent());
4892   }
4893 
4894   return HadError;
4895 }
4896 
4897 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4898   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4899     const RecordDecl *RD = RT->getDecl();
4900     if (RD->isAnonymousStructOrUnion()) {
4901       for (auto *Field : RD->fields())
4902         PopulateKeysForFields(Field, IdealInits);
4903       return;
4904     }
4905   }
4906   IdealInits.push_back(Field->getCanonicalDecl());
4907 }
4908 
4909 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4910   return Context.getCanonicalType(BaseType).getTypePtr();
4911 }
4912 
4913 static const void *GetKeyForMember(ASTContext &Context,
4914                                    CXXCtorInitializer *Member) {
4915   if (!Member->isAnyMemberInitializer())
4916     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4917 
4918   return Member->getAnyMember()->getCanonicalDecl();
4919 }
4920 
4921 static void DiagnoseBaseOrMemInitializerOrder(
4922     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4923     ArrayRef<CXXCtorInitializer *> Inits) {
4924   if (Constructor->getDeclContext()->isDependentContext())
4925     return;
4926 
4927   // Don't check initializers order unless the warning is enabled at the
4928   // location of at least one initializer.
4929   bool ShouldCheckOrder = false;
4930   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4931     CXXCtorInitializer *Init = Inits[InitIndex];
4932     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4933                                  Init->getSourceLocation())) {
4934       ShouldCheckOrder = true;
4935       break;
4936     }
4937   }
4938   if (!ShouldCheckOrder)
4939     return;
4940 
4941   // Build the list of bases and members in the order that they'll
4942   // actually be initialized.  The explicit initializers should be in
4943   // this same order but may be missing things.
4944   SmallVector<const void*, 32> IdealInitKeys;
4945 
4946   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4947 
4948   // 1. Virtual bases.
4949   for (const auto &VBase : ClassDecl->vbases())
4950     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4951 
4952   // 2. Non-virtual bases.
4953   for (const auto &Base : ClassDecl->bases()) {
4954     if (Base.isVirtual())
4955       continue;
4956     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4957   }
4958 
4959   // 3. Direct fields.
4960   for (auto *Field : ClassDecl->fields()) {
4961     if (Field->isUnnamedBitfield())
4962       continue;
4963 
4964     PopulateKeysForFields(Field, IdealInitKeys);
4965   }
4966 
4967   unsigned NumIdealInits = IdealInitKeys.size();
4968   unsigned IdealIndex = 0;
4969 
4970   CXXCtorInitializer *PrevInit = nullptr;
4971   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4972     CXXCtorInitializer *Init = Inits[InitIndex];
4973     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4974 
4975     // Scan forward to try to find this initializer in the idealized
4976     // initializers list.
4977     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4978       if (InitKey == IdealInitKeys[IdealIndex])
4979         break;
4980 
4981     // If we didn't find this initializer, it must be because we
4982     // scanned past it on a previous iteration.  That can only
4983     // happen if we're out of order;  emit a warning.
4984     if (IdealIndex == NumIdealInits && PrevInit) {
4985       Sema::SemaDiagnosticBuilder D =
4986         SemaRef.Diag(PrevInit->getSourceLocation(),
4987                      diag::warn_initializer_out_of_order);
4988 
4989       if (PrevInit->isAnyMemberInitializer())
4990         D << 0 << PrevInit->getAnyMember()->getDeclName();
4991       else
4992         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4993 
4994       if (Init->isAnyMemberInitializer())
4995         D << 0 << Init->getAnyMember()->getDeclName();
4996       else
4997         D << 1 << Init->getTypeSourceInfo()->getType();
4998 
4999       // Move back to the initializer's location in the ideal list.
5000       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5001         if (InitKey == IdealInitKeys[IdealIndex])
5002           break;
5003 
5004       assert(IdealIndex < NumIdealInits &&
5005              "initializer not found in initializer list");
5006     }
5007 
5008     PrevInit = Init;
5009   }
5010 }
5011 
5012 namespace {
5013 bool CheckRedundantInit(Sema &S,
5014                         CXXCtorInitializer *Init,
5015                         CXXCtorInitializer *&PrevInit) {
5016   if (!PrevInit) {
5017     PrevInit = Init;
5018     return false;
5019   }
5020 
5021   if (FieldDecl *Field = Init->getAnyMember())
5022     S.Diag(Init->getSourceLocation(),
5023            diag::err_multiple_mem_initialization)
5024       << Field->getDeclName()
5025       << Init->getSourceRange();
5026   else {
5027     const Type *BaseClass = Init->getBaseClass();
5028     assert(BaseClass && "neither field nor base");
5029     S.Diag(Init->getSourceLocation(),
5030            diag::err_multiple_base_initialization)
5031       << QualType(BaseClass, 0)
5032       << Init->getSourceRange();
5033   }
5034   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5035     << 0 << PrevInit->getSourceRange();
5036 
5037   return true;
5038 }
5039 
5040 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5041 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5042 
5043 bool CheckRedundantUnionInit(Sema &S,
5044                              CXXCtorInitializer *Init,
5045                              RedundantUnionMap &Unions) {
5046   FieldDecl *Field = Init->getAnyMember();
5047   RecordDecl *Parent = Field->getParent();
5048   NamedDecl *Child = Field;
5049 
5050   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5051     if (Parent->isUnion()) {
5052       UnionEntry &En = Unions[Parent];
5053       if (En.first && En.first != Child) {
5054         S.Diag(Init->getSourceLocation(),
5055                diag::err_multiple_mem_union_initialization)
5056           << Field->getDeclName()
5057           << Init->getSourceRange();
5058         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5059           << 0 << En.second->getSourceRange();
5060         return true;
5061       }
5062       if (!En.first) {
5063         En.first = Child;
5064         En.second = Init;
5065       }
5066       if (!Parent->isAnonymousStructOrUnion())
5067         return false;
5068     }
5069 
5070     Child = Parent;
5071     Parent = cast<RecordDecl>(Parent->getDeclContext());
5072   }
5073 
5074   return false;
5075 }
5076 }
5077 
5078 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5079 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5080                                 SourceLocation ColonLoc,
5081                                 ArrayRef<CXXCtorInitializer*> MemInits,
5082                                 bool AnyErrors) {
5083   if (!ConstructorDecl)
5084     return;
5085 
5086   AdjustDeclIfTemplate(ConstructorDecl);
5087 
5088   CXXConstructorDecl *Constructor
5089     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5090 
5091   if (!Constructor) {
5092     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5093     return;
5094   }
5095 
5096   // Mapping for the duplicate initializers check.
5097   // For member initializers, this is keyed with a FieldDecl*.
5098   // For base initializers, this is keyed with a Type*.
5099   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5100 
5101   // Mapping for the inconsistent anonymous-union initializers check.
5102   RedundantUnionMap MemberUnions;
5103 
5104   bool HadError = false;
5105   for (unsigned i = 0; i < MemInits.size(); i++) {
5106     CXXCtorInitializer *Init = MemInits[i];
5107 
5108     // Set the source order index.
5109     Init->setSourceOrder(i);
5110 
5111     if (Init->isAnyMemberInitializer()) {
5112       const void *Key = GetKeyForMember(Context, Init);
5113       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5114           CheckRedundantUnionInit(*this, Init, MemberUnions))
5115         HadError = true;
5116     } else if (Init->isBaseInitializer()) {
5117       const void *Key = GetKeyForMember(Context, Init);
5118       if (CheckRedundantInit(*this, Init, Members[Key]))
5119         HadError = true;
5120     } else {
5121       assert(Init->isDelegatingInitializer());
5122       // This must be the only initializer
5123       if (MemInits.size() != 1) {
5124         Diag(Init->getSourceLocation(),
5125              diag::err_delegating_initializer_alone)
5126           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5127         // We will treat this as being the only initializer.
5128       }
5129       SetDelegatingInitializer(Constructor, MemInits[i]);
5130       // Return immediately as the initializer is set.
5131       return;
5132     }
5133   }
5134 
5135   if (HadError)
5136     return;
5137 
5138   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5139 
5140   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5141 
5142   DiagnoseUninitializedFields(*this, Constructor);
5143 }
5144 
5145 void
5146 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5147                                              CXXRecordDecl *ClassDecl) {
5148   // Ignore dependent contexts. Also ignore unions, since their members never
5149   // have destructors implicitly called.
5150   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5151     return;
5152 
5153   // FIXME: all the access-control diagnostics are positioned on the
5154   // field/base declaration.  That's probably good; that said, the
5155   // user might reasonably want to know why the destructor is being
5156   // emitted, and we currently don't say.
5157 
5158   // Non-static data members.
5159   for (auto *Field : ClassDecl->fields()) {
5160     if (Field->isInvalidDecl())
5161       continue;
5162 
5163     // Don't destroy incomplete or zero-length arrays.
5164     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5165       continue;
5166 
5167     QualType FieldType = Context.getBaseElementType(Field->getType());
5168 
5169     const RecordType* RT = FieldType->getAs<RecordType>();
5170     if (!RT)
5171       continue;
5172 
5173     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5174     if (FieldClassDecl->isInvalidDecl())
5175       continue;
5176     if (FieldClassDecl->hasIrrelevantDestructor())
5177       continue;
5178     // The destructor for an implicit anonymous union member is never invoked.
5179     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5180       continue;
5181 
5182     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5183     assert(Dtor && "No dtor found for FieldClassDecl!");
5184     CheckDestructorAccess(Field->getLocation(), Dtor,
5185                           PDiag(diag::err_access_dtor_field)
5186                             << Field->getDeclName()
5187                             << FieldType);
5188 
5189     MarkFunctionReferenced(Location, Dtor);
5190     DiagnoseUseOfDecl(Dtor, Location);
5191   }
5192 
5193   // We only potentially invoke the destructors of potentially constructed
5194   // subobjects.
5195   bool VisitVirtualBases = !ClassDecl->isAbstract();
5196 
5197   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5198 
5199   // Bases.
5200   for (const auto &Base : ClassDecl->bases()) {
5201     // Bases are always records in a well-formed non-dependent class.
5202     const RecordType *RT = Base.getType()->getAs<RecordType>();
5203 
5204     // Remember direct virtual bases.
5205     if (Base.isVirtual()) {
5206       if (!VisitVirtualBases)
5207         continue;
5208       DirectVirtualBases.insert(RT);
5209     }
5210 
5211     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5212     // If our base class is invalid, we probably can't get its dtor anyway.
5213     if (BaseClassDecl->isInvalidDecl())
5214       continue;
5215     if (BaseClassDecl->hasIrrelevantDestructor())
5216       continue;
5217 
5218     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5219     assert(Dtor && "No dtor found for BaseClassDecl!");
5220 
5221     // FIXME: caret should be on the start of the class name
5222     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5223                           PDiag(diag::err_access_dtor_base)
5224                               << Base.getType() << Base.getSourceRange(),
5225                           Context.getTypeDeclType(ClassDecl));
5226 
5227     MarkFunctionReferenced(Location, Dtor);
5228     DiagnoseUseOfDecl(Dtor, Location);
5229   }
5230 
5231   if (!VisitVirtualBases)
5232     return;
5233 
5234   // Virtual bases.
5235   for (const auto &VBase : ClassDecl->vbases()) {
5236     // Bases are always records in a well-formed non-dependent class.
5237     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5238 
5239     // Ignore direct virtual bases.
5240     if (DirectVirtualBases.count(RT))
5241       continue;
5242 
5243     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5244     // If our base class is invalid, we probably can't get its dtor anyway.
5245     if (BaseClassDecl->isInvalidDecl())
5246       continue;
5247     if (BaseClassDecl->hasIrrelevantDestructor())
5248       continue;
5249 
5250     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5251     assert(Dtor && "No dtor found for BaseClassDecl!");
5252     if (CheckDestructorAccess(
5253             ClassDecl->getLocation(), Dtor,
5254             PDiag(diag::err_access_dtor_vbase)
5255                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5256             Context.getTypeDeclType(ClassDecl)) ==
5257         AR_accessible) {
5258       CheckDerivedToBaseConversion(
5259           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5260           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5261           SourceRange(), DeclarationName(), nullptr);
5262     }
5263 
5264     MarkFunctionReferenced(Location, Dtor);
5265     DiagnoseUseOfDecl(Dtor, Location);
5266   }
5267 }
5268 
5269 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5270   if (!CDtorDecl)
5271     return;
5272 
5273   if (CXXConstructorDecl *Constructor
5274       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5275     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5276     DiagnoseUninitializedFields(*this, Constructor);
5277   }
5278 }
5279 
5280 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5281   if (!getLangOpts().CPlusPlus)
5282     return false;
5283 
5284   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5285   if (!RD)
5286     return false;
5287 
5288   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5289   // class template specialization here, but doing so breaks a lot of code.
5290 
5291   // We can't answer whether something is abstract until it has a
5292   // definition. If it's currently being defined, we'll walk back
5293   // over all the declarations when we have a full definition.
5294   const CXXRecordDecl *Def = RD->getDefinition();
5295   if (!Def || Def->isBeingDefined())
5296     return false;
5297 
5298   return RD->isAbstract();
5299 }
5300 
5301 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5302                                   TypeDiagnoser &Diagnoser) {
5303   if (!isAbstractType(Loc, T))
5304     return false;
5305 
5306   T = Context.getBaseElementType(T);
5307   Diagnoser.diagnose(*this, Loc, T);
5308   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5309   return true;
5310 }
5311 
5312 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5313   // Check if we've already emitted the list of pure virtual functions
5314   // for this class.
5315   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5316     return;
5317 
5318   // If the diagnostic is suppressed, don't emit the notes. We're only
5319   // going to emit them once, so try to attach them to a diagnostic we're
5320   // actually going to show.
5321   if (Diags.isLastDiagnosticIgnored())
5322     return;
5323 
5324   CXXFinalOverriderMap FinalOverriders;
5325   RD->getFinalOverriders(FinalOverriders);
5326 
5327   // Keep a set of seen pure methods so we won't diagnose the same method
5328   // more than once.
5329   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5330 
5331   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5332                                    MEnd = FinalOverriders.end();
5333        M != MEnd;
5334        ++M) {
5335     for (OverridingMethods::iterator SO = M->second.begin(),
5336                                   SOEnd = M->second.end();
5337          SO != SOEnd; ++SO) {
5338       // C++ [class.abstract]p4:
5339       //   A class is abstract if it contains or inherits at least one
5340       //   pure virtual function for which the final overrider is pure
5341       //   virtual.
5342 
5343       //
5344       if (SO->second.size() != 1)
5345         continue;
5346 
5347       if (!SO->second.front().Method->isPure())
5348         continue;
5349 
5350       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5351         continue;
5352 
5353       Diag(SO->second.front().Method->getLocation(),
5354            diag::note_pure_virtual_function)
5355         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5356     }
5357   }
5358 
5359   if (!PureVirtualClassDiagSet)
5360     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5361   PureVirtualClassDiagSet->insert(RD);
5362 }
5363 
5364 namespace {
5365 struct AbstractUsageInfo {
5366   Sema &S;
5367   CXXRecordDecl *Record;
5368   CanQualType AbstractType;
5369   bool Invalid;
5370 
5371   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5372     : S(S), Record(Record),
5373       AbstractType(S.Context.getCanonicalType(
5374                    S.Context.getTypeDeclType(Record))),
5375       Invalid(false) {}
5376 
5377   void DiagnoseAbstractType() {
5378     if (Invalid) return;
5379     S.DiagnoseAbstractType(Record);
5380     Invalid = true;
5381   }
5382 
5383   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5384 };
5385 
5386 struct CheckAbstractUsage {
5387   AbstractUsageInfo &Info;
5388   const NamedDecl *Ctx;
5389 
5390   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5391     : Info(Info), Ctx(Ctx) {}
5392 
5393   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5394     switch (TL.getTypeLocClass()) {
5395 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5396 #define TYPELOC(CLASS, PARENT) \
5397     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5398 #include "clang/AST/TypeLocNodes.def"
5399     }
5400   }
5401 
5402   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5403     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5404     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5405       if (!TL.getParam(I))
5406         continue;
5407 
5408       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5409       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5410     }
5411   }
5412 
5413   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5414     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5415   }
5416 
5417   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5418     // Visit the type parameters from a permissive context.
5419     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5420       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5421       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5422         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5423           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5424       // TODO: other template argument types?
5425     }
5426   }
5427 
5428   // Visit pointee types from a permissive context.
5429 #define CheckPolymorphic(Type) \
5430   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5431     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5432   }
5433   CheckPolymorphic(PointerTypeLoc)
5434   CheckPolymorphic(ReferenceTypeLoc)
5435   CheckPolymorphic(MemberPointerTypeLoc)
5436   CheckPolymorphic(BlockPointerTypeLoc)
5437   CheckPolymorphic(AtomicTypeLoc)
5438 
5439   /// Handle all the types we haven't given a more specific
5440   /// implementation for above.
5441   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5442     // Every other kind of type that we haven't called out already
5443     // that has an inner type is either (1) sugar or (2) contains that
5444     // inner type in some way as a subobject.
5445     if (TypeLoc Next = TL.getNextTypeLoc())
5446       return Visit(Next, Sel);
5447 
5448     // If there's no inner type and we're in a permissive context,
5449     // don't diagnose.
5450     if (Sel == Sema::AbstractNone) return;
5451 
5452     // Check whether the type matches the abstract type.
5453     QualType T = TL.getType();
5454     if (T->isArrayType()) {
5455       Sel = Sema::AbstractArrayType;
5456       T = Info.S.Context.getBaseElementType(T);
5457     }
5458     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5459     if (CT != Info.AbstractType) return;
5460 
5461     // It matched; do some magic.
5462     if (Sel == Sema::AbstractArrayType) {
5463       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5464         << T << TL.getSourceRange();
5465     } else {
5466       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5467         << Sel << T << TL.getSourceRange();
5468     }
5469     Info.DiagnoseAbstractType();
5470   }
5471 };
5472 
5473 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5474                                   Sema::AbstractDiagSelID Sel) {
5475   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5476 }
5477 
5478 }
5479 
5480 /// Check for invalid uses of an abstract type in a method declaration.
5481 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5482                                     CXXMethodDecl *MD) {
5483   // No need to do the check on definitions, which require that
5484   // the return/param types be complete.
5485   if (MD->doesThisDeclarationHaveABody())
5486     return;
5487 
5488   // For safety's sake, just ignore it if we don't have type source
5489   // information.  This should never happen for non-implicit methods,
5490   // but...
5491   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5492     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5493 }
5494 
5495 /// Check for invalid uses of an abstract type within a class definition.
5496 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5497                                     CXXRecordDecl *RD) {
5498   for (auto *D : RD->decls()) {
5499     if (D->isImplicit()) continue;
5500 
5501     // Methods and method templates.
5502     if (isa<CXXMethodDecl>(D)) {
5503       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5504     } else if (isa<FunctionTemplateDecl>(D)) {
5505       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5506       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5507 
5508     // Fields and static variables.
5509     } else if (isa<FieldDecl>(D)) {
5510       FieldDecl *FD = cast<FieldDecl>(D);
5511       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5512         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5513     } else if (isa<VarDecl>(D)) {
5514       VarDecl *VD = cast<VarDecl>(D);
5515       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5516         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5517 
5518     // Nested classes and class templates.
5519     } else if (isa<CXXRecordDecl>(D)) {
5520       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5521     } else if (isa<ClassTemplateDecl>(D)) {
5522       CheckAbstractClassUsage(Info,
5523                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5524     }
5525   }
5526 }
5527 
5528 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5529   Attr *ClassAttr = getDLLAttr(Class);
5530   if (!ClassAttr)
5531     return;
5532 
5533   assert(ClassAttr->getKind() == attr::DLLExport);
5534 
5535   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5536 
5537   if (TSK == TSK_ExplicitInstantiationDeclaration)
5538     // Don't go any further if this is just an explicit instantiation
5539     // declaration.
5540     return;
5541 
5542   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5543     S.MarkVTableUsed(Class->getLocation(), Class, true);
5544 
5545   for (Decl *Member : Class->decls()) {
5546     // Defined static variables that are members of an exported base
5547     // class must be marked export too.
5548     auto *VD = dyn_cast<VarDecl>(Member);
5549     if (VD && Member->getAttr<DLLExportAttr>() &&
5550         VD->getStorageClass() == SC_Static &&
5551         TSK == TSK_ImplicitInstantiation)
5552       S.MarkVariableReferenced(VD->getLocation(), VD);
5553 
5554     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5555     if (!MD)
5556       continue;
5557 
5558     if (Member->getAttr<DLLExportAttr>()) {
5559       if (MD->isUserProvided()) {
5560         // Instantiate non-default class member functions ...
5561 
5562         // .. except for certain kinds of template specializations.
5563         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5564           continue;
5565 
5566         S.MarkFunctionReferenced(Class->getLocation(), MD);
5567 
5568         // The function will be passed to the consumer when its definition is
5569         // encountered.
5570       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5571                  MD->isCopyAssignmentOperator() ||
5572                  MD->isMoveAssignmentOperator()) {
5573         // Synthesize and instantiate non-trivial implicit methods, explicitly
5574         // defaulted methods, and the copy and move assignment operators. The
5575         // latter are exported even if they are trivial, because the address of
5576         // an operator can be taken and should compare equal across libraries.
5577         DiagnosticErrorTrap Trap(S.Diags);
5578         S.MarkFunctionReferenced(Class->getLocation(), MD);
5579         if (Trap.hasErrorOccurred()) {
5580           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5581               << Class << !S.getLangOpts().CPlusPlus11;
5582           break;
5583         }
5584 
5585         // There is no later point when we will see the definition of this
5586         // function, so pass it to the consumer now.
5587         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5588       }
5589     }
5590   }
5591 }
5592 
5593 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5594                                                         CXXRecordDecl *Class) {
5595   // Only the MS ABI has default constructor closures, so we don't need to do
5596   // this semantic checking anywhere else.
5597   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5598     return;
5599 
5600   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5601   for (Decl *Member : Class->decls()) {
5602     // Look for exported default constructors.
5603     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5604     if (!CD || !CD->isDefaultConstructor())
5605       continue;
5606     auto *Attr = CD->getAttr<DLLExportAttr>();
5607     if (!Attr)
5608       continue;
5609 
5610     // If the class is non-dependent, mark the default arguments as ODR-used so
5611     // that we can properly codegen the constructor closure.
5612     if (!Class->isDependentContext()) {
5613       for (ParmVarDecl *PD : CD->parameters()) {
5614         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5615         S.DiscardCleanupsInEvaluationContext();
5616       }
5617     }
5618 
5619     if (LastExportedDefaultCtor) {
5620       S.Diag(LastExportedDefaultCtor->getLocation(),
5621              diag::err_attribute_dll_ambiguous_default_ctor)
5622           << Class;
5623       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5624           << CD->getDeclName();
5625       return;
5626     }
5627     LastExportedDefaultCtor = CD;
5628   }
5629 }
5630 
5631 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5632   // Mark any compiler-generated routines with the implicit code_seg attribute.
5633   for (auto *Method : Class->methods()) {
5634     if (Method->isUserProvided())
5635       continue;
5636     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5637       Method->addAttr(A);
5638   }
5639 }
5640 
5641 /// Check class-level dllimport/dllexport attribute.
5642 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5643   Attr *ClassAttr = getDLLAttr(Class);
5644 
5645   // MSVC inherits DLL attributes to partial class template specializations.
5646   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5647     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5648       if (Attr *TemplateAttr =
5649               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5650         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5651         A->setInherited(true);
5652         ClassAttr = A;
5653       }
5654     }
5655   }
5656 
5657   if (!ClassAttr)
5658     return;
5659 
5660   if (!Class->isExternallyVisible()) {
5661     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5662         << Class << ClassAttr;
5663     return;
5664   }
5665 
5666   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5667       !ClassAttr->isInherited()) {
5668     // Diagnose dll attributes on members of class with dll attribute.
5669     for (Decl *Member : Class->decls()) {
5670       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5671         continue;
5672       InheritableAttr *MemberAttr = getDLLAttr(Member);
5673       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5674         continue;
5675 
5676       Diag(MemberAttr->getLocation(),
5677              diag::err_attribute_dll_member_of_dll_class)
5678           << MemberAttr << ClassAttr;
5679       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5680       Member->setInvalidDecl();
5681     }
5682   }
5683 
5684   if (Class->getDescribedClassTemplate())
5685     // Don't inherit dll attribute until the template is instantiated.
5686     return;
5687 
5688   // The class is either imported or exported.
5689   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5690 
5691   // Check if this was a dllimport attribute propagated from a derived class to
5692   // a base class template specialization. We don't apply these attributes to
5693   // static data members.
5694   const bool PropagatedImport =
5695       !ClassExported &&
5696       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5697 
5698   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5699 
5700   // Ignore explicit dllexport on explicit class template instantiation declarations.
5701   if (ClassExported && !ClassAttr->isInherited() &&
5702       TSK == TSK_ExplicitInstantiationDeclaration) {
5703     Class->dropAttr<DLLExportAttr>();
5704     return;
5705   }
5706 
5707   // Force declaration of implicit members so they can inherit the attribute.
5708   ForceDeclarationOfImplicitMembers(Class);
5709 
5710   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5711   // seem to be true in practice?
5712 
5713   for (Decl *Member : Class->decls()) {
5714     VarDecl *VD = dyn_cast<VarDecl>(Member);
5715     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5716 
5717     // Only methods and static fields inherit the attributes.
5718     if (!VD && !MD)
5719       continue;
5720 
5721     if (MD) {
5722       // Don't process deleted methods.
5723       if (MD->isDeleted())
5724         continue;
5725 
5726       if (MD->isInlined()) {
5727         // MinGW does not import or export inline methods.
5728         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5729             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5730           continue;
5731 
5732         // MSVC versions before 2015 don't export the move assignment operators
5733         // and move constructor, so don't attempt to import/export them if
5734         // we have a definition.
5735         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5736         if ((MD->isMoveAssignmentOperator() ||
5737              (Ctor && Ctor->isMoveConstructor())) &&
5738             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5739           continue;
5740 
5741         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5742         // operator is exported anyway.
5743         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5744             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5745           continue;
5746       }
5747     }
5748 
5749     // Don't apply dllimport attributes to static data members of class template
5750     // instantiations when the attribute is propagated from a derived class.
5751     if (VD && PropagatedImport)
5752       continue;
5753 
5754     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5755       continue;
5756 
5757     if (!getDLLAttr(Member)) {
5758       InheritableAttr *NewAttr = nullptr;
5759 
5760       // Do not export/import inline function when -fno-dllexport-inlines is
5761       // passed. But add attribute for later local static var check.
5762       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5763           TSK != TSK_ExplicitInstantiationDeclaration &&
5764           TSK != TSK_ExplicitInstantiationDefinition) {
5765         if (ClassExported) {
5766           NewAttr = ::new (getASTContext())
5767             DLLExportStaticLocalAttr(ClassAttr->getRange(),
5768                                      getASTContext(),
5769                                      ClassAttr->getSpellingListIndex());
5770         } else {
5771           NewAttr = ::new (getASTContext())
5772             DLLImportStaticLocalAttr(ClassAttr->getRange(),
5773                                      getASTContext(),
5774                                      ClassAttr->getSpellingListIndex());
5775         }
5776       } else {
5777         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5778       }
5779 
5780       NewAttr->setInherited(true);
5781       Member->addAttr(NewAttr);
5782 
5783       if (MD) {
5784         // Propagate DLLAttr to friend re-declarations of MD that have already
5785         // been constructed.
5786         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5787              FD = FD->getPreviousDecl()) {
5788           if (FD->getFriendObjectKind() == Decl::FOK_None)
5789             continue;
5790           assert(!getDLLAttr(FD) &&
5791                  "friend re-decl should not already have a DLLAttr");
5792           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5793           NewAttr->setInherited(true);
5794           FD->addAttr(NewAttr);
5795         }
5796       }
5797     }
5798   }
5799 
5800   if (ClassExported)
5801     DelayedDllExportClasses.push_back(Class);
5802 }
5803 
5804 /// Perform propagation of DLL attributes from a derived class to a
5805 /// templated base class for MS compatibility.
5806 void Sema::propagateDLLAttrToBaseClassTemplate(
5807     CXXRecordDecl *Class, Attr *ClassAttr,
5808     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5809   if (getDLLAttr(
5810           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5811     // If the base class template has a DLL attribute, don't try to change it.
5812     return;
5813   }
5814 
5815   auto TSK = BaseTemplateSpec->getSpecializationKind();
5816   if (!getDLLAttr(BaseTemplateSpec) &&
5817       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5818        TSK == TSK_ImplicitInstantiation)) {
5819     // The template hasn't been instantiated yet (or it has, but only as an
5820     // explicit instantiation declaration or implicit instantiation, which means
5821     // we haven't codegenned any members yet), so propagate the attribute.
5822     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5823     NewAttr->setInherited(true);
5824     BaseTemplateSpec->addAttr(NewAttr);
5825 
5826     // If this was an import, mark that we propagated it from a derived class to
5827     // a base class template specialization.
5828     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5829       ImportAttr->setPropagatedToBaseTemplate();
5830 
5831     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5832     // needs to be run again to work see the new attribute. Otherwise this will
5833     // get run whenever the template is instantiated.
5834     if (TSK != TSK_Undeclared)
5835       checkClassLevelDLLAttribute(BaseTemplateSpec);
5836 
5837     return;
5838   }
5839 
5840   if (getDLLAttr(BaseTemplateSpec)) {
5841     // The template has already been specialized or instantiated with an
5842     // attribute, explicitly or through propagation. We should not try to change
5843     // it.
5844     return;
5845   }
5846 
5847   // The template was previously instantiated or explicitly specialized without
5848   // a dll attribute, It's too late for us to add an attribute, so warn that
5849   // this is unsupported.
5850   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5851       << BaseTemplateSpec->isExplicitSpecialization();
5852   Diag(ClassAttr->getLocation(), diag::note_attribute);
5853   if (BaseTemplateSpec->isExplicitSpecialization()) {
5854     Diag(BaseTemplateSpec->getLocation(),
5855            diag::note_template_class_explicit_specialization_was_here)
5856         << BaseTemplateSpec;
5857   } else {
5858     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5859            diag::note_template_class_instantiation_was_here)
5860         << BaseTemplateSpec;
5861   }
5862 }
5863 
5864 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5865                                         SourceLocation DefaultLoc) {
5866   switch (S.getSpecialMember(MD)) {
5867   case Sema::CXXDefaultConstructor:
5868     S.DefineImplicitDefaultConstructor(DefaultLoc,
5869                                        cast<CXXConstructorDecl>(MD));
5870     break;
5871   case Sema::CXXCopyConstructor:
5872     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5873     break;
5874   case Sema::CXXCopyAssignment:
5875     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5876     break;
5877   case Sema::CXXDestructor:
5878     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5879     break;
5880   case Sema::CXXMoveConstructor:
5881     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5882     break;
5883   case Sema::CXXMoveAssignment:
5884     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5885     break;
5886   case Sema::CXXInvalid:
5887     llvm_unreachable("Invalid special member.");
5888   }
5889 }
5890 
5891 /// Determine whether a type is permitted to be passed or returned in
5892 /// registers, per C++ [class.temporary]p3.
5893 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5894                                TargetInfo::CallingConvKind CCK) {
5895   if (D->isDependentType() || D->isInvalidDecl())
5896     return false;
5897 
5898   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5899   // The PS4 platform ABI follows the behavior of Clang 3.2.
5900   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5901     return !D->hasNonTrivialDestructorForCall() &&
5902            !D->hasNonTrivialCopyConstructorForCall();
5903 
5904   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
5905     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5906     bool DtorIsTrivialForCall = false;
5907 
5908     // If a class has at least one non-deleted, trivial copy constructor, it
5909     // is passed according to the C ABI. Otherwise, it is passed indirectly.
5910     //
5911     // Note: This permits classes with non-trivial copy or move ctors to be
5912     // passed in registers, so long as they *also* have a trivial copy ctor,
5913     // which is non-conforming.
5914     if (D->needsImplicitCopyConstructor()) {
5915       if (!D->defaultedCopyConstructorIsDeleted()) {
5916         if (D->hasTrivialCopyConstructor())
5917           CopyCtorIsTrivial = true;
5918         if (D->hasTrivialCopyConstructorForCall())
5919           CopyCtorIsTrivialForCall = true;
5920       }
5921     } else {
5922       for (const CXXConstructorDecl *CD : D->ctors()) {
5923         if (CD->isCopyConstructor() && !CD->isDeleted()) {
5924           if (CD->isTrivial())
5925             CopyCtorIsTrivial = true;
5926           if (CD->isTrivialForCall())
5927             CopyCtorIsTrivialForCall = true;
5928         }
5929       }
5930     }
5931 
5932     if (D->needsImplicitDestructor()) {
5933       if (!D->defaultedDestructorIsDeleted() &&
5934           D->hasTrivialDestructorForCall())
5935         DtorIsTrivialForCall = true;
5936     } else if (const auto *DD = D->getDestructor()) {
5937       if (!DD->isDeleted() && DD->isTrivialForCall())
5938         DtorIsTrivialForCall = true;
5939     }
5940 
5941     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5942     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5943       return true;
5944 
5945     // If a class has a destructor, we'd really like to pass it indirectly
5946     // because it allows us to elide copies.  Unfortunately, MSVC makes that
5947     // impossible for small types, which it will pass in a single register or
5948     // stack slot. Most objects with dtors are large-ish, so handle that early.
5949     // We can't call out all large objects as being indirect because there are
5950     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5951     // how we pass large POD types.
5952 
5953     // Note: This permits small classes with nontrivial destructors to be
5954     // passed in registers, which is non-conforming.
5955     if (CopyCtorIsTrivial &&
5956         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64)
5957       return true;
5958     return false;
5959   }
5960 
5961   // Per C++ [class.temporary]p3, the relevant condition is:
5962   //   each copy constructor, move constructor, and destructor of X is
5963   //   either trivial or deleted, and X has at least one non-deleted copy
5964   //   or move constructor
5965   bool HasNonDeletedCopyOrMove = false;
5966 
5967   if (D->needsImplicitCopyConstructor() &&
5968       !D->defaultedCopyConstructorIsDeleted()) {
5969     if (!D->hasTrivialCopyConstructorForCall())
5970       return false;
5971     HasNonDeletedCopyOrMove = true;
5972   }
5973 
5974   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5975       !D->defaultedMoveConstructorIsDeleted()) {
5976     if (!D->hasTrivialMoveConstructorForCall())
5977       return false;
5978     HasNonDeletedCopyOrMove = true;
5979   }
5980 
5981   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5982       !D->hasTrivialDestructorForCall())
5983     return false;
5984 
5985   for (const CXXMethodDecl *MD : D->methods()) {
5986     if (MD->isDeleted())
5987       continue;
5988 
5989     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5990     if (CD && CD->isCopyOrMoveConstructor())
5991       HasNonDeletedCopyOrMove = true;
5992     else if (!isa<CXXDestructorDecl>(MD))
5993       continue;
5994 
5995     if (!MD->isTrivialForCall())
5996       return false;
5997   }
5998 
5999   return HasNonDeletedCopyOrMove;
6000 }
6001 
6002 /// Perform semantic checks on a class definition that has been
6003 /// completing, introducing implicitly-declared members, checking for
6004 /// abstract types, etc.
6005 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
6006   if (!Record)
6007     return;
6008 
6009   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6010     AbstractUsageInfo Info(*this, Record);
6011     CheckAbstractClassUsage(Info, Record);
6012   }
6013 
6014   // If this is not an aggregate type and has no user-declared constructor,
6015   // complain about any non-static data members of reference or const scalar
6016   // type, since they will never get initializers.
6017   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6018       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6019       !Record->isLambda()) {
6020     bool Complained = false;
6021     for (const auto *F : Record->fields()) {
6022       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6023         continue;
6024 
6025       if (F->getType()->isReferenceType() ||
6026           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6027         if (!Complained) {
6028           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6029             << Record->getTagKind() << Record;
6030           Complained = true;
6031         }
6032 
6033         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6034           << F->getType()->isReferenceType()
6035           << F->getDeclName();
6036       }
6037     }
6038   }
6039 
6040   if (Record->getIdentifier()) {
6041     // C++ [class.mem]p13:
6042     //   If T is the name of a class, then each of the following shall have a
6043     //   name different from T:
6044     //     - every member of every anonymous union that is a member of class T.
6045     //
6046     // C++ [class.mem]p14:
6047     //   In addition, if class T has a user-declared constructor (12.1), every
6048     //   non-static data member of class T shall have a name different from T.
6049     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6050     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6051          ++I) {
6052       NamedDecl *D = (*I)->getUnderlyingDecl();
6053       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6054            Record->hasUserDeclaredConstructor()) ||
6055           isa<IndirectFieldDecl>(D)) {
6056         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6057           << D->getDeclName();
6058         break;
6059       }
6060     }
6061   }
6062 
6063   // Warn if the class has virtual methods but non-virtual public destructor.
6064   if (Record->isPolymorphic() && !Record->isDependentType()) {
6065     CXXDestructorDecl *dtor = Record->getDestructor();
6066     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6067         !Record->hasAttr<FinalAttr>())
6068       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6069            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6070   }
6071 
6072   if (Record->isAbstract()) {
6073     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6074       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6075         << FA->isSpelledAsSealed();
6076       DiagnoseAbstractType(Record);
6077     }
6078   }
6079 
6080   // See if trivial_abi has to be dropped.
6081   if (Record->hasAttr<TrivialABIAttr>())
6082     checkIllFormedTrivialABIStruct(*Record);
6083 
6084   // Set HasTrivialSpecialMemberForCall if the record has attribute
6085   // "trivial_abi".
6086   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6087 
6088   if (HasTrivialABI)
6089     Record->setHasTrivialSpecialMemberForCall();
6090 
6091   bool HasMethodWithOverrideControl = false,
6092        HasOverridingMethodWithoutOverrideControl = false;
6093   if (!Record->isDependentType()) {
6094     for (auto *M : Record->methods()) {
6095       // See if a method overloads virtual methods in a base
6096       // class without overriding any.
6097       if (!M->isStatic())
6098         DiagnoseHiddenVirtualMethods(M);
6099       if (M->hasAttr<OverrideAttr>())
6100         HasMethodWithOverrideControl = true;
6101       else if (M->size_overridden_methods() > 0)
6102         HasOverridingMethodWithoutOverrideControl = true;
6103       // Check whether the explicitly-defaulted special members are valid.
6104       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6105         CheckExplicitlyDefaultedSpecialMember(M);
6106 
6107       // For an explicitly defaulted or deleted special member, we defer
6108       // determining triviality until the class is complete. That time is now!
6109       CXXSpecialMember CSM = getSpecialMember(M);
6110       if (!M->isImplicit() && !M->isUserProvided()) {
6111         if (CSM != CXXInvalid) {
6112           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6113           // Inform the class that we've finished declaring this member.
6114           Record->finishedDefaultedOrDeletedMember(M);
6115           M->setTrivialForCall(
6116               HasTrivialABI ||
6117               SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6118           Record->setTrivialForCallFlags(M);
6119         }
6120       }
6121 
6122       // Set triviality for the purpose of calls if this is a user-provided
6123       // copy/move constructor or destructor.
6124       if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6125            CSM == CXXDestructor) && M->isUserProvided()) {
6126         M->setTrivialForCall(HasTrivialABI);
6127         Record->setTrivialForCallFlags(M);
6128       }
6129 
6130       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6131           M->hasAttr<DLLExportAttr>()) {
6132         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6133             M->isTrivial() &&
6134             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6135              CSM == CXXDestructor))
6136           M->dropAttr<DLLExportAttr>();
6137 
6138         if (M->hasAttr<DLLExportAttr>()) {
6139           DefineImplicitSpecialMember(*this, M, M->getLocation());
6140           ActOnFinishInlineFunctionDef(M);
6141         }
6142       }
6143     }
6144   }
6145 
6146   if (HasMethodWithOverrideControl &&
6147       HasOverridingMethodWithoutOverrideControl) {
6148     // At least one method has the 'override' control declared.
6149     // Diagnose all other overridden methods which do not have 'override' specified on them.
6150     for (auto *M : Record->methods())
6151       DiagnoseAbsenceOfOverrideControl(M);
6152   }
6153 
6154   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6155   // whether this class uses any C++ features that are implemented
6156   // completely differently in MSVC, and if so, emit a diagnostic.
6157   // That diagnostic defaults to an error, but we allow projects to
6158   // map it down to a warning (or ignore it).  It's a fairly common
6159   // practice among users of the ms_struct pragma to mass-annotate
6160   // headers, sweeping up a bunch of types that the project doesn't
6161   // really rely on MSVC-compatible layout for.  We must therefore
6162   // support "ms_struct except for C++ stuff" as a secondary ABI.
6163   if (Record->isMsStruct(Context) &&
6164       (Record->isPolymorphic() || Record->getNumBases())) {
6165     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6166   }
6167 
6168   checkClassLevelDLLAttribute(Record);
6169   checkClassLevelCodeSegAttribute(Record);
6170 
6171   bool ClangABICompat4 =
6172       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6173   TargetInfo::CallingConvKind CCK =
6174       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6175   bool CanPass = canPassInRegisters(*this, Record, CCK);
6176 
6177   // Do not change ArgPassingRestrictions if it has already been set to
6178   // APK_CanNeverPassInRegs.
6179   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6180     Record->setArgPassingRestrictions(CanPass
6181                                           ? RecordDecl::APK_CanPassInRegs
6182                                           : RecordDecl::APK_CannotPassInRegs);
6183 
6184   // If canPassInRegisters returns true despite the record having a non-trivial
6185   // destructor, the record is destructed in the callee. This happens only when
6186   // the record or one of its subobjects has a field annotated with trivial_abi
6187   // or a field qualified with ObjC __strong/__weak.
6188   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6189     Record->setParamDestroyedInCallee(true);
6190   else if (Record->hasNonTrivialDestructor())
6191     Record->setParamDestroyedInCallee(CanPass);
6192 
6193   if (getLangOpts().ForceEmitVTables) {
6194     // If we want to emit all the vtables, we need to mark it as used.  This
6195     // is especially required for cases like vtable assumption loads.
6196     MarkVTableUsed(Record->getInnerLocStart(), Record);
6197   }
6198 }
6199 
6200 /// Look up the special member function that would be called by a special
6201 /// member function for a subobject of class type.
6202 ///
6203 /// \param Class The class type of the subobject.
6204 /// \param CSM The kind of special member function.
6205 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6206 /// \param ConstRHS True if this is a copy operation with a const object
6207 ///        on its RHS, that is, if the argument to the outer special member
6208 ///        function is 'const' and this is not a field marked 'mutable'.
6209 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6210     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6211     unsigned FieldQuals, bool ConstRHS) {
6212   unsigned LHSQuals = 0;
6213   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6214     LHSQuals = FieldQuals;
6215 
6216   unsigned RHSQuals = FieldQuals;
6217   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6218     RHSQuals = 0;
6219   else if (ConstRHS)
6220     RHSQuals |= Qualifiers::Const;
6221 
6222   return S.LookupSpecialMember(Class, CSM,
6223                                RHSQuals & Qualifiers::Const,
6224                                RHSQuals & Qualifiers::Volatile,
6225                                false,
6226                                LHSQuals & Qualifiers::Const,
6227                                LHSQuals & Qualifiers::Volatile);
6228 }
6229 
6230 class Sema::InheritedConstructorInfo {
6231   Sema &S;
6232   SourceLocation UseLoc;
6233 
6234   /// A mapping from the base classes through which the constructor was
6235   /// inherited to the using shadow declaration in that base class (or a null
6236   /// pointer if the constructor was declared in that base class).
6237   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6238       InheritedFromBases;
6239 
6240 public:
6241   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6242                            ConstructorUsingShadowDecl *Shadow)
6243       : S(S), UseLoc(UseLoc) {
6244     bool DiagnosedMultipleConstructedBases = false;
6245     CXXRecordDecl *ConstructedBase = nullptr;
6246     UsingDecl *ConstructedBaseUsing = nullptr;
6247 
6248     // Find the set of such base class subobjects and check that there's a
6249     // unique constructed subobject.
6250     for (auto *D : Shadow->redecls()) {
6251       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6252       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6253       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6254 
6255       InheritedFromBases.insert(
6256           std::make_pair(DNominatedBase->getCanonicalDecl(),
6257                          DShadow->getNominatedBaseClassShadowDecl()));
6258       if (DShadow->constructsVirtualBase())
6259         InheritedFromBases.insert(
6260             std::make_pair(DConstructedBase->getCanonicalDecl(),
6261                            DShadow->getConstructedBaseClassShadowDecl()));
6262       else
6263         assert(DNominatedBase == DConstructedBase);
6264 
6265       // [class.inhctor.init]p2:
6266       //   If the constructor was inherited from multiple base class subobjects
6267       //   of type B, the program is ill-formed.
6268       if (!ConstructedBase) {
6269         ConstructedBase = DConstructedBase;
6270         ConstructedBaseUsing = D->getUsingDecl();
6271       } else if (ConstructedBase != DConstructedBase &&
6272                  !Shadow->isInvalidDecl()) {
6273         if (!DiagnosedMultipleConstructedBases) {
6274           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6275               << Shadow->getTargetDecl();
6276           S.Diag(ConstructedBaseUsing->getLocation(),
6277                diag::note_ambiguous_inherited_constructor_using)
6278               << ConstructedBase;
6279           DiagnosedMultipleConstructedBases = true;
6280         }
6281         S.Diag(D->getUsingDecl()->getLocation(),
6282                diag::note_ambiguous_inherited_constructor_using)
6283             << DConstructedBase;
6284       }
6285     }
6286 
6287     if (DiagnosedMultipleConstructedBases)
6288       Shadow->setInvalidDecl();
6289   }
6290 
6291   /// Find the constructor to use for inherited construction of a base class,
6292   /// and whether that base class constructor inherits the constructor from a
6293   /// virtual base class (in which case it won't actually invoke it).
6294   std::pair<CXXConstructorDecl *, bool>
6295   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6296     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6297     if (It == InheritedFromBases.end())
6298       return std::make_pair(nullptr, false);
6299 
6300     // This is an intermediary class.
6301     if (It->second)
6302       return std::make_pair(
6303           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6304           It->second->constructsVirtualBase());
6305 
6306     // This is the base class from which the constructor was inherited.
6307     return std::make_pair(Ctor, false);
6308   }
6309 };
6310 
6311 /// Is the special member function which would be selected to perform the
6312 /// specified operation on the specified class type a constexpr constructor?
6313 static bool
6314 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6315                          Sema::CXXSpecialMember CSM, unsigned Quals,
6316                          bool ConstRHS,
6317                          CXXConstructorDecl *InheritedCtor = nullptr,
6318                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6319   // If we're inheriting a constructor, see if we need to call it for this base
6320   // class.
6321   if (InheritedCtor) {
6322     assert(CSM == Sema::CXXDefaultConstructor);
6323     auto BaseCtor =
6324         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6325     if (BaseCtor)
6326       return BaseCtor->isConstexpr();
6327   }
6328 
6329   if (CSM == Sema::CXXDefaultConstructor)
6330     return ClassDecl->hasConstexprDefaultConstructor();
6331 
6332   Sema::SpecialMemberOverloadResult SMOR =
6333       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6334   if (!SMOR.getMethod())
6335     // A constructor we wouldn't select can't be "involved in initializing"
6336     // anything.
6337     return true;
6338   return SMOR.getMethod()->isConstexpr();
6339 }
6340 
6341 /// Determine whether the specified special member function would be constexpr
6342 /// if it were implicitly defined.
6343 static bool defaultedSpecialMemberIsConstexpr(
6344     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6345     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6346     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6347   if (!S.getLangOpts().CPlusPlus11)
6348     return false;
6349 
6350   // C++11 [dcl.constexpr]p4:
6351   // In the definition of a constexpr constructor [...]
6352   bool Ctor = true;
6353   switch (CSM) {
6354   case Sema::CXXDefaultConstructor:
6355     if (Inherited)
6356       break;
6357     // Since default constructor lookup is essentially trivial (and cannot
6358     // involve, for instance, template instantiation), we compute whether a
6359     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6360     //
6361     // This is important for performance; we need to know whether the default
6362     // constructor is constexpr to determine whether the type is a literal type.
6363     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6364 
6365   case Sema::CXXCopyConstructor:
6366   case Sema::CXXMoveConstructor:
6367     // For copy or move constructors, we need to perform overload resolution.
6368     break;
6369 
6370   case Sema::CXXCopyAssignment:
6371   case Sema::CXXMoveAssignment:
6372     if (!S.getLangOpts().CPlusPlus14)
6373       return false;
6374     // In C++1y, we need to perform overload resolution.
6375     Ctor = false;
6376     break;
6377 
6378   case Sema::CXXDestructor:
6379   case Sema::CXXInvalid:
6380     return false;
6381   }
6382 
6383   //   -- if the class is a non-empty union, or for each non-empty anonymous
6384   //      union member of a non-union class, exactly one non-static data member
6385   //      shall be initialized; [DR1359]
6386   //
6387   // If we squint, this is guaranteed, since exactly one non-static data member
6388   // will be initialized (if the constructor isn't deleted), we just don't know
6389   // which one.
6390   if (Ctor && ClassDecl->isUnion())
6391     return CSM == Sema::CXXDefaultConstructor
6392                ? ClassDecl->hasInClassInitializer() ||
6393                      !ClassDecl->hasVariantMembers()
6394                : true;
6395 
6396   //   -- the class shall not have any virtual base classes;
6397   if (Ctor && ClassDecl->getNumVBases())
6398     return false;
6399 
6400   // C++1y [class.copy]p26:
6401   //   -- [the class] is a literal type, and
6402   if (!Ctor && !ClassDecl->isLiteral())
6403     return false;
6404 
6405   //   -- every constructor involved in initializing [...] base class
6406   //      sub-objects shall be a constexpr constructor;
6407   //   -- the assignment operator selected to copy/move each direct base
6408   //      class is a constexpr function, and
6409   for (const auto &B : ClassDecl->bases()) {
6410     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6411     if (!BaseType) continue;
6412 
6413     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6414     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6415                                   InheritedCtor, Inherited))
6416       return false;
6417   }
6418 
6419   //   -- every constructor involved in initializing non-static data members
6420   //      [...] shall be a constexpr constructor;
6421   //   -- every non-static data member and base class sub-object shall be
6422   //      initialized
6423   //   -- for each non-static data member of X that is of class type (or array
6424   //      thereof), the assignment operator selected to copy/move that member is
6425   //      a constexpr function
6426   for (const auto *F : ClassDecl->fields()) {
6427     if (F->isInvalidDecl())
6428       continue;
6429     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6430       continue;
6431     QualType BaseType = S.Context.getBaseElementType(F->getType());
6432     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6433       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6434       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6435                                     BaseType.getCVRQualifiers(),
6436                                     ConstArg && !F->isMutable()))
6437         return false;
6438     } else if (CSM == Sema::CXXDefaultConstructor) {
6439       return false;
6440     }
6441   }
6442 
6443   // All OK, it's constexpr!
6444   return true;
6445 }
6446 
6447 static Sema::ImplicitExceptionSpecification
6448 ComputeDefaultedSpecialMemberExceptionSpec(
6449     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6450     Sema::InheritedConstructorInfo *ICI);
6451 
6452 static Sema::ImplicitExceptionSpecification
6453 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6454   auto CSM = S.getSpecialMember(MD);
6455   if (CSM != Sema::CXXInvalid)
6456     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6457 
6458   auto *CD = cast<CXXConstructorDecl>(MD);
6459   assert(CD->getInheritedConstructor() &&
6460          "only special members have implicit exception specs");
6461   Sema::InheritedConstructorInfo ICI(
6462       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6463   return ComputeDefaultedSpecialMemberExceptionSpec(
6464       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6465 }
6466 
6467 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6468                                                             CXXMethodDecl *MD) {
6469   FunctionProtoType::ExtProtoInfo EPI;
6470 
6471   // Build an exception specification pointing back at this member.
6472   EPI.ExceptionSpec.Type = EST_Unevaluated;
6473   EPI.ExceptionSpec.SourceDecl = MD;
6474 
6475   // Set the calling convention to the default for C++ instance methods.
6476   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6477       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6478                                             /*IsCXXMethod=*/true));
6479   return EPI;
6480 }
6481 
6482 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6483   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6484   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6485     return;
6486 
6487   // Evaluate the exception specification.
6488   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6489   auto ESI = IES.getExceptionSpec();
6490 
6491   // Update the type of the special member to use it.
6492   UpdateExceptionSpec(MD, ESI);
6493 
6494   // A user-provided destructor can be defined outside the class. When that
6495   // happens, be sure to update the exception specification on both
6496   // declarations.
6497   const FunctionProtoType *CanonicalFPT =
6498     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6499   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6500     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6501 }
6502 
6503 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6504   CXXRecordDecl *RD = MD->getParent();
6505   CXXSpecialMember CSM = getSpecialMember(MD);
6506 
6507   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6508          "not an explicitly-defaulted special member");
6509 
6510   // Whether this was the first-declared instance of the constructor.
6511   // This affects whether we implicitly add an exception spec and constexpr.
6512   bool First = MD == MD->getCanonicalDecl();
6513 
6514   bool HadError = false;
6515 
6516   // C++11 [dcl.fct.def.default]p1:
6517   //   A function that is explicitly defaulted shall
6518   //     -- be a special member function (checked elsewhere),
6519   //     -- have the same type (except for ref-qualifiers, and except that a
6520   //        copy operation can take a non-const reference) as an implicit
6521   //        declaration, and
6522   //     -- not have default arguments.
6523   // C++2a changes the second bullet to instead delete the function if it's
6524   // defaulted on its first declaration, unless it's "an assignment operator,
6525   // and its return type differs or its parameter type is not a reference".
6526   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6527   bool ShouldDeleteForTypeMismatch = false;
6528   unsigned ExpectedParams = 1;
6529   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6530     ExpectedParams = 0;
6531   if (MD->getNumParams() != ExpectedParams) {
6532     // This checks for default arguments: a copy or move constructor with a
6533     // default argument is classified as a default constructor, and assignment
6534     // operations and destructors can't have default arguments.
6535     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6536       << CSM << MD->getSourceRange();
6537     HadError = true;
6538   } else if (MD->isVariadic()) {
6539     if (DeleteOnTypeMismatch)
6540       ShouldDeleteForTypeMismatch = true;
6541     else {
6542       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6543         << CSM << MD->getSourceRange();
6544       HadError = true;
6545     }
6546   }
6547 
6548   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6549 
6550   bool CanHaveConstParam = false;
6551   if (CSM == CXXCopyConstructor)
6552     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6553   else if (CSM == CXXCopyAssignment)
6554     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6555 
6556   QualType ReturnType = Context.VoidTy;
6557   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6558     // Check for return type matching.
6559     ReturnType = Type->getReturnType();
6560 
6561     QualType DeclType = Context.getTypeDeclType(RD);
6562     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
6563     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
6564 
6565     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6566       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6567         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6568       HadError = true;
6569     }
6570 
6571     // A defaulted special member cannot have cv-qualifiers.
6572     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
6573       if (DeleteOnTypeMismatch)
6574         ShouldDeleteForTypeMismatch = true;
6575       else {
6576         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6577           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6578         HadError = true;
6579       }
6580     }
6581   }
6582 
6583   // Check for parameter type matching.
6584   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6585   bool HasConstParam = false;
6586   if (ExpectedParams && ArgType->isReferenceType()) {
6587     // Argument must be reference to possibly-const T.
6588     QualType ReferentType = ArgType->getPointeeType();
6589     HasConstParam = ReferentType.isConstQualified();
6590 
6591     if (ReferentType.isVolatileQualified()) {
6592       if (DeleteOnTypeMismatch)
6593         ShouldDeleteForTypeMismatch = true;
6594       else {
6595         Diag(MD->getLocation(),
6596              diag::err_defaulted_special_member_volatile_param) << CSM;
6597         HadError = true;
6598       }
6599     }
6600 
6601     if (HasConstParam && !CanHaveConstParam) {
6602       if (DeleteOnTypeMismatch)
6603         ShouldDeleteForTypeMismatch = true;
6604       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6605         Diag(MD->getLocation(),
6606              diag::err_defaulted_special_member_copy_const_param)
6607           << (CSM == CXXCopyAssignment);
6608         // FIXME: Explain why this special member can't be const.
6609         HadError = true;
6610       } else {
6611         Diag(MD->getLocation(),
6612              diag::err_defaulted_special_member_move_const_param)
6613           << (CSM == CXXMoveAssignment);
6614         HadError = true;
6615       }
6616     }
6617   } else if (ExpectedParams) {
6618     // A copy assignment operator can take its argument by value, but a
6619     // defaulted one cannot.
6620     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6621     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6622     HadError = true;
6623   }
6624 
6625   // C++11 [dcl.fct.def.default]p2:
6626   //   An explicitly-defaulted function may be declared constexpr only if it
6627   //   would have been implicitly declared as constexpr,
6628   // Do not apply this rule to members of class templates, since core issue 1358
6629   // makes such functions always instantiate to constexpr functions. For
6630   // functions which cannot be constexpr (for non-constructors in C++11 and for
6631   // destructors in C++1y), this is checked elsewhere.
6632   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6633                                                      HasConstParam);
6634   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6635                                  : isa<CXXConstructorDecl>(MD)) &&
6636       MD->isConstexpr() && !Constexpr &&
6637       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6638     Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM;
6639     // FIXME: Explain why the special member can't be constexpr.
6640     HadError = true;
6641   }
6642 
6643   //   and may have an explicit exception-specification only if it is compatible
6644   //   with the exception-specification on the implicit declaration.
6645   if (Type->hasExceptionSpec()) {
6646     // Delay the check if this is the first declaration of the special member,
6647     // since we may not have parsed some necessary in-class initializers yet.
6648     if (First) {
6649       // If the exception specification needs to be instantiated, do so now,
6650       // before we clobber it with an EST_Unevaluated specification below.
6651       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6652         InstantiateExceptionSpec(MD->getBeginLoc(), MD);
6653         Type = MD->getType()->getAs<FunctionProtoType>();
6654       }
6655       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6656     } else
6657       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6658   }
6659 
6660   //   If a function is explicitly defaulted on its first declaration,
6661   if (First) {
6662     //  -- it is implicitly considered to be constexpr if the implicit
6663     //     definition would be,
6664     MD->setConstexpr(Constexpr);
6665 
6666     //  -- it is implicitly considered to have the same exception-specification
6667     //     as if it had been implicitly declared,
6668     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6669     EPI.ExceptionSpec.Type = EST_Unevaluated;
6670     EPI.ExceptionSpec.SourceDecl = MD;
6671     MD->setType(Context.getFunctionType(ReturnType,
6672                                         llvm::makeArrayRef(&ArgType,
6673                                                            ExpectedParams),
6674                                         EPI));
6675   }
6676 
6677   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6678     if (First) {
6679       SetDeclDeleted(MD, MD->getLocation());
6680       if (!inTemplateInstantiation() && !HadError) {
6681         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6682         if (ShouldDeleteForTypeMismatch) {
6683           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6684         } else {
6685           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6686         }
6687       }
6688       if (ShouldDeleteForTypeMismatch && !HadError) {
6689         Diag(MD->getLocation(),
6690              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6691       }
6692     } else {
6693       // C++11 [dcl.fct.def.default]p4:
6694       //   [For a] user-provided explicitly-defaulted function [...] if such a
6695       //   function is implicitly defined as deleted, the program is ill-formed.
6696       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6697       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
6698       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6699       HadError = true;
6700     }
6701   }
6702 
6703   if (HadError)
6704     MD->setInvalidDecl();
6705 }
6706 
6707 /// Check whether the exception specification provided for an
6708 /// explicitly-defaulted special member matches the exception specification
6709 /// that would have been generated for an implicit special member, per
6710 /// C++11 [dcl.fct.def.default]p2.
6711 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6712     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6713   // If the exception specification was explicitly specified but hadn't been
6714   // parsed when the method was defaulted, grab it now.
6715   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6716     SpecifiedType =
6717         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6718 
6719   // Compute the implicit exception specification.
6720   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6721                                                        /*IsCXXMethod=*/true);
6722   FunctionProtoType::ExtProtoInfo EPI(CC);
6723   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6724   EPI.ExceptionSpec = IES.getExceptionSpec();
6725   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6726     Context.getFunctionType(Context.VoidTy, None, EPI));
6727 
6728   // Ensure that it matches.
6729   CheckEquivalentExceptionSpec(
6730     PDiag(diag::err_incorrect_defaulted_exception_spec)
6731       << getSpecialMember(MD), PDiag(),
6732     ImplicitType, SourceLocation(),
6733     SpecifiedType, MD->getLocation());
6734 }
6735 
6736 void Sema::CheckDelayedMemberExceptionSpecs() {
6737   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6738   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6739   decltype(DelayedDefaultedMemberExceptionSpecs) Defaulted;
6740 
6741   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6742   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6743   std::swap(Defaulted, DelayedDefaultedMemberExceptionSpecs);
6744 
6745   // Perform any deferred checking of exception specifications for virtual
6746   // destructors.
6747   for (auto &Check : Overriding)
6748     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6749 
6750   // Perform any deferred checking of exception specifications for befriended
6751   // special members.
6752   for (auto &Check : Equivalent)
6753     CheckEquivalentExceptionSpec(Check.second, Check.first);
6754 
6755   // Check that any explicitly-defaulted methods have exception specifications
6756   // compatible with their implicit exception specifications.
6757   for (auto &Spec : Defaulted)
6758     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6759 }
6760 
6761 namespace {
6762 /// CRTP base class for visiting operations performed by a special member
6763 /// function (or inherited constructor).
6764 template<typename Derived>
6765 struct SpecialMemberVisitor {
6766   Sema &S;
6767   CXXMethodDecl *MD;
6768   Sema::CXXSpecialMember CSM;
6769   Sema::InheritedConstructorInfo *ICI;
6770 
6771   // Properties of the special member, computed for convenience.
6772   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6773 
6774   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6775                        Sema::InheritedConstructorInfo *ICI)
6776       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6777     switch (CSM) {
6778     case Sema::CXXDefaultConstructor:
6779     case Sema::CXXCopyConstructor:
6780     case Sema::CXXMoveConstructor:
6781       IsConstructor = true;
6782       break;
6783     case Sema::CXXCopyAssignment:
6784     case Sema::CXXMoveAssignment:
6785       IsAssignment = true;
6786       break;
6787     case Sema::CXXDestructor:
6788       break;
6789     case Sema::CXXInvalid:
6790       llvm_unreachable("invalid special member kind");
6791     }
6792 
6793     if (MD->getNumParams()) {
6794       if (const ReferenceType *RT =
6795               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6796         ConstArg = RT->getPointeeType().isConstQualified();
6797     }
6798   }
6799 
6800   Derived &getDerived() { return static_cast<Derived&>(*this); }
6801 
6802   /// Is this a "move" special member?
6803   bool isMove() const {
6804     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6805   }
6806 
6807   /// Look up the corresponding special member in the given class.
6808   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6809                                              unsigned Quals, bool IsMutable) {
6810     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6811                                        ConstArg && !IsMutable);
6812   }
6813 
6814   /// Look up the constructor for the specified base class to see if it's
6815   /// overridden due to this being an inherited constructor.
6816   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6817     if (!ICI)
6818       return {};
6819     assert(CSM == Sema::CXXDefaultConstructor);
6820     auto *BaseCtor =
6821       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6822     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6823       return MD;
6824     return {};
6825   }
6826 
6827   /// A base or member subobject.
6828   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6829 
6830   /// Get the location to use for a subobject in diagnostics.
6831   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6832     // FIXME: For an indirect virtual base, the direct base leading to
6833     // the indirect virtual base would be a more useful choice.
6834     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6835       return B->getBaseTypeLoc();
6836     else
6837       return Subobj.get<FieldDecl*>()->getLocation();
6838   }
6839 
6840   enum BasesToVisit {
6841     /// Visit all non-virtual (direct) bases.
6842     VisitNonVirtualBases,
6843     /// Visit all direct bases, virtual or not.
6844     VisitDirectBases,
6845     /// Visit all non-virtual bases, and all virtual bases if the class
6846     /// is not abstract.
6847     VisitPotentiallyConstructedBases,
6848     /// Visit all direct or virtual bases.
6849     VisitAllBases
6850   };
6851 
6852   // Visit the bases and members of the class.
6853   bool visit(BasesToVisit Bases) {
6854     CXXRecordDecl *RD = MD->getParent();
6855 
6856     if (Bases == VisitPotentiallyConstructedBases)
6857       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6858 
6859     for (auto &B : RD->bases())
6860       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6861           getDerived().visitBase(&B))
6862         return true;
6863 
6864     if (Bases == VisitAllBases)
6865       for (auto &B : RD->vbases())
6866         if (getDerived().visitBase(&B))
6867           return true;
6868 
6869     for (auto *F : RD->fields())
6870       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6871           getDerived().visitField(F))
6872         return true;
6873 
6874     return false;
6875   }
6876 };
6877 }
6878 
6879 namespace {
6880 struct SpecialMemberDeletionInfo
6881     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6882   bool Diagnose;
6883 
6884   SourceLocation Loc;
6885 
6886   bool AllFieldsAreConst;
6887 
6888   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6889                             Sema::CXXSpecialMember CSM,
6890                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6891       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6892         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6893 
6894   bool inUnion() const { return MD->getParent()->isUnion(); }
6895 
6896   Sema::CXXSpecialMember getEffectiveCSM() {
6897     return ICI ? Sema::CXXInvalid : CSM;
6898   }
6899 
6900   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
6901 
6902   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6903   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6904 
6905   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6906   bool shouldDeleteForField(FieldDecl *FD);
6907   bool shouldDeleteForAllConstMembers();
6908 
6909   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6910                                      unsigned Quals);
6911   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6912                                     Sema::SpecialMemberOverloadResult SMOR,
6913                                     bool IsDtorCallInCtor);
6914 
6915   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6916 };
6917 }
6918 
6919 /// Is the given special member inaccessible when used on the given
6920 /// sub-object.
6921 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6922                                              CXXMethodDecl *target) {
6923   /// If we're operating on a base class, the object type is the
6924   /// type of this special member.
6925   QualType objectTy;
6926   AccessSpecifier access = target->getAccess();
6927   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6928     objectTy = S.Context.getTypeDeclType(MD->getParent());
6929     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6930 
6931   // If we're operating on a field, the object type is the type of the field.
6932   } else {
6933     objectTy = S.Context.getTypeDeclType(target->getParent());
6934   }
6935 
6936   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6937 }
6938 
6939 /// Check whether we should delete a special member due to the implicit
6940 /// definition containing a call to a special member of a subobject.
6941 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6942     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6943     bool IsDtorCallInCtor) {
6944   CXXMethodDecl *Decl = SMOR.getMethod();
6945   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6946 
6947   int DiagKind = -1;
6948 
6949   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6950     DiagKind = !Decl ? 0 : 1;
6951   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6952     DiagKind = 2;
6953   else if (!isAccessible(Subobj, Decl))
6954     DiagKind = 3;
6955   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6956            !Decl->isTrivial()) {
6957     // A member of a union must have a trivial corresponding special member.
6958     // As a weird special case, a destructor call from a union's constructor
6959     // must be accessible and non-deleted, but need not be trivial. Such a
6960     // destructor is never actually called, but is semantically checked as
6961     // if it were.
6962     DiagKind = 4;
6963   }
6964 
6965   if (DiagKind == -1)
6966     return false;
6967 
6968   if (Diagnose) {
6969     if (Field) {
6970       S.Diag(Field->getLocation(),
6971              diag::note_deleted_special_member_class_subobject)
6972         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6973         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
6974     } else {
6975       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6976       S.Diag(Base->getBeginLoc(),
6977              diag::note_deleted_special_member_class_subobject)
6978           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6979           << Base->getType() << DiagKind << IsDtorCallInCtor
6980           << /*IsObjCPtr*/false;
6981     }
6982 
6983     if (DiagKind == 1)
6984       S.NoteDeletedFunction(Decl);
6985     // FIXME: Explain inaccessibility if DiagKind == 3.
6986   }
6987 
6988   return true;
6989 }
6990 
6991 /// Check whether we should delete a special member function due to having a
6992 /// direct or virtual base class or non-static data member of class type M.
6993 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6994     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6995   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6996   bool IsMutable = Field && Field->isMutable();
6997 
6998   // C++11 [class.ctor]p5:
6999   // -- any direct or virtual base class, or non-static data member with no
7000   //    brace-or-equal-initializer, has class type M (or array thereof) and
7001   //    either M has no default constructor or overload resolution as applied
7002   //    to M's default constructor results in an ambiguity or in a function
7003   //    that is deleted or inaccessible
7004   // C++11 [class.copy]p11, C++11 [class.copy]p23:
7005   // -- a direct or virtual base class B that cannot be copied/moved because
7006   //    overload resolution, as applied to B's corresponding special member,
7007   //    results in an ambiguity or a function that is deleted or inaccessible
7008   //    from the defaulted special member
7009   // C++11 [class.dtor]p5:
7010   // -- any direct or virtual base class [...] has a type with a destructor
7011   //    that is deleted or inaccessible
7012   if (!(CSM == Sema::CXXDefaultConstructor &&
7013         Field && Field->hasInClassInitializer()) &&
7014       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
7015                                    false))
7016     return true;
7017 
7018   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
7019   // -- any direct or virtual base class or non-static data member has a
7020   //    type with a destructor that is deleted or inaccessible
7021   if (IsConstructor) {
7022     Sema::SpecialMemberOverloadResult SMOR =
7023         S.LookupSpecialMember(Class, Sema::CXXDestructor,
7024                               false, false, false, false, false);
7025     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
7026       return true;
7027   }
7028 
7029   return false;
7030 }
7031 
7032 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
7033     FieldDecl *FD, QualType FieldType) {
7034   // The defaulted special functions are defined as deleted if this is a variant
7035   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
7036   // type under ARC.
7037   if (!FieldType.hasNonTrivialObjCLifetime())
7038     return false;
7039 
7040   // Don't make the defaulted default constructor defined as deleted if the
7041   // member has an in-class initializer.
7042   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
7043     return false;
7044 
7045   if (Diagnose) {
7046     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
7047     S.Diag(FD->getLocation(),
7048            diag::note_deleted_special_member_class_subobject)
7049         << getEffectiveCSM() << ParentClass << /*IsField*/true
7050         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
7051   }
7052 
7053   return true;
7054 }
7055 
7056 /// Check whether we should delete a special member function due to the class
7057 /// having a particular direct or virtual base class.
7058 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
7059   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
7060   // If program is correct, BaseClass cannot be null, but if it is, the error
7061   // must be reported elsewhere.
7062   if (!BaseClass)
7063     return false;
7064   // If we have an inheriting constructor, check whether we're calling an
7065   // inherited constructor instead of a default constructor.
7066   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
7067   if (auto *BaseCtor = SMOR.getMethod()) {
7068     // Note that we do not check access along this path; other than that,
7069     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
7070     // FIXME: Check that the base has a usable destructor! Sink this into
7071     // shouldDeleteForClassSubobject.
7072     if (BaseCtor->isDeleted() && Diagnose) {
7073       S.Diag(Base->getBeginLoc(),
7074              diag::note_deleted_special_member_class_subobject)
7075           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7076           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
7077           << /*IsObjCPtr*/false;
7078       S.NoteDeletedFunction(BaseCtor);
7079     }
7080     return BaseCtor->isDeleted();
7081   }
7082   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7083 }
7084 
7085 /// Check whether we should delete a special member function due to the class
7086 /// having a particular non-static data member.
7087 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7088   QualType FieldType = S.Context.getBaseElementType(FD->getType());
7089   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7090 
7091   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
7092     return true;
7093 
7094   if (CSM == Sema::CXXDefaultConstructor) {
7095     // For a default constructor, all references must be initialized in-class
7096     // and, if a union, it must have a non-const member.
7097     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7098       if (Diagnose)
7099         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7100           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7101       return true;
7102     }
7103     // C++11 [class.ctor]p5: any non-variant non-static data member of
7104     // const-qualified type (or array thereof) with no
7105     // brace-or-equal-initializer does not have a user-provided default
7106     // constructor.
7107     if (!inUnion() && FieldType.isConstQualified() &&
7108         !FD->hasInClassInitializer() &&
7109         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7110       if (Diagnose)
7111         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7112           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7113       return true;
7114     }
7115 
7116     if (inUnion() && !FieldType.isConstQualified())
7117       AllFieldsAreConst = false;
7118   } else if (CSM == Sema::CXXCopyConstructor) {
7119     // For a copy constructor, data members must not be of rvalue reference
7120     // type.
7121     if (FieldType->isRValueReferenceType()) {
7122       if (Diagnose)
7123         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7124           << MD->getParent() << FD << FieldType;
7125       return true;
7126     }
7127   } else if (IsAssignment) {
7128     // For an assignment operator, data members must not be of reference type.
7129     if (FieldType->isReferenceType()) {
7130       if (Diagnose)
7131         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7132           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7133       return true;
7134     }
7135     if (!FieldRecord && FieldType.isConstQualified()) {
7136       // C++11 [class.copy]p23:
7137       // -- a non-static data member of const non-class type (or array thereof)
7138       if (Diagnose)
7139         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7140           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7141       return true;
7142     }
7143   }
7144 
7145   if (FieldRecord) {
7146     // Some additional restrictions exist on the variant members.
7147     if (!inUnion() && FieldRecord->isUnion() &&
7148         FieldRecord->isAnonymousStructOrUnion()) {
7149       bool AllVariantFieldsAreConst = true;
7150 
7151       // FIXME: Handle anonymous unions declared within anonymous unions.
7152       for (auto *UI : FieldRecord->fields()) {
7153         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7154 
7155         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
7156           return true;
7157 
7158         if (!UnionFieldType.isConstQualified())
7159           AllVariantFieldsAreConst = false;
7160 
7161         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7162         if (UnionFieldRecord &&
7163             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7164                                           UnionFieldType.getCVRQualifiers()))
7165           return true;
7166       }
7167 
7168       // At least one member in each anonymous union must be non-const
7169       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7170           !FieldRecord->field_empty()) {
7171         if (Diagnose)
7172           S.Diag(FieldRecord->getLocation(),
7173                  diag::note_deleted_default_ctor_all_const)
7174             << !!ICI << MD->getParent() << /*anonymous union*/1;
7175         return true;
7176       }
7177 
7178       // Don't check the implicit member of the anonymous union type.
7179       // This is technically non-conformant, but sanity demands it.
7180       return false;
7181     }
7182 
7183     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7184                                       FieldType.getCVRQualifiers()))
7185       return true;
7186   }
7187 
7188   return false;
7189 }
7190 
7191 /// C++11 [class.ctor] p5:
7192 ///   A defaulted default constructor for a class X is defined as deleted if
7193 /// X is a union and all of its variant members are of const-qualified type.
7194 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7195   // This is a silly definition, because it gives an empty union a deleted
7196   // default constructor. Don't do that.
7197   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7198     bool AnyFields = false;
7199     for (auto *F : MD->getParent()->fields())
7200       if ((AnyFields = !F->isUnnamedBitfield()))
7201         break;
7202     if (!AnyFields)
7203       return false;
7204     if (Diagnose)
7205       S.Diag(MD->getParent()->getLocation(),
7206              diag::note_deleted_default_ctor_all_const)
7207         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7208     return true;
7209   }
7210   return false;
7211 }
7212 
7213 /// Determine whether a defaulted special member function should be defined as
7214 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7215 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7216 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7217                                      InheritedConstructorInfo *ICI,
7218                                      bool Diagnose) {
7219   if (MD->isInvalidDecl())
7220     return false;
7221   CXXRecordDecl *RD = MD->getParent();
7222   assert(!RD->isDependentType() && "do deletion after instantiation");
7223   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7224     return false;
7225 
7226   // C++11 [expr.lambda.prim]p19:
7227   //   The closure type associated with a lambda-expression has a
7228   //   deleted (8.4.3) default constructor and a deleted copy
7229   //   assignment operator.
7230   // C++2a adds back these operators if the lambda has no capture-default.
7231   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7232       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7233     if (Diagnose)
7234       Diag(RD->getLocation(), diag::note_lambda_decl);
7235     return true;
7236   }
7237 
7238   // For an anonymous struct or union, the copy and assignment special members
7239   // will never be used, so skip the check. For an anonymous union declared at
7240   // namespace scope, the constructor and destructor are used.
7241   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7242       RD->isAnonymousStructOrUnion())
7243     return false;
7244 
7245   // C++11 [class.copy]p7, p18:
7246   //   If the class definition declares a move constructor or move assignment
7247   //   operator, an implicitly declared copy constructor or copy assignment
7248   //   operator is defined as deleted.
7249   if (MD->isImplicit() &&
7250       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7251     CXXMethodDecl *UserDeclaredMove = nullptr;
7252 
7253     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7254     // deletion of the corresponding copy operation, not both copy operations.
7255     // MSVC 2015 has adopted the standards conforming behavior.
7256     bool DeletesOnlyMatchingCopy =
7257         getLangOpts().MSVCCompat &&
7258         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7259 
7260     if (RD->hasUserDeclaredMoveConstructor() &&
7261         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7262       if (!Diagnose) return true;
7263 
7264       // Find any user-declared move constructor.
7265       for (auto *I : RD->ctors()) {
7266         if (I->isMoveConstructor()) {
7267           UserDeclaredMove = I;
7268           break;
7269         }
7270       }
7271       assert(UserDeclaredMove);
7272     } else if (RD->hasUserDeclaredMoveAssignment() &&
7273                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7274       if (!Diagnose) return true;
7275 
7276       // Find any user-declared move assignment operator.
7277       for (auto *I : RD->methods()) {
7278         if (I->isMoveAssignmentOperator()) {
7279           UserDeclaredMove = I;
7280           break;
7281         }
7282       }
7283       assert(UserDeclaredMove);
7284     }
7285 
7286     if (UserDeclaredMove) {
7287       Diag(UserDeclaredMove->getLocation(),
7288            diag::note_deleted_copy_user_declared_move)
7289         << (CSM == CXXCopyAssignment) << RD
7290         << UserDeclaredMove->isMoveAssignmentOperator();
7291       return true;
7292     }
7293   }
7294 
7295   // Do access control from the special member function
7296   ContextRAII MethodContext(*this, MD);
7297 
7298   // C++11 [class.dtor]p5:
7299   // -- for a virtual destructor, lookup of the non-array deallocation function
7300   //    results in an ambiguity or in a function that is deleted or inaccessible
7301   if (CSM == CXXDestructor && MD->isVirtual()) {
7302     FunctionDecl *OperatorDelete = nullptr;
7303     DeclarationName Name =
7304       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7305     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7306                                  OperatorDelete, /*Diagnose*/false)) {
7307       if (Diagnose)
7308         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7309       return true;
7310     }
7311   }
7312 
7313   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7314 
7315   // Per DR1611, do not consider virtual bases of constructors of abstract
7316   // classes, since we are not going to construct them.
7317   // Per DR1658, do not consider virtual bases of destructors of abstract
7318   // classes either.
7319   // Per DR2180, for assignment operators we only assign (and thus only
7320   // consider) direct bases.
7321   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7322                                  : SMI.VisitPotentiallyConstructedBases))
7323     return true;
7324 
7325   if (SMI.shouldDeleteForAllConstMembers())
7326     return true;
7327 
7328   if (getLangOpts().CUDA) {
7329     // We should delete the special member in CUDA mode if target inference
7330     // failed.
7331     // For inherited constructors (non-null ICI), CSM may be passed so that MD
7332     // is treated as certain special member, which may not reflect what special
7333     // member MD really is. However inferCUDATargetForImplicitSpecialMember
7334     // expects CSM to match MD, therefore recalculate CSM.
7335     assert(ICI || CSM == getSpecialMember(MD));
7336     auto RealCSM = CSM;
7337     if (ICI)
7338       RealCSM = getSpecialMember(MD);
7339 
7340     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7341                                                    SMI.ConstArg, Diagnose);
7342   }
7343 
7344   return false;
7345 }
7346 
7347 /// Perform lookup for a special member of the specified kind, and determine
7348 /// whether it is trivial. If the triviality can be determined without the
7349 /// lookup, skip it. This is intended for use when determining whether a
7350 /// special member of a containing object is trivial, and thus does not ever
7351 /// perform overload resolution for default constructors.
7352 ///
7353 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7354 /// member that was most likely to be intended to be trivial, if any.
7355 ///
7356 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7357 /// determine whether the special member is trivial.
7358 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7359                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7360                                      bool ConstRHS,
7361                                      Sema::TrivialABIHandling TAH,
7362                                      CXXMethodDecl **Selected) {
7363   if (Selected)
7364     *Selected = nullptr;
7365 
7366   switch (CSM) {
7367   case Sema::CXXInvalid:
7368     llvm_unreachable("not a special member");
7369 
7370   case Sema::CXXDefaultConstructor:
7371     // C++11 [class.ctor]p5:
7372     //   A default constructor is trivial if:
7373     //    - all the [direct subobjects] have trivial default constructors
7374     //
7375     // Note, no overload resolution is performed in this case.
7376     if (RD->hasTrivialDefaultConstructor())
7377       return true;
7378 
7379     if (Selected) {
7380       // If there's a default constructor which could have been trivial, dig it
7381       // out. Otherwise, if there's any user-provided default constructor, point
7382       // to that as an example of why there's not a trivial one.
7383       CXXConstructorDecl *DefCtor = nullptr;
7384       if (RD->needsImplicitDefaultConstructor())
7385         S.DeclareImplicitDefaultConstructor(RD);
7386       for (auto *CI : RD->ctors()) {
7387         if (!CI->isDefaultConstructor())
7388           continue;
7389         DefCtor = CI;
7390         if (!DefCtor->isUserProvided())
7391           break;
7392       }
7393 
7394       *Selected = DefCtor;
7395     }
7396 
7397     return false;
7398 
7399   case Sema::CXXDestructor:
7400     // C++11 [class.dtor]p5:
7401     //   A destructor is trivial if:
7402     //    - all the direct [subobjects] have trivial destructors
7403     if (RD->hasTrivialDestructor() ||
7404         (TAH == Sema::TAH_ConsiderTrivialABI &&
7405          RD->hasTrivialDestructorForCall()))
7406       return true;
7407 
7408     if (Selected) {
7409       if (RD->needsImplicitDestructor())
7410         S.DeclareImplicitDestructor(RD);
7411       *Selected = RD->getDestructor();
7412     }
7413 
7414     return false;
7415 
7416   case Sema::CXXCopyConstructor:
7417     // C++11 [class.copy]p12:
7418     //   A copy constructor is trivial if:
7419     //    - the constructor selected to copy each direct [subobject] is trivial
7420     if (RD->hasTrivialCopyConstructor() ||
7421         (TAH == Sema::TAH_ConsiderTrivialABI &&
7422          RD->hasTrivialCopyConstructorForCall())) {
7423       if (Quals == Qualifiers::Const)
7424         // We must either select the trivial copy constructor or reach an
7425         // ambiguity; no need to actually perform overload resolution.
7426         return true;
7427     } else if (!Selected) {
7428       return false;
7429     }
7430     // In C++98, we are not supposed to perform overload resolution here, but we
7431     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7432     // cases like B as having a non-trivial copy constructor:
7433     //   struct A { template<typename T> A(T&); };
7434     //   struct B { mutable A a; };
7435     goto NeedOverloadResolution;
7436 
7437   case Sema::CXXCopyAssignment:
7438     // C++11 [class.copy]p25:
7439     //   A copy assignment operator is trivial if:
7440     //    - the assignment operator selected to copy each direct [subobject] is
7441     //      trivial
7442     if (RD->hasTrivialCopyAssignment()) {
7443       if (Quals == Qualifiers::Const)
7444         return true;
7445     } else if (!Selected) {
7446       return false;
7447     }
7448     // In C++98, we are not supposed to perform overload resolution here, but we
7449     // treat that as a language defect.
7450     goto NeedOverloadResolution;
7451 
7452   case Sema::CXXMoveConstructor:
7453   case Sema::CXXMoveAssignment:
7454   NeedOverloadResolution:
7455     Sema::SpecialMemberOverloadResult SMOR =
7456         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7457 
7458     // The standard doesn't describe how to behave if the lookup is ambiguous.
7459     // We treat it as not making the member non-trivial, just like the standard
7460     // mandates for the default constructor. This should rarely matter, because
7461     // the member will also be deleted.
7462     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7463       return true;
7464 
7465     if (!SMOR.getMethod()) {
7466       assert(SMOR.getKind() ==
7467              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7468       return false;
7469     }
7470 
7471     // We deliberately don't check if we found a deleted special member. We're
7472     // not supposed to!
7473     if (Selected)
7474       *Selected = SMOR.getMethod();
7475 
7476     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7477         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7478       return SMOR.getMethod()->isTrivialForCall();
7479     return SMOR.getMethod()->isTrivial();
7480   }
7481 
7482   llvm_unreachable("unknown special method kind");
7483 }
7484 
7485 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7486   for (auto *CI : RD->ctors())
7487     if (!CI->isImplicit())
7488       return CI;
7489 
7490   // Look for constructor templates.
7491   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7492   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7493     if (CXXConstructorDecl *CD =
7494           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7495       return CD;
7496   }
7497 
7498   return nullptr;
7499 }
7500 
7501 /// The kind of subobject we are checking for triviality. The values of this
7502 /// enumeration are used in diagnostics.
7503 enum TrivialSubobjectKind {
7504   /// The subobject is a base class.
7505   TSK_BaseClass,
7506   /// The subobject is a non-static data member.
7507   TSK_Field,
7508   /// The object is actually the complete object.
7509   TSK_CompleteObject
7510 };
7511 
7512 /// Check whether the special member selected for a given type would be trivial.
7513 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7514                                       QualType SubType, bool ConstRHS,
7515                                       Sema::CXXSpecialMember CSM,
7516                                       TrivialSubobjectKind Kind,
7517                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7518   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7519   if (!SubRD)
7520     return true;
7521 
7522   CXXMethodDecl *Selected;
7523   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7524                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7525     return true;
7526 
7527   if (Diagnose) {
7528     if (ConstRHS)
7529       SubType.addConst();
7530 
7531     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7532       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7533         << Kind << SubType.getUnqualifiedType();
7534       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7535         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7536     } else if (!Selected)
7537       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7538         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7539     else if (Selected->isUserProvided()) {
7540       if (Kind == TSK_CompleteObject)
7541         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7542           << Kind << SubType.getUnqualifiedType() << CSM;
7543       else {
7544         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7545           << Kind << SubType.getUnqualifiedType() << CSM;
7546         S.Diag(Selected->getLocation(), diag::note_declared_at);
7547       }
7548     } else {
7549       if (Kind != TSK_CompleteObject)
7550         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7551           << Kind << SubType.getUnqualifiedType() << CSM;
7552 
7553       // Explain why the defaulted or deleted special member isn't trivial.
7554       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7555                                Diagnose);
7556     }
7557   }
7558 
7559   return false;
7560 }
7561 
7562 /// Check whether the members of a class type allow a special member to be
7563 /// trivial.
7564 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7565                                      Sema::CXXSpecialMember CSM,
7566                                      bool ConstArg,
7567                                      Sema::TrivialABIHandling TAH,
7568                                      bool Diagnose) {
7569   for (const auto *FI : RD->fields()) {
7570     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7571       continue;
7572 
7573     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7574 
7575     // Pretend anonymous struct or union members are members of this class.
7576     if (FI->isAnonymousStructOrUnion()) {
7577       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7578                                     CSM, ConstArg, TAH, Diagnose))
7579         return false;
7580       continue;
7581     }
7582 
7583     // C++11 [class.ctor]p5:
7584     //   A default constructor is trivial if [...]
7585     //    -- no non-static data member of its class has a
7586     //       brace-or-equal-initializer
7587     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7588       if (Diagnose)
7589         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7590       return false;
7591     }
7592 
7593     // Objective C ARC 4.3.5:
7594     //   [...] nontrivally ownership-qualified types are [...] not trivially
7595     //   default constructible, copy constructible, move constructible, copy
7596     //   assignable, move assignable, or destructible [...]
7597     if (FieldType.hasNonTrivialObjCLifetime()) {
7598       if (Diagnose)
7599         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7600           << RD << FieldType.getObjCLifetime();
7601       return false;
7602     }
7603 
7604     bool ConstRHS = ConstArg && !FI->isMutable();
7605     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7606                                    CSM, TSK_Field, TAH, Diagnose))
7607       return false;
7608   }
7609 
7610   return true;
7611 }
7612 
7613 /// Diagnose why the specified class does not have a trivial special member of
7614 /// the given kind.
7615 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7616   QualType Ty = Context.getRecordType(RD);
7617 
7618   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7619   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7620                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7621                             /*Diagnose*/true);
7622 }
7623 
7624 /// Determine whether a defaulted or deleted special member function is trivial,
7625 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7626 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7627 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7628                                   TrivialABIHandling TAH, bool Diagnose) {
7629   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7630 
7631   CXXRecordDecl *RD = MD->getParent();
7632 
7633   bool ConstArg = false;
7634 
7635   // C++11 [class.copy]p12, p25: [DR1593]
7636   //   A [special member] is trivial if [...] its parameter-type-list is
7637   //   equivalent to the parameter-type-list of an implicit declaration [...]
7638   switch (CSM) {
7639   case CXXDefaultConstructor:
7640   case CXXDestructor:
7641     // Trivial default constructors and destructors cannot have parameters.
7642     break;
7643 
7644   case CXXCopyConstructor:
7645   case CXXCopyAssignment: {
7646     // Trivial copy operations always have const, non-volatile parameter types.
7647     ConstArg = true;
7648     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7649     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7650     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7651       if (Diagnose)
7652         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7653           << Param0->getSourceRange() << Param0->getType()
7654           << Context.getLValueReferenceType(
7655                Context.getRecordType(RD).withConst());
7656       return false;
7657     }
7658     break;
7659   }
7660 
7661   case CXXMoveConstructor:
7662   case CXXMoveAssignment: {
7663     // Trivial move operations always have non-cv-qualified parameters.
7664     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7665     const RValueReferenceType *RT =
7666       Param0->getType()->getAs<RValueReferenceType>();
7667     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7668       if (Diagnose)
7669         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7670           << Param0->getSourceRange() << Param0->getType()
7671           << Context.getRValueReferenceType(Context.getRecordType(RD));
7672       return false;
7673     }
7674     break;
7675   }
7676 
7677   case CXXInvalid:
7678     llvm_unreachable("not a special member");
7679   }
7680 
7681   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7682     if (Diagnose)
7683       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7684            diag::note_nontrivial_default_arg)
7685         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7686     return false;
7687   }
7688   if (MD->isVariadic()) {
7689     if (Diagnose)
7690       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7691     return false;
7692   }
7693 
7694   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7695   //   A copy/move [constructor or assignment operator] is trivial if
7696   //    -- the [member] selected to copy/move each direct base class subobject
7697   //       is trivial
7698   //
7699   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7700   //   A [default constructor or destructor] is trivial if
7701   //    -- all the direct base classes have trivial [default constructors or
7702   //       destructors]
7703   for (const auto &BI : RD->bases())
7704     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7705                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7706       return false;
7707 
7708   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7709   //   A copy/move [constructor or assignment operator] for a class X is
7710   //   trivial if
7711   //    -- for each non-static data member of X that is of class type (or array
7712   //       thereof), the constructor selected to copy/move that member is
7713   //       trivial
7714   //
7715   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7716   //   A [default constructor or destructor] is trivial if
7717   //    -- for all of the non-static data members of its class that are of class
7718   //       type (or array thereof), each such class has a trivial [default
7719   //       constructor or destructor]
7720   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7721     return false;
7722 
7723   // C++11 [class.dtor]p5:
7724   //   A destructor is trivial if [...]
7725   //    -- the destructor is not virtual
7726   if (CSM == CXXDestructor && MD->isVirtual()) {
7727     if (Diagnose)
7728       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7729     return false;
7730   }
7731 
7732   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7733   //   A [special member] for class X is trivial if [...]
7734   //    -- class X has no virtual functions and no virtual base classes
7735   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7736     if (!Diagnose)
7737       return false;
7738 
7739     if (RD->getNumVBases()) {
7740       // Check for virtual bases. We already know that the corresponding
7741       // member in all bases is trivial, so vbases must all be direct.
7742       CXXBaseSpecifier &BS = *RD->vbases_begin();
7743       assert(BS.isVirtual());
7744       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7745       return false;
7746     }
7747 
7748     // Must have a virtual method.
7749     for (const auto *MI : RD->methods()) {
7750       if (MI->isVirtual()) {
7751         SourceLocation MLoc = MI->getBeginLoc();
7752         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7753         return false;
7754       }
7755     }
7756 
7757     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7758   }
7759 
7760   // Looks like it's trivial!
7761   return true;
7762 }
7763 
7764 namespace {
7765 struct FindHiddenVirtualMethod {
7766   Sema *S;
7767   CXXMethodDecl *Method;
7768   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7769   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7770 
7771 private:
7772   /// Check whether any most overridden method from MD in Methods
7773   static bool CheckMostOverridenMethods(
7774       const CXXMethodDecl *MD,
7775       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7776     if (MD->size_overridden_methods() == 0)
7777       return Methods.count(MD->getCanonicalDecl());
7778     for (const CXXMethodDecl *O : MD->overridden_methods())
7779       if (CheckMostOverridenMethods(O, Methods))
7780         return true;
7781     return false;
7782   }
7783 
7784 public:
7785   /// Member lookup function that determines whether a given C++
7786   /// method overloads virtual methods in a base class without overriding any,
7787   /// to be used with CXXRecordDecl::lookupInBases().
7788   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7789     RecordDecl *BaseRecord =
7790         Specifier->getType()->getAs<RecordType>()->getDecl();
7791 
7792     DeclarationName Name = Method->getDeclName();
7793     assert(Name.getNameKind() == DeclarationName::Identifier);
7794 
7795     bool foundSameNameMethod = false;
7796     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7797     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7798          Path.Decls = Path.Decls.slice(1)) {
7799       NamedDecl *D = Path.Decls.front();
7800       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7801         MD = MD->getCanonicalDecl();
7802         foundSameNameMethod = true;
7803         // Interested only in hidden virtual methods.
7804         if (!MD->isVirtual())
7805           continue;
7806         // If the method we are checking overrides a method from its base
7807         // don't warn about the other overloaded methods. Clang deviates from
7808         // GCC by only diagnosing overloads of inherited virtual functions that
7809         // do not override any other virtual functions in the base. GCC's
7810         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7811         // function from a base class. These cases may be better served by a
7812         // warning (not specific to virtual functions) on call sites when the
7813         // call would select a different function from the base class, were it
7814         // visible.
7815         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7816         if (!S->IsOverload(Method, MD, false))
7817           return true;
7818         // Collect the overload only if its hidden.
7819         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7820           overloadedMethods.push_back(MD);
7821       }
7822     }
7823 
7824     if (foundSameNameMethod)
7825       OverloadedMethods.append(overloadedMethods.begin(),
7826                                overloadedMethods.end());
7827     return foundSameNameMethod;
7828   }
7829 };
7830 } // end anonymous namespace
7831 
7832 /// Add the most overriden methods from MD to Methods
7833 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7834                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7835   if (MD->size_overridden_methods() == 0)
7836     Methods.insert(MD->getCanonicalDecl());
7837   else
7838     for (const CXXMethodDecl *O : MD->overridden_methods())
7839       AddMostOverridenMethods(O, Methods);
7840 }
7841 
7842 /// Check if a method overloads virtual methods in a base class without
7843 /// overriding any.
7844 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7845                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7846   if (!MD->getDeclName().isIdentifier())
7847     return;
7848 
7849   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7850                      /*bool RecordPaths=*/false,
7851                      /*bool DetectVirtual=*/false);
7852   FindHiddenVirtualMethod FHVM;
7853   FHVM.Method = MD;
7854   FHVM.S = this;
7855 
7856   // Keep the base methods that were overridden or introduced in the subclass
7857   // by 'using' in a set. A base method not in this set is hidden.
7858   CXXRecordDecl *DC = MD->getParent();
7859   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7860   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7861     NamedDecl *ND = *I;
7862     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7863       ND = shad->getTargetDecl();
7864     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7865       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7866   }
7867 
7868   if (DC->lookupInBases(FHVM, Paths))
7869     OverloadedMethods = FHVM.OverloadedMethods;
7870 }
7871 
7872 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7873                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7874   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7875     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7876     PartialDiagnostic PD = PDiag(
7877          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7878     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7879     Diag(overloadedMD->getLocation(), PD);
7880   }
7881 }
7882 
7883 /// Diagnose methods which overload virtual methods in a base class
7884 /// without overriding any.
7885 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7886   if (MD->isInvalidDecl())
7887     return;
7888 
7889   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7890     return;
7891 
7892   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7893   FindHiddenVirtualMethods(MD, OverloadedMethods);
7894   if (!OverloadedMethods.empty()) {
7895     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7896       << MD << (OverloadedMethods.size() > 1);
7897 
7898     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7899   }
7900 }
7901 
7902 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7903   auto PrintDiagAndRemoveAttr = [&]() {
7904     // No diagnostics if this is a template instantiation.
7905     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7906       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7907            diag::ext_cannot_use_trivial_abi) << &RD;
7908     RD.dropAttr<TrivialABIAttr>();
7909   };
7910 
7911   // Ill-formed if the struct has virtual functions.
7912   if (RD.isPolymorphic()) {
7913     PrintDiagAndRemoveAttr();
7914     return;
7915   }
7916 
7917   for (const auto &B : RD.bases()) {
7918     // Ill-formed if the base class is non-trivial for the purpose of calls or a
7919     // virtual base.
7920     if ((!B.getType()->isDependentType() &&
7921          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7922         B.isVirtual()) {
7923       PrintDiagAndRemoveAttr();
7924       return;
7925     }
7926   }
7927 
7928   for (const auto *FD : RD.fields()) {
7929     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7930     // non-trivial for the purpose of calls.
7931     QualType FT = FD->getType();
7932     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7933       PrintDiagAndRemoveAttr();
7934       return;
7935     }
7936 
7937     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7938       if (!RT->isDependentType() &&
7939           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7940         PrintDiagAndRemoveAttr();
7941         return;
7942       }
7943   }
7944 }
7945 
7946 void Sema::ActOnFinishCXXMemberSpecification(
7947     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
7948     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
7949   if (!TagDecl)
7950     return;
7951 
7952   AdjustDeclIfTemplate(TagDecl);
7953 
7954   for (const ParsedAttr &AL : AttrList) {
7955     if (AL.getKind() != ParsedAttr::AT_Visibility)
7956       continue;
7957     AL.setInvalid();
7958     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
7959         << AL.getName();
7960   }
7961 
7962   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7963               // strict aliasing violation!
7964               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7965               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7966 
7967   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7968 }
7969 
7970 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7971 /// special functions, such as the default constructor, copy
7972 /// constructor, or destructor, to the given C++ class (C++
7973 /// [special]p1).  This routine can only be executed just before the
7974 /// definition of the class is complete.
7975 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7976   if (ClassDecl->needsImplicitDefaultConstructor()) {
7977     ++getASTContext().NumImplicitDefaultConstructors;
7978 
7979     if (ClassDecl->hasInheritedConstructor())
7980       DeclareImplicitDefaultConstructor(ClassDecl);
7981   }
7982 
7983   if (ClassDecl->needsImplicitCopyConstructor()) {
7984     ++getASTContext().NumImplicitCopyConstructors;
7985 
7986     // If the properties or semantics of the copy constructor couldn't be
7987     // determined while the class was being declared, force a declaration
7988     // of it now.
7989     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7990         ClassDecl->hasInheritedConstructor())
7991       DeclareImplicitCopyConstructor(ClassDecl);
7992     // For the MS ABI we need to know whether the copy ctor is deleted. A
7993     // prerequisite for deleting the implicit copy ctor is that the class has a
7994     // move ctor or move assignment that is either user-declared or whose
7995     // semantics are inherited from a subobject. FIXME: We should provide a more
7996     // direct way for CodeGen to ask whether the constructor was deleted.
7997     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7998              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7999               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8000               ClassDecl->hasUserDeclaredMoveAssignment() ||
8001               ClassDecl->needsOverloadResolutionForMoveAssignment()))
8002       DeclareImplicitCopyConstructor(ClassDecl);
8003   }
8004 
8005   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
8006     ++getASTContext().NumImplicitMoveConstructors;
8007 
8008     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8009         ClassDecl->hasInheritedConstructor())
8010       DeclareImplicitMoveConstructor(ClassDecl);
8011   }
8012 
8013   if (ClassDecl->needsImplicitCopyAssignment()) {
8014     ++getASTContext().NumImplicitCopyAssignmentOperators;
8015 
8016     // If we have a dynamic class, then the copy assignment operator may be
8017     // virtual, so we have to declare it immediately. This ensures that, e.g.,
8018     // it shows up in the right place in the vtable and that we diagnose
8019     // problems with the implicit exception specification.
8020     if (ClassDecl->isDynamicClass() ||
8021         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
8022         ClassDecl->hasInheritedAssignment())
8023       DeclareImplicitCopyAssignment(ClassDecl);
8024   }
8025 
8026   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
8027     ++getASTContext().NumImplicitMoveAssignmentOperators;
8028 
8029     // Likewise for the move assignment operator.
8030     if (ClassDecl->isDynamicClass() ||
8031         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
8032         ClassDecl->hasInheritedAssignment())
8033       DeclareImplicitMoveAssignment(ClassDecl);
8034   }
8035 
8036   if (ClassDecl->needsImplicitDestructor()) {
8037     ++getASTContext().NumImplicitDestructors;
8038 
8039     // If we have a dynamic class, then the destructor may be virtual, so we
8040     // have to declare the destructor immediately. This ensures that, e.g., it
8041     // shows up in the right place in the vtable and that we diagnose problems
8042     // with the implicit exception specification.
8043     if (ClassDecl->isDynamicClass() ||
8044         ClassDecl->needsOverloadResolutionForDestructor())
8045       DeclareImplicitDestructor(ClassDecl);
8046   }
8047 }
8048 
8049 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
8050   if (!D)
8051     return 0;
8052 
8053   // The order of template parameters is not important here. All names
8054   // get added to the same scope.
8055   SmallVector<TemplateParameterList *, 4> ParameterLists;
8056 
8057   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8058     D = TD->getTemplatedDecl();
8059 
8060   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
8061     ParameterLists.push_back(PSD->getTemplateParameters());
8062 
8063   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
8064     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
8065       ParameterLists.push_back(DD->getTemplateParameterList(i));
8066 
8067     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8068       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
8069         ParameterLists.push_back(FTD->getTemplateParameters());
8070     }
8071   }
8072 
8073   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8074     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
8075       ParameterLists.push_back(TD->getTemplateParameterList(i));
8076 
8077     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
8078       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
8079         ParameterLists.push_back(CTD->getTemplateParameters());
8080     }
8081   }
8082 
8083   unsigned Count = 0;
8084   for (TemplateParameterList *Params : ParameterLists) {
8085     if (Params->size() > 0)
8086       // Ignore explicit specializations; they don't contribute to the template
8087       // depth.
8088       ++Count;
8089     for (NamedDecl *Param : *Params) {
8090       if (Param->getDeclName()) {
8091         S->AddDecl(Param);
8092         IdResolver.AddDecl(Param);
8093       }
8094     }
8095   }
8096 
8097   return Count;
8098 }
8099 
8100 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8101   if (!RecordD) return;
8102   AdjustDeclIfTemplate(RecordD);
8103   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8104   PushDeclContext(S, Record);
8105 }
8106 
8107 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8108   if (!RecordD) return;
8109   PopDeclContext();
8110 }
8111 
8112 /// This is used to implement the constant expression evaluation part of the
8113 /// attribute enable_if extension. There is nothing in standard C++ which would
8114 /// require reentering parameters.
8115 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8116   if (!Param)
8117     return;
8118 
8119   S->AddDecl(Param);
8120   if (Param->getDeclName())
8121     IdResolver.AddDecl(Param);
8122 }
8123 
8124 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
8125 /// parsing a top-level (non-nested) C++ class, and we are now
8126 /// parsing those parts of the given Method declaration that could
8127 /// not be parsed earlier (C++ [class.mem]p2), such as default
8128 /// arguments. This action should enter the scope of the given
8129 /// Method declaration as if we had just parsed the qualified method
8130 /// name. However, it should not bring the parameters into scope;
8131 /// that will be performed by ActOnDelayedCXXMethodParameter.
8132 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8133 }
8134 
8135 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8136 /// C++ method declaration. We're (re-)introducing the given
8137 /// function parameter into scope for use in parsing later parts of
8138 /// the method declaration. For example, we could see an
8139 /// ActOnParamDefaultArgument event for this parameter.
8140 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8141   if (!ParamD)
8142     return;
8143 
8144   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8145 
8146   // If this parameter has an unparsed default argument, clear it out
8147   // to make way for the parsed default argument.
8148   if (Param->hasUnparsedDefaultArg())
8149     Param->setDefaultArg(nullptr);
8150 
8151   S->AddDecl(Param);
8152   if (Param->getDeclName())
8153     IdResolver.AddDecl(Param);
8154 }
8155 
8156 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8157 /// processing the delayed method declaration for Method. The method
8158 /// declaration is now considered finished. There may be a separate
8159 /// ActOnStartOfFunctionDef action later (not necessarily
8160 /// immediately!) for this method, if it was also defined inside the
8161 /// class body.
8162 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8163   if (!MethodD)
8164     return;
8165 
8166   AdjustDeclIfTemplate(MethodD);
8167 
8168   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8169 
8170   // Now that we have our default arguments, check the constructor
8171   // again. It could produce additional diagnostics or affect whether
8172   // the class has implicitly-declared destructors, among other
8173   // things.
8174   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8175     CheckConstructor(Constructor);
8176 
8177   // Check the default arguments, which we may have added.
8178   if (!Method->isInvalidDecl())
8179     CheckCXXDefaultArguments(Method);
8180 }
8181 
8182 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8183 /// the well-formedness of the constructor declarator @p D with type @p
8184 /// R. If there are any errors in the declarator, this routine will
8185 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8186 /// will be updated to reflect a well-formed type for the constructor and
8187 /// returned.
8188 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8189                                           StorageClass &SC) {
8190   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8191 
8192   // C++ [class.ctor]p3:
8193   //   A constructor shall not be virtual (10.3) or static (9.4). A
8194   //   constructor can be invoked for a const, volatile or const
8195   //   volatile object. A constructor shall not be declared const,
8196   //   volatile, or const volatile (9.3.2).
8197   if (isVirtual) {
8198     if (!D.isInvalidType())
8199       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8200         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8201         << SourceRange(D.getIdentifierLoc());
8202     D.setInvalidType();
8203   }
8204   if (SC == SC_Static) {
8205     if (!D.isInvalidType())
8206       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8207         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8208         << SourceRange(D.getIdentifierLoc());
8209     D.setInvalidType();
8210     SC = SC_None;
8211   }
8212 
8213   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8214     diagnoseIgnoredQualifiers(
8215         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8216         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8217         D.getDeclSpec().getRestrictSpecLoc(),
8218         D.getDeclSpec().getAtomicSpecLoc());
8219     D.setInvalidType();
8220   }
8221 
8222   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8223   if (FTI.hasMethodTypeQualifiers()) {
8224     FTI.MethodQualifiers->forEachQualifier(
8225         [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
8226           Diag(SL, diag::err_invalid_qualified_constructor)
8227               << QualName << SourceRange(SL);
8228         });
8229     D.setInvalidType();
8230   }
8231 
8232   // C++0x [class.ctor]p4:
8233   //   A constructor shall not be declared with a ref-qualifier.
8234   if (FTI.hasRefQualifier()) {
8235     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8236       << FTI.RefQualifierIsLValueRef
8237       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8238     D.setInvalidType();
8239   }
8240 
8241   // Rebuild the function type "R" without any type qualifiers (in
8242   // case any of the errors above fired) and with "void" as the
8243   // return type, since constructors don't have return types.
8244   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8245   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8246     return R;
8247 
8248   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8249   EPI.TypeQuals = Qualifiers();
8250   EPI.RefQualifier = RQ_None;
8251 
8252   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8253 }
8254 
8255 /// CheckConstructor - Checks a fully-formed constructor for
8256 /// well-formedness, issuing any diagnostics required. Returns true if
8257 /// the constructor declarator is invalid.
8258 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8259   CXXRecordDecl *ClassDecl
8260     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8261   if (!ClassDecl)
8262     return Constructor->setInvalidDecl();
8263 
8264   // C++ [class.copy]p3:
8265   //   A declaration of a constructor for a class X is ill-formed if
8266   //   its first parameter is of type (optionally cv-qualified) X and
8267   //   either there are no other parameters or else all other
8268   //   parameters have default arguments.
8269   if (!Constructor->isInvalidDecl() &&
8270       ((Constructor->getNumParams() == 1) ||
8271        (Constructor->getNumParams() > 1 &&
8272         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8273       Constructor->getTemplateSpecializationKind()
8274                                               != TSK_ImplicitInstantiation) {
8275     QualType ParamType = Constructor->getParamDecl(0)->getType();
8276     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8277     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8278       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8279       const char *ConstRef
8280         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8281                                                         : " const &";
8282       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8283         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8284 
8285       // FIXME: Rather that making the constructor invalid, we should endeavor
8286       // to fix the type.
8287       Constructor->setInvalidDecl();
8288     }
8289   }
8290 }
8291 
8292 /// CheckDestructor - Checks a fully-formed destructor definition for
8293 /// well-formedness, issuing any diagnostics required.  Returns true
8294 /// on error.
8295 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8296   CXXRecordDecl *RD = Destructor->getParent();
8297 
8298   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8299     SourceLocation Loc;
8300 
8301     if (!Destructor->isImplicit())
8302       Loc = Destructor->getLocation();
8303     else
8304       Loc = RD->getLocation();
8305 
8306     // If we have a virtual destructor, look up the deallocation function
8307     if (FunctionDecl *OperatorDelete =
8308             FindDeallocationFunctionForDestructor(Loc, RD)) {
8309       Expr *ThisArg = nullptr;
8310 
8311       // If the notional 'delete this' expression requires a non-trivial
8312       // conversion from 'this' to the type of a destroying operator delete's
8313       // first parameter, perform that conversion now.
8314       if (OperatorDelete->isDestroyingOperatorDelete()) {
8315         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8316         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8317           // C++ [class.dtor]p13:
8318           //   ... as if for the expression 'delete this' appearing in a
8319           //   non-virtual destructor of the destructor's class.
8320           ContextRAII SwitchContext(*this, Destructor);
8321           ExprResult This =
8322               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8323           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8324           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8325           if (This.isInvalid()) {
8326             // FIXME: Register this as a context note so that it comes out
8327             // in the right order.
8328             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8329             return true;
8330           }
8331           ThisArg = This.get();
8332         }
8333       }
8334 
8335       DiagnoseUseOfDecl(OperatorDelete, Loc);
8336       MarkFunctionReferenced(Loc, OperatorDelete);
8337       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8338     }
8339   }
8340 
8341   return false;
8342 }
8343 
8344 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8345 /// the well-formednes of the destructor declarator @p D with type @p
8346 /// R. If there are any errors in the declarator, this routine will
8347 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8348 /// will be updated to reflect a well-formed type for the destructor and
8349 /// returned.
8350 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8351                                          StorageClass& SC) {
8352   // C++ [class.dtor]p1:
8353   //   [...] A typedef-name that names a class is a class-name
8354   //   (7.1.3); however, a typedef-name that names a class shall not
8355   //   be used as the identifier in the declarator for a destructor
8356   //   declaration.
8357   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8358   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8359     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8360       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8361   else if (const TemplateSpecializationType *TST =
8362              DeclaratorType->getAs<TemplateSpecializationType>())
8363     if (TST->isTypeAlias())
8364       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8365         << DeclaratorType << 1;
8366 
8367   // C++ [class.dtor]p2:
8368   //   A destructor is used to destroy objects of its class type. A
8369   //   destructor takes no parameters, and no return type can be
8370   //   specified for it (not even void). The address of a destructor
8371   //   shall not be taken. A destructor shall not be static. A
8372   //   destructor can be invoked for a const, volatile or const
8373   //   volatile object. A destructor shall not be declared const,
8374   //   volatile or const volatile (9.3.2).
8375   if (SC == SC_Static) {
8376     if (!D.isInvalidType())
8377       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8378         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8379         << SourceRange(D.getIdentifierLoc())
8380         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8381 
8382     SC = SC_None;
8383   }
8384   if (!D.isInvalidType()) {
8385     // Destructors don't have return types, but the parser will
8386     // happily parse something like:
8387     //
8388     //   class X {
8389     //     float ~X();
8390     //   };
8391     //
8392     // The return type will be eliminated later.
8393     if (D.getDeclSpec().hasTypeSpecifier())
8394       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8395         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8396         << SourceRange(D.getIdentifierLoc());
8397     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8398       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8399                                 SourceLocation(),
8400                                 D.getDeclSpec().getConstSpecLoc(),
8401                                 D.getDeclSpec().getVolatileSpecLoc(),
8402                                 D.getDeclSpec().getRestrictSpecLoc(),
8403                                 D.getDeclSpec().getAtomicSpecLoc());
8404       D.setInvalidType();
8405     }
8406   }
8407 
8408   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8409   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
8410     FTI.MethodQualifiers->forEachQualifier(
8411         [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
8412           Diag(SL, diag::err_invalid_qualified_destructor)
8413               << QualName << SourceRange(SL);
8414         });
8415     D.setInvalidType();
8416   }
8417 
8418   // C++0x [class.dtor]p2:
8419   //   A destructor shall not be declared with a ref-qualifier.
8420   if (FTI.hasRefQualifier()) {
8421     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8422       << FTI.RefQualifierIsLValueRef
8423       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8424     D.setInvalidType();
8425   }
8426 
8427   // Make sure we don't have any parameters.
8428   if (FTIHasNonVoidParameters(FTI)) {
8429     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8430 
8431     // Delete the parameters.
8432     FTI.freeParams();
8433     D.setInvalidType();
8434   }
8435 
8436   // Make sure the destructor isn't variadic.
8437   if (FTI.isVariadic) {
8438     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8439     D.setInvalidType();
8440   }
8441 
8442   // Rebuild the function type "R" without any type qualifiers or
8443   // parameters (in case any of the errors above fired) and with
8444   // "void" as the return type, since destructors don't have return
8445   // types.
8446   if (!D.isInvalidType())
8447     return R;
8448 
8449   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8450   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8451   EPI.Variadic = false;
8452   EPI.TypeQuals = Qualifiers();
8453   EPI.RefQualifier = RQ_None;
8454   return Context.getFunctionType(Context.VoidTy, None, EPI);
8455 }
8456 
8457 static void extendLeft(SourceRange &R, SourceRange Before) {
8458   if (Before.isInvalid())
8459     return;
8460   R.setBegin(Before.getBegin());
8461   if (R.getEnd().isInvalid())
8462     R.setEnd(Before.getEnd());
8463 }
8464 
8465 static void extendRight(SourceRange &R, SourceRange After) {
8466   if (After.isInvalid())
8467     return;
8468   if (R.getBegin().isInvalid())
8469     R.setBegin(After.getBegin());
8470   R.setEnd(After.getEnd());
8471 }
8472 
8473 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8474 /// well-formednes of the conversion function declarator @p D with
8475 /// type @p R. If there are any errors in the declarator, this routine
8476 /// will emit diagnostics and return true. Otherwise, it will return
8477 /// false. Either way, the type @p R will be updated to reflect a
8478 /// well-formed type for the conversion operator.
8479 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8480                                      StorageClass& SC) {
8481   // C++ [class.conv.fct]p1:
8482   //   Neither parameter types nor return type can be specified. The
8483   //   type of a conversion function (8.3.5) is "function taking no
8484   //   parameter returning conversion-type-id."
8485   if (SC == SC_Static) {
8486     if (!D.isInvalidType())
8487       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8488         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8489         << D.getName().getSourceRange();
8490     D.setInvalidType();
8491     SC = SC_None;
8492   }
8493 
8494   TypeSourceInfo *ConvTSI = nullptr;
8495   QualType ConvType =
8496       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8497 
8498   const DeclSpec &DS = D.getDeclSpec();
8499   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8500     // Conversion functions don't have return types, but the parser will
8501     // happily parse something like:
8502     //
8503     //   class X {
8504     //     float operator bool();
8505     //   };
8506     //
8507     // The return type will be changed later anyway.
8508     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8509       << SourceRange(DS.getTypeSpecTypeLoc())
8510       << SourceRange(D.getIdentifierLoc());
8511     D.setInvalidType();
8512   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8513     // It's also plausible that the user writes type qualifiers in the wrong
8514     // place, such as:
8515     //   struct S { const operator int(); };
8516     // FIXME: we could provide a fixit to move the qualifiers onto the
8517     // conversion type.
8518     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8519         << SourceRange(D.getIdentifierLoc()) << 0;
8520     D.setInvalidType();
8521   }
8522 
8523   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8524 
8525   // Make sure we don't have any parameters.
8526   if (Proto->getNumParams() > 0) {
8527     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8528 
8529     // Delete the parameters.
8530     D.getFunctionTypeInfo().freeParams();
8531     D.setInvalidType();
8532   } else if (Proto->isVariadic()) {
8533     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8534     D.setInvalidType();
8535   }
8536 
8537   // Diagnose "&operator bool()" and other such nonsense.  This
8538   // is actually a gcc extension which we don't support.
8539   if (Proto->getReturnType() != ConvType) {
8540     bool NeedsTypedef = false;
8541     SourceRange Before, After;
8542 
8543     // Walk the chunks and extract information on them for our diagnostic.
8544     bool PastFunctionChunk = false;
8545     for (auto &Chunk : D.type_objects()) {
8546       switch (Chunk.Kind) {
8547       case DeclaratorChunk::Function:
8548         if (!PastFunctionChunk) {
8549           if (Chunk.Fun.HasTrailingReturnType) {
8550             TypeSourceInfo *TRT = nullptr;
8551             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8552             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8553           }
8554           PastFunctionChunk = true;
8555           break;
8556         }
8557         LLVM_FALLTHROUGH;
8558       case DeclaratorChunk::Array:
8559         NeedsTypedef = true;
8560         extendRight(After, Chunk.getSourceRange());
8561         break;
8562 
8563       case DeclaratorChunk::Pointer:
8564       case DeclaratorChunk::BlockPointer:
8565       case DeclaratorChunk::Reference:
8566       case DeclaratorChunk::MemberPointer:
8567       case DeclaratorChunk::Pipe:
8568         extendLeft(Before, Chunk.getSourceRange());
8569         break;
8570 
8571       case DeclaratorChunk::Paren:
8572         extendLeft(Before, Chunk.Loc);
8573         extendRight(After, Chunk.EndLoc);
8574         break;
8575       }
8576     }
8577 
8578     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8579                          After.isValid()  ? After.getBegin() :
8580                                             D.getIdentifierLoc();
8581     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8582     DB << Before << After;
8583 
8584     if (!NeedsTypedef) {
8585       DB << /*don't need a typedef*/0;
8586 
8587       // If we can provide a correct fix-it hint, do so.
8588       if (After.isInvalid() && ConvTSI) {
8589         SourceLocation InsertLoc =
8590             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8591         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8592            << FixItHint::CreateInsertionFromRange(
8593                   InsertLoc, CharSourceRange::getTokenRange(Before))
8594            << FixItHint::CreateRemoval(Before);
8595       }
8596     } else if (!Proto->getReturnType()->isDependentType()) {
8597       DB << /*typedef*/1 << Proto->getReturnType();
8598     } else if (getLangOpts().CPlusPlus11) {
8599       DB << /*alias template*/2 << Proto->getReturnType();
8600     } else {
8601       DB << /*might not be fixable*/3;
8602     }
8603 
8604     // Recover by incorporating the other type chunks into the result type.
8605     // Note, this does *not* change the name of the function. This is compatible
8606     // with the GCC extension:
8607     //   struct S { &operator int(); } s;
8608     //   int &r = s.operator int(); // ok in GCC
8609     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8610     ConvType = Proto->getReturnType();
8611   }
8612 
8613   // C++ [class.conv.fct]p4:
8614   //   The conversion-type-id shall not represent a function type nor
8615   //   an array type.
8616   if (ConvType->isArrayType()) {
8617     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8618     ConvType = Context.getPointerType(ConvType);
8619     D.setInvalidType();
8620   } else if (ConvType->isFunctionType()) {
8621     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8622     ConvType = Context.getPointerType(ConvType);
8623     D.setInvalidType();
8624   }
8625 
8626   // Rebuild the function type "R" without any parameters (in case any
8627   // of the errors above fired) and with the conversion type as the
8628   // return type.
8629   if (D.isInvalidType())
8630     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8631 
8632   // C++0x explicit conversion operators.
8633   if (DS.isExplicitSpecified())
8634     Diag(DS.getExplicitSpecLoc(),
8635          getLangOpts().CPlusPlus11
8636              ? diag::warn_cxx98_compat_explicit_conversion_functions
8637              : diag::ext_explicit_conversion_functions)
8638         << SourceRange(DS.getExplicitSpecLoc());
8639 }
8640 
8641 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8642 /// the declaration of the given C++ conversion function. This routine
8643 /// is responsible for recording the conversion function in the C++
8644 /// class, if possible.
8645 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8646   assert(Conversion && "Expected to receive a conversion function declaration");
8647 
8648   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8649 
8650   // Make sure we aren't redeclaring the conversion function.
8651   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8652 
8653   // C++ [class.conv.fct]p1:
8654   //   [...] A conversion function is never used to convert a
8655   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8656   //   same object type (or a reference to it), to a (possibly
8657   //   cv-qualified) base class of that type (or a reference to it),
8658   //   or to (possibly cv-qualified) void.
8659   // FIXME: Suppress this warning if the conversion function ends up being a
8660   // virtual function that overrides a virtual function in a base class.
8661   QualType ClassType
8662     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8663   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8664     ConvType = ConvTypeRef->getPointeeType();
8665   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8666       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8667     /* Suppress diagnostics for instantiations. */;
8668   else if (ConvType->isRecordType()) {
8669     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8670     if (ConvType == ClassType)
8671       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8672         << ClassType;
8673     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8674       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8675         <<  ClassType << ConvType;
8676   } else if (ConvType->isVoidType()) {
8677     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8678       << ClassType << ConvType;
8679   }
8680 
8681   if (FunctionTemplateDecl *ConversionTemplate
8682                                 = Conversion->getDescribedFunctionTemplate())
8683     return ConversionTemplate;
8684 
8685   return Conversion;
8686 }
8687 
8688 namespace {
8689 /// Utility class to accumulate and print a diagnostic listing the invalid
8690 /// specifier(s) on a declaration.
8691 struct BadSpecifierDiagnoser {
8692   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8693       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8694   ~BadSpecifierDiagnoser() {
8695     Diagnostic << Specifiers;
8696   }
8697 
8698   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8699     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8700   }
8701   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8702     return check(SpecLoc,
8703                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8704   }
8705   void check(SourceLocation SpecLoc, const char *Spec) {
8706     if (SpecLoc.isInvalid()) return;
8707     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8708     if (!Specifiers.empty()) Specifiers += " ";
8709     Specifiers += Spec;
8710   }
8711 
8712   Sema &S;
8713   Sema::SemaDiagnosticBuilder Diagnostic;
8714   std::string Specifiers;
8715 };
8716 }
8717 
8718 /// Check the validity of a declarator that we parsed for a deduction-guide.
8719 /// These aren't actually declarators in the grammar, so we need to check that
8720 /// the user didn't specify any pieces that are not part of the deduction-guide
8721 /// grammar.
8722 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8723                                          StorageClass &SC) {
8724   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8725   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8726   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8727 
8728   // C++ [temp.deduct.guide]p3:
8729   //   A deduction-gide shall be declared in the same scope as the
8730   //   corresponding class template.
8731   if (!CurContext->getRedeclContext()->Equals(
8732           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8733     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8734       << GuidedTemplateDecl;
8735     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8736   }
8737 
8738   auto &DS = D.getMutableDeclSpec();
8739   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8740   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8741       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8742       DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8743     BadSpecifierDiagnoser Diagnoser(
8744         *this, D.getIdentifierLoc(),
8745         diag::err_deduction_guide_invalid_specifier);
8746 
8747     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8748     DS.ClearStorageClassSpecs();
8749     SC = SC_None;
8750 
8751     // 'explicit' is permitted.
8752     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8753     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8754     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8755     DS.ClearConstexprSpec();
8756 
8757     Diagnoser.check(DS.getConstSpecLoc(), "const");
8758     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8759     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8760     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8761     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8762     DS.ClearTypeQualifiers();
8763 
8764     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8765     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8766     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8767     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8768     DS.ClearTypeSpecType();
8769   }
8770 
8771   if (D.isInvalidType())
8772     return;
8773 
8774   // Check the declarator is simple enough.
8775   bool FoundFunction = false;
8776   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8777     if (Chunk.Kind == DeclaratorChunk::Paren)
8778       continue;
8779     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8780       Diag(D.getDeclSpec().getBeginLoc(),
8781            diag::err_deduction_guide_with_complex_decl)
8782           << D.getSourceRange();
8783       break;
8784     }
8785     if (!Chunk.Fun.hasTrailingReturnType()) {
8786       Diag(D.getName().getBeginLoc(),
8787            diag::err_deduction_guide_no_trailing_return_type);
8788       break;
8789     }
8790 
8791     // Check that the return type is written as a specialization of
8792     // the template specified as the deduction-guide's name.
8793     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8794     TypeSourceInfo *TSI = nullptr;
8795     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8796     assert(TSI && "deduction guide has valid type but invalid return type?");
8797     bool AcceptableReturnType = false;
8798     bool MightInstantiateToSpecialization = false;
8799     if (auto RetTST =
8800             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8801       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8802       bool TemplateMatches =
8803           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8804       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8805         AcceptableReturnType = true;
8806       else {
8807         // This could still instantiate to the right type, unless we know it
8808         // names the wrong class template.
8809         auto *TD = SpecifiedName.getAsTemplateDecl();
8810         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8811                                              !TemplateMatches);
8812       }
8813     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8814       MightInstantiateToSpecialization = true;
8815     }
8816 
8817     if (!AcceptableReturnType) {
8818       Diag(TSI->getTypeLoc().getBeginLoc(),
8819            diag::err_deduction_guide_bad_trailing_return_type)
8820           << GuidedTemplate << TSI->getType()
8821           << MightInstantiateToSpecialization
8822           << TSI->getTypeLoc().getSourceRange();
8823     }
8824 
8825     // Keep going to check that we don't have any inner declarator pieces (we
8826     // could still have a function returning a pointer to a function).
8827     FoundFunction = true;
8828   }
8829 
8830   if (D.isFunctionDefinition())
8831     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8832 }
8833 
8834 //===----------------------------------------------------------------------===//
8835 // Namespace Handling
8836 //===----------------------------------------------------------------------===//
8837 
8838 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8839 /// reopened.
8840 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8841                                             SourceLocation Loc,
8842                                             IdentifierInfo *II, bool *IsInline,
8843                                             NamespaceDecl *PrevNS) {
8844   assert(*IsInline != PrevNS->isInline());
8845 
8846   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8847   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8848   // inline namespaces, with the intention of bringing names into namespace std.
8849   //
8850   // We support this just well enough to get that case working; this is not
8851   // sufficient to support reopening namespaces as inline in general.
8852   if (*IsInline && II && II->getName().startswith("__atomic") &&
8853       S.getSourceManager().isInSystemHeader(Loc)) {
8854     // Mark all prior declarations of the namespace as inline.
8855     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8856          NS = NS->getPreviousDecl())
8857       NS->setInline(*IsInline);
8858     // Patch up the lookup table for the containing namespace. This isn't really
8859     // correct, but it's good enough for this particular case.
8860     for (auto *I : PrevNS->decls())
8861       if (auto *ND = dyn_cast<NamedDecl>(I))
8862         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8863     return;
8864   }
8865 
8866   if (PrevNS->isInline())
8867     // The user probably just forgot the 'inline', so suggest that it
8868     // be added back.
8869     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8870       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8871   else
8872     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8873 
8874   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8875   *IsInline = PrevNS->isInline();
8876 }
8877 
8878 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8879 /// definition.
8880 Decl *Sema::ActOnStartNamespaceDef(
8881     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
8882     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
8883     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
8884   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8885   // For anonymous namespace, take the location of the left brace.
8886   SourceLocation Loc = II ? IdentLoc : LBrace;
8887   bool IsInline = InlineLoc.isValid();
8888   bool IsInvalid = false;
8889   bool IsStd = false;
8890   bool AddToKnown = false;
8891   Scope *DeclRegionScope = NamespcScope->getParent();
8892 
8893   NamespaceDecl *PrevNS = nullptr;
8894   if (II) {
8895     // C++ [namespace.def]p2:
8896     //   The identifier in an original-namespace-definition shall not
8897     //   have been previously defined in the declarative region in
8898     //   which the original-namespace-definition appears. The
8899     //   identifier in an original-namespace-definition is the name of
8900     //   the namespace. Subsequently in that declarative region, it is
8901     //   treated as an original-namespace-name.
8902     //
8903     // Since namespace names are unique in their scope, and we don't
8904     // look through using directives, just look for any ordinary names
8905     // as if by qualified name lookup.
8906     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8907                    ForExternalRedeclaration);
8908     LookupQualifiedName(R, CurContext->getRedeclContext());
8909     NamedDecl *PrevDecl =
8910         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8911     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8912 
8913     if (PrevNS) {
8914       // This is an extended namespace definition.
8915       if (IsInline != PrevNS->isInline())
8916         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8917                                         &IsInline, PrevNS);
8918     } else if (PrevDecl) {
8919       // This is an invalid name redefinition.
8920       Diag(Loc, diag::err_redefinition_different_kind)
8921         << II;
8922       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8923       IsInvalid = true;
8924       // Continue on to push Namespc as current DeclContext and return it.
8925     } else if (II->isStr("std") &&
8926                CurContext->getRedeclContext()->isTranslationUnit()) {
8927       // This is the first "real" definition of the namespace "std", so update
8928       // our cache of the "std" namespace to point at this definition.
8929       PrevNS = getStdNamespace();
8930       IsStd = true;
8931       AddToKnown = !IsInline;
8932     } else {
8933       // We've seen this namespace for the first time.
8934       AddToKnown = !IsInline;
8935     }
8936   } else {
8937     // Anonymous namespaces.
8938 
8939     // Determine whether the parent already has an anonymous namespace.
8940     DeclContext *Parent = CurContext->getRedeclContext();
8941     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8942       PrevNS = TU->getAnonymousNamespace();
8943     } else {
8944       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8945       PrevNS = ND->getAnonymousNamespace();
8946     }
8947 
8948     if (PrevNS && IsInline != PrevNS->isInline())
8949       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8950                                       &IsInline, PrevNS);
8951   }
8952 
8953   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8954                                                  StartLoc, Loc, II, PrevNS);
8955   if (IsInvalid)
8956     Namespc->setInvalidDecl();
8957 
8958   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8959   AddPragmaAttributes(DeclRegionScope, Namespc);
8960 
8961   // FIXME: Should we be merging attributes?
8962   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8963     PushNamespaceVisibilityAttr(Attr, Loc);
8964 
8965   if (IsStd)
8966     StdNamespace = Namespc;
8967   if (AddToKnown)
8968     KnownNamespaces[Namespc] = false;
8969 
8970   if (II) {
8971     PushOnScopeChains(Namespc, DeclRegionScope);
8972   } else {
8973     // Link the anonymous namespace into its parent.
8974     DeclContext *Parent = CurContext->getRedeclContext();
8975     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8976       TU->setAnonymousNamespace(Namespc);
8977     } else {
8978       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8979     }
8980 
8981     CurContext->addDecl(Namespc);
8982 
8983     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8984     //   behaves as if it were replaced by
8985     //     namespace unique { /* empty body */ }
8986     //     using namespace unique;
8987     //     namespace unique { namespace-body }
8988     //   where all occurrences of 'unique' in a translation unit are
8989     //   replaced by the same identifier and this identifier differs
8990     //   from all other identifiers in the entire program.
8991 
8992     // We just create the namespace with an empty name and then add an
8993     // implicit using declaration, just like the standard suggests.
8994     //
8995     // CodeGen enforces the "universally unique" aspect by giving all
8996     // declarations semantically contained within an anonymous
8997     // namespace internal linkage.
8998 
8999     if (!PrevNS) {
9000       UD = UsingDirectiveDecl::Create(Context, Parent,
9001                                       /* 'using' */ LBrace,
9002                                       /* 'namespace' */ SourceLocation(),
9003                                       /* qualifier */ NestedNameSpecifierLoc(),
9004                                       /* identifier */ SourceLocation(),
9005                                       Namespc,
9006                                       /* Ancestor */ Parent);
9007       UD->setImplicit();
9008       Parent->addDecl(UD);
9009     }
9010   }
9011 
9012   ActOnDocumentableDecl(Namespc);
9013 
9014   // Although we could have an invalid decl (i.e. the namespace name is a
9015   // redefinition), push it as current DeclContext and try to continue parsing.
9016   // FIXME: We should be able to push Namespc here, so that the each DeclContext
9017   // for the namespace has the declarations that showed up in that particular
9018   // namespace definition.
9019   PushDeclContext(NamespcScope, Namespc);
9020   return Namespc;
9021 }
9022 
9023 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
9024 /// is a namespace alias, returns the namespace it points to.
9025 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
9026   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
9027     return AD->getNamespace();
9028   return dyn_cast_or_null<NamespaceDecl>(D);
9029 }
9030 
9031 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
9032 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
9033 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
9034   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
9035   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
9036   Namespc->setRBraceLoc(RBrace);
9037   PopDeclContext();
9038   if (Namespc->hasAttr<VisibilityAttr>())
9039     PopPragmaVisibility(true, RBrace);
9040 }
9041 
9042 CXXRecordDecl *Sema::getStdBadAlloc() const {
9043   return cast_or_null<CXXRecordDecl>(
9044                                   StdBadAlloc.get(Context.getExternalSource()));
9045 }
9046 
9047 EnumDecl *Sema::getStdAlignValT() const {
9048   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9049 }
9050 
9051 NamespaceDecl *Sema::getStdNamespace() const {
9052   return cast_or_null<NamespaceDecl>(
9053                                  StdNamespace.get(Context.getExternalSource()));
9054 }
9055 
9056 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
9057   if (!StdExperimentalNamespaceCache) {
9058     if (auto Std = getStdNamespace()) {
9059       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9060                           SourceLocation(), LookupNamespaceName);
9061       if (!LookupQualifiedName(Result, Std) ||
9062           !(StdExperimentalNamespaceCache =
9063                 Result.getAsSingle<NamespaceDecl>()))
9064         Result.suppressDiagnostics();
9065     }
9066   }
9067   return StdExperimentalNamespaceCache;
9068 }
9069 
9070 namespace {
9071 
9072 enum UnsupportedSTLSelect {
9073   USS_InvalidMember,
9074   USS_MissingMember,
9075   USS_NonTrivial,
9076   USS_Other
9077 };
9078 
9079 struct InvalidSTLDiagnoser {
9080   Sema &S;
9081   SourceLocation Loc;
9082   QualType TyForDiags;
9083 
9084   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9085                       const VarDecl *VD = nullptr) {
9086     {
9087       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9088                << TyForDiags << ((int)Sel);
9089       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9090         assert(!Name.empty());
9091         D << Name;
9092       }
9093     }
9094     if (Sel == USS_InvalidMember) {
9095       S.Diag(VD->getLocation(), diag::note_var_declared_here)
9096           << VD << VD->getSourceRange();
9097     }
9098     return QualType();
9099   }
9100 };
9101 } // namespace
9102 
9103 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9104                                            SourceLocation Loc) {
9105   assert(getLangOpts().CPlusPlus &&
9106          "Looking for comparison category type outside of C++.");
9107 
9108   // Check if we've already successfully checked the comparison category type
9109   // before. If so, skip checking it again.
9110   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9111   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9112     return Info->getType();
9113 
9114   // If lookup failed
9115   if (!Info) {
9116     std::string NameForDiags = "std::";
9117     NameForDiags += ComparisonCategories::getCategoryString(Kind);
9118     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9119         << NameForDiags;
9120     return QualType();
9121   }
9122 
9123   assert(Info->Kind == Kind);
9124   assert(Info->Record);
9125 
9126   // Update the Record decl in case we encountered a forward declaration on our
9127   // first pass. FIXME: This is a bit of a hack.
9128   if (Info->Record->hasDefinition())
9129     Info->Record = Info->Record->getDefinition();
9130 
9131   // Use an elaborated type for diagnostics which has a name containing the
9132   // prepended 'std' namespace but not any inline namespace names.
9133   QualType TyForDiags = [&]() {
9134     auto *NNS =
9135         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9136     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9137   }();
9138 
9139   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9140     return QualType();
9141 
9142   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9143 
9144   if (!Info->Record->isTriviallyCopyable())
9145     return UnsupportedSTLError(USS_NonTrivial);
9146 
9147   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9148     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9149     // Tolerate empty base classes.
9150     if (Base->isEmpty())
9151       continue;
9152     // Reject STL implementations which have at least one non-empty base.
9153     return UnsupportedSTLError();
9154   }
9155 
9156   // Check that the STL has implemented the types using a single integer field.
9157   // This expectation allows better codegen for builtin operators. We require:
9158   //   (1) The class has exactly one field.
9159   //   (2) The field is an integral or enumeration type.
9160   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9161   if (std::distance(FIt, FEnd) != 1 ||
9162       !FIt->getType()->isIntegralOrEnumerationType()) {
9163     return UnsupportedSTLError();
9164   }
9165 
9166   // Build each of the require values and store them in Info.
9167   for (ComparisonCategoryResult CCR :
9168        ComparisonCategories::getPossibleResultsForType(Kind)) {
9169     StringRef MemName = ComparisonCategories::getResultString(CCR);
9170     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9171 
9172     if (!ValInfo)
9173       return UnsupportedSTLError(USS_MissingMember, MemName);
9174 
9175     VarDecl *VD = ValInfo->VD;
9176     assert(VD && "should not be null!");
9177 
9178     // Attempt to diagnose reasons why the STL definition of this type
9179     // might be foobar, including it failing to be a constant expression.
9180     // TODO Handle more ways the lookup or result can be invalid.
9181     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9182         !VD->checkInitIsICE())
9183       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9184 
9185     // Attempt to evaluate the var decl as a constant expression and extract
9186     // the value of its first field as a ICE. If this fails, the STL
9187     // implementation is not supported.
9188     if (!ValInfo->hasValidIntValue())
9189       return UnsupportedSTLError();
9190 
9191     MarkVariableReferenced(Loc, VD);
9192   }
9193 
9194   // We've successfully built the required types and expressions. Update
9195   // the cache and return the newly cached value.
9196   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9197   return Info->getType();
9198 }
9199 
9200 /// Retrieve the special "std" namespace, which may require us to
9201 /// implicitly define the namespace.
9202 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9203   if (!StdNamespace) {
9204     // The "std" namespace has not yet been defined, so build one implicitly.
9205     StdNamespace = NamespaceDecl::Create(Context,
9206                                          Context.getTranslationUnitDecl(),
9207                                          /*Inline=*/false,
9208                                          SourceLocation(), SourceLocation(),
9209                                          &PP.getIdentifierTable().get("std"),
9210                                          /*PrevDecl=*/nullptr);
9211     getStdNamespace()->setImplicit(true);
9212   }
9213 
9214   return getStdNamespace();
9215 }
9216 
9217 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9218   assert(getLangOpts().CPlusPlus &&
9219          "Looking for std::initializer_list outside of C++.");
9220 
9221   // We're looking for implicit instantiations of
9222   // template <typename E> class std::initializer_list.
9223 
9224   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9225     return false;
9226 
9227   ClassTemplateDecl *Template = nullptr;
9228   const TemplateArgument *Arguments = nullptr;
9229 
9230   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9231 
9232     ClassTemplateSpecializationDecl *Specialization =
9233         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9234     if (!Specialization)
9235       return false;
9236 
9237     Template = Specialization->getSpecializedTemplate();
9238     Arguments = Specialization->getTemplateArgs().data();
9239   } else if (const TemplateSpecializationType *TST =
9240                  Ty->getAs<TemplateSpecializationType>()) {
9241     Template = dyn_cast_or_null<ClassTemplateDecl>(
9242         TST->getTemplateName().getAsTemplateDecl());
9243     Arguments = TST->getArgs();
9244   }
9245   if (!Template)
9246     return false;
9247 
9248   if (!StdInitializerList) {
9249     // Haven't recognized std::initializer_list yet, maybe this is it.
9250     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9251     if (TemplateClass->getIdentifier() !=
9252             &PP.getIdentifierTable().get("initializer_list") ||
9253         !getStdNamespace()->InEnclosingNamespaceSetOf(
9254             TemplateClass->getDeclContext()))
9255       return false;
9256     // This is a template called std::initializer_list, but is it the right
9257     // template?
9258     TemplateParameterList *Params = Template->getTemplateParameters();
9259     if (Params->getMinRequiredArguments() != 1)
9260       return false;
9261     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9262       return false;
9263 
9264     // It's the right template.
9265     StdInitializerList = Template;
9266   }
9267 
9268   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9269     return false;
9270 
9271   // This is an instance of std::initializer_list. Find the argument type.
9272   if (Element)
9273     *Element = Arguments[0].getAsType();
9274   return true;
9275 }
9276 
9277 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9278   NamespaceDecl *Std = S.getStdNamespace();
9279   if (!Std) {
9280     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9281     return nullptr;
9282   }
9283 
9284   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9285                       Loc, Sema::LookupOrdinaryName);
9286   if (!S.LookupQualifiedName(Result, Std)) {
9287     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9288     return nullptr;
9289   }
9290   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9291   if (!Template) {
9292     Result.suppressDiagnostics();
9293     // We found something weird. Complain about the first thing we found.
9294     NamedDecl *Found = *Result.begin();
9295     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9296     return nullptr;
9297   }
9298 
9299   // We found some template called std::initializer_list. Now verify that it's
9300   // correct.
9301   TemplateParameterList *Params = Template->getTemplateParameters();
9302   if (Params->getMinRequiredArguments() != 1 ||
9303       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9304     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9305     return nullptr;
9306   }
9307 
9308   return Template;
9309 }
9310 
9311 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9312   if (!StdInitializerList) {
9313     StdInitializerList = LookupStdInitializerList(*this, Loc);
9314     if (!StdInitializerList)
9315       return QualType();
9316   }
9317 
9318   TemplateArgumentListInfo Args(Loc, Loc);
9319   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9320                                        Context.getTrivialTypeSourceInfo(Element,
9321                                                                         Loc)));
9322   return Context.getCanonicalType(
9323       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9324 }
9325 
9326 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9327   // C++ [dcl.init.list]p2:
9328   //   A constructor is an initializer-list constructor if its first parameter
9329   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9330   //   std::initializer_list<E> for some type E, and either there are no other
9331   //   parameters or else all other parameters have default arguments.
9332   if (Ctor->getNumParams() < 1 ||
9333       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9334     return false;
9335 
9336   QualType ArgType = Ctor->getParamDecl(0)->getType();
9337   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9338     ArgType = RT->getPointeeType().getUnqualifiedType();
9339 
9340   return isStdInitializerList(ArgType, nullptr);
9341 }
9342 
9343 /// Determine whether a using statement is in a context where it will be
9344 /// apply in all contexts.
9345 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9346   switch (CurContext->getDeclKind()) {
9347     case Decl::TranslationUnit:
9348       return true;
9349     case Decl::LinkageSpec:
9350       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9351     default:
9352       return false;
9353   }
9354 }
9355 
9356 namespace {
9357 
9358 // Callback to only accept typo corrections that are namespaces.
9359 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
9360 public:
9361   bool ValidateCandidate(const TypoCorrection &candidate) override {
9362     if (NamedDecl *ND = candidate.getCorrectionDecl())
9363       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9364     return false;
9365   }
9366 
9367   std::unique_ptr<CorrectionCandidateCallback> clone() override {
9368     return llvm::make_unique<NamespaceValidatorCCC>(*this);
9369   }
9370 };
9371 
9372 }
9373 
9374 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9375                                        CXXScopeSpec &SS,
9376                                        SourceLocation IdentLoc,
9377                                        IdentifierInfo *Ident) {
9378   R.clear();
9379   NamespaceValidatorCCC CCC{};
9380   if (TypoCorrection Corrected =
9381           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
9382                         Sema::CTK_ErrorRecovery)) {
9383     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9384       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9385       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9386                               Ident->getName().equals(CorrectedStr);
9387       S.diagnoseTypo(Corrected,
9388                      S.PDiag(diag::err_using_directive_member_suggest)
9389                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9390                      S.PDiag(diag::note_namespace_defined_here));
9391     } else {
9392       S.diagnoseTypo(Corrected,
9393                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9394                      S.PDiag(diag::note_namespace_defined_here));
9395     }
9396     R.addDecl(Corrected.getFoundDecl());
9397     return true;
9398   }
9399   return false;
9400 }
9401 
9402 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9403                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9404                                 SourceLocation IdentLoc,
9405                                 IdentifierInfo *NamespcName,
9406                                 const ParsedAttributesView &AttrList) {
9407   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9408   assert(NamespcName && "Invalid NamespcName.");
9409   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9410 
9411   // This can only happen along a recovery path.
9412   while (S->isTemplateParamScope())
9413     S = S->getParent();
9414   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9415 
9416   UsingDirectiveDecl *UDir = nullptr;
9417   NestedNameSpecifier *Qualifier = nullptr;
9418   if (SS.isSet())
9419     Qualifier = SS.getScopeRep();
9420 
9421   // Lookup namespace name.
9422   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9423   LookupParsedName(R, S, &SS);
9424   if (R.isAmbiguous())
9425     return nullptr;
9426 
9427   if (R.empty()) {
9428     R.clear();
9429     // Allow "using namespace std;" or "using namespace ::std;" even if
9430     // "std" hasn't been defined yet, for GCC compatibility.
9431     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9432         NamespcName->isStr("std")) {
9433       Diag(IdentLoc, diag::ext_using_undefined_std);
9434       R.addDecl(getOrCreateStdNamespace());
9435       R.resolveKind();
9436     }
9437     // Otherwise, attempt typo correction.
9438     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9439   }
9440 
9441   if (!R.empty()) {
9442     NamedDecl *Named = R.getRepresentativeDecl();
9443     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9444     assert(NS && "expected namespace decl");
9445 
9446     // The use of a nested name specifier may trigger deprecation warnings.
9447     DiagnoseUseOfDecl(Named, IdentLoc);
9448 
9449     // C++ [namespace.udir]p1:
9450     //   A using-directive specifies that the names in the nominated
9451     //   namespace can be used in the scope in which the
9452     //   using-directive appears after the using-directive. During
9453     //   unqualified name lookup (3.4.1), the names appear as if they
9454     //   were declared in the nearest enclosing namespace which
9455     //   contains both the using-directive and the nominated
9456     //   namespace. [Note: in this context, "contains" means "contains
9457     //   directly or indirectly". ]
9458 
9459     // Find enclosing context containing both using-directive and
9460     // nominated namespace.
9461     DeclContext *CommonAncestor = NS;
9462     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9463       CommonAncestor = CommonAncestor->getParent();
9464 
9465     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9466                                       SS.getWithLocInContext(Context),
9467                                       IdentLoc, Named, CommonAncestor);
9468 
9469     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9470         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9471       Diag(IdentLoc, diag::warn_using_directive_in_header);
9472     }
9473 
9474     PushUsingDirective(S, UDir);
9475   } else {
9476     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9477   }
9478 
9479   if (UDir)
9480     ProcessDeclAttributeList(S, UDir, AttrList);
9481 
9482   return UDir;
9483 }
9484 
9485 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9486   // If the scope has an associated entity and the using directive is at
9487   // namespace or translation unit scope, add the UsingDirectiveDecl into
9488   // its lookup structure so qualified name lookup can find it.
9489   DeclContext *Ctx = S->getEntity();
9490   if (Ctx && !Ctx->isFunctionOrMethod())
9491     Ctx->addDecl(UDir);
9492   else
9493     // Otherwise, it is at block scope. The using-directives will affect lookup
9494     // only to the end of the scope.
9495     S->PushUsingDirective(UDir);
9496 }
9497 
9498 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9499                                   SourceLocation UsingLoc,
9500                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
9501                                   UnqualifiedId &Name,
9502                                   SourceLocation EllipsisLoc,
9503                                   const ParsedAttributesView &AttrList) {
9504   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9505 
9506   if (SS.isEmpty()) {
9507     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9508     return nullptr;
9509   }
9510 
9511   switch (Name.getKind()) {
9512   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9513   case UnqualifiedIdKind::IK_Identifier:
9514   case UnqualifiedIdKind::IK_OperatorFunctionId:
9515   case UnqualifiedIdKind::IK_LiteralOperatorId:
9516   case UnqualifiedIdKind::IK_ConversionFunctionId:
9517     break;
9518 
9519   case UnqualifiedIdKind::IK_ConstructorName:
9520   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9521     // C++11 inheriting constructors.
9522     Diag(Name.getBeginLoc(),
9523          getLangOpts().CPlusPlus11
9524              ? diag::warn_cxx98_compat_using_decl_constructor
9525              : diag::err_using_decl_constructor)
9526         << SS.getRange();
9527 
9528     if (getLangOpts().CPlusPlus11) break;
9529 
9530     return nullptr;
9531 
9532   case UnqualifiedIdKind::IK_DestructorName:
9533     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9534     return nullptr;
9535 
9536   case UnqualifiedIdKind::IK_TemplateId:
9537     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9538         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9539     return nullptr;
9540 
9541   case UnqualifiedIdKind::IK_DeductionGuideName:
9542     llvm_unreachable("cannot parse qualified deduction guide name");
9543   }
9544 
9545   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9546   DeclarationName TargetName = TargetNameInfo.getName();
9547   if (!TargetName)
9548     return nullptr;
9549 
9550   // Warn about access declarations.
9551   if (UsingLoc.isInvalid()) {
9552     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9553                                  ? diag::err_access_decl
9554                                  : diag::warn_access_decl_deprecated)
9555         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9556   }
9557 
9558   if (EllipsisLoc.isInvalid()) {
9559     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9560         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9561       return nullptr;
9562   } else {
9563     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9564         !TargetNameInfo.containsUnexpandedParameterPack()) {
9565       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9566         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9567       EllipsisLoc = SourceLocation();
9568     }
9569   }
9570 
9571   NamedDecl *UD =
9572       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9573                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9574                             /*IsInstantiation*/false);
9575   if (UD)
9576     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9577 
9578   return UD;
9579 }
9580 
9581 /// Determine whether a using declaration considers the given
9582 /// declarations as "equivalent", e.g., if they are redeclarations of
9583 /// the same entity or are both typedefs of the same type.
9584 static bool
9585 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9586   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9587     return true;
9588 
9589   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9590     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9591       return Context.hasSameType(TD1->getUnderlyingType(),
9592                                  TD2->getUnderlyingType());
9593 
9594   return false;
9595 }
9596 
9597 
9598 /// Determines whether to create a using shadow decl for a particular
9599 /// decl, given the set of decls existing prior to this using lookup.
9600 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9601                                 const LookupResult &Previous,
9602                                 UsingShadowDecl *&PrevShadow) {
9603   // Diagnose finding a decl which is not from a base class of the
9604   // current class.  We do this now because there are cases where this
9605   // function will silently decide not to build a shadow decl, which
9606   // will pre-empt further diagnostics.
9607   //
9608   // We don't need to do this in C++11 because we do the check once on
9609   // the qualifier.
9610   //
9611   // FIXME: diagnose the following if we care enough:
9612   //   struct A { int foo; };
9613   //   struct B : A { using A::foo; };
9614   //   template <class T> struct C : A {};
9615   //   template <class T> struct D : C<T> { using B::foo; } // <---
9616   // This is invalid (during instantiation) in C++03 because B::foo
9617   // resolves to the using decl in B, which is not a base class of D<T>.
9618   // We can't diagnose it immediately because C<T> is an unknown
9619   // specialization.  The UsingShadowDecl in D<T> then points directly
9620   // to A::foo, which will look well-formed when we instantiate.
9621   // The right solution is to not collapse the shadow-decl chain.
9622   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9623     DeclContext *OrigDC = Orig->getDeclContext();
9624 
9625     // Handle enums and anonymous structs.
9626     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9627     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9628     while (OrigRec->isAnonymousStructOrUnion())
9629       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9630 
9631     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9632       if (OrigDC == CurContext) {
9633         Diag(Using->getLocation(),
9634              diag::err_using_decl_nested_name_specifier_is_current_class)
9635           << Using->getQualifierLoc().getSourceRange();
9636         Diag(Orig->getLocation(), diag::note_using_decl_target);
9637         Using->setInvalidDecl();
9638         return true;
9639       }
9640 
9641       Diag(Using->getQualifierLoc().getBeginLoc(),
9642            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9643         << Using->getQualifier()
9644         << cast<CXXRecordDecl>(CurContext)
9645         << Using->getQualifierLoc().getSourceRange();
9646       Diag(Orig->getLocation(), diag::note_using_decl_target);
9647       Using->setInvalidDecl();
9648       return true;
9649     }
9650   }
9651 
9652   if (Previous.empty()) return false;
9653 
9654   NamedDecl *Target = Orig;
9655   if (isa<UsingShadowDecl>(Target))
9656     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9657 
9658   // If the target happens to be one of the previous declarations, we
9659   // don't have a conflict.
9660   //
9661   // FIXME: but we might be increasing its access, in which case we
9662   // should redeclare it.
9663   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9664   bool FoundEquivalentDecl = false;
9665   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9666          I != E; ++I) {
9667     NamedDecl *D = (*I)->getUnderlyingDecl();
9668     // We can have UsingDecls in our Previous results because we use the same
9669     // LookupResult for checking whether the UsingDecl itself is a valid
9670     // redeclaration.
9671     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9672       continue;
9673 
9674     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9675       // C++ [class.mem]p19:
9676       //   If T is the name of a class, then [every named member other than
9677       //   a non-static data member] shall have a name different from T
9678       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9679           !isa<IndirectFieldDecl>(Target) &&
9680           !isa<UnresolvedUsingValueDecl>(Target) &&
9681           DiagnoseClassNameShadow(
9682               CurContext,
9683               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9684         return true;
9685     }
9686 
9687     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9688       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9689         PrevShadow = Shadow;
9690       FoundEquivalentDecl = true;
9691     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9692       // We don't conflict with an existing using shadow decl of an equivalent
9693       // declaration, but we're not a redeclaration of it.
9694       FoundEquivalentDecl = true;
9695     }
9696 
9697     if (isVisible(D))
9698       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9699   }
9700 
9701   if (FoundEquivalentDecl)
9702     return false;
9703 
9704   if (FunctionDecl *FD = Target->getAsFunction()) {
9705     NamedDecl *OldDecl = nullptr;
9706     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9707                           /*IsForUsingDecl*/ true)) {
9708     case Ovl_Overload:
9709       return false;
9710 
9711     case Ovl_NonFunction:
9712       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9713       break;
9714 
9715     // We found a decl with the exact signature.
9716     case Ovl_Match:
9717       // If we're in a record, we want to hide the target, so we
9718       // return true (without a diagnostic) to tell the caller not to
9719       // build a shadow decl.
9720       if (CurContext->isRecord())
9721         return true;
9722 
9723       // If we're not in a record, this is an error.
9724       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9725       break;
9726     }
9727 
9728     Diag(Target->getLocation(), diag::note_using_decl_target);
9729     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9730     Using->setInvalidDecl();
9731     return true;
9732   }
9733 
9734   // Target is not a function.
9735 
9736   if (isa<TagDecl>(Target)) {
9737     // No conflict between a tag and a non-tag.
9738     if (!Tag) return false;
9739 
9740     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9741     Diag(Target->getLocation(), diag::note_using_decl_target);
9742     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9743     Using->setInvalidDecl();
9744     return true;
9745   }
9746 
9747   // No conflict between a tag and a non-tag.
9748   if (!NonTag) return false;
9749 
9750   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9751   Diag(Target->getLocation(), diag::note_using_decl_target);
9752   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9753   Using->setInvalidDecl();
9754   return true;
9755 }
9756 
9757 /// Determine whether a direct base class is a virtual base class.
9758 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9759   if (!Derived->getNumVBases())
9760     return false;
9761   for (auto &B : Derived->bases())
9762     if (B.getType()->getAsCXXRecordDecl() == Base)
9763       return B.isVirtual();
9764   llvm_unreachable("not a direct base class");
9765 }
9766 
9767 /// Builds a shadow declaration corresponding to a 'using' declaration.
9768 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9769                                             UsingDecl *UD,
9770                                             NamedDecl *Orig,
9771                                             UsingShadowDecl *PrevDecl) {
9772   // If we resolved to another shadow declaration, just coalesce them.
9773   NamedDecl *Target = Orig;
9774   if (isa<UsingShadowDecl>(Target)) {
9775     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9776     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9777   }
9778 
9779   NamedDecl *NonTemplateTarget = Target;
9780   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9781     NonTemplateTarget = TargetTD->getTemplatedDecl();
9782 
9783   UsingShadowDecl *Shadow;
9784   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9785     bool IsVirtualBase =
9786         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9787                             UD->getQualifier()->getAsRecordDecl());
9788     Shadow = ConstructorUsingShadowDecl::Create(
9789         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9790   } else {
9791     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9792                                      Target);
9793   }
9794   UD->addShadowDecl(Shadow);
9795 
9796   Shadow->setAccess(UD->getAccess());
9797   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9798     Shadow->setInvalidDecl();
9799 
9800   Shadow->setPreviousDecl(PrevDecl);
9801 
9802   if (S)
9803     PushOnScopeChains(Shadow, S);
9804   else
9805     CurContext->addDecl(Shadow);
9806 
9807 
9808   return Shadow;
9809 }
9810 
9811 /// Hides a using shadow declaration.  This is required by the current
9812 /// using-decl implementation when a resolvable using declaration in a
9813 /// class is followed by a declaration which would hide or override
9814 /// one or more of the using decl's targets; for example:
9815 ///
9816 ///   struct Base { void foo(int); };
9817 ///   struct Derived : Base {
9818 ///     using Base::foo;
9819 ///     void foo(int);
9820 ///   };
9821 ///
9822 /// The governing language is C++03 [namespace.udecl]p12:
9823 ///
9824 ///   When a using-declaration brings names from a base class into a
9825 ///   derived class scope, member functions in the derived class
9826 ///   override and/or hide member functions with the same name and
9827 ///   parameter types in a base class (rather than conflicting).
9828 ///
9829 /// There are two ways to implement this:
9830 ///   (1) optimistically create shadow decls when they're not hidden
9831 ///       by existing declarations, or
9832 ///   (2) don't create any shadow decls (or at least don't make them
9833 ///       visible) until we've fully parsed/instantiated the class.
9834 /// The problem with (1) is that we might have to retroactively remove
9835 /// a shadow decl, which requires several O(n) operations because the
9836 /// decl structures are (very reasonably) not designed for removal.
9837 /// (2) avoids this but is very fiddly and phase-dependent.
9838 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9839   if (Shadow->getDeclName().getNameKind() ==
9840         DeclarationName::CXXConversionFunctionName)
9841     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9842 
9843   // Remove it from the DeclContext...
9844   Shadow->getDeclContext()->removeDecl(Shadow);
9845 
9846   // ...and the scope, if applicable...
9847   if (S) {
9848     S->RemoveDecl(Shadow);
9849     IdResolver.RemoveDecl(Shadow);
9850   }
9851 
9852   // ...and the using decl.
9853   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9854 
9855   // TODO: complain somehow if Shadow was used.  It shouldn't
9856   // be possible for this to happen, because...?
9857 }
9858 
9859 /// Find the base specifier for a base class with the given type.
9860 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9861                                                 QualType DesiredBase,
9862                                                 bool &AnyDependentBases) {
9863   // Check whether the named type is a direct base class.
9864   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9865   for (auto &Base : Derived->bases()) {
9866     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9867     if (CanonicalDesiredBase == BaseType)
9868       return &Base;
9869     if (BaseType->isDependentType())
9870       AnyDependentBases = true;
9871   }
9872   return nullptr;
9873 }
9874 
9875 namespace {
9876 class UsingValidatorCCC final : public CorrectionCandidateCallback {
9877 public:
9878   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9879                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9880       : HasTypenameKeyword(HasTypenameKeyword),
9881         IsInstantiation(IsInstantiation), OldNNS(NNS),
9882         RequireMemberOf(RequireMemberOf) {}
9883 
9884   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9885     NamedDecl *ND = Candidate.getCorrectionDecl();
9886 
9887     // Keywords are not valid here.
9888     if (!ND || isa<NamespaceDecl>(ND))
9889       return false;
9890 
9891     // Completely unqualified names are invalid for a 'using' declaration.
9892     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9893       return false;
9894 
9895     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9896     // reject.
9897 
9898     if (RequireMemberOf) {
9899       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9900       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9901         // No-one ever wants a using-declaration to name an injected-class-name
9902         // of a base class, unless they're declaring an inheriting constructor.
9903         ASTContext &Ctx = ND->getASTContext();
9904         if (!Ctx.getLangOpts().CPlusPlus11)
9905           return false;
9906         QualType FoundType = Ctx.getRecordType(FoundRecord);
9907 
9908         // Check that the injected-class-name is named as a member of its own
9909         // type; we don't want to suggest 'using Derived::Base;', since that
9910         // means something else.
9911         NestedNameSpecifier *Specifier =
9912             Candidate.WillReplaceSpecifier()
9913                 ? Candidate.getCorrectionSpecifier()
9914                 : OldNNS;
9915         if (!Specifier->getAsType() ||
9916             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9917           return false;
9918 
9919         // Check that this inheriting constructor declaration actually names a
9920         // direct base class of the current class.
9921         bool AnyDependentBases = false;
9922         if (!findDirectBaseWithType(RequireMemberOf,
9923                                     Ctx.getRecordType(FoundRecord),
9924                                     AnyDependentBases) &&
9925             !AnyDependentBases)
9926           return false;
9927       } else {
9928         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9929         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9930           return false;
9931 
9932         // FIXME: Check that the base class member is accessible?
9933       }
9934     } else {
9935       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9936       if (FoundRecord && FoundRecord->isInjectedClassName())
9937         return false;
9938     }
9939 
9940     if (isa<TypeDecl>(ND))
9941       return HasTypenameKeyword || !IsInstantiation;
9942 
9943     return !HasTypenameKeyword;
9944   }
9945 
9946   std::unique_ptr<CorrectionCandidateCallback> clone() override {
9947     return llvm::make_unique<UsingValidatorCCC>(*this);
9948   }
9949 
9950 private:
9951   bool HasTypenameKeyword;
9952   bool IsInstantiation;
9953   NestedNameSpecifier *OldNNS;
9954   CXXRecordDecl *RequireMemberOf;
9955 };
9956 } // end anonymous namespace
9957 
9958 /// Builds a using declaration.
9959 ///
9960 /// \param IsInstantiation - Whether this call arises from an
9961 ///   instantiation of an unresolved using declaration.  We treat
9962 ///   the lookup differently for these declarations.
9963 NamedDecl *Sema::BuildUsingDeclaration(
9964     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9965     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9966     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9967     const ParsedAttributesView &AttrList, bool IsInstantiation) {
9968   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9969   SourceLocation IdentLoc = NameInfo.getLoc();
9970   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9971 
9972   // FIXME: We ignore attributes for now.
9973 
9974   // For an inheriting constructor declaration, the name of the using
9975   // declaration is the name of a constructor in this class, not in the
9976   // base class.
9977   DeclarationNameInfo UsingName = NameInfo;
9978   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9979     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9980       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9981           Context.getCanonicalType(Context.getRecordType(RD))));
9982 
9983   // Do the redeclaration lookup in the current scope.
9984   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9985                         ForVisibleRedeclaration);
9986   Previous.setHideTags(false);
9987   if (S) {
9988     LookupName(Previous, S);
9989 
9990     // It is really dumb that we have to do this.
9991     LookupResult::Filter F = Previous.makeFilter();
9992     while (F.hasNext()) {
9993       NamedDecl *D = F.next();
9994       if (!isDeclInScope(D, CurContext, S))
9995         F.erase();
9996       // If we found a local extern declaration that's not ordinarily visible,
9997       // and this declaration is being added to a non-block scope, ignore it.
9998       // We're only checking for scope conflicts here, not also for violations
9999       // of the linkage rules.
10000       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
10001                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
10002         F.erase();
10003     }
10004     F.done();
10005   } else {
10006     assert(IsInstantiation && "no scope in non-instantiation");
10007     if (CurContext->isRecord())
10008       LookupQualifiedName(Previous, CurContext);
10009     else {
10010       // No redeclaration check is needed here; in non-member contexts we
10011       // diagnosed all possible conflicts with other using-declarations when
10012       // building the template:
10013       //
10014       // For a dependent non-type using declaration, the only valid case is
10015       // if we instantiate to a single enumerator. We check for conflicts
10016       // between shadow declarations we introduce, and we check in the template
10017       // definition for conflicts between a non-type using declaration and any
10018       // other declaration, which together covers all cases.
10019       //
10020       // A dependent typename using declaration will never successfully
10021       // instantiate, since it will always name a class member, so we reject
10022       // that in the template definition.
10023     }
10024   }
10025 
10026   // Check for invalid redeclarations.
10027   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
10028                                   SS, IdentLoc, Previous))
10029     return nullptr;
10030 
10031   // Check for bad qualifiers.
10032   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
10033                               IdentLoc))
10034     return nullptr;
10035 
10036   DeclContext *LookupContext = computeDeclContext(SS);
10037   NamedDecl *D;
10038   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10039   if (!LookupContext || EllipsisLoc.isValid()) {
10040     if (HasTypenameKeyword) {
10041       // FIXME: not all declaration name kinds are legal here
10042       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
10043                                               UsingLoc, TypenameLoc,
10044                                               QualifierLoc,
10045                                               IdentLoc, NameInfo.getName(),
10046                                               EllipsisLoc);
10047     } else {
10048       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
10049                                            QualifierLoc, NameInfo, EllipsisLoc);
10050     }
10051     D->setAccess(AS);
10052     CurContext->addDecl(D);
10053     return D;
10054   }
10055 
10056   auto Build = [&](bool Invalid) {
10057     UsingDecl *UD =
10058         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10059                           UsingName, HasTypenameKeyword);
10060     UD->setAccess(AS);
10061     CurContext->addDecl(UD);
10062     UD->setInvalidDecl(Invalid);
10063     return UD;
10064   };
10065   auto BuildInvalid = [&]{ return Build(true); };
10066   auto BuildValid = [&]{ return Build(false); };
10067 
10068   if (RequireCompleteDeclContext(SS, LookupContext))
10069     return BuildInvalid();
10070 
10071   // Look up the target name.
10072   LookupResult R(*this, NameInfo, LookupOrdinaryName);
10073 
10074   // Unlike most lookups, we don't always want to hide tag
10075   // declarations: tag names are visible through the using declaration
10076   // even if hidden by ordinary names, *except* in a dependent context
10077   // where it's important for the sanity of two-phase lookup.
10078   if (!IsInstantiation)
10079     R.setHideTags(false);
10080 
10081   // For the purposes of this lookup, we have a base object type
10082   // equal to that of the current context.
10083   if (CurContext->isRecord()) {
10084     R.setBaseObjectType(
10085                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10086   }
10087 
10088   LookupQualifiedName(R, LookupContext);
10089 
10090   // Try to correct typos if possible. If constructor name lookup finds no
10091   // results, that means the named class has no explicit constructors, and we
10092   // suppressed declaring implicit ones (probably because it's dependent or
10093   // invalid).
10094   if (R.empty() &&
10095       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10096     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10097     // it will believe that glibc provides a ::gets in cases where it does not,
10098     // and will try to pull it into namespace std with a using-declaration.
10099     // Just ignore the using-declaration in that case.
10100     auto *II = NameInfo.getName().getAsIdentifierInfo();
10101     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10102         CurContext->isStdNamespace() &&
10103         isa<TranslationUnitDecl>(LookupContext) &&
10104         getSourceManager().isInSystemHeader(UsingLoc))
10105       return nullptr;
10106     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10107                           dyn_cast<CXXRecordDecl>(CurContext));
10108     if (TypoCorrection Corrected =
10109             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
10110                         CTK_ErrorRecovery)) {
10111       // We reject candidates where DroppedSpecifier == true, hence the
10112       // literal '0' below.
10113       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10114                                 << NameInfo.getName() << LookupContext << 0
10115                                 << SS.getRange());
10116 
10117       // If we picked a correction with no attached Decl we can't do anything
10118       // useful with it, bail out.
10119       NamedDecl *ND = Corrected.getCorrectionDecl();
10120       if (!ND)
10121         return BuildInvalid();
10122 
10123       // If we corrected to an inheriting constructor, handle it as one.
10124       auto *RD = dyn_cast<CXXRecordDecl>(ND);
10125       if (RD && RD->isInjectedClassName()) {
10126         // The parent of the injected class name is the class itself.
10127         RD = cast<CXXRecordDecl>(RD->getParent());
10128 
10129         // Fix up the information we'll use to build the using declaration.
10130         if (Corrected.WillReplaceSpecifier()) {
10131           NestedNameSpecifierLocBuilder Builder;
10132           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10133                               QualifierLoc.getSourceRange());
10134           QualifierLoc = Builder.getWithLocInContext(Context);
10135         }
10136 
10137         // In this case, the name we introduce is the name of a derived class
10138         // constructor.
10139         auto *CurClass = cast<CXXRecordDecl>(CurContext);
10140         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10141             Context.getCanonicalType(Context.getRecordType(CurClass))));
10142         UsingName.setNamedTypeInfo(nullptr);
10143         for (auto *Ctor : LookupConstructors(RD))
10144           R.addDecl(Ctor);
10145         R.resolveKind();
10146       } else {
10147         // FIXME: Pick up all the declarations if we found an overloaded
10148         // function.
10149         UsingName.setName(ND->getDeclName());
10150         R.addDecl(ND);
10151       }
10152     } else {
10153       Diag(IdentLoc, diag::err_no_member)
10154         << NameInfo.getName() << LookupContext << SS.getRange();
10155       return BuildInvalid();
10156     }
10157   }
10158 
10159   if (R.isAmbiguous())
10160     return BuildInvalid();
10161 
10162   if (HasTypenameKeyword) {
10163     // If we asked for a typename and got a non-type decl, error out.
10164     if (!R.getAsSingle<TypeDecl>()) {
10165       Diag(IdentLoc, diag::err_using_typename_non_type);
10166       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10167         Diag((*I)->getUnderlyingDecl()->getLocation(),
10168              diag::note_using_decl_target);
10169       return BuildInvalid();
10170     }
10171   } else {
10172     // If we asked for a non-typename and we got a type, error out,
10173     // but only if this is an instantiation of an unresolved using
10174     // decl.  Otherwise just silently find the type name.
10175     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10176       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10177       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10178       return BuildInvalid();
10179     }
10180   }
10181 
10182   // C++14 [namespace.udecl]p6:
10183   // A using-declaration shall not name a namespace.
10184   if (R.getAsSingle<NamespaceDecl>()) {
10185     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10186       << SS.getRange();
10187     return BuildInvalid();
10188   }
10189 
10190   // C++14 [namespace.udecl]p7:
10191   // A using-declaration shall not name a scoped enumerator.
10192   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10193     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10194       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10195         << SS.getRange();
10196       return BuildInvalid();
10197     }
10198   }
10199 
10200   UsingDecl *UD = BuildValid();
10201 
10202   // Some additional rules apply to inheriting constructors.
10203   if (UsingName.getName().getNameKind() ==
10204         DeclarationName::CXXConstructorName) {
10205     // Suppress access diagnostics; the access check is instead performed at the
10206     // point of use for an inheriting constructor.
10207     R.suppressDiagnostics();
10208     if (CheckInheritingConstructorUsingDecl(UD))
10209       return UD;
10210   }
10211 
10212   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10213     UsingShadowDecl *PrevDecl = nullptr;
10214     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10215       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10216   }
10217 
10218   return UD;
10219 }
10220 
10221 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10222                                     ArrayRef<NamedDecl *> Expansions) {
10223   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10224          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10225          isa<UsingPackDecl>(InstantiatedFrom));
10226 
10227   auto *UPD =
10228       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10229   UPD->setAccess(InstantiatedFrom->getAccess());
10230   CurContext->addDecl(UPD);
10231   return UPD;
10232 }
10233 
10234 /// Additional checks for a using declaration referring to a constructor name.
10235 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10236   assert(!UD->hasTypename() && "expecting a constructor name");
10237 
10238   const Type *SourceType = UD->getQualifier()->getAsType();
10239   assert(SourceType &&
10240          "Using decl naming constructor doesn't have type in scope spec.");
10241   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10242 
10243   // Check whether the named type is a direct base class.
10244   bool AnyDependentBases = false;
10245   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10246                                       AnyDependentBases);
10247   if (!Base && !AnyDependentBases) {
10248     Diag(UD->getUsingLoc(),
10249          diag::err_using_decl_constructor_not_in_direct_base)
10250       << UD->getNameInfo().getSourceRange()
10251       << QualType(SourceType, 0) << TargetClass;
10252     UD->setInvalidDecl();
10253     return true;
10254   }
10255 
10256   if (Base)
10257     Base->setInheritConstructors();
10258 
10259   return false;
10260 }
10261 
10262 /// Checks that the given using declaration is not an invalid
10263 /// redeclaration.  Note that this is checking only for the using decl
10264 /// itself, not for any ill-formedness among the UsingShadowDecls.
10265 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10266                                        bool HasTypenameKeyword,
10267                                        const CXXScopeSpec &SS,
10268                                        SourceLocation NameLoc,
10269                                        const LookupResult &Prev) {
10270   NestedNameSpecifier *Qual = SS.getScopeRep();
10271 
10272   // C++03 [namespace.udecl]p8:
10273   // C++0x [namespace.udecl]p10:
10274   //   A using-declaration is a declaration and can therefore be used
10275   //   repeatedly where (and only where) multiple declarations are
10276   //   allowed.
10277   //
10278   // That's in non-member contexts.
10279   if (!CurContext->getRedeclContext()->isRecord()) {
10280     // A dependent qualifier outside a class can only ever resolve to an
10281     // enumeration type. Therefore it conflicts with any other non-type
10282     // declaration in the same scope.
10283     // FIXME: How should we check for dependent type-type conflicts at block
10284     // scope?
10285     if (Qual->isDependent() && !HasTypenameKeyword) {
10286       for (auto *D : Prev) {
10287         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10288           bool OldCouldBeEnumerator =
10289               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10290           Diag(NameLoc,
10291                OldCouldBeEnumerator ? diag::err_redefinition
10292                                     : diag::err_redefinition_different_kind)
10293               << Prev.getLookupName();
10294           Diag(D->getLocation(), diag::note_previous_definition);
10295           return true;
10296         }
10297       }
10298     }
10299     return false;
10300   }
10301 
10302   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10303     NamedDecl *D = *I;
10304 
10305     bool DTypename;
10306     NestedNameSpecifier *DQual;
10307     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10308       DTypename = UD->hasTypename();
10309       DQual = UD->getQualifier();
10310     } else if (UnresolvedUsingValueDecl *UD
10311                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10312       DTypename = false;
10313       DQual = UD->getQualifier();
10314     } else if (UnresolvedUsingTypenameDecl *UD
10315                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10316       DTypename = true;
10317       DQual = UD->getQualifier();
10318     } else continue;
10319 
10320     // using decls differ if one says 'typename' and the other doesn't.
10321     // FIXME: non-dependent using decls?
10322     if (HasTypenameKeyword != DTypename) continue;
10323 
10324     // using decls differ if they name different scopes (but note that
10325     // template instantiation can cause this check to trigger when it
10326     // didn't before instantiation).
10327     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10328         Context.getCanonicalNestedNameSpecifier(DQual))
10329       continue;
10330 
10331     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10332     Diag(D->getLocation(), diag::note_using_decl) << 1;
10333     return true;
10334   }
10335 
10336   return false;
10337 }
10338 
10339 
10340 /// Checks that the given nested-name qualifier used in a using decl
10341 /// in the current context is appropriately related to the current
10342 /// scope.  If an error is found, diagnoses it and returns true.
10343 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10344                                    bool HasTypename,
10345                                    const CXXScopeSpec &SS,
10346                                    const DeclarationNameInfo &NameInfo,
10347                                    SourceLocation NameLoc) {
10348   DeclContext *NamedContext = computeDeclContext(SS);
10349 
10350   if (!CurContext->isRecord()) {
10351     // C++03 [namespace.udecl]p3:
10352     // C++0x [namespace.udecl]p8:
10353     //   A using-declaration for a class member shall be a member-declaration.
10354 
10355     // If we weren't able to compute a valid scope, it might validly be a
10356     // dependent class scope or a dependent enumeration unscoped scope. If
10357     // we have a 'typename' keyword, the scope must resolve to a class type.
10358     if ((HasTypename && !NamedContext) ||
10359         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10360       auto *RD = NamedContext
10361                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10362                      : nullptr;
10363       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10364         RD = nullptr;
10365 
10366       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10367         << SS.getRange();
10368 
10369       // If we have a complete, non-dependent source type, try to suggest a
10370       // way to get the same effect.
10371       if (!RD)
10372         return true;
10373 
10374       // Find what this using-declaration was referring to.
10375       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10376       R.setHideTags(false);
10377       R.suppressDiagnostics();
10378       LookupQualifiedName(R, RD);
10379 
10380       if (R.getAsSingle<TypeDecl>()) {
10381         if (getLangOpts().CPlusPlus11) {
10382           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10383           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10384             << 0 // alias declaration
10385             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10386                                           NameInfo.getName().getAsString() +
10387                                               " = ");
10388         } else {
10389           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10390           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10391           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10392             << 1 // typedef declaration
10393             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10394             << FixItHint::CreateInsertion(
10395                    InsertLoc, " " + NameInfo.getName().getAsString());
10396         }
10397       } else if (R.getAsSingle<VarDecl>()) {
10398         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10399         // repeating the type of the static data member here.
10400         FixItHint FixIt;
10401         if (getLangOpts().CPlusPlus11) {
10402           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10403           FixIt = FixItHint::CreateReplacement(
10404               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10405         }
10406 
10407         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10408           << 2 // reference declaration
10409           << FixIt;
10410       } else if (R.getAsSingle<EnumConstantDecl>()) {
10411         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10412         // repeating the type of the enumeration here, and we can't do so if
10413         // the type is anonymous.
10414         FixItHint FixIt;
10415         if (getLangOpts().CPlusPlus11) {
10416           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10417           FixIt = FixItHint::CreateReplacement(
10418               UsingLoc,
10419               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10420         }
10421 
10422         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10423           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10424           << FixIt;
10425       }
10426       return true;
10427     }
10428 
10429     // Otherwise, this might be valid.
10430     return false;
10431   }
10432 
10433   // The current scope is a record.
10434 
10435   // If the named context is dependent, we can't decide much.
10436   if (!NamedContext) {
10437     // FIXME: in C++0x, we can diagnose if we can prove that the
10438     // nested-name-specifier does not refer to a base class, which is
10439     // still possible in some cases.
10440 
10441     // Otherwise we have to conservatively report that things might be
10442     // okay.
10443     return false;
10444   }
10445 
10446   if (!NamedContext->isRecord()) {
10447     // Ideally this would point at the last name in the specifier,
10448     // but we don't have that level of source info.
10449     Diag(SS.getRange().getBegin(),
10450          diag::err_using_decl_nested_name_specifier_is_not_class)
10451       << SS.getScopeRep() << SS.getRange();
10452     return true;
10453   }
10454 
10455   if (!NamedContext->isDependentContext() &&
10456       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10457     return true;
10458 
10459   if (getLangOpts().CPlusPlus11) {
10460     // C++11 [namespace.udecl]p3:
10461     //   In a using-declaration used as a member-declaration, the
10462     //   nested-name-specifier shall name a base class of the class
10463     //   being defined.
10464 
10465     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10466                                  cast<CXXRecordDecl>(NamedContext))) {
10467       if (CurContext == NamedContext) {
10468         Diag(NameLoc,
10469              diag::err_using_decl_nested_name_specifier_is_current_class)
10470           << SS.getRange();
10471         return true;
10472       }
10473 
10474       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10475         Diag(SS.getRange().getBegin(),
10476              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10477           << SS.getScopeRep()
10478           << cast<CXXRecordDecl>(CurContext)
10479           << SS.getRange();
10480       }
10481       return true;
10482     }
10483 
10484     return false;
10485   }
10486 
10487   // C++03 [namespace.udecl]p4:
10488   //   A using-declaration used as a member-declaration shall refer
10489   //   to a member of a base class of the class being defined [etc.].
10490 
10491   // Salient point: SS doesn't have to name a base class as long as
10492   // lookup only finds members from base classes.  Therefore we can
10493   // diagnose here only if we can prove that that can't happen,
10494   // i.e. if the class hierarchies provably don't intersect.
10495 
10496   // TODO: it would be nice if "definitely valid" results were cached
10497   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10498   // need to be repeated.
10499 
10500   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10501   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10502     Bases.insert(Base);
10503     return true;
10504   };
10505 
10506   // Collect all bases. Return false if we find a dependent base.
10507   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10508     return false;
10509 
10510   // Returns true if the base is dependent or is one of the accumulated base
10511   // classes.
10512   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10513     return !Bases.count(Base);
10514   };
10515 
10516   // Return false if the class has a dependent base or if it or one
10517   // of its bases is present in the base set of the current context.
10518   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10519       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10520     return false;
10521 
10522   Diag(SS.getRange().getBegin(),
10523        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10524     << SS.getScopeRep()
10525     << cast<CXXRecordDecl>(CurContext)
10526     << SS.getRange();
10527 
10528   return true;
10529 }
10530 
10531 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10532                                   MultiTemplateParamsArg TemplateParamLists,
10533                                   SourceLocation UsingLoc, UnqualifiedId &Name,
10534                                   const ParsedAttributesView &AttrList,
10535                                   TypeResult Type, Decl *DeclFromDeclSpec) {
10536   // Skip up to the relevant declaration scope.
10537   while (S->isTemplateParamScope())
10538     S = S->getParent();
10539   assert((S->getFlags() & Scope::DeclScope) &&
10540          "got alias-declaration outside of declaration scope");
10541 
10542   if (Type.isInvalid())
10543     return nullptr;
10544 
10545   bool Invalid = false;
10546   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10547   TypeSourceInfo *TInfo = nullptr;
10548   GetTypeFromParser(Type.get(), &TInfo);
10549 
10550   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10551     return nullptr;
10552 
10553   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10554                                       UPPC_DeclarationType)) {
10555     Invalid = true;
10556     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10557                                              TInfo->getTypeLoc().getBeginLoc());
10558   }
10559 
10560   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10561                         TemplateParamLists.size()
10562                             ? forRedeclarationInCurContext()
10563                             : ForVisibleRedeclaration);
10564   LookupName(Previous, S);
10565 
10566   // Warn about shadowing the name of a template parameter.
10567   if (Previous.isSingleResult() &&
10568       Previous.getFoundDecl()->isTemplateParameter()) {
10569     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10570     Previous.clear();
10571   }
10572 
10573   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10574          "name in alias declaration must be an identifier");
10575   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10576                                                Name.StartLocation,
10577                                                Name.Identifier, TInfo);
10578 
10579   NewTD->setAccess(AS);
10580 
10581   if (Invalid)
10582     NewTD->setInvalidDecl();
10583 
10584   ProcessDeclAttributeList(S, NewTD, AttrList);
10585   AddPragmaAttributes(S, NewTD);
10586 
10587   CheckTypedefForVariablyModifiedType(S, NewTD);
10588   Invalid |= NewTD->isInvalidDecl();
10589 
10590   bool Redeclaration = false;
10591 
10592   NamedDecl *NewND;
10593   if (TemplateParamLists.size()) {
10594     TypeAliasTemplateDecl *OldDecl = nullptr;
10595     TemplateParameterList *OldTemplateParams = nullptr;
10596 
10597     if (TemplateParamLists.size() != 1) {
10598       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10599         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10600          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10601     }
10602     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10603 
10604     // Check that we can declare a template here.
10605     if (CheckTemplateDeclScope(S, TemplateParams))
10606       return nullptr;
10607 
10608     // Only consider previous declarations in the same scope.
10609     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10610                          /*ExplicitInstantiationOrSpecialization*/false);
10611     if (!Previous.empty()) {
10612       Redeclaration = true;
10613 
10614       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10615       if (!OldDecl && !Invalid) {
10616         Diag(UsingLoc, diag::err_redefinition_different_kind)
10617           << Name.Identifier;
10618 
10619         NamedDecl *OldD = Previous.getRepresentativeDecl();
10620         if (OldD->getLocation().isValid())
10621           Diag(OldD->getLocation(), diag::note_previous_definition);
10622 
10623         Invalid = true;
10624       }
10625 
10626       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10627         if (TemplateParameterListsAreEqual(TemplateParams,
10628                                            OldDecl->getTemplateParameters(),
10629                                            /*Complain=*/true,
10630                                            TPL_TemplateMatch))
10631           OldTemplateParams =
10632               OldDecl->getMostRecentDecl()->getTemplateParameters();
10633         else
10634           Invalid = true;
10635 
10636         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10637         if (!Invalid &&
10638             !Context.hasSameType(OldTD->getUnderlyingType(),
10639                                  NewTD->getUnderlyingType())) {
10640           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10641           // but we can't reasonably accept it.
10642           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10643             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10644           if (OldTD->getLocation().isValid())
10645             Diag(OldTD->getLocation(), diag::note_previous_definition);
10646           Invalid = true;
10647         }
10648       }
10649     }
10650 
10651     // Merge any previous default template arguments into our parameters,
10652     // and check the parameter list.
10653     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10654                                    TPC_TypeAliasTemplate))
10655       return nullptr;
10656 
10657     TypeAliasTemplateDecl *NewDecl =
10658       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10659                                     Name.Identifier, TemplateParams,
10660                                     NewTD);
10661     NewTD->setDescribedAliasTemplate(NewDecl);
10662 
10663     NewDecl->setAccess(AS);
10664 
10665     if (Invalid)
10666       NewDecl->setInvalidDecl();
10667     else if (OldDecl) {
10668       NewDecl->setPreviousDecl(OldDecl);
10669       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10670     }
10671 
10672     NewND = NewDecl;
10673   } else {
10674     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10675       setTagNameForLinkagePurposes(TD, NewTD);
10676       handleTagNumbering(TD, S);
10677     }
10678     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10679     NewND = NewTD;
10680   }
10681 
10682   PushOnScopeChains(NewND, S);
10683   ActOnDocumentableDecl(NewND);
10684   return NewND;
10685 }
10686 
10687 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10688                                    SourceLocation AliasLoc,
10689                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10690                                    SourceLocation IdentLoc,
10691                                    IdentifierInfo *Ident) {
10692 
10693   // Lookup the namespace name.
10694   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10695   LookupParsedName(R, S, &SS);
10696 
10697   if (R.isAmbiguous())
10698     return nullptr;
10699 
10700   if (R.empty()) {
10701     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10702       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10703       return nullptr;
10704     }
10705   }
10706   assert(!R.isAmbiguous() && !R.empty());
10707   NamedDecl *ND = R.getRepresentativeDecl();
10708 
10709   // Check if we have a previous declaration with the same name.
10710   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10711                      ForVisibleRedeclaration);
10712   LookupName(PrevR, S);
10713 
10714   // Check we're not shadowing a template parameter.
10715   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10716     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10717     PrevR.clear();
10718   }
10719 
10720   // Filter out any other lookup result from an enclosing scope.
10721   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10722                        /*AllowInlineNamespace*/false);
10723 
10724   // Find the previous declaration and check that we can redeclare it.
10725   NamespaceAliasDecl *Prev = nullptr;
10726   if (PrevR.isSingleResult()) {
10727     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10728     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10729       // We already have an alias with the same name that points to the same
10730       // namespace; check that it matches.
10731       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10732         Prev = AD;
10733       } else if (isVisible(PrevDecl)) {
10734         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10735           << Alias;
10736         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10737           << AD->getNamespace();
10738         return nullptr;
10739       }
10740     } else if (isVisible(PrevDecl)) {
10741       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10742                             ? diag::err_redefinition
10743                             : diag::err_redefinition_different_kind;
10744       Diag(AliasLoc, DiagID) << Alias;
10745       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10746       return nullptr;
10747     }
10748   }
10749 
10750   // The use of a nested name specifier may trigger deprecation warnings.
10751   DiagnoseUseOfDecl(ND, IdentLoc);
10752 
10753   NamespaceAliasDecl *AliasDecl =
10754     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10755                                Alias, SS.getWithLocInContext(Context),
10756                                IdentLoc, ND);
10757   if (Prev)
10758     AliasDecl->setPreviousDecl(Prev);
10759 
10760   PushOnScopeChains(AliasDecl, S);
10761   return AliasDecl;
10762 }
10763 
10764 namespace {
10765 struct SpecialMemberExceptionSpecInfo
10766     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10767   SourceLocation Loc;
10768   Sema::ImplicitExceptionSpecification ExceptSpec;
10769 
10770   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10771                                  Sema::CXXSpecialMember CSM,
10772                                  Sema::InheritedConstructorInfo *ICI,
10773                                  SourceLocation Loc)
10774       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10775 
10776   bool visitBase(CXXBaseSpecifier *Base);
10777   bool visitField(FieldDecl *FD);
10778 
10779   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10780                            unsigned Quals);
10781 
10782   void visitSubobjectCall(Subobject Subobj,
10783                           Sema::SpecialMemberOverloadResult SMOR);
10784 };
10785 }
10786 
10787 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10788   auto *RT = Base->getType()->getAs<RecordType>();
10789   if (!RT)
10790     return false;
10791 
10792   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10793   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10794   if (auto *BaseCtor = SMOR.getMethod()) {
10795     visitSubobjectCall(Base, BaseCtor);
10796     return false;
10797   }
10798 
10799   visitClassSubobject(BaseClass, Base, 0);
10800   return false;
10801 }
10802 
10803 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10804   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10805     Expr *E = FD->getInClassInitializer();
10806     if (!E)
10807       // FIXME: It's a little wasteful to build and throw away a
10808       // CXXDefaultInitExpr here.
10809       // FIXME: We should have a single context note pointing at Loc, and
10810       // this location should be MD->getLocation() instead, since that's
10811       // the location where we actually use the default init expression.
10812       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10813     if (E)
10814       ExceptSpec.CalledExpr(E);
10815   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10816                             ->getAs<RecordType>()) {
10817     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10818                         FD->getType().getCVRQualifiers());
10819   }
10820   return false;
10821 }
10822 
10823 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10824                                                          Subobject Subobj,
10825                                                          unsigned Quals) {
10826   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10827   bool IsMutable = Field && Field->isMutable();
10828   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10829 }
10830 
10831 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10832     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10833   // Note, if lookup fails, it doesn't matter what exception specification we
10834   // choose because the special member will be deleted.
10835   if (CXXMethodDecl *MD = SMOR.getMethod())
10836     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10837 }
10838 
10839 namespace {
10840 /// RAII object to register a special member as being currently declared.
10841 struct ComputingExceptionSpec {
10842   Sema &S;
10843 
10844   ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
10845       : S(S) {
10846     Sema::CodeSynthesisContext Ctx;
10847     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
10848     Ctx.PointOfInstantiation = Loc;
10849     Ctx.Entity = MD;
10850     S.pushCodeSynthesisContext(Ctx);
10851   }
10852   ~ComputingExceptionSpec() {
10853     S.popCodeSynthesisContext();
10854   }
10855 };
10856 }
10857 
10858 static Sema::ImplicitExceptionSpecification
10859 ComputeDefaultedSpecialMemberExceptionSpec(
10860     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10861     Sema::InheritedConstructorInfo *ICI) {
10862   ComputingExceptionSpec CES(S, MD, Loc);
10863 
10864   CXXRecordDecl *ClassDecl = MD->getParent();
10865 
10866   // C++ [except.spec]p14:
10867   //   An implicitly declared special member function (Clause 12) shall have an
10868   //   exception-specification. [...]
10869   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
10870   if (ClassDecl->isInvalidDecl())
10871     return Info.ExceptSpec;
10872 
10873   // FIXME: If this diagnostic fires, we're probably missing a check for
10874   // attempting to resolve an exception specification before it's known
10875   // at a higher level.
10876   if (S.RequireCompleteType(MD->getLocation(),
10877                             S.Context.getRecordType(ClassDecl),
10878                             diag::err_exception_spec_incomplete_type))
10879     return Info.ExceptSpec;
10880 
10881   // C++1z [except.spec]p7:
10882   //   [Look for exceptions thrown by] a constructor selected [...] to
10883   //   initialize a potentially constructed subobject,
10884   // C++1z [except.spec]p8:
10885   //   The exception specification for an implicitly-declared destructor, or a
10886   //   destructor without a noexcept-specifier, is potentially-throwing if and
10887   //   only if any of the destructors for any of its potentially constructed
10888   //   subojects is potentially throwing.
10889   // FIXME: We respect the first rule but ignore the "potentially constructed"
10890   // in the second rule to resolve a core issue (no number yet) that would have
10891   // us reject:
10892   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10893   //   struct B : A {};
10894   //   struct C : B { void f(); };
10895   // ... due to giving B::~B() a non-throwing exception specification.
10896   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10897                                 : Info.VisitAllBases);
10898 
10899   return Info.ExceptSpec;
10900 }
10901 
10902 namespace {
10903 /// RAII object to register a special member as being currently declared.
10904 struct DeclaringSpecialMember {
10905   Sema &S;
10906   Sema::SpecialMemberDecl D;
10907   Sema::ContextRAII SavedContext;
10908   bool WasAlreadyBeingDeclared;
10909 
10910   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10911       : S(S), D(RD, CSM), SavedContext(S, RD) {
10912     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10913     if (WasAlreadyBeingDeclared)
10914       // This almost never happens, but if it does, ensure that our cache
10915       // doesn't contain a stale result.
10916       S.SpecialMemberCache.clear();
10917     else {
10918       // Register a note to be produced if we encounter an error while
10919       // declaring the special member.
10920       Sema::CodeSynthesisContext Ctx;
10921       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10922       // FIXME: We don't have a location to use here. Using the class's
10923       // location maintains the fiction that we declare all special members
10924       // with the class, but (1) it's not clear that lying about that helps our
10925       // users understand what's going on, and (2) there may be outer contexts
10926       // on the stack (some of which are relevant) and printing them exposes
10927       // our lies.
10928       Ctx.PointOfInstantiation = RD->getLocation();
10929       Ctx.Entity = RD;
10930       Ctx.SpecialMember = CSM;
10931       S.pushCodeSynthesisContext(Ctx);
10932     }
10933   }
10934   ~DeclaringSpecialMember() {
10935     if (!WasAlreadyBeingDeclared) {
10936       S.SpecialMembersBeingDeclared.erase(D);
10937       S.popCodeSynthesisContext();
10938     }
10939   }
10940 
10941   /// Are we already trying to declare this special member?
10942   bool isAlreadyBeingDeclared() const {
10943     return WasAlreadyBeingDeclared;
10944   }
10945 };
10946 }
10947 
10948 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10949   // Look up any existing declarations, but don't trigger declaration of all
10950   // implicit special members with this name.
10951   DeclarationName Name = FD->getDeclName();
10952   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10953                  ForExternalRedeclaration);
10954   for (auto *D : FD->getParent()->lookup(Name))
10955     if (auto *Acceptable = R.getAcceptableDecl(D))
10956       R.addDecl(Acceptable);
10957   R.resolveKind();
10958   R.suppressDiagnostics();
10959 
10960   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10961 }
10962 
10963 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
10964                                           QualType ResultTy,
10965                                           ArrayRef<QualType> Args) {
10966   // Build an exception specification pointing back at this constructor.
10967   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
10968 
10969   if (getLangOpts().OpenCLCPlusPlus) {
10970     // OpenCL: Implicitly defaulted special member are of the generic address
10971     // space.
10972     EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
10973   }
10974 
10975   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
10976   SpecialMem->setType(QT);
10977 }
10978 
10979 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10980                                                      CXXRecordDecl *ClassDecl) {
10981   // C++ [class.ctor]p5:
10982   //   A default constructor for a class X is a constructor of class X
10983   //   that can be called without an argument. If there is no
10984   //   user-declared constructor for class X, a default constructor is
10985   //   implicitly declared. An implicitly-declared default constructor
10986   //   is an inline public member of its class.
10987   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10988          "Should not build implicit default constructor!");
10989 
10990   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10991   if (DSM.isAlreadyBeingDeclared())
10992     return nullptr;
10993 
10994   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10995                                                      CXXDefaultConstructor,
10996                                                      false);
10997 
10998   // Create the actual constructor declaration.
10999   CanQualType ClassType
11000     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11001   SourceLocation ClassLoc = ClassDecl->getLocation();
11002   DeclarationName Name
11003     = Context.DeclarationNames.getCXXConstructorName(ClassType);
11004   DeclarationNameInfo NameInfo(Name, ClassLoc);
11005   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
11006       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
11007       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
11008       /*isImplicitlyDeclared=*/true, Constexpr);
11009   DefaultCon->setAccess(AS_public);
11010   DefaultCon->setDefaulted();
11011 
11012   if (getLangOpts().CUDA) {
11013     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
11014                                             DefaultCon,
11015                                             /* ConstRHS */ false,
11016                                             /* Diagnose */ false);
11017   }
11018 
11019   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
11020 
11021   // We don't need to use SpecialMemberIsTrivial here; triviality for default
11022   // constructors is easy to compute.
11023   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
11024 
11025   // Note that we have declared this constructor.
11026   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
11027 
11028   Scope *S = getScopeForContext(ClassDecl);
11029   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
11030 
11031   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
11032     SetDeclDeleted(DefaultCon, ClassLoc);
11033 
11034   if (S)
11035     PushOnScopeChains(DefaultCon, S, false);
11036   ClassDecl->addDecl(DefaultCon);
11037 
11038   return DefaultCon;
11039 }
11040 
11041 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
11042                                             CXXConstructorDecl *Constructor) {
11043   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
11044           !Constructor->doesThisDeclarationHaveABody() &&
11045           !Constructor->isDeleted()) &&
11046     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
11047   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11048     return;
11049 
11050   CXXRecordDecl *ClassDecl = Constructor->getParent();
11051   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
11052 
11053   SynthesizedFunctionScope Scope(*this, Constructor);
11054 
11055   // The exception specification is needed because we are defining the
11056   // function.
11057   ResolveExceptionSpec(CurrentLocation,
11058                        Constructor->getType()->castAs<FunctionProtoType>());
11059   MarkVTableUsed(CurrentLocation, ClassDecl);
11060 
11061   // Add a context note for diagnostics produced after this point.
11062   Scope.addContextNote(CurrentLocation);
11063 
11064   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11065     Constructor->setInvalidDecl();
11066     return;
11067   }
11068 
11069   SourceLocation Loc = Constructor->getEndLoc().isValid()
11070                            ? Constructor->getEndLoc()
11071                            : Constructor->getLocation();
11072   Constructor->setBody(new (Context) CompoundStmt(Loc));
11073   Constructor->markUsed(Context);
11074 
11075   if (ASTMutationListener *L = getASTMutationListener()) {
11076     L->CompletedImplicitDefinition(Constructor);
11077   }
11078 
11079   DiagnoseUninitializedFields(*this, Constructor);
11080 }
11081 
11082 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
11083   // Perform any delayed checks on exception specifications.
11084   CheckDelayedMemberExceptionSpecs();
11085 }
11086 
11087 /// Find or create the fake constructor we synthesize to model constructing an
11088 /// object of a derived class via a constructor of a base class.
11089 CXXConstructorDecl *
11090 Sema::findInheritingConstructor(SourceLocation Loc,
11091                                 CXXConstructorDecl *BaseCtor,
11092                                 ConstructorUsingShadowDecl *Shadow) {
11093   CXXRecordDecl *Derived = Shadow->getParent();
11094   SourceLocation UsingLoc = Shadow->getLocation();
11095 
11096   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11097   // For now we use the name of the base class constructor as a member of the
11098   // derived class to indicate a (fake) inherited constructor name.
11099   DeclarationName Name = BaseCtor->getDeclName();
11100 
11101   // Check to see if we already have a fake constructor for this inherited
11102   // constructor call.
11103   for (NamedDecl *Ctor : Derived->lookup(Name))
11104     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11105                                ->getInheritedConstructor()
11106                                .getConstructor(),
11107                            BaseCtor))
11108       return cast<CXXConstructorDecl>(Ctor);
11109 
11110   DeclarationNameInfo NameInfo(Name, UsingLoc);
11111   TypeSourceInfo *TInfo =
11112       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11113   FunctionProtoTypeLoc ProtoLoc =
11114       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11115 
11116   // Check the inherited constructor is valid and find the list of base classes
11117   // from which it was inherited.
11118   InheritedConstructorInfo ICI(*this, Loc, Shadow);
11119 
11120   bool Constexpr =
11121       BaseCtor->isConstexpr() &&
11122       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11123                                         false, BaseCtor, &ICI);
11124 
11125   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11126       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11127       BaseCtor->isExplicit(), /*Inline=*/true,
11128       /*ImplicitlyDeclared=*/true, Constexpr,
11129       InheritedConstructor(Shadow, BaseCtor));
11130   if (Shadow->isInvalidDecl())
11131     DerivedCtor->setInvalidDecl();
11132 
11133   // Build an unevaluated exception specification for this fake constructor.
11134   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11135   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11136   EPI.ExceptionSpec.Type = EST_Unevaluated;
11137   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11138   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11139                                                FPT->getParamTypes(), EPI));
11140 
11141   // Build the parameter declarations.
11142   SmallVector<ParmVarDecl *, 16> ParamDecls;
11143   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11144     TypeSourceInfo *TInfo =
11145         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11146     ParmVarDecl *PD = ParmVarDecl::Create(
11147         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11148         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
11149     PD->setScopeInfo(0, I);
11150     PD->setImplicit();
11151     // Ensure attributes are propagated onto parameters (this matters for
11152     // format, pass_object_size, ...).
11153     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11154     ParamDecls.push_back(PD);
11155     ProtoLoc.setParam(I, PD);
11156   }
11157 
11158   // Set up the new constructor.
11159   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11160   DerivedCtor->setAccess(BaseCtor->getAccess());
11161   DerivedCtor->setParams(ParamDecls);
11162   Derived->addDecl(DerivedCtor);
11163 
11164   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11165     SetDeclDeleted(DerivedCtor, UsingLoc);
11166 
11167   return DerivedCtor;
11168 }
11169 
11170 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11171   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11172                                Ctor->getInheritedConstructor().getShadowDecl());
11173   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11174                             /*Diagnose*/true);
11175 }
11176 
11177 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11178                                        CXXConstructorDecl *Constructor) {
11179   CXXRecordDecl *ClassDecl = Constructor->getParent();
11180   assert(Constructor->getInheritedConstructor() &&
11181          !Constructor->doesThisDeclarationHaveABody() &&
11182          !Constructor->isDeleted());
11183   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11184     return;
11185 
11186   // Initializations are performed "as if by a defaulted default constructor",
11187   // so enter the appropriate scope.
11188   SynthesizedFunctionScope Scope(*this, Constructor);
11189 
11190   // The exception specification is needed because we are defining the
11191   // function.
11192   ResolveExceptionSpec(CurrentLocation,
11193                        Constructor->getType()->castAs<FunctionProtoType>());
11194   MarkVTableUsed(CurrentLocation, ClassDecl);
11195 
11196   // Add a context note for diagnostics produced after this point.
11197   Scope.addContextNote(CurrentLocation);
11198 
11199   ConstructorUsingShadowDecl *Shadow =
11200       Constructor->getInheritedConstructor().getShadowDecl();
11201   CXXConstructorDecl *InheritedCtor =
11202       Constructor->getInheritedConstructor().getConstructor();
11203 
11204   // [class.inhctor.init]p1:
11205   //   initialization proceeds as if a defaulted default constructor is used to
11206   //   initialize the D object and each base class subobject from which the
11207   //   constructor was inherited
11208 
11209   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11210   CXXRecordDecl *RD = Shadow->getParent();
11211   SourceLocation InitLoc = Shadow->getLocation();
11212 
11213   // Build explicit initializers for all base classes from which the
11214   // constructor was inherited.
11215   SmallVector<CXXCtorInitializer*, 8> Inits;
11216   for (bool VBase : {false, true}) {
11217     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11218       if (B.isVirtual() != VBase)
11219         continue;
11220 
11221       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11222       if (!BaseRD)
11223         continue;
11224 
11225       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11226       if (!BaseCtor.first)
11227         continue;
11228 
11229       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11230       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11231           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11232 
11233       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11234       Inits.push_back(new (Context) CXXCtorInitializer(
11235           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11236           SourceLocation()));
11237     }
11238   }
11239 
11240   // We now proceed as if for a defaulted default constructor, with the relevant
11241   // initializers replaced.
11242 
11243   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11244     Constructor->setInvalidDecl();
11245     return;
11246   }
11247 
11248   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11249   Constructor->markUsed(Context);
11250 
11251   if (ASTMutationListener *L = getASTMutationListener()) {
11252     L->CompletedImplicitDefinition(Constructor);
11253   }
11254 
11255   DiagnoseUninitializedFields(*this, Constructor);
11256 }
11257 
11258 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11259   // C++ [class.dtor]p2:
11260   //   If a class has no user-declared destructor, a destructor is
11261   //   declared implicitly. An implicitly-declared destructor is an
11262   //   inline public member of its class.
11263   assert(ClassDecl->needsImplicitDestructor());
11264 
11265   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11266   if (DSM.isAlreadyBeingDeclared())
11267     return nullptr;
11268 
11269   // Create the actual destructor declaration.
11270   CanQualType ClassType
11271     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11272   SourceLocation ClassLoc = ClassDecl->getLocation();
11273   DeclarationName Name
11274     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11275   DeclarationNameInfo NameInfo(Name, ClassLoc);
11276   CXXDestructorDecl *Destructor
11277       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11278                                   QualType(), nullptr, /*isInline=*/true,
11279                                   /*isImplicitlyDeclared=*/true);
11280   Destructor->setAccess(AS_public);
11281   Destructor->setDefaulted();
11282 
11283   if (getLangOpts().CUDA) {
11284     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11285                                             Destructor,
11286                                             /* ConstRHS */ false,
11287                                             /* Diagnose */ false);
11288   }
11289 
11290   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
11291 
11292   // We don't need to use SpecialMemberIsTrivial here; triviality for
11293   // destructors is easy to compute.
11294   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11295   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11296                                 ClassDecl->hasTrivialDestructorForCall());
11297 
11298   // Note that we have declared this destructor.
11299   ++getASTContext().NumImplicitDestructorsDeclared;
11300 
11301   Scope *S = getScopeForContext(ClassDecl);
11302   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11303 
11304   // We can't check whether an implicit destructor is deleted before we complete
11305   // the definition of the class, because its validity depends on the alignment
11306   // of the class. We'll check this from ActOnFields once the class is complete.
11307   if (ClassDecl->isCompleteDefinition() &&
11308       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11309     SetDeclDeleted(Destructor, ClassLoc);
11310 
11311   // Introduce this destructor into its scope.
11312   if (S)
11313     PushOnScopeChains(Destructor, S, false);
11314   ClassDecl->addDecl(Destructor);
11315 
11316   return Destructor;
11317 }
11318 
11319 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11320                                     CXXDestructorDecl *Destructor) {
11321   assert((Destructor->isDefaulted() &&
11322           !Destructor->doesThisDeclarationHaveABody() &&
11323           !Destructor->isDeleted()) &&
11324          "DefineImplicitDestructor - call it for implicit default dtor");
11325   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11326     return;
11327 
11328   CXXRecordDecl *ClassDecl = Destructor->getParent();
11329   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11330 
11331   SynthesizedFunctionScope Scope(*this, Destructor);
11332 
11333   // The exception specification is needed because we are defining the
11334   // function.
11335   ResolveExceptionSpec(CurrentLocation,
11336                        Destructor->getType()->castAs<FunctionProtoType>());
11337   MarkVTableUsed(CurrentLocation, ClassDecl);
11338 
11339   // Add a context note for diagnostics produced after this point.
11340   Scope.addContextNote(CurrentLocation);
11341 
11342   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11343                                          Destructor->getParent());
11344 
11345   if (CheckDestructor(Destructor)) {
11346     Destructor->setInvalidDecl();
11347     return;
11348   }
11349 
11350   SourceLocation Loc = Destructor->getEndLoc().isValid()
11351                            ? Destructor->getEndLoc()
11352                            : Destructor->getLocation();
11353   Destructor->setBody(new (Context) CompoundStmt(Loc));
11354   Destructor->markUsed(Context);
11355 
11356   if (ASTMutationListener *L = getASTMutationListener()) {
11357     L->CompletedImplicitDefinition(Destructor);
11358   }
11359 }
11360 
11361 /// Perform any semantic analysis which needs to be delayed until all
11362 /// pending class member declarations have been parsed.
11363 void Sema::ActOnFinishCXXMemberDecls() {
11364   // If the context is an invalid C++ class, just suppress these checks.
11365   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11366     if (Record->isInvalidDecl()) {
11367       DelayedOverridingExceptionSpecChecks.clear();
11368       DelayedEquivalentExceptionSpecChecks.clear();
11369       DelayedDefaultedMemberExceptionSpecs.clear();
11370       return;
11371     }
11372     checkForMultipleExportedDefaultConstructors(*this, Record);
11373   }
11374 }
11375 
11376 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11377   referenceDLLExportedClassMethods();
11378 }
11379 
11380 void Sema::referenceDLLExportedClassMethods() {
11381   if (!DelayedDllExportClasses.empty()) {
11382     // Calling ReferenceDllExportedMembers might cause the current function to
11383     // be called again, so use a local copy of DelayedDllExportClasses.
11384     SmallVector<CXXRecordDecl *, 4> WorkList;
11385     std::swap(DelayedDllExportClasses, WorkList);
11386     for (CXXRecordDecl *Class : WorkList)
11387       ReferenceDllExportedMembers(*this, Class);
11388   }
11389 }
11390 
11391 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11392   assert(getLangOpts().CPlusPlus11 &&
11393          "adjusting dtor exception specs was introduced in c++11");
11394 
11395   if (Destructor->isDependentContext())
11396     return;
11397 
11398   // C++11 [class.dtor]p3:
11399   //   A declaration of a destructor that does not have an exception-
11400   //   specification is implicitly considered to have the same exception-
11401   //   specification as an implicit declaration.
11402   const FunctionProtoType *DtorType = Destructor->getType()->
11403                                         getAs<FunctionProtoType>();
11404   if (DtorType->hasExceptionSpec())
11405     return;
11406 
11407   // Replace the destructor's type, building off the existing one. Fortunately,
11408   // the only thing of interest in the destructor type is its extended info.
11409   // The return and arguments are fixed.
11410   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11411   EPI.ExceptionSpec.Type = EST_Unevaluated;
11412   EPI.ExceptionSpec.SourceDecl = Destructor;
11413   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11414 
11415   // FIXME: If the destructor has a body that could throw, and the newly created
11416   // spec doesn't allow exceptions, we should emit a warning, because this
11417   // change in behavior can break conforming C++03 programs at runtime.
11418   // However, we don't have a body or an exception specification yet, so it
11419   // needs to be done somewhere else.
11420 }
11421 
11422 namespace {
11423 /// An abstract base class for all helper classes used in building the
11424 //  copy/move operators. These classes serve as factory functions and help us
11425 //  avoid using the same Expr* in the AST twice.
11426 class ExprBuilder {
11427   ExprBuilder(const ExprBuilder&) = delete;
11428   ExprBuilder &operator=(const ExprBuilder&) = delete;
11429 
11430 protected:
11431   static Expr *assertNotNull(Expr *E) {
11432     assert(E && "Expression construction must not fail.");
11433     return E;
11434   }
11435 
11436 public:
11437   ExprBuilder() {}
11438   virtual ~ExprBuilder() {}
11439 
11440   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11441 };
11442 
11443 class RefBuilder: public ExprBuilder {
11444   VarDecl *Var;
11445   QualType VarType;
11446 
11447 public:
11448   Expr *build(Sema &S, SourceLocation Loc) const override {
11449     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11450   }
11451 
11452   RefBuilder(VarDecl *Var, QualType VarType)
11453       : Var(Var), VarType(VarType) {}
11454 };
11455 
11456 class ThisBuilder: public ExprBuilder {
11457 public:
11458   Expr *build(Sema &S, SourceLocation Loc) const override {
11459     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11460   }
11461 };
11462 
11463 class CastBuilder: public ExprBuilder {
11464   const ExprBuilder &Builder;
11465   QualType Type;
11466   ExprValueKind Kind;
11467   const CXXCastPath &Path;
11468 
11469 public:
11470   Expr *build(Sema &S, SourceLocation Loc) const override {
11471     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11472                                              CK_UncheckedDerivedToBase, Kind,
11473                                              &Path).get());
11474   }
11475 
11476   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11477               const CXXCastPath &Path)
11478       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11479 };
11480 
11481 class DerefBuilder: public ExprBuilder {
11482   const ExprBuilder &Builder;
11483 
11484 public:
11485   Expr *build(Sema &S, SourceLocation Loc) const override {
11486     return assertNotNull(
11487         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11488   }
11489 
11490   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11491 };
11492 
11493 class MemberBuilder: public ExprBuilder {
11494   const ExprBuilder &Builder;
11495   QualType Type;
11496   CXXScopeSpec SS;
11497   bool IsArrow;
11498   LookupResult &MemberLookup;
11499 
11500 public:
11501   Expr *build(Sema &S, SourceLocation Loc) const override {
11502     return assertNotNull(S.BuildMemberReferenceExpr(
11503         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11504         nullptr, MemberLookup, nullptr, nullptr).get());
11505   }
11506 
11507   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11508                 LookupResult &MemberLookup)
11509       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11510         MemberLookup(MemberLookup) {}
11511 };
11512 
11513 class MoveCastBuilder: public ExprBuilder {
11514   const ExprBuilder &Builder;
11515 
11516 public:
11517   Expr *build(Sema &S, SourceLocation Loc) const override {
11518     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11519   }
11520 
11521   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11522 };
11523 
11524 class LvalueConvBuilder: public ExprBuilder {
11525   const ExprBuilder &Builder;
11526 
11527 public:
11528   Expr *build(Sema &S, SourceLocation Loc) const override {
11529     return assertNotNull(
11530         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11531   }
11532 
11533   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11534 };
11535 
11536 class SubscriptBuilder: public ExprBuilder {
11537   const ExprBuilder &Base;
11538   const ExprBuilder &Index;
11539 
11540 public:
11541   Expr *build(Sema &S, SourceLocation Loc) const override {
11542     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11543         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11544   }
11545 
11546   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11547       : Base(Base), Index(Index) {}
11548 };
11549 
11550 } // end anonymous namespace
11551 
11552 /// When generating a defaulted copy or move assignment operator, if a field
11553 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11554 /// do so. This optimization only applies for arrays of scalars, and for arrays
11555 /// of class type where the selected copy/move-assignment operator is trivial.
11556 static StmtResult
11557 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11558                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11559   // Compute the size of the memory buffer to be copied.
11560   QualType SizeType = S.Context.getSizeType();
11561   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11562                    S.Context.getTypeSizeInChars(T).getQuantity());
11563 
11564   // Take the address of the field references for "from" and "to". We
11565   // directly construct UnaryOperators here because semantic analysis
11566   // does not permit us to take the address of an xvalue.
11567   Expr *From = FromB.build(S, Loc);
11568   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11569                          S.Context.getPointerType(From->getType()),
11570                          VK_RValue, OK_Ordinary, Loc, false);
11571   Expr *To = ToB.build(S, Loc);
11572   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11573                        S.Context.getPointerType(To->getType()),
11574                        VK_RValue, OK_Ordinary, Loc, false);
11575 
11576   const Type *E = T->getBaseElementTypeUnsafe();
11577   bool NeedsCollectableMemCpy =
11578     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11579 
11580   // Create a reference to the __builtin_objc_memmove_collectable function
11581   StringRef MemCpyName = NeedsCollectableMemCpy ?
11582     "__builtin_objc_memmove_collectable" :
11583     "__builtin_memcpy";
11584   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11585                  Sema::LookupOrdinaryName);
11586   S.LookupName(R, S.TUScope, true);
11587 
11588   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11589   if (!MemCpy)
11590     // Something went horribly wrong earlier, and we will have complained
11591     // about it.
11592     return StmtError();
11593 
11594   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11595                                             VK_RValue, Loc, nullptr);
11596   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11597 
11598   Expr *CallArgs[] = {
11599     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11600   };
11601   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11602                                     Loc, CallArgs, Loc);
11603 
11604   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11605   return Call.getAs<Stmt>();
11606 }
11607 
11608 /// Builds a statement that copies/moves the given entity from \p From to
11609 /// \c To.
11610 ///
11611 /// This routine is used to copy/move the members of a class with an
11612 /// implicitly-declared copy/move assignment operator. When the entities being
11613 /// copied are arrays, this routine builds for loops to copy them.
11614 ///
11615 /// \param S The Sema object used for type-checking.
11616 ///
11617 /// \param Loc The location where the implicit copy/move is being generated.
11618 ///
11619 /// \param T The type of the expressions being copied/moved. Both expressions
11620 /// must have this type.
11621 ///
11622 /// \param To The expression we are copying/moving to.
11623 ///
11624 /// \param From The expression we are copying/moving from.
11625 ///
11626 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11627 /// Otherwise, it's a non-static member subobject.
11628 ///
11629 /// \param Copying Whether we're copying or moving.
11630 ///
11631 /// \param Depth Internal parameter recording the depth of the recursion.
11632 ///
11633 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11634 /// if a memcpy should be used instead.
11635 static StmtResult
11636 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11637                                  const ExprBuilder &To, const ExprBuilder &From,
11638                                  bool CopyingBaseSubobject, bool Copying,
11639                                  unsigned Depth = 0) {
11640   // C++11 [class.copy]p28:
11641   //   Each subobject is assigned in the manner appropriate to its type:
11642   //
11643   //     - if the subobject is of class type, as if by a call to operator= with
11644   //       the subobject as the object expression and the corresponding
11645   //       subobject of x as a single function argument (as if by explicit
11646   //       qualification; that is, ignoring any possible virtual overriding
11647   //       functions in more derived classes);
11648   //
11649   // C++03 [class.copy]p13:
11650   //     - if the subobject is of class type, the copy assignment operator for
11651   //       the class is used (as if by explicit qualification; that is,
11652   //       ignoring any possible virtual overriding functions in more derived
11653   //       classes);
11654   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11655     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11656 
11657     // Look for operator=.
11658     DeclarationName Name
11659       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11660     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11661     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11662 
11663     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11664     // operator.
11665     if (!S.getLangOpts().CPlusPlus11) {
11666       LookupResult::Filter F = OpLookup.makeFilter();
11667       while (F.hasNext()) {
11668         NamedDecl *D = F.next();
11669         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11670           if (Method->isCopyAssignmentOperator() ||
11671               (!Copying && Method->isMoveAssignmentOperator()))
11672             continue;
11673 
11674         F.erase();
11675       }
11676       F.done();
11677     }
11678 
11679     // Suppress the protected check (C++ [class.protected]) for each of the
11680     // assignment operators we found. This strange dance is required when
11681     // we're assigning via a base classes's copy-assignment operator. To
11682     // ensure that we're getting the right base class subobject (without
11683     // ambiguities), we need to cast "this" to that subobject type; to
11684     // ensure that we don't go through the virtual call mechanism, we need
11685     // to qualify the operator= name with the base class (see below). However,
11686     // this means that if the base class has a protected copy assignment
11687     // operator, the protected member access check will fail. So, we
11688     // rewrite "protected" access to "public" access in this case, since we
11689     // know by construction that we're calling from a derived class.
11690     if (CopyingBaseSubobject) {
11691       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11692            L != LEnd; ++L) {
11693         if (L.getAccess() == AS_protected)
11694           L.setAccess(AS_public);
11695       }
11696     }
11697 
11698     // Create the nested-name-specifier that will be used to qualify the
11699     // reference to operator=; this is required to suppress the virtual
11700     // call mechanism.
11701     CXXScopeSpec SS;
11702     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11703     SS.MakeTrivial(S.Context,
11704                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11705                                                CanonicalT),
11706                    Loc);
11707 
11708     // Create the reference to operator=.
11709     ExprResult OpEqualRef
11710       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11711                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11712                                    /*FirstQualifierInScope=*/nullptr,
11713                                    OpLookup,
11714                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11715                                    /*SuppressQualifierCheck=*/true);
11716     if (OpEqualRef.isInvalid())
11717       return StmtError();
11718 
11719     // Build the call to the assignment operator.
11720 
11721     Expr *FromInst = From.build(S, Loc);
11722     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11723                                                   OpEqualRef.getAs<Expr>(),
11724                                                   Loc, FromInst, Loc);
11725     if (Call.isInvalid())
11726       return StmtError();
11727 
11728     // If we built a call to a trivial 'operator=' while copying an array,
11729     // bail out. We'll replace the whole shebang with a memcpy.
11730     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11731     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11732       return StmtResult((Stmt*)nullptr);
11733 
11734     // Convert to an expression-statement, and clean up any produced
11735     // temporaries.
11736     return S.ActOnExprStmt(Call);
11737   }
11738 
11739   //     - if the subobject is of scalar type, the built-in assignment
11740   //       operator is used.
11741   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11742   if (!ArrayTy) {
11743     ExprResult Assignment = S.CreateBuiltinBinOp(
11744         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11745     if (Assignment.isInvalid())
11746       return StmtError();
11747     return S.ActOnExprStmt(Assignment);
11748   }
11749 
11750   //     - if the subobject is an array, each element is assigned, in the
11751   //       manner appropriate to the element type;
11752 
11753   // Construct a loop over the array bounds, e.g.,
11754   //
11755   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11756   //
11757   // that will copy each of the array elements.
11758   QualType SizeType = S.Context.getSizeType();
11759 
11760   // Create the iteration variable.
11761   IdentifierInfo *IterationVarName = nullptr;
11762   {
11763     SmallString<8> Str;
11764     llvm::raw_svector_ostream OS(Str);
11765     OS << "__i" << Depth;
11766     IterationVarName = &S.Context.Idents.get(OS.str());
11767   }
11768   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11769                                           IterationVarName, SizeType,
11770                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11771                                           SC_None);
11772 
11773   // Initialize the iteration variable to zero.
11774   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11775   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11776 
11777   // Creates a reference to the iteration variable.
11778   RefBuilder IterationVarRef(IterationVar, SizeType);
11779   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11780 
11781   // Create the DeclStmt that holds the iteration variable.
11782   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11783 
11784   // Subscript the "from" and "to" expressions with the iteration variable.
11785   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11786   MoveCastBuilder FromIndexMove(FromIndexCopy);
11787   const ExprBuilder *FromIndex;
11788   if (Copying)
11789     FromIndex = &FromIndexCopy;
11790   else
11791     FromIndex = &FromIndexMove;
11792 
11793   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11794 
11795   // Build the copy/move for an individual element of the array.
11796   StmtResult Copy =
11797     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11798                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11799                                      Copying, Depth + 1);
11800   // Bail out if copying fails or if we determined that we should use memcpy.
11801   if (Copy.isInvalid() || !Copy.get())
11802     return Copy;
11803 
11804   // Create the comparison against the array bound.
11805   llvm::APInt Upper
11806     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11807   Expr *Comparison
11808     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11809                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11810                                      BO_NE, S.Context.BoolTy,
11811                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11812 
11813   // Create the pre-increment of the iteration variable. We can determine
11814   // whether the increment will overflow based on the value of the array
11815   // bound.
11816   Expr *Increment = new (S.Context)
11817       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11818                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11819 
11820   // Construct the loop that copies all elements of this array.
11821   return S.ActOnForStmt(
11822       Loc, Loc, InitStmt,
11823       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11824       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11825 }
11826 
11827 static StmtResult
11828 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11829                       const ExprBuilder &To, const ExprBuilder &From,
11830                       bool CopyingBaseSubobject, bool Copying) {
11831   // Maybe we should use a memcpy?
11832   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11833       T.isTriviallyCopyableType(S.Context))
11834     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11835 
11836   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11837                                                      CopyingBaseSubobject,
11838                                                      Copying, 0));
11839 
11840   // If we ended up picking a trivial assignment operator for an array of a
11841   // non-trivially-copyable class type, just emit a memcpy.
11842   if (!Result.isInvalid() && !Result.get())
11843     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11844 
11845   return Result;
11846 }
11847 
11848 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11849   // Note: The following rules are largely analoguous to the copy
11850   // constructor rules. Note that virtual bases are not taken into account
11851   // for determining the argument type of the operator. Note also that
11852   // operators taking an object instead of a reference are allowed.
11853   assert(ClassDecl->needsImplicitCopyAssignment());
11854 
11855   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11856   if (DSM.isAlreadyBeingDeclared())
11857     return nullptr;
11858 
11859   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11860   if (Context.getLangOpts().OpenCLCPlusPlus)
11861     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
11862   QualType RetType = Context.getLValueReferenceType(ArgType);
11863   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11864   if (Const)
11865     ArgType = ArgType.withConst();
11866 
11867   ArgType = Context.getLValueReferenceType(ArgType);
11868 
11869   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11870                                                      CXXCopyAssignment,
11871                                                      Const);
11872 
11873   //   An implicitly-declared copy assignment operator is an inline public
11874   //   member of its class.
11875   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11876   SourceLocation ClassLoc = ClassDecl->getLocation();
11877   DeclarationNameInfo NameInfo(Name, ClassLoc);
11878   CXXMethodDecl *CopyAssignment =
11879       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11880                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11881                             /*isInline=*/true, Constexpr, SourceLocation());
11882   CopyAssignment->setAccess(AS_public);
11883   CopyAssignment->setDefaulted();
11884   CopyAssignment->setImplicit();
11885 
11886   if (getLangOpts().CUDA) {
11887     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11888                                             CopyAssignment,
11889                                             /* ConstRHS */ Const,
11890                                             /* Diagnose */ false);
11891   }
11892 
11893   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
11894 
11895   // Add the parameter to the operator.
11896   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11897                                                ClassLoc, ClassLoc,
11898                                                /*Id=*/nullptr, ArgType,
11899                                                /*TInfo=*/nullptr, SC_None,
11900                                                nullptr);
11901   CopyAssignment->setParams(FromParam);
11902 
11903   CopyAssignment->setTrivial(
11904     ClassDecl->needsOverloadResolutionForCopyAssignment()
11905       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11906       : ClassDecl->hasTrivialCopyAssignment());
11907 
11908   // Note that we have added this copy-assignment operator.
11909   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
11910 
11911   Scope *S = getScopeForContext(ClassDecl);
11912   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11913 
11914   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11915     SetDeclDeleted(CopyAssignment, ClassLoc);
11916 
11917   if (S)
11918     PushOnScopeChains(CopyAssignment, S, false);
11919   ClassDecl->addDecl(CopyAssignment);
11920 
11921   return CopyAssignment;
11922 }
11923 
11924 /// Diagnose an implicit copy operation for a class which is odr-used, but
11925 /// which is deprecated because the class has a user-declared copy constructor,
11926 /// copy assignment operator, or destructor.
11927 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11928   assert(CopyOp->isImplicit());
11929 
11930   CXXRecordDecl *RD = CopyOp->getParent();
11931   CXXMethodDecl *UserDeclaredOperation = nullptr;
11932 
11933   // In Microsoft mode, assignment operations don't affect constructors and
11934   // vice versa.
11935   if (RD->hasUserDeclaredDestructor()) {
11936     UserDeclaredOperation = RD->getDestructor();
11937   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11938              RD->hasUserDeclaredCopyConstructor() &&
11939              !S.getLangOpts().MSVCCompat) {
11940     // Find any user-declared copy constructor.
11941     for (auto *I : RD->ctors()) {
11942       if (I->isCopyConstructor()) {
11943         UserDeclaredOperation = I;
11944         break;
11945       }
11946     }
11947     assert(UserDeclaredOperation);
11948   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11949              RD->hasUserDeclaredCopyAssignment() &&
11950              !S.getLangOpts().MSVCCompat) {
11951     // Find any user-declared move assignment operator.
11952     for (auto *I : RD->methods()) {
11953       if (I->isCopyAssignmentOperator()) {
11954         UserDeclaredOperation = I;
11955         break;
11956       }
11957     }
11958     assert(UserDeclaredOperation);
11959   }
11960 
11961   if (UserDeclaredOperation) {
11962     S.Diag(UserDeclaredOperation->getLocation(),
11963          diag::warn_deprecated_copy_operation)
11964       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11965       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11966   }
11967 }
11968 
11969 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11970                                         CXXMethodDecl *CopyAssignOperator) {
11971   assert((CopyAssignOperator->isDefaulted() &&
11972           CopyAssignOperator->isOverloadedOperator() &&
11973           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11974           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11975           !CopyAssignOperator->isDeleted()) &&
11976          "DefineImplicitCopyAssignment called for wrong function");
11977   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11978     return;
11979 
11980   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11981   if (ClassDecl->isInvalidDecl()) {
11982     CopyAssignOperator->setInvalidDecl();
11983     return;
11984   }
11985 
11986   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11987 
11988   // The exception specification is needed because we are defining the
11989   // function.
11990   ResolveExceptionSpec(CurrentLocation,
11991                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11992 
11993   // Add a context note for diagnostics produced after this point.
11994   Scope.addContextNote(CurrentLocation);
11995 
11996   // C++11 [class.copy]p18:
11997   //   The [definition of an implicitly declared copy assignment operator] is
11998   //   deprecated if the class has a user-declared copy constructor or a
11999   //   user-declared destructor.
12000   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
12001     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
12002 
12003   // C++0x [class.copy]p30:
12004   //   The implicitly-defined or explicitly-defaulted copy assignment operator
12005   //   for a non-union class X performs memberwise copy assignment of its
12006   //   subobjects. The direct base classes of X are assigned first, in the
12007   //   order of their declaration in the base-specifier-list, and then the
12008   //   immediate non-static data members of X are assigned, in the order in
12009   //   which they were declared in the class definition.
12010 
12011   // The statements that form the synthesized function body.
12012   SmallVector<Stmt*, 8> Statements;
12013 
12014   // The parameter for the "other" object, which we are copying from.
12015   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
12016   Qualifiers OtherQuals = Other->getType().getQualifiers();
12017   QualType OtherRefType = Other->getType();
12018   if (const LValueReferenceType *OtherRef
12019                                 = OtherRefType->getAs<LValueReferenceType>()) {
12020     OtherRefType = OtherRef->getPointeeType();
12021     OtherQuals = OtherRefType.getQualifiers();
12022   }
12023 
12024   // Our location for everything implicitly-generated.
12025   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
12026                            ? CopyAssignOperator->getEndLoc()
12027                            : CopyAssignOperator->getLocation();
12028 
12029   // Builds a DeclRefExpr for the "other" object.
12030   RefBuilder OtherRef(Other, OtherRefType);
12031 
12032   // Builds the "this" pointer.
12033   ThisBuilder This;
12034 
12035   // Assign base classes.
12036   bool Invalid = false;
12037   for (auto &Base : ClassDecl->bases()) {
12038     // Form the assignment:
12039     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
12040     QualType BaseType = Base.getType().getUnqualifiedType();
12041     if (!BaseType->isRecordType()) {
12042       Invalid = true;
12043       continue;
12044     }
12045 
12046     CXXCastPath BasePath;
12047     BasePath.push_back(&Base);
12048 
12049     // Construct the "from" expression, which is an implicit cast to the
12050     // appropriately-qualified base type.
12051     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
12052                      VK_LValue, BasePath);
12053 
12054     // Dereference "this".
12055     DerefBuilder DerefThis(This);
12056     CastBuilder To(DerefThis,
12057                    Context.getQualifiedType(
12058                        BaseType, CopyAssignOperator->getMethodQualifiers()),
12059                    VK_LValue, BasePath);
12060 
12061     // Build the copy.
12062     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12063                                             To, From,
12064                                             /*CopyingBaseSubobject=*/true,
12065                                             /*Copying=*/true);
12066     if (Copy.isInvalid()) {
12067       CopyAssignOperator->setInvalidDecl();
12068       return;
12069     }
12070 
12071     // Success! Record the copy.
12072     Statements.push_back(Copy.getAs<Expr>());
12073   }
12074 
12075   // Assign non-static members.
12076   for (auto *Field : ClassDecl->fields()) {
12077     // FIXME: We should form some kind of AST representation for the implied
12078     // memcpy in a union copy operation.
12079     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12080       continue;
12081 
12082     if (Field->isInvalidDecl()) {
12083       Invalid = true;
12084       continue;
12085     }
12086 
12087     // Check for members of reference type; we can't copy those.
12088     if (Field->getType()->isReferenceType()) {
12089       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12090         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12091       Diag(Field->getLocation(), diag::note_declared_at);
12092       Invalid = true;
12093       continue;
12094     }
12095 
12096     // Check for members of const-qualified, non-class type.
12097     QualType BaseType = Context.getBaseElementType(Field->getType());
12098     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12099       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12100         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12101       Diag(Field->getLocation(), diag::note_declared_at);
12102       Invalid = true;
12103       continue;
12104     }
12105 
12106     // Suppress assigning zero-width bitfields.
12107     if (Field->isZeroLengthBitField(Context))
12108       continue;
12109 
12110     QualType FieldType = Field->getType().getNonReferenceType();
12111     if (FieldType->isIncompleteArrayType()) {
12112       assert(ClassDecl->hasFlexibleArrayMember() &&
12113              "Incomplete array type is not valid");
12114       continue;
12115     }
12116 
12117     // Build references to the field in the object we're copying from and to.
12118     CXXScopeSpec SS; // Intentionally empty
12119     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12120                               LookupMemberName);
12121     MemberLookup.addDecl(Field);
12122     MemberLookup.resolveKind();
12123 
12124     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12125 
12126     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12127 
12128     // Build the copy of this field.
12129     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12130                                             To, From,
12131                                             /*CopyingBaseSubobject=*/false,
12132                                             /*Copying=*/true);
12133     if (Copy.isInvalid()) {
12134       CopyAssignOperator->setInvalidDecl();
12135       return;
12136     }
12137 
12138     // Success! Record the copy.
12139     Statements.push_back(Copy.getAs<Stmt>());
12140   }
12141 
12142   if (!Invalid) {
12143     // Add a "return *this;"
12144     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12145 
12146     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12147     if (Return.isInvalid())
12148       Invalid = true;
12149     else
12150       Statements.push_back(Return.getAs<Stmt>());
12151   }
12152 
12153   if (Invalid) {
12154     CopyAssignOperator->setInvalidDecl();
12155     return;
12156   }
12157 
12158   StmtResult Body;
12159   {
12160     CompoundScopeRAII CompoundScope(*this);
12161     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12162                              /*isStmtExpr=*/false);
12163     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12164   }
12165   CopyAssignOperator->setBody(Body.getAs<Stmt>());
12166   CopyAssignOperator->markUsed(Context);
12167 
12168   if (ASTMutationListener *L = getASTMutationListener()) {
12169     L->CompletedImplicitDefinition(CopyAssignOperator);
12170   }
12171 }
12172 
12173 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12174   assert(ClassDecl->needsImplicitMoveAssignment());
12175 
12176   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12177   if (DSM.isAlreadyBeingDeclared())
12178     return nullptr;
12179 
12180   // Note: The following rules are largely analoguous to the move
12181   // constructor rules.
12182 
12183   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12184   if (Context.getLangOpts().OpenCLCPlusPlus)
12185     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12186   QualType RetType = Context.getLValueReferenceType(ArgType);
12187   ArgType = Context.getRValueReferenceType(ArgType);
12188 
12189   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12190                                                      CXXMoveAssignment,
12191                                                      false);
12192 
12193   //   An implicitly-declared move assignment operator is an inline public
12194   //   member of its class.
12195   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12196   SourceLocation ClassLoc = ClassDecl->getLocation();
12197   DeclarationNameInfo NameInfo(Name, ClassLoc);
12198   CXXMethodDecl *MoveAssignment =
12199       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12200                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12201                             /*isInline=*/true, Constexpr, SourceLocation());
12202   MoveAssignment->setAccess(AS_public);
12203   MoveAssignment->setDefaulted();
12204   MoveAssignment->setImplicit();
12205 
12206   if (getLangOpts().CUDA) {
12207     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12208                                             MoveAssignment,
12209                                             /* ConstRHS */ false,
12210                                             /* Diagnose */ false);
12211   }
12212 
12213   // Build an exception specification pointing back at this member.
12214   FunctionProtoType::ExtProtoInfo EPI =
12215       getImplicitMethodEPI(*this, MoveAssignment);
12216   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12217 
12218   // Add the parameter to the operator.
12219   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12220                                                ClassLoc, ClassLoc,
12221                                                /*Id=*/nullptr, ArgType,
12222                                                /*TInfo=*/nullptr, SC_None,
12223                                                nullptr);
12224   MoveAssignment->setParams(FromParam);
12225 
12226   MoveAssignment->setTrivial(
12227     ClassDecl->needsOverloadResolutionForMoveAssignment()
12228       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12229       : ClassDecl->hasTrivialMoveAssignment());
12230 
12231   // Note that we have added this copy-assignment operator.
12232   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
12233 
12234   Scope *S = getScopeForContext(ClassDecl);
12235   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12236 
12237   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12238     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12239     SetDeclDeleted(MoveAssignment, ClassLoc);
12240   }
12241 
12242   if (S)
12243     PushOnScopeChains(MoveAssignment, S, false);
12244   ClassDecl->addDecl(MoveAssignment);
12245 
12246   return MoveAssignment;
12247 }
12248 
12249 /// Check if we're implicitly defining a move assignment operator for a class
12250 /// with virtual bases. Such a move assignment might move-assign the virtual
12251 /// base multiple times.
12252 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12253                                                SourceLocation CurrentLocation) {
12254   assert(!Class->isDependentContext() && "should not define dependent move");
12255 
12256   // Only a virtual base could get implicitly move-assigned multiple times.
12257   // Only a non-trivial move assignment can observe this. We only want to
12258   // diagnose if we implicitly define an assignment operator that assigns
12259   // two base classes, both of which move-assign the same virtual base.
12260   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12261       Class->getNumBases() < 2)
12262     return;
12263 
12264   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12265   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12266   VBaseMap VBases;
12267 
12268   for (auto &BI : Class->bases()) {
12269     Worklist.push_back(&BI);
12270     while (!Worklist.empty()) {
12271       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12272       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12273 
12274       // If the base has no non-trivial move assignment operators,
12275       // we don't care about moves from it.
12276       if (!Base->hasNonTrivialMoveAssignment())
12277         continue;
12278 
12279       // If there's nothing virtual here, skip it.
12280       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12281         continue;
12282 
12283       // If we're not actually going to call a move assignment for this base,
12284       // or the selected move assignment is trivial, skip it.
12285       Sema::SpecialMemberOverloadResult SMOR =
12286         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12287                               /*ConstArg*/false, /*VolatileArg*/false,
12288                               /*RValueThis*/true, /*ConstThis*/false,
12289                               /*VolatileThis*/false);
12290       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12291           !SMOR.getMethod()->isMoveAssignmentOperator())
12292         continue;
12293 
12294       if (BaseSpec->isVirtual()) {
12295         // We're going to move-assign this virtual base, and its move
12296         // assignment operator is not trivial. If this can happen for
12297         // multiple distinct direct bases of Class, diagnose it. (If it
12298         // only happens in one base, we'll diagnose it when synthesizing
12299         // that base class's move assignment operator.)
12300         CXXBaseSpecifier *&Existing =
12301             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12302                 .first->second;
12303         if (Existing && Existing != &BI) {
12304           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12305             << Class << Base;
12306           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12307               << (Base->getCanonicalDecl() ==
12308                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12309               << Base << Existing->getType() << Existing->getSourceRange();
12310           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12311               << (Base->getCanonicalDecl() ==
12312                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12313               << Base << BI.getType() << BaseSpec->getSourceRange();
12314 
12315           // Only diagnose each vbase once.
12316           Existing = nullptr;
12317         }
12318       } else {
12319         // Only walk over bases that have defaulted move assignment operators.
12320         // We assume that any user-provided move assignment operator handles
12321         // the multiple-moves-of-vbase case itself somehow.
12322         if (!SMOR.getMethod()->isDefaulted())
12323           continue;
12324 
12325         // We're going to move the base classes of Base. Add them to the list.
12326         for (auto &BI : Base->bases())
12327           Worklist.push_back(&BI);
12328       }
12329     }
12330   }
12331 }
12332 
12333 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12334                                         CXXMethodDecl *MoveAssignOperator) {
12335   assert((MoveAssignOperator->isDefaulted() &&
12336           MoveAssignOperator->isOverloadedOperator() &&
12337           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12338           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12339           !MoveAssignOperator->isDeleted()) &&
12340          "DefineImplicitMoveAssignment called for wrong function");
12341   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12342     return;
12343 
12344   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12345   if (ClassDecl->isInvalidDecl()) {
12346     MoveAssignOperator->setInvalidDecl();
12347     return;
12348   }
12349 
12350   // C++0x [class.copy]p28:
12351   //   The implicitly-defined or move assignment operator for a non-union class
12352   //   X performs memberwise move assignment of its subobjects. The direct base
12353   //   classes of X are assigned first, in the order of their declaration in the
12354   //   base-specifier-list, and then the immediate non-static data members of X
12355   //   are assigned, in the order in which they were declared in the class
12356   //   definition.
12357 
12358   // Issue a warning if our implicit move assignment operator will move
12359   // from a virtual base more than once.
12360   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12361 
12362   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12363 
12364   // The exception specification is needed because we are defining the
12365   // function.
12366   ResolveExceptionSpec(CurrentLocation,
12367                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12368 
12369   // Add a context note for diagnostics produced after this point.
12370   Scope.addContextNote(CurrentLocation);
12371 
12372   // The statements that form the synthesized function body.
12373   SmallVector<Stmt*, 8> Statements;
12374 
12375   // The parameter for the "other" object, which we are move from.
12376   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12377   QualType OtherRefType = Other->getType()->
12378       getAs<RValueReferenceType>()->getPointeeType();
12379 
12380   // Our location for everything implicitly-generated.
12381   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12382                            ? MoveAssignOperator->getEndLoc()
12383                            : MoveAssignOperator->getLocation();
12384 
12385   // Builds a reference to the "other" object.
12386   RefBuilder OtherRef(Other, OtherRefType);
12387   // Cast to rvalue.
12388   MoveCastBuilder MoveOther(OtherRef);
12389 
12390   // Builds the "this" pointer.
12391   ThisBuilder This;
12392 
12393   // Assign base classes.
12394   bool Invalid = false;
12395   for (auto &Base : ClassDecl->bases()) {
12396     // C++11 [class.copy]p28:
12397     //   It is unspecified whether subobjects representing virtual base classes
12398     //   are assigned more than once by the implicitly-defined copy assignment
12399     //   operator.
12400     // FIXME: Do not assign to a vbase that will be assigned by some other base
12401     // class. For a move-assignment, this can result in the vbase being moved
12402     // multiple times.
12403 
12404     // Form the assignment:
12405     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12406     QualType BaseType = Base.getType().getUnqualifiedType();
12407     if (!BaseType->isRecordType()) {
12408       Invalid = true;
12409       continue;
12410     }
12411 
12412     CXXCastPath BasePath;
12413     BasePath.push_back(&Base);
12414 
12415     // Construct the "from" expression, which is an implicit cast to the
12416     // appropriately-qualified base type.
12417     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12418 
12419     // Dereference "this".
12420     DerefBuilder DerefThis(This);
12421 
12422     // Implicitly cast "this" to the appropriately-qualified base type.
12423     CastBuilder To(DerefThis,
12424                    Context.getQualifiedType(
12425                        BaseType, MoveAssignOperator->getMethodQualifiers()),
12426                    VK_LValue, BasePath);
12427 
12428     // Build the move.
12429     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12430                                             To, From,
12431                                             /*CopyingBaseSubobject=*/true,
12432                                             /*Copying=*/false);
12433     if (Move.isInvalid()) {
12434       MoveAssignOperator->setInvalidDecl();
12435       return;
12436     }
12437 
12438     // Success! Record the move.
12439     Statements.push_back(Move.getAs<Expr>());
12440   }
12441 
12442   // Assign non-static members.
12443   for (auto *Field : ClassDecl->fields()) {
12444     // FIXME: We should form some kind of AST representation for the implied
12445     // memcpy in a union copy operation.
12446     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12447       continue;
12448 
12449     if (Field->isInvalidDecl()) {
12450       Invalid = true;
12451       continue;
12452     }
12453 
12454     // Check for members of reference type; we can't move those.
12455     if (Field->getType()->isReferenceType()) {
12456       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12457         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12458       Diag(Field->getLocation(), diag::note_declared_at);
12459       Invalid = true;
12460       continue;
12461     }
12462 
12463     // Check for members of const-qualified, non-class type.
12464     QualType BaseType = Context.getBaseElementType(Field->getType());
12465     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12466       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12467         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12468       Diag(Field->getLocation(), diag::note_declared_at);
12469       Invalid = true;
12470       continue;
12471     }
12472 
12473     // Suppress assigning zero-width bitfields.
12474     if (Field->isZeroLengthBitField(Context))
12475       continue;
12476 
12477     QualType FieldType = Field->getType().getNonReferenceType();
12478     if (FieldType->isIncompleteArrayType()) {
12479       assert(ClassDecl->hasFlexibleArrayMember() &&
12480              "Incomplete array type is not valid");
12481       continue;
12482     }
12483 
12484     // Build references to the field in the object we're copying from and to.
12485     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12486                               LookupMemberName);
12487     MemberLookup.addDecl(Field);
12488     MemberLookup.resolveKind();
12489     MemberBuilder From(MoveOther, OtherRefType,
12490                        /*IsArrow=*/false, MemberLookup);
12491     MemberBuilder To(This, getCurrentThisType(),
12492                      /*IsArrow=*/true, MemberLookup);
12493 
12494     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12495         "Member reference with rvalue base must be rvalue except for reference "
12496         "members, which aren't allowed for move assignment.");
12497 
12498     // Build the move of this field.
12499     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12500                                             To, From,
12501                                             /*CopyingBaseSubobject=*/false,
12502                                             /*Copying=*/false);
12503     if (Move.isInvalid()) {
12504       MoveAssignOperator->setInvalidDecl();
12505       return;
12506     }
12507 
12508     // Success! Record the copy.
12509     Statements.push_back(Move.getAs<Stmt>());
12510   }
12511 
12512   if (!Invalid) {
12513     // Add a "return *this;"
12514     ExprResult ThisObj =
12515         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12516 
12517     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12518     if (Return.isInvalid())
12519       Invalid = true;
12520     else
12521       Statements.push_back(Return.getAs<Stmt>());
12522   }
12523 
12524   if (Invalid) {
12525     MoveAssignOperator->setInvalidDecl();
12526     return;
12527   }
12528 
12529   StmtResult Body;
12530   {
12531     CompoundScopeRAII CompoundScope(*this);
12532     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12533                              /*isStmtExpr=*/false);
12534     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12535   }
12536   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12537   MoveAssignOperator->markUsed(Context);
12538 
12539   if (ASTMutationListener *L = getASTMutationListener()) {
12540     L->CompletedImplicitDefinition(MoveAssignOperator);
12541   }
12542 }
12543 
12544 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12545                                                     CXXRecordDecl *ClassDecl) {
12546   // C++ [class.copy]p4:
12547   //   If the class definition does not explicitly declare a copy
12548   //   constructor, one is declared implicitly.
12549   assert(ClassDecl->needsImplicitCopyConstructor());
12550 
12551   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12552   if (DSM.isAlreadyBeingDeclared())
12553     return nullptr;
12554 
12555   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12556   QualType ArgType = ClassType;
12557   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12558   if (Const)
12559     ArgType = ArgType.withConst();
12560 
12561   if (Context.getLangOpts().OpenCLCPlusPlus)
12562     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12563 
12564   ArgType = Context.getLValueReferenceType(ArgType);
12565 
12566   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12567                                                      CXXCopyConstructor,
12568                                                      Const);
12569 
12570   DeclarationName Name
12571     = Context.DeclarationNames.getCXXConstructorName(
12572                                            Context.getCanonicalType(ClassType));
12573   SourceLocation ClassLoc = ClassDecl->getLocation();
12574   DeclarationNameInfo NameInfo(Name, ClassLoc);
12575 
12576   //   An implicitly-declared copy constructor is an inline public
12577   //   member of its class.
12578   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12579       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12580       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12581       Constexpr);
12582   CopyConstructor->setAccess(AS_public);
12583   CopyConstructor->setDefaulted();
12584 
12585   if (getLangOpts().CUDA) {
12586     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12587                                             CopyConstructor,
12588                                             /* ConstRHS */ Const,
12589                                             /* Diagnose */ false);
12590   }
12591 
12592   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
12593 
12594   // Add the parameter to the constructor.
12595   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12596                                                ClassLoc, ClassLoc,
12597                                                /*IdentifierInfo=*/nullptr,
12598                                                ArgType, /*TInfo=*/nullptr,
12599                                                SC_None, nullptr);
12600   CopyConstructor->setParams(FromParam);
12601 
12602   CopyConstructor->setTrivial(
12603       ClassDecl->needsOverloadResolutionForCopyConstructor()
12604           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12605           : ClassDecl->hasTrivialCopyConstructor());
12606 
12607   CopyConstructor->setTrivialForCall(
12608       ClassDecl->hasAttr<TrivialABIAttr>() ||
12609       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12610            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12611              TAH_ConsiderTrivialABI)
12612            : ClassDecl->hasTrivialCopyConstructorForCall()));
12613 
12614   // Note that we have declared this constructor.
12615   ++getASTContext().NumImplicitCopyConstructorsDeclared;
12616 
12617   Scope *S = getScopeForContext(ClassDecl);
12618   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12619 
12620   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12621     ClassDecl->setImplicitCopyConstructorIsDeleted();
12622     SetDeclDeleted(CopyConstructor, ClassLoc);
12623   }
12624 
12625   if (S)
12626     PushOnScopeChains(CopyConstructor, S, false);
12627   ClassDecl->addDecl(CopyConstructor);
12628 
12629   return CopyConstructor;
12630 }
12631 
12632 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12633                                          CXXConstructorDecl *CopyConstructor) {
12634   assert((CopyConstructor->isDefaulted() &&
12635           CopyConstructor->isCopyConstructor() &&
12636           !CopyConstructor->doesThisDeclarationHaveABody() &&
12637           !CopyConstructor->isDeleted()) &&
12638          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12639   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12640     return;
12641 
12642   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12643   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12644 
12645   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12646 
12647   // The exception specification is needed because we are defining the
12648   // function.
12649   ResolveExceptionSpec(CurrentLocation,
12650                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12651   MarkVTableUsed(CurrentLocation, ClassDecl);
12652 
12653   // Add a context note for diagnostics produced after this point.
12654   Scope.addContextNote(CurrentLocation);
12655 
12656   // C++11 [class.copy]p7:
12657   //   The [definition of an implicitly declared copy constructor] is
12658   //   deprecated if the class has a user-declared copy assignment operator
12659   //   or a user-declared destructor.
12660   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12661     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12662 
12663   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12664     CopyConstructor->setInvalidDecl();
12665   }  else {
12666     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12667                              ? CopyConstructor->getEndLoc()
12668                              : CopyConstructor->getLocation();
12669     Sema::CompoundScopeRAII CompoundScope(*this);
12670     CopyConstructor->setBody(
12671         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12672     CopyConstructor->markUsed(Context);
12673   }
12674 
12675   if (ASTMutationListener *L = getASTMutationListener()) {
12676     L->CompletedImplicitDefinition(CopyConstructor);
12677   }
12678 }
12679 
12680 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12681                                                     CXXRecordDecl *ClassDecl) {
12682   assert(ClassDecl->needsImplicitMoveConstructor());
12683 
12684   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12685   if (DSM.isAlreadyBeingDeclared())
12686     return nullptr;
12687 
12688   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12689 
12690   QualType ArgType = ClassType;
12691   if (Context.getLangOpts().OpenCLCPlusPlus)
12692     ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
12693   ArgType = Context.getRValueReferenceType(ArgType);
12694 
12695   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12696                                                      CXXMoveConstructor,
12697                                                      false);
12698 
12699   DeclarationName Name
12700     = Context.DeclarationNames.getCXXConstructorName(
12701                                            Context.getCanonicalType(ClassType));
12702   SourceLocation ClassLoc = ClassDecl->getLocation();
12703   DeclarationNameInfo NameInfo(Name, ClassLoc);
12704 
12705   // C++11 [class.copy]p11:
12706   //   An implicitly-declared copy/move constructor is an inline public
12707   //   member of its class.
12708   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12709       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12710       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12711       Constexpr);
12712   MoveConstructor->setAccess(AS_public);
12713   MoveConstructor->setDefaulted();
12714 
12715   if (getLangOpts().CUDA) {
12716     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12717                                             MoveConstructor,
12718                                             /* ConstRHS */ false,
12719                                             /* Diagnose */ false);
12720   }
12721 
12722   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
12723 
12724   // Add the parameter to the constructor.
12725   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12726                                                ClassLoc, ClassLoc,
12727                                                /*IdentifierInfo=*/nullptr,
12728                                                ArgType, /*TInfo=*/nullptr,
12729                                                SC_None, nullptr);
12730   MoveConstructor->setParams(FromParam);
12731 
12732   MoveConstructor->setTrivial(
12733       ClassDecl->needsOverloadResolutionForMoveConstructor()
12734           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12735           : ClassDecl->hasTrivialMoveConstructor());
12736 
12737   MoveConstructor->setTrivialForCall(
12738       ClassDecl->hasAttr<TrivialABIAttr>() ||
12739       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12740            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12741                                     TAH_ConsiderTrivialABI)
12742            : ClassDecl->hasTrivialMoveConstructorForCall()));
12743 
12744   // Note that we have declared this constructor.
12745   ++getASTContext().NumImplicitMoveConstructorsDeclared;
12746 
12747   Scope *S = getScopeForContext(ClassDecl);
12748   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12749 
12750   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12751     ClassDecl->setImplicitMoveConstructorIsDeleted();
12752     SetDeclDeleted(MoveConstructor, ClassLoc);
12753   }
12754 
12755   if (S)
12756     PushOnScopeChains(MoveConstructor, S, false);
12757   ClassDecl->addDecl(MoveConstructor);
12758 
12759   return MoveConstructor;
12760 }
12761 
12762 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12763                                          CXXConstructorDecl *MoveConstructor) {
12764   assert((MoveConstructor->isDefaulted() &&
12765           MoveConstructor->isMoveConstructor() &&
12766           !MoveConstructor->doesThisDeclarationHaveABody() &&
12767           !MoveConstructor->isDeleted()) &&
12768          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12769   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12770     return;
12771 
12772   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12773   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12774 
12775   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12776 
12777   // The exception specification is needed because we are defining the
12778   // function.
12779   ResolveExceptionSpec(CurrentLocation,
12780                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12781   MarkVTableUsed(CurrentLocation, ClassDecl);
12782 
12783   // Add a context note for diagnostics produced after this point.
12784   Scope.addContextNote(CurrentLocation);
12785 
12786   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12787     MoveConstructor->setInvalidDecl();
12788   } else {
12789     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12790                              ? MoveConstructor->getEndLoc()
12791                              : MoveConstructor->getLocation();
12792     Sema::CompoundScopeRAII CompoundScope(*this);
12793     MoveConstructor->setBody(ActOnCompoundStmt(
12794         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12795     MoveConstructor->markUsed(Context);
12796   }
12797 
12798   if (ASTMutationListener *L = getASTMutationListener()) {
12799     L->CompletedImplicitDefinition(MoveConstructor);
12800   }
12801 }
12802 
12803 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12804   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12805 }
12806 
12807 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12808                             SourceLocation CurrentLocation,
12809                             CXXConversionDecl *Conv) {
12810   SynthesizedFunctionScope Scope(*this, Conv);
12811   assert(!Conv->getReturnType()->isUndeducedType());
12812 
12813   CXXRecordDecl *Lambda = Conv->getParent();
12814   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12815   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12816 
12817   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12818     CallOp = InstantiateFunctionDeclaration(
12819         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12820     if (!CallOp)
12821       return;
12822 
12823     Invoker = InstantiateFunctionDeclaration(
12824         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12825     if (!Invoker)
12826       return;
12827   }
12828 
12829   if (CallOp->isInvalidDecl())
12830     return;
12831 
12832   // Mark the call operator referenced (and add to pending instantiations
12833   // if necessary).
12834   // For both the conversion and static-invoker template specializations
12835   // we construct their body's in this function, so no need to add them
12836   // to the PendingInstantiations.
12837   MarkFunctionReferenced(CurrentLocation, CallOp);
12838 
12839   // Fill in the __invoke function with a dummy implementation. IR generation
12840   // will fill in the actual details. Update its type in case it contained
12841   // an 'auto'.
12842   Invoker->markUsed(Context);
12843   Invoker->setReferenced();
12844   Invoker->setType(Conv->getReturnType()->getPointeeType());
12845   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12846 
12847   // Construct the body of the conversion function { return __invoke; }.
12848   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12849                                        VK_LValue, Conv->getLocation()).get();
12850   assert(FunctionRef && "Can't refer to __invoke function?");
12851   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12852   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12853                                      Conv->getLocation()));
12854   Conv->markUsed(Context);
12855   Conv->setReferenced();
12856 
12857   if (ASTMutationListener *L = getASTMutationListener()) {
12858     L->CompletedImplicitDefinition(Conv);
12859     L->CompletedImplicitDefinition(Invoker);
12860   }
12861 }
12862 
12863 
12864 
12865 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12866        SourceLocation CurrentLocation,
12867        CXXConversionDecl *Conv)
12868 {
12869   assert(!Conv->getParent()->isGenericLambda());
12870 
12871   SynthesizedFunctionScope Scope(*this, Conv);
12872 
12873   // Copy-initialize the lambda object as needed to capture it.
12874   Expr *This = ActOnCXXThis(CurrentLocation).get();
12875   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12876 
12877   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12878                                                         Conv->getLocation(),
12879                                                         Conv, DerefThis);
12880 
12881   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12882   // behavior.  Note that only the general conversion function does this
12883   // (since it's unusable otherwise); in the case where we inline the
12884   // block literal, it has block literal lifetime semantics.
12885   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12886     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12887                                           CK_CopyAndAutoreleaseBlockObject,
12888                                           BuildBlock.get(), nullptr, VK_RValue);
12889 
12890   if (BuildBlock.isInvalid()) {
12891     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12892     Conv->setInvalidDecl();
12893     return;
12894   }
12895 
12896   // Create the return statement that returns the block from the conversion
12897   // function.
12898   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12899   if (Return.isInvalid()) {
12900     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12901     Conv->setInvalidDecl();
12902     return;
12903   }
12904 
12905   // Set the body of the conversion function.
12906   Stmt *ReturnS = Return.get();
12907   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12908                                      Conv->getLocation()));
12909   Conv->markUsed(Context);
12910 
12911   // We're done; notify the mutation listener, if any.
12912   if (ASTMutationListener *L = getASTMutationListener()) {
12913     L->CompletedImplicitDefinition(Conv);
12914   }
12915 }
12916 
12917 /// Determine whether the given list arguments contains exactly one
12918 /// "real" (non-default) argument.
12919 static bool hasOneRealArgument(MultiExprArg Args) {
12920   switch (Args.size()) {
12921   case 0:
12922     return false;
12923 
12924   default:
12925     if (!Args[1]->isDefaultArgument())
12926       return false;
12927 
12928     LLVM_FALLTHROUGH;
12929   case 1:
12930     return !Args[0]->isDefaultArgument();
12931   }
12932 
12933   return false;
12934 }
12935 
12936 ExprResult
12937 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12938                             NamedDecl *FoundDecl,
12939                             CXXConstructorDecl *Constructor,
12940                             MultiExprArg ExprArgs,
12941                             bool HadMultipleCandidates,
12942                             bool IsListInitialization,
12943                             bool IsStdInitListInitialization,
12944                             bool RequiresZeroInit,
12945                             unsigned ConstructKind,
12946                             SourceRange ParenRange) {
12947   bool Elidable = false;
12948 
12949   // C++0x [class.copy]p34:
12950   //   When certain criteria are met, an implementation is allowed to
12951   //   omit the copy/move construction of a class object, even if the
12952   //   copy/move constructor and/or destructor for the object have
12953   //   side effects. [...]
12954   //     - when a temporary class object that has not been bound to a
12955   //       reference (12.2) would be copied/moved to a class object
12956   //       with the same cv-unqualified type, the copy/move operation
12957   //       can be omitted by constructing the temporary object
12958   //       directly into the target of the omitted copy/move
12959   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12960       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12961     Expr *SubExpr = ExprArgs[0];
12962     Elidable = SubExpr->isTemporaryObject(
12963         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12964   }
12965 
12966   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12967                                FoundDecl, Constructor,
12968                                Elidable, ExprArgs, HadMultipleCandidates,
12969                                IsListInitialization,
12970                                IsStdInitListInitialization, RequiresZeroInit,
12971                                ConstructKind, ParenRange);
12972 }
12973 
12974 ExprResult
12975 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12976                             NamedDecl *FoundDecl,
12977                             CXXConstructorDecl *Constructor,
12978                             bool Elidable,
12979                             MultiExprArg ExprArgs,
12980                             bool HadMultipleCandidates,
12981                             bool IsListInitialization,
12982                             bool IsStdInitListInitialization,
12983                             bool RequiresZeroInit,
12984                             unsigned ConstructKind,
12985                             SourceRange ParenRange) {
12986   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12987     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12988     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12989       return ExprError();
12990   }
12991 
12992   return BuildCXXConstructExpr(
12993       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12994       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12995       RequiresZeroInit, ConstructKind, ParenRange);
12996 }
12997 
12998 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12999 /// including handling of its default argument expressions.
13000 ExprResult
13001 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13002                             CXXConstructorDecl *Constructor,
13003                             bool Elidable,
13004                             MultiExprArg ExprArgs,
13005                             bool HadMultipleCandidates,
13006                             bool IsListInitialization,
13007                             bool IsStdInitListInitialization,
13008                             bool RequiresZeroInit,
13009                             unsigned ConstructKind,
13010                             SourceRange ParenRange) {
13011   assert(declaresSameEntity(
13012              Constructor->getParent(),
13013              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
13014          "given constructor for wrong type");
13015   MarkFunctionReferenced(ConstructLoc, Constructor);
13016   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
13017     return ExprError();
13018 
13019   return CXXConstructExpr::Create(
13020       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
13021       ExprArgs, HadMultipleCandidates, IsListInitialization,
13022       IsStdInitListInitialization, RequiresZeroInit,
13023       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
13024       ParenRange);
13025 }
13026 
13027 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
13028   assert(Field->hasInClassInitializer());
13029 
13030   // If we already have the in-class initializer nothing needs to be done.
13031   if (Field->getInClassInitializer())
13032     return CXXDefaultInitExpr::Create(Context, Loc, Field);
13033 
13034   // If we might have already tried and failed to instantiate, don't try again.
13035   if (Field->isInvalidDecl())
13036     return ExprError();
13037 
13038   // Maybe we haven't instantiated the in-class initializer. Go check the
13039   // pattern FieldDecl to see if it has one.
13040   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
13041 
13042   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
13043     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
13044     DeclContext::lookup_result Lookup =
13045         ClassPattern->lookup(Field->getDeclName());
13046 
13047     // Lookup can return at most two results: the pattern for the field, or the
13048     // injected class name of the parent record. No other member can have the
13049     // same name as the field.
13050     // In modules mode, lookup can return multiple results (coming from
13051     // different modules).
13052     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
13053            "more than two lookup results for field name");
13054     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
13055     if (!Pattern) {
13056       assert(isa<CXXRecordDecl>(Lookup[0]) &&
13057              "cannot have other non-field member with same name");
13058       for (auto L : Lookup)
13059         if (isa<FieldDecl>(L)) {
13060           Pattern = cast<FieldDecl>(L);
13061           break;
13062         }
13063       assert(Pattern && "We must have set the Pattern!");
13064     }
13065 
13066     if (!Pattern->hasInClassInitializer() ||
13067         InstantiateInClassInitializer(Loc, Field, Pattern,
13068                                       getTemplateInstantiationArgs(Field))) {
13069       // Don't diagnose this again.
13070       Field->setInvalidDecl();
13071       return ExprError();
13072     }
13073     return CXXDefaultInitExpr::Create(Context, Loc, Field);
13074   }
13075 
13076   // DR1351:
13077   //   If the brace-or-equal-initializer of a non-static data member
13078   //   invokes a defaulted default constructor of its class or of an
13079   //   enclosing class in a potentially evaluated subexpression, the
13080   //   program is ill-formed.
13081   //
13082   // This resolution is unworkable: the exception specification of the
13083   // default constructor can be needed in an unevaluated context, in
13084   // particular, in the operand of a noexcept-expression, and we can be
13085   // unable to compute an exception specification for an enclosed class.
13086   //
13087   // Any attempt to resolve the exception specification of a defaulted default
13088   // constructor before the initializer is lexically complete will ultimately
13089   // come here at which point we can diagnose it.
13090   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13091   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13092       << OutermostClass << Field;
13093   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13094   // Recover by marking the field invalid, unless we're in a SFINAE context.
13095   if (!isSFINAEContext())
13096     Field->setInvalidDecl();
13097   return ExprError();
13098 }
13099 
13100 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13101   if (VD->isInvalidDecl()) return;
13102 
13103   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13104   if (ClassDecl->isInvalidDecl()) return;
13105   if (ClassDecl->hasIrrelevantDestructor()) return;
13106   if (ClassDecl->isDependentContext()) return;
13107 
13108   if (VD->isNoDestroy(getASTContext()))
13109     return;
13110 
13111   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13112   MarkFunctionReferenced(VD->getLocation(), Destructor);
13113   CheckDestructorAccess(VD->getLocation(), Destructor,
13114                         PDiag(diag::err_access_dtor_var)
13115                         << VD->getDeclName()
13116                         << VD->getType());
13117   DiagnoseUseOfDecl(Destructor, VD->getLocation());
13118 
13119   if (Destructor->isTrivial()) return;
13120   if (!VD->hasGlobalStorage()) return;
13121 
13122   // Emit warning for non-trivial dtor in global scope (a real global,
13123   // class-static, function-static).
13124   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13125 
13126   // TODO: this should be re-enabled for static locals by !CXAAtExit
13127   if (!VD->isStaticLocal())
13128     Diag(VD->getLocation(), diag::warn_global_destructor);
13129 }
13130 
13131 /// Given a constructor and the set of arguments provided for the
13132 /// constructor, convert the arguments and add any required default arguments
13133 /// to form a proper call to this constructor.
13134 ///
13135 /// \returns true if an error occurred, false otherwise.
13136 bool
13137 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13138                               MultiExprArg ArgsPtr,
13139                               SourceLocation Loc,
13140                               SmallVectorImpl<Expr*> &ConvertedArgs,
13141                               bool AllowExplicit,
13142                               bool IsListInitialization) {
13143   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13144   unsigned NumArgs = ArgsPtr.size();
13145   Expr **Args = ArgsPtr.data();
13146 
13147   const FunctionProtoType *Proto
13148     = Constructor->getType()->getAs<FunctionProtoType>();
13149   assert(Proto && "Constructor without a prototype?");
13150   unsigned NumParams = Proto->getNumParams();
13151 
13152   // If too few arguments are available, we'll fill in the rest with defaults.
13153   if (NumArgs < NumParams)
13154     ConvertedArgs.reserve(NumParams);
13155   else
13156     ConvertedArgs.reserve(NumArgs);
13157 
13158   VariadicCallType CallType =
13159     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13160   SmallVector<Expr *, 8> AllArgs;
13161   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13162                                         Proto, 0,
13163                                         llvm::makeArrayRef(Args, NumArgs),
13164                                         AllArgs,
13165                                         CallType, AllowExplicit,
13166                                         IsListInitialization);
13167   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13168 
13169   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13170 
13171   CheckConstructorCall(Constructor,
13172                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13173                        Proto, Loc);
13174 
13175   return Invalid;
13176 }
13177 
13178 static inline bool
13179 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13180                                        const FunctionDecl *FnDecl) {
13181   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13182   if (isa<NamespaceDecl>(DC)) {
13183     return SemaRef.Diag(FnDecl->getLocation(),
13184                         diag::err_operator_new_delete_declared_in_namespace)
13185       << FnDecl->getDeclName();
13186   }
13187 
13188   if (isa<TranslationUnitDecl>(DC) &&
13189       FnDecl->getStorageClass() == SC_Static) {
13190     return SemaRef.Diag(FnDecl->getLocation(),
13191                         diag::err_operator_new_delete_declared_static)
13192       << FnDecl->getDeclName();
13193   }
13194 
13195   return false;
13196 }
13197 
13198 static QualType
13199 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13200   QualType QTy = PtrTy->getPointeeType();
13201   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13202   return SemaRef.Context.getPointerType(QTy);
13203 }
13204 
13205 static inline bool
13206 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13207                             CanQualType ExpectedResultType,
13208                             CanQualType ExpectedFirstParamType,
13209                             unsigned DependentParamTypeDiag,
13210                             unsigned InvalidParamTypeDiag) {
13211   QualType ResultType =
13212       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13213 
13214   // Check that the result type is not dependent.
13215   if (ResultType->isDependentType())
13216     return SemaRef.Diag(FnDecl->getLocation(),
13217                         diag::err_operator_new_delete_dependent_result_type)
13218     << FnDecl->getDeclName() << ExpectedResultType;
13219 
13220   // OpenCL C++: the operator is valid on any address space.
13221   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13222     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13223       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13224     }
13225   }
13226 
13227   // Check that the result type is what we expect.
13228   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13229     return SemaRef.Diag(FnDecl->getLocation(),
13230                         diag::err_operator_new_delete_invalid_result_type)
13231     << FnDecl->getDeclName() << ExpectedResultType;
13232 
13233   // A function template must have at least 2 parameters.
13234   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13235     return SemaRef.Diag(FnDecl->getLocation(),
13236                       diag::err_operator_new_delete_template_too_few_parameters)
13237         << FnDecl->getDeclName();
13238 
13239   // The function decl must have at least 1 parameter.
13240   if (FnDecl->getNumParams() == 0)
13241     return SemaRef.Diag(FnDecl->getLocation(),
13242                         diag::err_operator_new_delete_too_few_parameters)
13243       << FnDecl->getDeclName();
13244 
13245   // Check the first parameter type is not dependent.
13246   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13247   if (FirstParamType->isDependentType())
13248     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13249       << FnDecl->getDeclName() << ExpectedFirstParamType;
13250 
13251   // Check that the first parameter type is what we expect.
13252   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13253     // OpenCL C++: the operator is valid on any address space.
13254     if (auto *PtrTy =
13255             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13256       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13257     }
13258   }
13259   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13260       ExpectedFirstParamType)
13261     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13262     << FnDecl->getDeclName() << ExpectedFirstParamType;
13263 
13264   return false;
13265 }
13266 
13267 static bool
13268 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13269   // C++ [basic.stc.dynamic.allocation]p1:
13270   //   A program is ill-formed if an allocation function is declared in a
13271   //   namespace scope other than global scope or declared static in global
13272   //   scope.
13273   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13274     return true;
13275 
13276   CanQualType SizeTy =
13277     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13278 
13279   // C++ [basic.stc.dynamic.allocation]p1:
13280   //  The return type shall be void*. The first parameter shall have type
13281   //  std::size_t.
13282   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13283                                   SizeTy,
13284                                   diag::err_operator_new_dependent_param_type,
13285                                   diag::err_operator_new_param_type))
13286     return true;
13287 
13288   // C++ [basic.stc.dynamic.allocation]p1:
13289   //  The first parameter shall not have an associated default argument.
13290   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13291     return SemaRef.Diag(FnDecl->getLocation(),
13292                         diag::err_operator_new_default_arg)
13293       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13294 
13295   return false;
13296 }
13297 
13298 static bool
13299 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13300   // C++ [basic.stc.dynamic.deallocation]p1:
13301   //   A program is ill-formed if deallocation functions are declared in a
13302   //   namespace scope other than global scope or declared static in global
13303   //   scope.
13304   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13305     return true;
13306 
13307   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13308 
13309   // C++ P0722:
13310   //   Within a class C, the first parameter of a destroying operator delete
13311   //   shall be of type C *. The first parameter of any other deallocation
13312   //   function shall be of type void *.
13313   CanQualType ExpectedFirstParamType =
13314       MD && MD->isDestroyingOperatorDelete()
13315           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13316                 SemaRef.Context.getRecordType(MD->getParent())))
13317           : SemaRef.Context.VoidPtrTy;
13318 
13319   // C++ [basic.stc.dynamic.deallocation]p2:
13320   //   Each deallocation function shall return void
13321   if (CheckOperatorNewDeleteTypes(
13322           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13323           diag::err_operator_delete_dependent_param_type,
13324           diag::err_operator_delete_param_type))
13325     return true;
13326 
13327   // C++ P0722:
13328   //   A destroying operator delete shall be a usual deallocation function.
13329   if (MD && !MD->getParent()->isDependentContext() &&
13330       MD->isDestroyingOperatorDelete() &&
13331       !SemaRef.isUsualDeallocationFunction(MD)) {
13332     SemaRef.Diag(MD->getLocation(),
13333                  diag::err_destroying_operator_delete_not_usual);
13334     return true;
13335   }
13336 
13337   return false;
13338 }
13339 
13340 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13341 /// of this overloaded operator is well-formed. If so, returns false;
13342 /// otherwise, emits appropriate diagnostics and returns true.
13343 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13344   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13345          "Expected an overloaded operator declaration");
13346 
13347   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13348 
13349   // C++ [over.oper]p5:
13350   //   The allocation and deallocation functions, operator new,
13351   //   operator new[], operator delete and operator delete[], are
13352   //   described completely in 3.7.3. The attributes and restrictions
13353   //   found in the rest of this subclause do not apply to them unless
13354   //   explicitly stated in 3.7.3.
13355   if (Op == OO_Delete || Op == OO_Array_Delete)
13356     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13357 
13358   if (Op == OO_New || Op == OO_Array_New)
13359     return CheckOperatorNewDeclaration(*this, FnDecl);
13360 
13361   // C++ [over.oper]p6:
13362   //   An operator function shall either be a non-static member
13363   //   function or be a non-member function and have at least one
13364   //   parameter whose type is a class, a reference to a class, an
13365   //   enumeration, or a reference to an enumeration.
13366   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13367     if (MethodDecl->isStatic())
13368       return Diag(FnDecl->getLocation(),
13369                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13370   } else {
13371     bool ClassOrEnumParam = false;
13372     for (auto Param : FnDecl->parameters()) {
13373       QualType ParamType = Param->getType().getNonReferenceType();
13374       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13375           ParamType->isEnumeralType()) {
13376         ClassOrEnumParam = true;
13377         break;
13378       }
13379     }
13380 
13381     if (!ClassOrEnumParam)
13382       return Diag(FnDecl->getLocation(),
13383                   diag::err_operator_overload_needs_class_or_enum)
13384         << FnDecl->getDeclName();
13385   }
13386 
13387   // C++ [over.oper]p8:
13388   //   An operator function cannot have default arguments (8.3.6),
13389   //   except where explicitly stated below.
13390   //
13391   // Only the function-call operator allows default arguments
13392   // (C++ [over.call]p1).
13393   if (Op != OO_Call) {
13394     for (auto Param : FnDecl->parameters()) {
13395       if (Param->hasDefaultArg())
13396         return Diag(Param->getLocation(),
13397                     diag::err_operator_overload_default_arg)
13398           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13399     }
13400   }
13401 
13402   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13403     { false, false, false }
13404 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13405     , { Unary, Binary, MemberOnly }
13406 #include "clang/Basic/OperatorKinds.def"
13407   };
13408 
13409   bool CanBeUnaryOperator = OperatorUses[Op][0];
13410   bool CanBeBinaryOperator = OperatorUses[Op][1];
13411   bool MustBeMemberOperator = OperatorUses[Op][2];
13412 
13413   // C++ [over.oper]p8:
13414   //   [...] Operator functions cannot have more or fewer parameters
13415   //   than the number required for the corresponding operator, as
13416   //   described in the rest of this subclause.
13417   unsigned NumParams = FnDecl->getNumParams()
13418                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13419   if (Op != OO_Call &&
13420       ((NumParams == 1 && !CanBeUnaryOperator) ||
13421        (NumParams == 2 && !CanBeBinaryOperator) ||
13422        (NumParams < 1) || (NumParams > 2))) {
13423     // We have the wrong number of parameters.
13424     unsigned ErrorKind;
13425     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13426       ErrorKind = 2;  // 2 -> unary or binary.
13427     } else if (CanBeUnaryOperator) {
13428       ErrorKind = 0;  // 0 -> unary
13429     } else {
13430       assert(CanBeBinaryOperator &&
13431              "All non-call overloaded operators are unary or binary!");
13432       ErrorKind = 1;  // 1 -> binary
13433     }
13434 
13435     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13436       << FnDecl->getDeclName() << NumParams << ErrorKind;
13437   }
13438 
13439   // Overloaded operators other than operator() cannot be variadic.
13440   if (Op != OO_Call &&
13441       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13442     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13443       << FnDecl->getDeclName();
13444   }
13445 
13446   // Some operators must be non-static member functions.
13447   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13448     return Diag(FnDecl->getLocation(),
13449                 diag::err_operator_overload_must_be_member)
13450       << FnDecl->getDeclName();
13451   }
13452 
13453   // C++ [over.inc]p1:
13454   //   The user-defined function called operator++ implements the
13455   //   prefix and postfix ++ operator. If this function is a member
13456   //   function with no parameters, or a non-member function with one
13457   //   parameter of class or enumeration type, it defines the prefix
13458   //   increment operator ++ for objects of that type. If the function
13459   //   is a member function with one parameter (which shall be of type
13460   //   int) or a non-member function with two parameters (the second
13461   //   of which shall be of type int), it defines the postfix
13462   //   increment operator ++ for objects of that type.
13463   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13464     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13465     QualType ParamType = LastParam->getType();
13466 
13467     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13468         !ParamType->isDependentType())
13469       return Diag(LastParam->getLocation(),
13470                   diag::err_operator_overload_post_incdec_must_be_int)
13471         << LastParam->getType() << (Op == OO_MinusMinus);
13472   }
13473 
13474   return false;
13475 }
13476 
13477 static bool
13478 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13479                                           FunctionTemplateDecl *TpDecl) {
13480   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13481 
13482   // Must have one or two template parameters.
13483   if (TemplateParams->size() == 1) {
13484     NonTypeTemplateParmDecl *PmDecl =
13485         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13486 
13487     // The template parameter must be a char parameter pack.
13488     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13489         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13490       return false;
13491 
13492   } else if (TemplateParams->size() == 2) {
13493     TemplateTypeParmDecl *PmType =
13494         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13495     NonTypeTemplateParmDecl *PmArgs =
13496         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13497 
13498     // The second template parameter must be a parameter pack with the
13499     // first template parameter as its type.
13500     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13501         PmArgs->isTemplateParameterPack()) {
13502       const TemplateTypeParmType *TArgs =
13503           PmArgs->getType()->getAs<TemplateTypeParmType>();
13504       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13505           TArgs->getIndex() == PmType->getIndex()) {
13506         if (!SemaRef.inTemplateInstantiation())
13507           SemaRef.Diag(TpDecl->getLocation(),
13508                        diag::ext_string_literal_operator_template);
13509         return false;
13510       }
13511     }
13512   }
13513 
13514   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13515                diag::err_literal_operator_template)
13516       << TpDecl->getTemplateParameters()->getSourceRange();
13517   return true;
13518 }
13519 
13520 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13521 /// of this literal operator function is well-formed. If so, returns
13522 /// false; otherwise, emits appropriate diagnostics and returns true.
13523 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13524   if (isa<CXXMethodDecl>(FnDecl)) {
13525     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13526       << FnDecl->getDeclName();
13527     return true;
13528   }
13529 
13530   if (FnDecl->isExternC()) {
13531     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13532     if (const LinkageSpecDecl *LSD =
13533             FnDecl->getDeclContext()->getExternCContext())
13534       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13535     return true;
13536   }
13537 
13538   // This might be the definition of a literal operator template.
13539   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13540 
13541   // This might be a specialization of a literal operator template.
13542   if (!TpDecl)
13543     TpDecl = FnDecl->getPrimaryTemplate();
13544 
13545   // template <char...> type operator "" name() and
13546   // template <class T, T...> type operator "" name() are the only valid
13547   // template signatures, and the only valid signatures with no parameters.
13548   if (TpDecl) {
13549     if (FnDecl->param_size() != 0) {
13550       Diag(FnDecl->getLocation(),
13551            diag::err_literal_operator_template_with_params);
13552       return true;
13553     }
13554 
13555     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13556       return true;
13557 
13558   } else if (FnDecl->param_size() == 1) {
13559     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13560 
13561     QualType ParamType = Param->getType().getUnqualifiedType();
13562 
13563     // Only unsigned long long int, long double, any character type, and const
13564     // char * are allowed as the only parameters.
13565     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13566         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13567         Context.hasSameType(ParamType, Context.CharTy) ||
13568         Context.hasSameType(ParamType, Context.WideCharTy) ||
13569         Context.hasSameType(ParamType, Context.Char8Ty) ||
13570         Context.hasSameType(ParamType, Context.Char16Ty) ||
13571         Context.hasSameType(ParamType, Context.Char32Ty)) {
13572     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13573       QualType InnerType = Ptr->getPointeeType();
13574 
13575       // Pointer parameter must be a const char *.
13576       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13577                                 Context.CharTy) &&
13578             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13579         Diag(Param->getSourceRange().getBegin(),
13580              diag::err_literal_operator_param)
13581             << ParamType << "'const char *'" << Param->getSourceRange();
13582         return true;
13583       }
13584 
13585     } else if (ParamType->isRealFloatingType()) {
13586       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13587           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13588       return true;
13589 
13590     } else if (ParamType->isIntegerType()) {
13591       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13592           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13593       return true;
13594 
13595     } else {
13596       Diag(Param->getSourceRange().getBegin(),
13597            diag::err_literal_operator_invalid_param)
13598           << ParamType << Param->getSourceRange();
13599       return true;
13600     }
13601 
13602   } else if (FnDecl->param_size() == 2) {
13603     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13604 
13605     // First, verify that the first parameter is correct.
13606 
13607     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13608 
13609     // Two parameter function must have a pointer to const as a
13610     // first parameter; let's strip those qualifiers.
13611     const PointerType *PT = FirstParamType->getAs<PointerType>();
13612 
13613     if (!PT) {
13614       Diag((*Param)->getSourceRange().getBegin(),
13615            diag::err_literal_operator_param)
13616           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13617       return true;
13618     }
13619 
13620     QualType PointeeType = PT->getPointeeType();
13621     // First parameter must be const
13622     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13623       Diag((*Param)->getSourceRange().getBegin(),
13624            diag::err_literal_operator_param)
13625           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13626       return true;
13627     }
13628 
13629     QualType InnerType = PointeeType.getUnqualifiedType();
13630     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13631     // const char32_t* are allowed as the first parameter to a two-parameter
13632     // function
13633     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13634           Context.hasSameType(InnerType, Context.WideCharTy) ||
13635           Context.hasSameType(InnerType, Context.Char8Ty) ||
13636           Context.hasSameType(InnerType, Context.Char16Ty) ||
13637           Context.hasSameType(InnerType, Context.Char32Ty))) {
13638       Diag((*Param)->getSourceRange().getBegin(),
13639            diag::err_literal_operator_param)
13640           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13641       return true;
13642     }
13643 
13644     // Move on to the second and final parameter.
13645     ++Param;
13646 
13647     // The second parameter must be a std::size_t.
13648     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13649     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13650       Diag((*Param)->getSourceRange().getBegin(),
13651            diag::err_literal_operator_param)
13652           << SecondParamType << Context.getSizeType()
13653           << (*Param)->getSourceRange();
13654       return true;
13655     }
13656   } else {
13657     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13658     return true;
13659   }
13660 
13661   // Parameters are good.
13662 
13663   // A parameter-declaration-clause containing a default argument is not
13664   // equivalent to any of the permitted forms.
13665   for (auto Param : FnDecl->parameters()) {
13666     if (Param->hasDefaultArg()) {
13667       Diag(Param->getDefaultArgRange().getBegin(),
13668            diag::err_literal_operator_default_argument)
13669         << Param->getDefaultArgRange();
13670       break;
13671     }
13672   }
13673 
13674   StringRef LiteralName
13675     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13676   if (LiteralName[0] != '_' &&
13677       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13678     // C++11 [usrlit.suffix]p1:
13679     //   Literal suffix identifiers that do not start with an underscore
13680     //   are reserved for future standardization.
13681     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13682       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13683   }
13684 
13685   return false;
13686 }
13687 
13688 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13689 /// linkage specification, including the language and (if present)
13690 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13691 /// language string literal. LBraceLoc, if valid, provides the location of
13692 /// the '{' brace. Otherwise, this linkage specification does not
13693 /// have any braces.
13694 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13695                                            Expr *LangStr,
13696                                            SourceLocation LBraceLoc) {
13697   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13698   if (!Lit->isAscii()) {
13699     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13700       << LangStr->getSourceRange();
13701     return nullptr;
13702   }
13703 
13704   StringRef Lang = Lit->getString();
13705   LinkageSpecDecl::LanguageIDs Language;
13706   if (Lang == "C")
13707     Language = LinkageSpecDecl::lang_c;
13708   else if (Lang == "C++")
13709     Language = LinkageSpecDecl::lang_cxx;
13710   else {
13711     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13712       << LangStr->getSourceRange();
13713     return nullptr;
13714   }
13715 
13716   // FIXME: Add all the various semantics of linkage specifications
13717 
13718   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13719                                                LangStr->getExprLoc(), Language,
13720                                                LBraceLoc.isValid());
13721   CurContext->addDecl(D);
13722   PushDeclContext(S, D);
13723   return D;
13724 }
13725 
13726 /// ActOnFinishLinkageSpecification - Complete the definition of
13727 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13728 /// valid, it's the position of the closing '}' brace in a linkage
13729 /// specification that uses braces.
13730 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13731                                             Decl *LinkageSpec,
13732                                             SourceLocation RBraceLoc) {
13733   if (RBraceLoc.isValid()) {
13734     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13735     LSDecl->setRBraceLoc(RBraceLoc);
13736   }
13737   PopDeclContext();
13738   return LinkageSpec;
13739 }
13740 
13741 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13742                                   const ParsedAttributesView &AttrList,
13743                                   SourceLocation SemiLoc) {
13744   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13745   // Attribute declarations appertain to empty declaration so we handle
13746   // them here.
13747   ProcessDeclAttributeList(S, ED, AttrList);
13748 
13749   CurContext->addDecl(ED);
13750   return ED;
13751 }
13752 
13753 /// Perform semantic analysis for the variable declaration that
13754 /// occurs within a C++ catch clause, returning the newly-created
13755 /// variable.
13756 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13757                                          TypeSourceInfo *TInfo,
13758                                          SourceLocation StartLoc,
13759                                          SourceLocation Loc,
13760                                          IdentifierInfo *Name) {
13761   bool Invalid = false;
13762   QualType ExDeclType = TInfo->getType();
13763 
13764   // Arrays and functions decay.
13765   if (ExDeclType->isArrayType())
13766     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13767   else if (ExDeclType->isFunctionType())
13768     ExDeclType = Context.getPointerType(ExDeclType);
13769 
13770   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13771   // The exception-declaration shall not denote a pointer or reference to an
13772   // incomplete type, other than [cv] void*.
13773   // N2844 forbids rvalue references.
13774   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13775     Diag(Loc, diag::err_catch_rvalue_ref);
13776     Invalid = true;
13777   }
13778 
13779   if (ExDeclType->isVariablyModifiedType()) {
13780     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13781     Invalid = true;
13782   }
13783 
13784   QualType BaseType = ExDeclType;
13785   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13786   unsigned DK = diag::err_catch_incomplete;
13787   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13788     BaseType = Ptr->getPointeeType();
13789     Mode = 1;
13790     DK = diag::err_catch_incomplete_ptr;
13791   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13792     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13793     BaseType = Ref->getPointeeType();
13794     Mode = 2;
13795     DK = diag::err_catch_incomplete_ref;
13796   }
13797   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13798       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13799     Invalid = true;
13800 
13801   if (!Invalid && !ExDeclType->isDependentType() &&
13802       RequireNonAbstractType(Loc, ExDeclType,
13803                              diag::err_abstract_type_in_decl,
13804                              AbstractVariableType))
13805     Invalid = true;
13806 
13807   // Only the non-fragile NeXT runtime currently supports C++ catches
13808   // of ObjC types, and no runtime supports catching ObjC types by value.
13809   if (!Invalid && getLangOpts().ObjC) {
13810     QualType T = ExDeclType;
13811     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13812       T = RT->getPointeeType();
13813 
13814     if (T->isObjCObjectType()) {
13815       Diag(Loc, diag::err_objc_object_catch);
13816       Invalid = true;
13817     } else if (T->isObjCObjectPointerType()) {
13818       // FIXME: should this be a test for macosx-fragile specifically?
13819       if (getLangOpts().ObjCRuntime.isFragile())
13820         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13821     }
13822   }
13823 
13824   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13825                                     ExDeclType, TInfo, SC_None);
13826   ExDecl->setExceptionVariable(true);
13827 
13828   // In ARC, infer 'retaining' for variables of retainable type.
13829   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13830     Invalid = true;
13831 
13832   if (!Invalid && !ExDeclType->isDependentType()) {
13833     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13834       // Insulate this from anything else we might currently be parsing.
13835       EnterExpressionEvaluationContext scope(
13836           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13837 
13838       // C++ [except.handle]p16:
13839       //   The object declared in an exception-declaration or, if the
13840       //   exception-declaration does not specify a name, a temporary (12.2) is
13841       //   copy-initialized (8.5) from the exception object. [...]
13842       //   The object is destroyed when the handler exits, after the destruction
13843       //   of any automatic objects initialized within the handler.
13844       //
13845       // We just pretend to initialize the object with itself, then make sure
13846       // it can be destroyed later.
13847       QualType initType = Context.getExceptionObjectType(ExDeclType);
13848 
13849       InitializedEntity entity =
13850         InitializedEntity::InitializeVariable(ExDecl);
13851       InitializationKind initKind =
13852         InitializationKind::CreateCopy(Loc, SourceLocation());
13853 
13854       Expr *opaqueValue =
13855         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13856       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13857       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13858       if (result.isInvalid())
13859         Invalid = true;
13860       else {
13861         // If the constructor used was non-trivial, set this as the
13862         // "initializer".
13863         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13864         if (!construct->getConstructor()->isTrivial()) {
13865           Expr *init = MaybeCreateExprWithCleanups(construct);
13866           ExDecl->setInit(init);
13867         }
13868 
13869         // And make sure it's destructable.
13870         FinalizeVarWithDestructor(ExDecl, recordType);
13871       }
13872     }
13873   }
13874 
13875   if (Invalid)
13876     ExDecl->setInvalidDecl();
13877 
13878   return ExDecl;
13879 }
13880 
13881 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13882 /// handler.
13883 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13884   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13885   bool Invalid = D.isInvalidType();
13886 
13887   // Check for unexpanded parameter packs.
13888   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13889                                       UPPC_ExceptionType)) {
13890     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13891                                              D.getIdentifierLoc());
13892     Invalid = true;
13893   }
13894 
13895   IdentifierInfo *II = D.getIdentifier();
13896   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13897                                              LookupOrdinaryName,
13898                                              ForVisibleRedeclaration)) {
13899     // The scope should be freshly made just for us. There is just no way
13900     // it contains any previous declaration, except for function parameters in
13901     // a function-try-block's catch statement.
13902     assert(!S->isDeclScope(PrevDecl));
13903     if (isDeclInScope(PrevDecl, CurContext, S)) {
13904       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13905         << D.getIdentifier();
13906       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13907       Invalid = true;
13908     } else if (PrevDecl->isTemplateParameter())
13909       // Maybe we will complain about the shadowed template parameter.
13910       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13911   }
13912 
13913   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13914     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13915       << D.getCXXScopeSpec().getRange();
13916     Invalid = true;
13917   }
13918 
13919   VarDecl *ExDecl = BuildExceptionDeclaration(
13920       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
13921   if (Invalid)
13922     ExDecl->setInvalidDecl();
13923 
13924   // Add the exception declaration into this scope.
13925   if (II)
13926     PushOnScopeChains(ExDecl, S);
13927   else
13928     CurContext->addDecl(ExDecl);
13929 
13930   ProcessDeclAttributes(S, ExDecl, D);
13931   return ExDecl;
13932 }
13933 
13934 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13935                                          Expr *AssertExpr,
13936                                          Expr *AssertMessageExpr,
13937                                          SourceLocation RParenLoc) {
13938   StringLiteral *AssertMessage =
13939       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13940 
13941   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13942     return nullptr;
13943 
13944   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13945                                       AssertMessage, RParenLoc, false);
13946 }
13947 
13948 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13949                                          Expr *AssertExpr,
13950                                          StringLiteral *AssertMessage,
13951                                          SourceLocation RParenLoc,
13952                                          bool Failed) {
13953   assert(AssertExpr != nullptr && "Expected non-null condition");
13954   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13955       !Failed) {
13956     // In a static_assert-declaration, the constant-expression shall be a
13957     // constant expression that can be contextually converted to bool.
13958     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13959     if (Converted.isInvalid())
13960       Failed = true;
13961     else
13962       Converted = ConstantExpr::Create(Context, Converted.get());
13963 
13964     llvm::APSInt Cond;
13965     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13966           diag::err_static_assert_expression_is_not_constant,
13967           /*AllowFold=*/false).isInvalid())
13968       Failed = true;
13969 
13970     if (!Failed && !Cond) {
13971       SmallString<256> MsgBuffer;
13972       llvm::raw_svector_ostream Msg(MsgBuffer);
13973       if (AssertMessage)
13974         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13975 
13976       Expr *InnerCond = nullptr;
13977       std::string InnerCondDescription;
13978       std::tie(InnerCond, InnerCondDescription) =
13979         findFailedBooleanCondition(Converted.get());
13980       if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
13981                     && !isa<IntegerLiteral>(InnerCond)) {
13982         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13983           << InnerCondDescription << !AssertMessage
13984           << Msg.str() << InnerCond->getSourceRange();
13985       } else {
13986         Diag(StaticAssertLoc, diag::err_static_assert_failed)
13987           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13988       }
13989       Failed = true;
13990     }
13991   }
13992 
13993   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13994                                                   /*DiscardedValue*/false,
13995                                                   /*IsConstexpr*/true);
13996   if (FullAssertExpr.isInvalid())
13997     Failed = true;
13998   else
13999     AssertExpr = FullAssertExpr.get();
14000 
14001   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
14002                                         AssertExpr, AssertMessage, RParenLoc,
14003                                         Failed);
14004 
14005   CurContext->addDecl(Decl);
14006   return Decl;
14007 }
14008 
14009 /// Perform semantic analysis of the given friend type declaration.
14010 ///
14011 /// \returns A friend declaration that.
14012 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
14013                                       SourceLocation FriendLoc,
14014                                       TypeSourceInfo *TSInfo) {
14015   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
14016 
14017   QualType T = TSInfo->getType();
14018   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
14019 
14020   // C++03 [class.friend]p2:
14021   //   An elaborated-type-specifier shall be used in a friend declaration
14022   //   for a class.*
14023   //
14024   //   * The class-key of the elaborated-type-specifier is required.
14025   if (!CodeSynthesisContexts.empty()) {
14026     // Do not complain about the form of friend template types during any kind
14027     // of code synthesis. For template instantiation, we will have complained
14028     // when the template was defined.
14029   } else {
14030     if (!T->isElaboratedTypeSpecifier()) {
14031       // If we evaluated the type to a record type, suggest putting
14032       // a tag in front.
14033       if (const RecordType *RT = T->getAs<RecordType>()) {
14034         RecordDecl *RD = RT->getDecl();
14035 
14036         SmallString<16> InsertionText(" ");
14037         InsertionText += RD->getKindName();
14038 
14039         Diag(TypeRange.getBegin(),
14040              getLangOpts().CPlusPlus11 ?
14041                diag::warn_cxx98_compat_unelaborated_friend_type :
14042                diag::ext_unelaborated_friend_type)
14043           << (unsigned) RD->getTagKind()
14044           << T
14045           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
14046                                         InsertionText);
14047       } else {
14048         Diag(FriendLoc,
14049              getLangOpts().CPlusPlus11 ?
14050                diag::warn_cxx98_compat_nonclass_type_friend :
14051                diag::ext_nonclass_type_friend)
14052           << T
14053           << TypeRange;
14054       }
14055     } else if (T->getAs<EnumType>()) {
14056       Diag(FriendLoc,
14057            getLangOpts().CPlusPlus11 ?
14058              diag::warn_cxx98_compat_enum_friend :
14059              diag::ext_enum_friend)
14060         << T
14061         << TypeRange;
14062     }
14063 
14064     // C++11 [class.friend]p3:
14065     //   A friend declaration that does not declare a function shall have one
14066     //   of the following forms:
14067     //     friend elaborated-type-specifier ;
14068     //     friend simple-type-specifier ;
14069     //     friend typename-specifier ;
14070     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14071       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14072   }
14073 
14074   //   If the type specifier in a friend declaration designates a (possibly
14075   //   cv-qualified) class type, that class is declared as a friend; otherwise,
14076   //   the friend declaration is ignored.
14077   return FriendDecl::Create(Context, CurContext,
14078                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14079                             FriendLoc);
14080 }
14081 
14082 /// Handle a friend tag declaration where the scope specifier was
14083 /// templated.
14084 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
14085                                     unsigned TagSpec, SourceLocation TagLoc,
14086                                     CXXScopeSpec &SS, IdentifierInfo *Name,
14087                                     SourceLocation NameLoc,
14088                                     const ParsedAttributesView &Attr,
14089                                     MultiTemplateParamsArg TempParamLists) {
14090   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14091 
14092   bool IsMemberSpecialization = false;
14093   bool Invalid = false;
14094 
14095   if (TemplateParameterList *TemplateParams =
14096           MatchTemplateParametersToScopeSpecifier(
14097               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14098               IsMemberSpecialization, Invalid)) {
14099     if (TemplateParams->size() > 0) {
14100       // This is a declaration of a class template.
14101       if (Invalid)
14102         return nullptr;
14103 
14104       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14105                                 NameLoc, Attr, TemplateParams, AS_public,
14106                                 /*ModulePrivateLoc=*/SourceLocation(),
14107                                 FriendLoc, TempParamLists.size() - 1,
14108                                 TempParamLists.data()).get();
14109     } else {
14110       // The "template<>" header is extraneous.
14111       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14112         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14113       IsMemberSpecialization = true;
14114     }
14115   }
14116 
14117   if (Invalid) return nullptr;
14118 
14119   bool isAllExplicitSpecializations = true;
14120   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14121     if (TempParamLists[I]->size()) {
14122       isAllExplicitSpecializations = false;
14123       break;
14124     }
14125   }
14126 
14127   // FIXME: don't ignore attributes.
14128 
14129   // If it's explicit specializations all the way down, just forget
14130   // about the template header and build an appropriate non-templated
14131   // friend.  TODO: for source fidelity, remember the headers.
14132   if (isAllExplicitSpecializations) {
14133     if (SS.isEmpty()) {
14134       bool Owned = false;
14135       bool IsDependent = false;
14136       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14137                       Attr, AS_public,
14138                       /*ModulePrivateLoc=*/SourceLocation(),
14139                       MultiTemplateParamsArg(), Owned, IsDependent,
14140                       /*ScopedEnumKWLoc=*/SourceLocation(),
14141                       /*ScopedEnumUsesClassTag=*/false,
14142                       /*UnderlyingType=*/TypeResult(),
14143                       /*IsTypeSpecifier=*/false,
14144                       /*IsTemplateParamOrArg=*/false);
14145     }
14146 
14147     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14148     ElaboratedTypeKeyword Keyword
14149       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14150     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14151                                    *Name, NameLoc);
14152     if (T.isNull())
14153       return nullptr;
14154 
14155     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14156     if (isa<DependentNameType>(T)) {
14157       DependentNameTypeLoc TL =
14158           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14159       TL.setElaboratedKeywordLoc(TagLoc);
14160       TL.setQualifierLoc(QualifierLoc);
14161       TL.setNameLoc(NameLoc);
14162     } else {
14163       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14164       TL.setElaboratedKeywordLoc(TagLoc);
14165       TL.setQualifierLoc(QualifierLoc);
14166       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14167     }
14168 
14169     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14170                                             TSI, FriendLoc, TempParamLists);
14171     Friend->setAccess(AS_public);
14172     CurContext->addDecl(Friend);
14173     return Friend;
14174   }
14175 
14176   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14177 
14178 
14179 
14180   // Handle the case of a templated-scope friend class.  e.g.
14181   //   template <class T> class A<T>::B;
14182   // FIXME: we don't support these right now.
14183   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14184     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14185   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14186   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14187   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14188   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14189   TL.setElaboratedKeywordLoc(TagLoc);
14190   TL.setQualifierLoc(SS.getWithLocInContext(Context));
14191   TL.setNameLoc(NameLoc);
14192 
14193   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14194                                           TSI, FriendLoc, TempParamLists);
14195   Friend->setAccess(AS_public);
14196   Friend->setUnsupportedFriend(true);
14197   CurContext->addDecl(Friend);
14198   return Friend;
14199 }
14200 
14201 /// Handle a friend type declaration.  This works in tandem with
14202 /// ActOnTag.
14203 ///
14204 /// Notes on friend class templates:
14205 ///
14206 /// We generally treat friend class declarations as if they were
14207 /// declaring a class.  So, for example, the elaborated type specifier
14208 /// in a friend declaration is required to obey the restrictions of a
14209 /// class-head (i.e. no typedefs in the scope chain), template
14210 /// parameters are required to match up with simple template-ids, &c.
14211 /// However, unlike when declaring a template specialization, it's
14212 /// okay to refer to a template specialization without an empty
14213 /// template parameter declaration, e.g.
14214 ///   friend class A<T>::B<unsigned>;
14215 /// We permit this as a special case; if there are any template
14216 /// parameters present at all, require proper matching, i.e.
14217 ///   template <> template \<class T> friend class A<int>::B;
14218 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14219                                 MultiTemplateParamsArg TempParams) {
14220   SourceLocation Loc = DS.getBeginLoc();
14221 
14222   assert(DS.isFriendSpecified());
14223   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14224 
14225   // C++ [class.friend]p3:
14226   // A friend declaration that does not declare a function shall have one of
14227   // the following forms:
14228   //     friend elaborated-type-specifier ;
14229   //     friend simple-type-specifier ;
14230   //     friend typename-specifier ;
14231   //
14232   // Any declaration with a type qualifier does not have that form. (It's
14233   // legal to specify a qualified type as a friend, you just can't write the
14234   // keywords.)
14235   if (DS.getTypeQualifiers()) {
14236     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14237       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14238     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14239       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14240     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14241       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14242     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14243       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14244     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14245       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14246   }
14247 
14248   // Try to convert the decl specifier to a type.  This works for
14249   // friend templates because ActOnTag never produces a ClassTemplateDecl
14250   // for a TUK_Friend.
14251   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14252   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14253   QualType T = TSI->getType();
14254   if (TheDeclarator.isInvalidType())
14255     return nullptr;
14256 
14257   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14258     return nullptr;
14259 
14260   // This is definitely an error in C++98.  It's probably meant to
14261   // be forbidden in C++0x, too, but the specification is just
14262   // poorly written.
14263   //
14264   // The problem is with declarations like the following:
14265   //   template <T> friend A<T>::foo;
14266   // where deciding whether a class C is a friend or not now hinges
14267   // on whether there exists an instantiation of A that causes
14268   // 'foo' to equal C.  There are restrictions on class-heads
14269   // (which we declare (by fiat) elaborated friend declarations to
14270   // be) that makes this tractable.
14271   //
14272   // FIXME: handle "template <> friend class A<T>;", which
14273   // is possibly well-formed?  Who even knows?
14274   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14275     Diag(Loc, diag::err_tagless_friend_type_template)
14276       << DS.getSourceRange();
14277     return nullptr;
14278   }
14279 
14280   // C++98 [class.friend]p1: A friend of a class is a function
14281   //   or class that is not a member of the class . . .
14282   // This is fixed in DR77, which just barely didn't make the C++03
14283   // deadline.  It's also a very silly restriction that seriously
14284   // affects inner classes and which nobody else seems to implement;
14285   // thus we never diagnose it, not even in -pedantic.
14286   //
14287   // But note that we could warn about it: it's always useless to
14288   // friend one of your own members (it's not, however, worthless to
14289   // friend a member of an arbitrary specialization of your template).
14290 
14291   Decl *D;
14292   if (!TempParams.empty())
14293     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14294                                    TempParams,
14295                                    TSI,
14296                                    DS.getFriendSpecLoc());
14297   else
14298     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14299 
14300   if (!D)
14301     return nullptr;
14302 
14303   D->setAccess(AS_public);
14304   CurContext->addDecl(D);
14305 
14306   return D;
14307 }
14308 
14309 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14310                                         MultiTemplateParamsArg TemplateParams) {
14311   const DeclSpec &DS = D.getDeclSpec();
14312 
14313   assert(DS.isFriendSpecified());
14314   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14315 
14316   SourceLocation Loc = D.getIdentifierLoc();
14317   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14318 
14319   // C++ [class.friend]p1
14320   //   A friend of a class is a function or class....
14321   // Note that this sees through typedefs, which is intended.
14322   // It *doesn't* see through dependent types, which is correct
14323   // according to [temp.arg.type]p3:
14324   //   If a declaration acquires a function type through a
14325   //   type dependent on a template-parameter and this causes
14326   //   a declaration that does not use the syntactic form of a
14327   //   function declarator to have a function type, the program
14328   //   is ill-formed.
14329   if (!TInfo->getType()->isFunctionType()) {
14330     Diag(Loc, diag::err_unexpected_friend);
14331 
14332     // It might be worthwhile to try to recover by creating an
14333     // appropriate declaration.
14334     return nullptr;
14335   }
14336 
14337   // C++ [namespace.memdef]p3
14338   //  - If a friend declaration in a non-local class first declares a
14339   //    class or function, the friend class or function is a member
14340   //    of the innermost enclosing namespace.
14341   //  - The name of the friend is not found by simple name lookup
14342   //    until a matching declaration is provided in that namespace
14343   //    scope (either before or after the class declaration granting
14344   //    friendship).
14345   //  - If a friend function is called, its name may be found by the
14346   //    name lookup that considers functions from namespaces and
14347   //    classes associated with the types of the function arguments.
14348   //  - When looking for a prior declaration of a class or a function
14349   //    declared as a friend, scopes outside the innermost enclosing
14350   //    namespace scope are not considered.
14351 
14352   CXXScopeSpec &SS = D.getCXXScopeSpec();
14353   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14354   assert(NameInfo.getName());
14355 
14356   // Check for unexpanded parameter packs.
14357   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14358       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14359       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14360     return nullptr;
14361 
14362   // The context we found the declaration in, or in which we should
14363   // create the declaration.
14364   DeclContext *DC;
14365   Scope *DCScope = S;
14366   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14367                         ForExternalRedeclaration);
14368 
14369   // There are five cases here.
14370   //   - There's no scope specifier and we're in a local class. Only look
14371   //     for functions declared in the immediately-enclosing block scope.
14372   // We recover from invalid scope qualifiers as if they just weren't there.
14373   FunctionDecl *FunctionContainingLocalClass = nullptr;
14374   if ((SS.isInvalid() || !SS.isSet()) &&
14375       (FunctionContainingLocalClass =
14376            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14377     // C++11 [class.friend]p11:
14378     //   If a friend declaration appears in a local class and the name
14379     //   specified is an unqualified name, a prior declaration is
14380     //   looked up without considering scopes that are outside the
14381     //   innermost enclosing non-class scope. For a friend function
14382     //   declaration, if there is no prior declaration, the program is
14383     //   ill-formed.
14384 
14385     // Find the innermost enclosing non-class scope. This is the block
14386     // scope containing the local class definition (or for a nested class,
14387     // the outer local class).
14388     DCScope = S->getFnParent();
14389 
14390     // Look up the function name in the scope.
14391     Previous.clear(LookupLocalFriendName);
14392     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14393 
14394     if (!Previous.empty()) {
14395       // All possible previous declarations must have the same context:
14396       // either they were declared at block scope or they are members of
14397       // one of the enclosing local classes.
14398       DC = Previous.getRepresentativeDecl()->getDeclContext();
14399     } else {
14400       // This is ill-formed, but provide the context that we would have
14401       // declared the function in, if we were permitted to, for error recovery.
14402       DC = FunctionContainingLocalClass;
14403     }
14404     adjustContextForLocalExternDecl(DC);
14405 
14406     // C++ [class.friend]p6:
14407     //   A function can be defined in a friend declaration of a class if and
14408     //   only if the class is a non-local class (9.8), the function name is
14409     //   unqualified, and the function has namespace scope.
14410     if (D.isFunctionDefinition()) {
14411       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14412     }
14413 
14414   //   - There's no scope specifier, in which case we just go to the
14415   //     appropriate scope and look for a function or function template
14416   //     there as appropriate.
14417   } else if (SS.isInvalid() || !SS.isSet()) {
14418     // C++11 [namespace.memdef]p3:
14419     //   If the name in a friend declaration is neither qualified nor
14420     //   a template-id and the declaration is a function or an
14421     //   elaborated-type-specifier, the lookup to determine whether
14422     //   the entity has been previously declared shall not consider
14423     //   any scopes outside the innermost enclosing namespace.
14424     bool isTemplateId =
14425         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14426 
14427     // Find the appropriate context according to the above.
14428     DC = CurContext;
14429 
14430     // Skip class contexts.  If someone can cite chapter and verse
14431     // for this behavior, that would be nice --- it's what GCC and
14432     // EDG do, and it seems like a reasonable intent, but the spec
14433     // really only says that checks for unqualified existing
14434     // declarations should stop at the nearest enclosing namespace,
14435     // not that they should only consider the nearest enclosing
14436     // namespace.
14437     while (DC->isRecord())
14438       DC = DC->getParent();
14439 
14440     DeclContext *LookupDC = DC;
14441     while (LookupDC->isTransparentContext())
14442       LookupDC = LookupDC->getParent();
14443 
14444     while (true) {
14445       LookupQualifiedName(Previous, LookupDC);
14446 
14447       if (!Previous.empty()) {
14448         DC = LookupDC;
14449         break;
14450       }
14451 
14452       if (isTemplateId) {
14453         if (isa<TranslationUnitDecl>(LookupDC)) break;
14454       } else {
14455         if (LookupDC->isFileContext()) break;
14456       }
14457       LookupDC = LookupDC->getParent();
14458     }
14459 
14460     DCScope = getScopeForDeclContext(S, DC);
14461 
14462   //   - There's a non-dependent scope specifier, in which case we
14463   //     compute it and do a previous lookup there for a function
14464   //     or function template.
14465   } else if (!SS.getScopeRep()->isDependent()) {
14466     DC = computeDeclContext(SS);
14467     if (!DC) return nullptr;
14468 
14469     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14470 
14471     LookupQualifiedName(Previous, DC);
14472 
14473     // C++ [class.friend]p1: A friend of a class is a function or
14474     //   class that is not a member of the class . . .
14475     if (DC->Equals(CurContext))
14476       Diag(DS.getFriendSpecLoc(),
14477            getLangOpts().CPlusPlus11 ?
14478              diag::warn_cxx98_compat_friend_is_member :
14479              diag::err_friend_is_member);
14480 
14481     if (D.isFunctionDefinition()) {
14482       // C++ [class.friend]p6:
14483       //   A function can be defined in a friend declaration of a class if and
14484       //   only if the class is a non-local class (9.8), the function name is
14485       //   unqualified, and the function has namespace scope.
14486       //
14487       // FIXME: We should only do this if the scope specifier names the
14488       // innermost enclosing namespace; otherwise the fixit changes the
14489       // meaning of the code.
14490       SemaDiagnosticBuilder DB
14491         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14492 
14493       DB << SS.getScopeRep();
14494       if (DC->isFileContext())
14495         DB << FixItHint::CreateRemoval(SS.getRange());
14496       SS.clear();
14497     }
14498 
14499   //   - There's a scope specifier that does not match any template
14500   //     parameter lists, in which case we use some arbitrary context,
14501   //     create a method or method template, and wait for instantiation.
14502   //   - There's a scope specifier that does match some template
14503   //     parameter lists, which we don't handle right now.
14504   } else {
14505     if (D.isFunctionDefinition()) {
14506       // C++ [class.friend]p6:
14507       //   A function can be defined in a friend declaration of a class if and
14508       //   only if the class is a non-local class (9.8), the function name is
14509       //   unqualified, and the function has namespace scope.
14510       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14511         << SS.getScopeRep();
14512     }
14513 
14514     DC = CurContext;
14515     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14516   }
14517 
14518   if (!DC->isRecord()) {
14519     int DiagArg = -1;
14520     switch (D.getName().getKind()) {
14521     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14522     case UnqualifiedIdKind::IK_ConstructorName:
14523       DiagArg = 0;
14524       break;
14525     case UnqualifiedIdKind::IK_DestructorName:
14526       DiagArg = 1;
14527       break;
14528     case UnqualifiedIdKind::IK_ConversionFunctionId:
14529       DiagArg = 2;
14530       break;
14531     case UnqualifiedIdKind::IK_DeductionGuideName:
14532       DiagArg = 3;
14533       break;
14534     case UnqualifiedIdKind::IK_Identifier:
14535     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14536     case UnqualifiedIdKind::IK_LiteralOperatorId:
14537     case UnqualifiedIdKind::IK_OperatorFunctionId:
14538     case UnqualifiedIdKind::IK_TemplateId:
14539       break;
14540     }
14541     // This implies that it has to be an operator or function.
14542     if (DiagArg >= 0) {
14543       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14544       return nullptr;
14545     }
14546   }
14547 
14548   // FIXME: This is an egregious hack to cope with cases where the scope stack
14549   // does not contain the declaration context, i.e., in an out-of-line
14550   // definition of a class.
14551   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14552   if (!DCScope) {
14553     FakeDCScope.setEntity(DC);
14554     DCScope = &FakeDCScope;
14555   }
14556 
14557   bool AddToScope = true;
14558   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14559                                           TemplateParams, AddToScope);
14560   if (!ND) return nullptr;
14561 
14562   assert(ND->getLexicalDeclContext() == CurContext);
14563 
14564   // If we performed typo correction, we might have added a scope specifier
14565   // and changed the decl context.
14566   DC = ND->getDeclContext();
14567 
14568   // Add the function declaration to the appropriate lookup tables,
14569   // adjusting the redeclarations list as necessary.  We don't
14570   // want to do this yet if the friending class is dependent.
14571   //
14572   // Also update the scope-based lookup if the target context's
14573   // lookup context is in lexical scope.
14574   if (!CurContext->isDependentContext()) {
14575     DC = DC->getRedeclContext();
14576     DC->makeDeclVisibleInContext(ND);
14577     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14578       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14579   }
14580 
14581   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14582                                        D.getIdentifierLoc(), ND,
14583                                        DS.getFriendSpecLoc());
14584   FrD->setAccess(AS_public);
14585   CurContext->addDecl(FrD);
14586 
14587   if (ND->isInvalidDecl()) {
14588     FrD->setInvalidDecl();
14589   } else {
14590     if (DC->isRecord()) CheckFriendAccess(ND);
14591 
14592     FunctionDecl *FD;
14593     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14594       FD = FTD->getTemplatedDecl();
14595     else
14596       FD = cast<FunctionDecl>(ND);
14597 
14598     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14599     // default argument expression, that declaration shall be a definition
14600     // and shall be the only declaration of the function or function
14601     // template in the translation unit.
14602     if (functionDeclHasDefaultArgument(FD)) {
14603       // We can't look at FD->getPreviousDecl() because it may not have been set
14604       // if we're in a dependent context. If the function is known to be a
14605       // redeclaration, we will have narrowed Previous down to the right decl.
14606       if (D.isRedeclaration()) {
14607         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14608         Diag(Previous.getRepresentativeDecl()->getLocation(),
14609              diag::note_previous_declaration);
14610       } else if (!D.isFunctionDefinition())
14611         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14612     }
14613 
14614     // Mark templated-scope function declarations as unsupported.
14615     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14616       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14617         << SS.getScopeRep() << SS.getRange()
14618         << cast<CXXRecordDecl>(CurContext);
14619       FrD->setUnsupportedFriend(true);
14620     }
14621   }
14622 
14623   return ND;
14624 }
14625 
14626 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14627   AdjustDeclIfTemplate(Dcl);
14628 
14629   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14630   if (!Fn) {
14631     Diag(DelLoc, diag::err_deleted_non_function);
14632     return;
14633   }
14634 
14635   // Deleted function does not have a body.
14636   Fn->setWillHaveBody(false);
14637 
14638   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14639     // Don't consider the implicit declaration we generate for explicit
14640     // specializations. FIXME: Do not generate these implicit declarations.
14641     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14642          Prev->getPreviousDecl()) &&
14643         !Prev->isDefined()) {
14644       Diag(DelLoc, diag::err_deleted_decl_not_first);
14645       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14646            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14647                               : diag::note_previous_declaration);
14648     }
14649     // If the declaration wasn't the first, we delete the function anyway for
14650     // recovery.
14651     Fn = Fn->getCanonicalDecl();
14652   }
14653 
14654   // dllimport/dllexport cannot be deleted.
14655   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14656     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14657     Fn->setInvalidDecl();
14658   }
14659 
14660   if (Fn->isDeleted())
14661     return;
14662 
14663   // See if we're deleting a function which is already known to override a
14664   // non-deleted virtual function.
14665   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14666     bool IssuedDiagnostic = false;
14667     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14668       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14669         if (!IssuedDiagnostic) {
14670           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14671           IssuedDiagnostic = true;
14672         }
14673         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14674       }
14675     }
14676     // If this function was implicitly deleted because it was defaulted,
14677     // explain why it was deleted.
14678     if (IssuedDiagnostic && MD->isDefaulted())
14679       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14680                                 /*Diagnose*/true);
14681   }
14682 
14683   // C++11 [basic.start.main]p3:
14684   //   A program that defines main as deleted [...] is ill-formed.
14685   if (Fn->isMain())
14686     Diag(DelLoc, diag::err_deleted_main);
14687 
14688   // C++11 [dcl.fct.def.delete]p4:
14689   //  A deleted function is implicitly inline.
14690   Fn->setImplicitlyInline();
14691   Fn->setDeletedAsWritten();
14692 }
14693 
14694 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14695   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14696 
14697   if (MD) {
14698     if (MD->getParent()->isDependentType()) {
14699       MD->setDefaulted();
14700       MD->setExplicitlyDefaulted();
14701       return;
14702     }
14703 
14704     CXXSpecialMember Member = getSpecialMember(MD);
14705     if (Member == CXXInvalid) {
14706       if (!MD->isInvalidDecl())
14707         Diag(DefaultLoc, diag::err_default_special_members);
14708       return;
14709     }
14710 
14711     MD->setDefaulted();
14712     MD->setExplicitlyDefaulted();
14713 
14714     // Unset that we will have a body for this function. We might not,
14715     // if it turns out to be trivial, and we don't need this marking now
14716     // that we've marked it as defaulted.
14717     MD->setWillHaveBody(false);
14718 
14719     // If this definition appears within the record, do the checking when
14720     // the record is complete.
14721     const FunctionDecl *Primary = MD;
14722     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14723       // Ask the template instantiation pattern that actually had the
14724       // '= default' on it.
14725       Primary = Pattern;
14726 
14727     // If the method was defaulted on its first declaration, we will have
14728     // already performed the checking in CheckCompletedCXXClass. Such a
14729     // declaration doesn't trigger an implicit definition.
14730     if (Primary->getCanonicalDecl()->isDefaulted())
14731       return;
14732 
14733     CheckExplicitlyDefaultedSpecialMember(MD);
14734 
14735     if (!MD->isInvalidDecl())
14736       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14737   } else {
14738     Diag(DefaultLoc, diag::err_default_special_members);
14739   }
14740 }
14741 
14742 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14743   for (Stmt *SubStmt : S->children()) {
14744     if (!SubStmt)
14745       continue;
14746     if (isa<ReturnStmt>(SubStmt))
14747       Self.Diag(SubStmt->getBeginLoc(),
14748                 diag::err_return_in_constructor_handler);
14749     if (!isa<Expr>(SubStmt))
14750       SearchForReturnInStmt(Self, SubStmt);
14751   }
14752 }
14753 
14754 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14755   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14756     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14757     SearchForReturnInStmt(*this, Handler);
14758   }
14759 }
14760 
14761 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14762                                              const CXXMethodDecl *Old) {
14763   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14764   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14765 
14766   if (OldFT->hasExtParameterInfos()) {
14767     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14768       // A parameter of the overriding method should be annotated with noescape
14769       // if the corresponding parameter of the overridden method is annotated.
14770       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14771           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14772         Diag(New->getParamDecl(I)->getLocation(),
14773              diag::warn_overriding_method_missing_noescape);
14774         Diag(Old->getParamDecl(I)->getLocation(),
14775              diag::note_overridden_marked_noescape);
14776       }
14777   }
14778 
14779   // Virtual overrides must have the same code_seg.
14780   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14781   const auto *NewCSA = New->getAttr<CodeSegAttr>();
14782   if ((NewCSA || OldCSA) &&
14783       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14784     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14785     Diag(Old->getLocation(), diag::note_previous_declaration);
14786     return true;
14787   }
14788 
14789   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14790 
14791   // If the calling conventions match, everything is fine
14792   if (NewCC == OldCC)
14793     return false;
14794 
14795   // If the calling conventions mismatch because the new function is static,
14796   // suppress the calling convention mismatch error; the error about static
14797   // function override (err_static_overrides_virtual from
14798   // Sema::CheckFunctionDeclaration) is more clear.
14799   if (New->getStorageClass() == SC_Static)
14800     return false;
14801 
14802   Diag(New->getLocation(),
14803        diag::err_conflicting_overriding_cc_attributes)
14804     << New->getDeclName() << New->getType() << Old->getType();
14805   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14806   return true;
14807 }
14808 
14809 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14810                                              const CXXMethodDecl *Old) {
14811   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14812   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14813 
14814   if (Context.hasSameType(NewTy, OldTy) ||
14815       NewTy->isDependentType() || OldTy->isDependentType())
14816     return false;
14817 
14818   // Check if the return types are covariant
14819   QualType NewClassTy, OldClassTy;
14820 
14821   /// Both types must be pointers or references to classes.
14822   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14823     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14824       NewClassTy = NewPT->getPointeeType();
14825       OldClassTy = OldPT->getPointeeType();
14826     }
14827   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14828     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14829       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14830         NewClassTy = NewRT->getPointeeType();
14831         OldClassTy = OldRT->getPointeeType();
14832       }
14833     }
14834   }
14835 
14836   // The return types aren't either both pointers or references to a class type.
14837   if (NewClassTy.isNull()) {
14838     Diag(New->getLocation(),
14839          diag::err_different_return_type_for_overriding_virtual_function)
14840         << New->getDeclName() << NewTy << OldTy
14841         << New->getReturnTypeSourceRange();
14842     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14843         << Old->getReturnTypeSourceRange();
14844 
14845     return true;
14846   }
14847 
14848   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14849     // C++14 [class.virtual]p8:
14850     //   If the class type in the covariant return type of D::f differs from
14851     //   that of B::f, the class type in the return type of D::f shall be
14852     //   complete at the point of declaration of D::f or shall be the class
14853     //   type D.
14854     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14855       if (!RT->isBeingDefined() &&
14856           RequireCompleteType(New->getLocation(), NewClassTy,
14857                               diag::err_covariant_return_incomplete,
14858                               New->getDeclName()))
14859         return true;
14860     }
14861 
14862     // Check if the new class derives from the old class.
14863     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14864       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14865           << New->getDeclName() << NewTy << OldTy
14866           << New->getReturnTypeSourceRange();
14867       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14868           << Old->getReturnTypeSourceRange();
14869       return true;
14870     }
14871 
14872     // Check if we the conversion from derived to base is valid.
14873     if (CheckDerivedToBaseConversion(
14874             NewClassTy, OldClassTy,
14875             diag::err_covariant_return_inaccessible_base,
14876             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14877             New->getLocation(), New->getReturnTypeSourceRange(),
14878             New->getDeclName(), nullptr)) {
14879       // FIXME: this note won't trigger for delayed access control
14880       // diagnostics, and it's impossible to get an undelayed error
14881       // here from access control during the original parse because
14882       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14883       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14884           << Old->getReturnTypeSourceRange();
14885       return true;
14886     }
14887   }
14888 
14889   // The qualifiers of the return types must be the same.
14890   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14891     Diag(New->getLocation(),
14892          diag::err_covariant_return_type_different_qualifications)
14893         << New->getDeclName() << NewTy << OldTy
14894         << New->getReturnTypeSourceRange();
14895     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14896         << Old->getReturnTypeSourceRange();
14897     return true;
14898   }
14899 
14900 
14901   // The new class type must have the same or less qualifiers as the old type.
14902   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14903     Diag(New->getLocation(),
14904          diag::err_covariant_return_type_class_type_more_qualified)
14905         << New->getDeclName() << NewTy << OldTy
14906         << New->getReturnTypeSourceRange();
14907     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14908         << Old->getReturnTypeSourceRange();
14909     return true;
14910   }
14911 
14912   return false;
14913 }
14914 
14915 /// Mark the given method pure.
14916 ///
14917 /// \param Method the method to be marked pure.
14918 ///
14919 /// \param InitRange the source range that covers the "0" initializer.
14920 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14921   SourceLocation EndLoc = InitRange.getEnd();
14922   if (EndLoc.isValid())
14923     Method->setRangeEnd(EndLoc);
14924 
14925   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14926     Method->setPure();
14927     return false;
14928   }
14929 
14930   if (!Method->isInvalidDecl())
14931     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14932       << Method->getDeclName() << InitRange;
14933   return true;
14934 }
14935 
14936 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14937   if (D->getFriendObjectKind())
14938     Diag(D->getLocation(), diag::err_pure_friend);
14939   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14940     CheckPureMethod(M, ZeroLoc);
14941   else
14942     Diag(D->getLocation(), diag::err_illegal_initializer);
14943 }
14944 
14945 /// Determine whether the given declaration is a global variable or
14946 /// static data member.
14947 static bool isNonlocalVariable(const Decl *D) {
14948   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14949     return Var->hasGlobalStorage();
14950 
14951   return false;
14952 }
14953 
14954 /// Invoked when we are about to parse an initializer for the declaration
14955 /// 'Dcl'.
14956 ///
14957 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14958 /// static data member of class X, names should be looked up in the scope of
14959 /// class X. If the declaration had a scope specifier, a scope will have
14960 /// been created and passed in for this purpose. Otherwise, S will be null.
14961 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14962   // If there is no declaration, there was an error parsing it.
14963   if (!D || D->isInvalidDecl())
14964     return;
14965 
14966   // We will always have a nested name specifier here, but this declaration
14967   // might not be out of line if the specifier names the current namespace:
14968   //   extern int n;
14969   //   int ::n = 0;
14970   if (S && D->isOutOfLine())
14971     EnterDeclaratorContext(S, D->getDeclContext());
14972 
14973   // If we are parsing the initializer for a static data member, push a
14974   // new expression evaluation context that is associated with this static
14975   // data member.
14976   if (isNonlocalVariable(D))
14977     PushExpressionEvaluationContext(
14978         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14979 }
14980 
14981 /// Invoked after we are finished parsing an initializer for the declaration D.
14982 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14983   // If there is no declaration, there was an error parsing it.
14984   if (!D || D->isInvalidDecl())
14985     return;
14986 
14987   if (isNonlocalVariable(D))
14988     PopExpressionEvaluationContext();
14989 
14990   if (S && D->isOutOfLine())
14991     ExitDeclaratorContext(S);
14992 }
14993 
14994 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14995 /// C++ if/switch/while/for statement.
14996 /// e.g: "if (int x = f()) {...}"
14997 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14998   // C++ 6.4p2:
14999   // The declarator shall not specify a function or an array.
15000   // The type-specifier-seq shall not contain typedef and shall not declare a
15001   // new class or enumeration.
15002   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
15003          "Parser allowed 'typedef' as storage class of condition decl.");
15004 
15005   Decl *Dcl = ActOnDeclarator(S, D);
15006   if (!Dcl)
15007     return true;
15008 
15009   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
15010     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
15011       << D.getSourceRange();
15012     return true;
15013   }
15014 
15015   return Dcl;
15016 }
15017 
15018 void Sema::LoadExternalVTableUses() {
15019   if (!ExternalSource)
15020     return;
15021 
15022   SmallVector<ExternalVTableUse, 4> VTables;
15023   ExternalSource->ReadUsedVTables(VTables);
15024   SmallVector<VTableUse, 4> NewUses;
15025   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
15026     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
15027       = VTablesUsed.find(VTables[I].Record);
15028     // Even if a definition wasn't required before, it may be required now.
15029     if (Pos != VTablesUsed.end()) {
15030       if (!Pos->second && VTables[I].DefinitionRequired)
15031         Pos->second = true;
15032       continue;
15033     }
15034 
15035     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
15036     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
15037   }
15038 
15039   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
15040 }
15041 
15042 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
15043                           bool DefinitionRequired) {
15044   // Ignore any vtable uses in unevaluated operands or for classes that do
15045   // not have a vtable.
15046   if (!Class->isDynamicClass() || Class->isDependentContext() ||
15047       CurContext->isDependentContext() || isUnevaluatedContext())
15048     return;
15049   // Do not mark as used if compiling for the device outside of the target
15050   // region.
15051   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15052       !isInOpenMPDeclareTargetContext() &&
15053       !isInOpenMPTargetExecutionDirective()) {
15054     if (!DefinitionRequired)
15055       MarkVirtualMembersReferenced(Loc, Class);
15056     return;
15057   }
15058 
15059   // Try to insert this class into the map.
15060   LoadExternalVTableUses();
15061   Class = Class->getCanonicalDecl();
15062   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15063     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15064   if (!Pos.second) {
15065     // If we already had an entry, check to see if we are promoting this vtable
15066     // to require a definition. If so, we need to reappend to the VTableUses
15067     // list, since we may have already processed the first entry.
15068     if (DefinitionRequired && !Pos.first->second) {
15069       Pos.first->second = true;
15070     } else {
15071       // Otherwise, we can early exit.
15072       return;
15073     }
15074   } else {
15075     // The Microsoft ABI requires that we perform the destructor body
15076     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15077     // the deleting destructor is emitted with the vtable, not with the
15078     // destructor definition as in the Itanium ABI.
15079     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15080       CXXDestructorDecl *DD = Class->getDestructor();
15081       if (DD && DD->isVirtual() && !DD->isDeleted()) {
15082         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15083           // If this is an out-of-line declaration, marking it referenced will
15084           // not do anything. Manually call CheckDestructor to look up operator
15085           // delete().
15086           ContextRAII SavedContext(*this, DD);
15087           CheckDestructor(DD);
15088         } else {
15089           MarkFunctionReferenced(Loc, Class->getDestructor());
15090         }
15091       }
15092     }
15093   }
15094 
15095   // Local classes need to have their virtual members marked
15096   // immediately. For all other classes, we mark their virtual members
15097   // at the end of the translation unit.
15098   if (Class->isLocalClass())
15099     MarkVirtualMembersReferenced(Loc, Class);
15100   else
15101     VTableUses.push_back(std::make_pair(Class, Loc));
15102 }
15103 
15104 bool Sema::DefineUsedVTables() {
15105   LoadExternalVTableUses();
15106   if (VTableUses.empty())
15107     return false;
15108 
15109   // Note: The VTableUses vector could grow as a result of marking
15110   // the members of a class as "used", so we check the size each
15111   // time through the loop and prefer indices (which are stable) to
15112   // iterators (which are not).
15113   bool DefinedAnything = false;
15114   for (unsigned I = 0; I != VTableUses.size(); ++I) {
15115     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15116     if (!Class)
15117       continue;
15118     TemplateSpecializationKind ClassTSK =
15119         Class->getTemplateSpecializationKind();
15120 
15121     SourceLocation Loc = VTableUses[I].second;
15122 
15123     bool DefineVTable = true;
15124 
15125     // If this class has a key function, but that key function is
15126     // defined in another translation unit, we don't need to emit the
15127     // vtable even though we're using it.
15128     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15129     if (KeyFunction && !KeyFunction->hasBody()) {
15130       // The key function is in another translation unit.
15131       DefineVTable = false;
15132       TemplateSpecializationKind TSK =
15133           KeyFunction->getTemplateSpecializationKind();
15134       assert(TSK != TSK_ExplicitInstantiationDefinition &&
15135              TSK != TSK_ImplicitInstantiation &&
15136              "Instantiations don't have key functions");
15137       (void)TSK;
15138     } else if (!KeyFunction) {
15139       // If we have a class with no key function that is the subject
15140       // of an explicit instantiation declaration, suppress the
15141       // vtable; it will live with the explicit instantiation
15142       // definition.
15143       bool IsExplicitInstantiationDeclaration =
15144           ClassTSK == TSK_ExplicitInstantiationDeclaration;
15145       for (auto R : Class->redecls()) {
15146         TemplateSpecializationKind TSK
15147           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15148         if (TSK == TSK_ExplicitInstantiationDeclaration)
15149           IsExplicitInstantiationDeclaration = true;
15150         else if (TSK == TSK_ExplicitInstantiationDefinition) {
15151           IsExplicitInstantiationDeclaration = false;
15152           break;
15153         }
15154       }
15155 
15156       if (IsExplicitInstantiationDeclaration)
15157         DefineVTable = false;
15158     }
15159 
15160     // The exception specifications for all virtual members may be needed even
15161     // if we are not providing an authoritative form of the vtable in this TU.
15162     // We may choose to emit it available_externally anyway.
15163     if (!DefineVTable) {
15164       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15165       continue;
15166     }
15167 
15168     // Mark all of the virtual members of this class as referenced, so
15169     // that we can build a vtable. Then, tell the AST consumer that a
15170     // vtable for this class is required.
15171     DefinedAnything = true;
15172     MarkVirtualMembersReferenced(Loc, Class);
15173     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15174     if (VTablesUsed[Canonical])
15175       Consumer.HandleVTable(Class);
15176 
15177     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15178     // no key function or the key function is inlined. Don't warn in C++ ABIs
15179     // that lack key functions, since the user won't be able to make one.
15180     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15181         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15182       const FunctionDecl *KeyFunctionDef = nullptr;
15183       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15184                            KeyFunctionDef->isInlined())) {
15185         Diag(Class->getLocation(),
15186              ClassTSK == TSK_ExplicitInstantiationDefinition
15187                  ? diag::warn_weak_template_vtable
15188                  : diag::warn_weak_vtable)
15189             << Class;
15190       }
15191     }
15192   }
15193   VTableUses.clear();
15194 
15195   return DefinedAnything;
15196 }
15197 
15198 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15199                                                  const CXXRecordDecl *RD) {
15200   for (const auto *I : RD->methods())
15201     if (I->isVirtual() && !I->isPure())
15202       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15203 }
15204 
15205 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15206                                         const CXXRecordDecl *RD) {
15207   // Mark all functions which will appear in RD's vtable as used.
15208   CXXFinalOverriderMap FinalOverriders;
15209   RD->getFinalOverriders(FinalOverriders);
15210   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15211                                             E = FinalOverriders.end();
15212        I != E; ++I) {
15213     for (OverridingMethods::const_iterator OI = I->second.begin(),
15214                                            OE = I->second.end();
15215          OI != OE; ++OI) {
15216       assert(OI->second.size() > 0 && "no final overrider");
15217       CXXMethodDecl *Overrider = OI->second.front().Method;
15218 
15219       // C++ [basic.def.odr]p2:
15220       //   [...] A virtual member function is used if it is not pure. [...]
15221       if (!Overrider->isPure())
15222         MarkFunctionReferenced(Loc, Overrider);
15223     }
15224   }
15225 
15226   // Only classes that have virtual bases need a VTT.
15227   if (RD->getNumVBases() == 0)
15228     return;
15229 
15230   for (const auto &I : RD->bases()) {
15231     const CXXRecordDecl *Base =
15232         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15233     if (Base->getNumVBases() == 0)
15234       continue;
15235     MarkVirtualMembersReferenced(Loc, Base);
15236   }
15237 }
15238 
15239 /// SetIvarInitializers - This routine builds initialization ASTs for the
15240 /// Objective-C implementation whose ivars need be initialized.
15241 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15242   if (!getLangOpts().CPlusPlus)
15243     return;
15244   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15245     SmallVector<ObjCIvarDecl*, 8> ivars;
15246     CollectIvarsToConstructOrDestruct(OID, ivars);
15247     if (ivars.empty())
15248       return;
15249     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15250     for (unsigned i = 0; i < ivars.size(); i++) {
15251       FieldDecl *Field = ivars[i];
15252       if (Field->isInvalidDecl())
15253         continue;
15254 
15255       CXXCtorInitializer *Member;
15256       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15257       InitializationKind InitKind =
15258         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15259 
15260       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15261       ExprResult MemberInit =
15262         InitSeq.Perform(*this, InitEntity, InitKind, None);
15263       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15264       // Note, MemberInit could actually come back empty if no initialization
15265       // is required (e.g., because it would call a trivial default constructor)
15266       if (!MemberInit.get() || MemberInit.isInvalid())
15267         continue;
15268 
15269       Member =
15270         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15271                                          SourceLocation(),
15272                                          MemberInit.getAs<Expr>(),
15273                                          SourceLocation());
15274       AllToInit.push_back(Member);
15275 
15276       // Be sure that the destructor is accessible and is marked as referenced.
15277       if (const RecordType *RecordTy =
15278               Context.getBaseElementType(Field->getType())
15279                   ->getAs<RecordType>()) {
15280         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15281         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15282           MarkFunctionReferenced(Field->getLocation(), Destructor);
15283           CheckDestructorAccess(Field->getLocation(), Destructor,
15284                             PDiag(diag::err_access_dtor_ivar)
15285                               << Context.getBaseElementType(Field->getType()));
15286         }
15287       }
15288     }
15289     ObjCImplementation->setIvarInitializers(Context,
15290                                             AllToInit.data(), AllToInit.size());
15291   }
15292 }
15293 
15294 static
15295 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15296                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15297                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15298                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15299                            Sema &S) {
15300   if (Ctor->isInvalidDecl())
15301     return;
15302 
15303   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15304 
15305   // Target may not be determinable yet, for instance if this is a dependent
15306   // call in an uninstantiated template.
15307   if (Target) {
15308     const FunctionDecl *FNTarget = nullptr;
15309     (void)Target->hasBody(FNTarget);
15310     Target = const_cast<CXXConstructorDecl*>(
15311       cast_or_null<CXXConstructorDecl>(FNTarget));
15312   }
15313 
15314   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15315                      // Avoid dereferencing a null pointer here.
15316                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15317 
15318   if (!Current.insert(Canonical).second)
15319     return;
15320 
15321   // We know that beyond here, we aren't chaining into a cycle.
15322   if (!Target || !Target->isDelegatingConstructor() ||
15323       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15324     Valid.insert(Current.begin(), Current.end());
15325     Current.clear();
15326   // We've hit a cycle.
15327   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15328              Current.count(TCanonical)) {
15329     // If we haven't diagnosed this cycle yet, do so now.
15330     if (!Invalid.count(TCanonical)) {
15331       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15332              diag::warn_delegating_ctor_cycle)
15333         << Ctor;
15334 
15335       // Don't add a note for a function delegating directly to itself.
15336       if (TCanonical != Canonical)
15337         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15338 
15339       CXXConstructorDecl *C = Target;
15340       while (C->getCanonicalDecl() != Canonical) {
15341         const FunctionDecl *FNTarget = nullptr;
15342         (void)C->getTargetConstructor()->hasBody(FNTarget);
15343         assert(FNTarget && "Ctor cycle through bodiless function");
15344 
15345         C = const_cast<CXXConstructorDecl*>(
15346           cast<CXXConstructorDecl>(FNTarget));
15347         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15348       }
15349     }
15350 
15351     Invalid.insert(Current.begin(), Current.end());
15352     Current.clear();
15353   } else {
15354     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15355   }
15356 }
15357 
15358 
15359 void Sema::CheckDelegatingCtorCycles() {
15360   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15361 
15362   for (DelegatingCtorDeclsType::iterator
15363          I = DelegatingCtorDecls.begin(ExternalSource),
15364          E = DelegatingCtorDecls.end();
15365        I != E; ++I)
15366     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15367 
15368   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15369     (*CI)->setInvalidDecl();
15370 }
15371 
15372 namespace {
15373   /// AST visitor that finds references to the 'this' expression.
15374   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15375     Sema &S;
15376 
15377   public:
15378     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15379 
15380     bool VisitCXXThisExpr(CXXThisExpr *E) {
15381       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15382         << E->isImplicit();
15383       return false;
15384     }
15385   };
15386 }
15387 
15388 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15389   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15390   if (!TSInfo)
15391     return false;
15392 
15393   TypeLoc TL = TSInfo->getTypeLoc();
15394   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15395   if (!ProtoTL)
15396     return false;
15397 
15398   // C++11 [expr.prim.general]p3:
15399   //   [The expression this] shall not appear before the optional
15400   //   cv-qualifier-seq and it shall not appear within the declaration of a
15401   //   static member function (although its type and value category are defined
15402   //   within a static member function as they are within a non-static member
15403   //   function). [ Note: this is because declaration matching does not occur
15404   //  until the complete declarator is known. - end note ]
15405   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15406   FindCXXThisExpr Finder(*this);
15407 
15408   // If the return type came after the cv-qualifier-seq, check it now.
15409   if (Proto->hasTrailingReturn() &&
15410       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15411     return true;
15412 
15413   // Check the exception specification.
15414   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15415     return true;
15416 
15417   return checkThisInStaticMemberFunctionAttributes(Method);
15418 }
15419 
15420 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15421   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15422   if (!TSInfo)
15423     return false;
15424 
15425   TypeLoc TL = TSInfo->getTypeLoc();
15426   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15427   if (!ProtoTL)
15428     return false;
15429 
15430   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15431   FindCXXThisExpr Finder(*this);
15432 
15433   switch (Proto->getExceptionSpecType()) {
15434   case EST_Unparsed:
15435   case EST_Uninstantiated:
15436   case EST_Unevaluated:
15437   case EST_BasicNoexcept:
15438   case EST_DynamicNone:
15439   case EST_MSAny:
15440   case EST_None:
15441     break;
15442 
15443   case EST_DependentNoexcept:
15444   case EST_NoexceptFalse:
15445   case EST_NoexceptTrue:
15446     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15447       return true;
15448     LLVM_FALLTHROUGH;
15449 
15450   case EST_Dynamic:
15451     for (const auto &E : Proto->exceptions()) {
15452       if (!Finder.TraverseType(E))
15453         return true;
15454     }
15455     break;
15456   }
15457 
15458   return false;
15459 }
15460 
15461 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15462   FindCXXThisExpr Finder(*this);
15463 
15464   // Check attributes.
15465   for (const auto *A : Method->attrs()) {
15466     // FIXME: This should be emitted by tblgen.
15467     Expr *Arg = nullptr;
15468     ArrayRef<Expr *> Args;
15469     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15470       Arg = G->getArg();
15471     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15472       Arg = G->getArg();
15473     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15474       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15475     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15476       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15477     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15478       Arg = ETLF->getSuccessValue();
15479       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15480     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15481       Arg = STLF->getSuccessValue();
15482       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15483     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15484       Arg = LR->getArg();
15485     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15486       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15487     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15488       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15489     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15490       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15491     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15492       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15493     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15494       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15495 
15496     if (Arg && !Finder.TraverseStmt(Arg))
15497       return true;
15498 
15499     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15500       if (!Finder.TraverseStmt(Args[I]))
15501         return true;
15502     }
15503   }
15504 
15505   return false;
15506 }
15507 
15508 void Sema::checkExceptionSpecification(
15509     bool IsTopLevel, ExceptionSpecificationType EST,
15510     ArrayRef<ParsedType> DynamicExceptions,
15511     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15512     SmallVectorImpl<QualType> &Exceptions,
15513     FunctionProtoType::ExceptionSpecInfo &ESI) {
15514   Exceptions.clear();
15515   ESI.Type = EST;
15516   if (EST == EST_Dynamic) {
15517     Exceptions.reserve(DynamicExceptions.size());
15518     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15519       // FIXME: Preserve type source info.
15520       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15521 
15522       if (IsTopLevel) {
15523         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15524         collectUnexpandedParameterPacks(ET, Unexpanded);
15525         if (!Unexpanded.empty()) {
15526           DiagnoseUnexpandedParameterPacks(
15527               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15528               Unexpanded);
15529           continue;
15530         }
15531       }
15532 
15533       // Check that the type is valid for an exception spec, and
15534       // drop it if not.
15535       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15536         Exceptions.push_back(ET);
15537     }
15538     ESI.Exceptions = Exceptions;
15539     return;
15540   }
15541 
15542   if (isComputedNoexcept(EST)) {
15543     assert((NoexceptExpr->isTypeDependent() ||
15544             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15545             Context.BoolTy) &&
15546            "Parser should have made sure that the expression is boolean");
15547     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15548       ESI.Type = EST_BasicNoexcept;
15549       return;
15550     }
15551 
15552     ESI.NoexceptExpr = NoexceptExpr;
15553     return;
15554   }
15555 }
15556 
15557 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15558              ExceptionSpecificationType EST,
15559              SourceRange SpecificationRange,
15560              ArrayRef<ParsedType> DynamicExceptions,
15561              ArrayRef<SourceRange> DynamicExceptionRanges,
15562              Expr *NoexceptExpr) {
15563   if (!MethodD)
15564     return;
15565 
15566   // Dig out the method we're referring to.
15567   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15568     MethodD = FunTmpl->getTemplatedDecl();
15569 
15570   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15571   if (!Method)
15572     return;
15573 
15574   // Check the exception specification.
15575   llvm::SmallVector<QualType, 4> Exceptions;
15576   FunctionProtoType::ExceptionSpecInfo ESI;
15577   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15578                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15579                               ESI);
15580 
15581   // Update the exception specification on the function type.
15582   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15583 
15584   if (Method->isStatic())
15585     checkThisInStaticMemberFunctionExceptionSpec(Method);
15586 
15587   if (Method->isVirtual()) {
15588     // Check overrides, which we previously had to delay.
15589     for (const CXXMethodDecl *O : Method->overridden_methods())
15590       CheckOverridingFunctionExceptionSpec(Method, O);
15591   }
15592 }
15593 
15594 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15595 ///
15596 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15597                                        SourceLocation DeclStart, Declarator &D,
15598                                        Expr *BitWidth,
15599                                        InClassInitStyle InitStyle,
15600                                        AccessSpecifier AS,
15601                                        const ParsedAttr &MSPropertyAttr) {
15602   IdentifierInfo *II = D.getIdentifier();
15603   if (!II) {
15604     Diag(DeclStart, diag::err_anonymous_property);
15605     return nullptr;
15606   }
15607   SourceLocation Loc = D.getIdentifierLoc();
15608 
15609   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15610   QualType T = TInfo->getType();
15611   if (getLangOpts().CPlusPlus) {
15612     CheckExtraCXXDefaultArguments(D);
15613 
15614     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15615                                         UPPC_DataMemberType)) {
15616       D.setInvalidType();
15617       T = Context.IntTy;
15618       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15619     }
15620   }
15621 
15622   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15623 
15624   if (D.getDeclSpec().isInlineSpecified())
15625     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15626         << getLangOpts().CPlusPlus17;
15627   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15628     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15629          diag::err_invalid_thread)
15630       << DeclSpec::getSpecifierName(TSCS);
15631 
15632   // Check to see if this name was declared as a member previously
15633   NamedDecl *PrevDecl = nullptr;
15634   LookupResult Previous(*this, II, Loc, LookupMemberName,
15635                         ForVisibleRedeclaration);
15636   LookupName(Previous, S);
15637   switch (Previous.getResultKind()) {
15638   case LookupResult::Found:
15639   case LookupResult::FoundUnresolvedValue:
15640     PrevDecl = Previous.getAsSingle<NamedDecl>();
15641     break;
15642 
15643   case LookupResult::FoundOverloaded:
15644     PrevDecl = Previous.getRepresentativeDecl();
15645     break;
15646 
15647   case LookupResult::NotFound:
15648   case LookupResult::NotFoundInCurrentInstantiation:
15649   case LookupResult::Ambiguous:
15650     break;
15651   }
15652 
15653   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15654     // Maybe we will complain about the shadowed template parameter.
15655     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15656     // Just pretend that we didn't see the previous declaration.
15657     PrevDecl = nullptr;
15658   }
15659 
15660   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15661     PrevDecl = nullptr;
15662 
15663   SourceLocation TSSL = D.getBeginLoc();
15664   MSPropertyDecl *NewPD =
15665       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15666                              MSPropertyAttr.getPropertyDataGetter(),
15667                              MSPropertyAttr.getPropertyDataSetter());
15668   ProcessDeclAttributes(TUScope, NewPD, D);
15669   NewPD->setAccess(AS);
15670 
15671   if (NewPD->isInvalidDecl())
15672     Record->setInvalidDecl();
15673 
15674   if (D.getDeclSpec().isModulePrivateSpecified())
15675     NewPD->setModulePrivate();
15676 
15677   if (NewPD->isInvalidDecl() && PrevDecl) {
15678     // Don't introduce NewFD into scope; there's already something
15679     // with the same name in the same scope.
15680   } else if (II) {
15681     PushOnScopeChains(NewPD, S);
15682   } else
15683     Record->addDecl(NewPD);
15684 
15685   return NewPD;
15686 }
15687