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   // If this namespace contains an export-declaration, export it now.
9041   if (DeferredExportedNamespaces.erase(Namespc))
9042     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
9043 }
9044 
9045 CXXRecordDecl *Sema::getStdBadAlloc() const {
9046   return cast_or_null<CXXRecordDecl>(
9047                                   StdBadAlloc.get(Context.getExternalSource()));
9048 }
9049 
9050 EnumDecl *Sema::getStdAlignValT() const {
9051   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9052 }
9053 
9054 NamespaceDecl *Sema::getStdNamespace() const {
9055   return cast_or_null<NamespaceDecl>(
9056                                  StdNamespace.get(Context.getExternalSource()));
9057 }
9058 
9059 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
9060   if (!StdExperimentalNamespaceCache) {
9061     if (auto Std = getStdNamespace()) {
9062       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9063                           SourceLocation(), LookupNamespaceName);
9064       if (!LookupQualifiedName(Result, Std) ||
9065           !(StdExperimentalNamespaceCache =
9066                 Result.getAsSingle<NamespaceDecl>()))
9067         Result.suppressDiagnostics();
9068     }
9069   }
9070   return StdExperimentalNamespaceCache;
9071 }
9072 
9073 namespace {
9074 
9075 enum UnsupportedSTLSelect {
9076   USS_InvalidMember,
9077   USS_MissingMember,
9078   USS_NonTrivial,
9079   USS_Other
9080 };
9081 
9082 struct InvalidSTLDiagnoser {
9083   Sema &S;
9084   SourceLocation Loc;
9085   QualType TyForDiags;
9086 
9087   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9088                       const VarDecl *VD = nullptr) {
9089     {
9090       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9091                << TyForDiags << ((int)Sel);
9092       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9093         assert(!Name.empty());
9094         D << Name;
9095       }
9096     }
9097     if (Sel == USS_InvalidMember) {
9098       S.Diag(VD->getLocation(), diag::note_var_declared_here)
9099           << VD << VD->getSourceRange();
9100     }
9101     return QualType();
9102   }
9103 };
9104 } // namespace
9105 
9106 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9107                                            SourceLocation Loc) {
9108   assert(getLangOpts().CPlusPlus &&
9109          "Looking for comparison category type outside of C++.");
9110 
9111   // Check if we've already successfully checked the comparison category type
9112   // before. If so, skip checking it again.
9113   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9114   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9115     return Info->getType();
9116 
9117   // If lookup failed
9118   if (!Info) {
9119     std::string NameForDiags = "std::";
9120     NameForDiags += ComparisonCategories::getCategoryString(Kind);
9121     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9122         << NameForDiags;
9123     return QualType();
9124   }
9125 
9126   assert(Info->Kind == Kind);
9127   assert(Info->Record);
9128 
9129   // Update the Record decl in case we encountered a forward declaration on our
9130   // first pass. FIXME: This is a bit of a hack.
9131   if (Info->Record->hasDefinition())
9132     Info->Record = Info->Record->getDefinition();
9133 
9134   // Use an elaborated type for diagnostics which has a name containing the
9135   // prepended 'std' namespace but not any inline namespace names.
9136   QualType TyForDiags = [&]() {
9137     auto *NNS =
9138         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9139     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9140   }();
9141 
9142   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9143     return QualType();
9144 
9145   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9146 
9147   if (!Info->Record->isTriviallyCopyable())
9148     return UnsupportedSTLError(USS_NonTrivial);
9149 
9150   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9151     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9152     // Tolerate empty base classes.
9153     if (Base->isEmpty())
9154       continue;
9155     // Reject STL implementations which have at least one non-empty base.
9156     return UnsupportedSTLError();
9157   }
9158 
9159   // Check that the STL has implemented the types using a single integer field.
9160   // This expectation allows better codegen for builtin operators. We require:
9161   //   (1) The class has exactly one field.
9162   //   (2) The field is an integral or enumeration type.
9163   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9164   if (std::distance(FIt, FEnd) != 1 ||
9165       !FIt->getType()->isIntegralOrEnumerationType()) {
9166     return UnsupportedSTLError();
9167   }
9168 
9169   // Build each of the require values and store them in Info.
9170   for (ComparisonCategoryResult CCR :
9171        ComparisonCategories::getPossibleResultsForType(Kind)) {
9172     StringRef MemName = ComparisonCategories::getResultString(CCR);
9173     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9174 
9175     if (!ValInfo)
9176       return UnsupportedSTLError(USS_MissingMember, MemName);
9177 
9178     VarDecl *VD = ValInfo->VD;
9179     assert(VD && "should not be null!");
9180 
9181     // Attempt to diagnose reasons why the STL definition of this type
9182     // might be foobar, including it failing to be a constant expression.
9183     // TODO Handle more ways the lookup or result can be invalid.
9184     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9185         !VD->checkInitIsICE())
9186       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9187 
9188     // Attempt to evaluate the var decl as a constant expression and extract
9189     // the value of its first field as a ICE. If this fails, the STL
9190     // implementation is not supported.
9191     if (!ValInfo->hasValidIntValue())
9192       return UnsupportedSTLError();
9193 
9194     MarkVariableReferenced(Loc, VD);
9195   }
9196 
9197   // We've successfully built the required types and expressions. Update
9198   // the cache and return the newly cached value.
9199   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9200   return Info->getType();
9201 }
9202 
9203 /// Retrieve the special "std" namespace, which may require us to
9204 /// implicitly define the namespace.
9205 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9206   if (!StdNamespace) {
9207     // The "std" namespace has not yet been defined, so build one implicitly.
9208     StdNamespace = NamespaceDecl::Create(Context,
9209                                          Context.getTranslationUnitDecl(),
9210                                          /*Inline=*/false,
9211                                          SourceLocation(), SourceLocation(),
9212                                          &PP.getIdentifierTable().get("std"),
9213                                          /*PrevDecl=*/nullptr);
9214     getStdNamespace()->setImplicit(true);
9215   }
9216 
9217   return getStdNamespace();
9218 }
9219 
9220 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9221   assert(getLangOpts().CPlusPlus &&
9222          "Looking for std::initializer_list outside of C++.");
9223 
9224   // We're looking for implicit instantiations of
9225   // template <typename E> class std::initializer_list.
9226 
9227   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9228     return false;
9229 
9230   ClassTemplateDecl *Template = nullptr;
9231   const TemplateArgument *Arguments = nullptr;
9232 
9233   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9234 
9235     ClassTemplateSpecializationDecl *Specialization =
9236         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9237     if (!Specialization)
9238       return false;
9239 
9240     Template = Specialization->getSpecializedTemplate();
9241     Arguments = Specialization->getTemplateArgs().data();
9242   } else if (const TemplateSpecializationType *TST =
9243                  Ty->getAs<TemplateSpecializationType>()) {
9244     Template = dyn_cast_or_null<ClassTemplateDecl>(
9245         TST->getTemplateName().getAsTemplateDecl());
9246     Arguments = TST->getArgs();
9247   }
9248   if (!Template)
9249     return false;
9250 
9251   if (!StdInitializerList) {
9252     // Haven't recognized std::initializer_list yet, maybe this is it.
9253     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9254     if (TemplateClass->getIdentifier() !=
9255             &PP.getIdentifierTable().get("initializer_list") ||
9256         !getStdNamespace()->InEnclosingNamespaceSetOf(
9257             TemplateClass->getDeclContext()))
9258       return false;
9259     // This is a template called std::initializer_list, but is it the right
9260     // template?
9261     TemplateParameterList *Params = Template->getTemplateParameters();
9262     if (Params->getMinRequiredArguments() != 1)
9263       return false;
9264     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9265       return false;
9266 
9267     // It's the right template.
9268     StdInitializerList = Template;
9269   }
9270 
9271   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9272     return false;
9273 
9274   // This is an instance of std::initializer_list. Find the argument type.
9275   if (Element)
9276     *Element = Arguments[0].getAsType();
9277   return true;
9278 }
9279 
9280 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9281   NamespaceDecl *Std = S.getStdNamespace();
9282   if (!Std) {
9283     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9284     return nullptr;
9285   }
9286 
9287   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9288                       Loc, Sema::LookupOrdinaryName);
9289   if (!S.LookupQualifiedName(Result, Std)) {
9290     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9291     return nullptr;
9292   }
9293   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9294   if (!Template) {
9295     Result.suppressDiagnostics();
9296     // We found something weird. Complain about the first thing we found.
9297     NamedDecl *Found = *Result.begin();
9298     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9299     return nullptr;
9300   }
9301 
9302   // We found some template called std::initializer_list. Now verify that it's
9303   // correct.
9304   TemplateParameterList *Params = Template->getTemplateParameters();
9305   if (Params->getMinRequiredArguments() != 1 ||
9306       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9307     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9308     return nullptr;
9309   }
9310 
9311   return Template;
9312 }
9313 
9314 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9315   if (!StdInitializerList) {
9316     StdInitializerList = LookupStdInitializerList(*this, Loc);
9317     if (!StdInitializerList)
9318       return QualType();
9319   }
9320 
9321   TemplateArgumentListInfo Args(Loc, Loc);
9322   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9323                                        Context.getTrivialTypeSourceInfo(Element,
9324                                                                         Loc)));
9325   return Context.getCanonicalType(
9326       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9327 }
9328 
9329 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9330   // C++ [dcl.init.list]p2:
9331   //   A constructor is an initializer-list constructor if its first parameter
9332   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9333   //   std::initializer_list<E> for some type E, and either there are no other
9334   //   parameters or else all other parameters have default arguments.
9335   if (Ctor->getNumParams() < 1 ||
9336       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9337     return false;
9338 
9339   QualType ArgType = Ctor->getParamDecl(0)->getType();
9340   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9341     ArgType = RT->getPointeeType().getUnqualifiedType();
9342 
9343   return isStdInitializerList(ArgType, nullptr);
9344 }
9345 
9346 /// Determine whether a using statement is in a context where it will be
9347 /// apply in all contexts.
9348 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9349   switch (CurContext->getDeclKind()) {
9350     case Decl::TranslationUnit:
9351       return true;
9352     case Decl::LinkageSpec:
9353       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9354     default:
9355       return false;
9356   }
9357 }
9358 
9359 namespace {
9360 
9361 // Callback to only accept typo corrections that are namespaces.
9362 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
9363 public:
9364   bool ValidateCandidate(const TypoCorrection &candidate) override {
9365     if (NamedDecl *ND = candidate.getCorrectionDecl())
9366       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9367     return false;
9368   }
9369 
9370   std::unique_ptr<CorrectionCandidateCallback> clone() override {
9371     return llvm::make_unique<NamespaceValidatorCCC>(*this);
9372   }
9373 };
9374 
9375 }
9376 
9377 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9378                                        CXXScopeSpec &SS,
9379                                        SourceLocation IdentLoc,
9380                                        IdentifierInfo *Ident) {
9381   R.clear();
9382   NamespaceValidatorCCC CCC{};
9383   if (TypoCorrection Corrected =
9384           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
9385                         Sema::CTK_ErrorRecovery)) {
9386     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9387       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9388       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9389                               Ident->getName().equals(CorrectedStr);
9390       S.diagnoseTypo(Corrected,
9391                      S.PDiag(diag::err_using_directive_member_suggest)
9392                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9393                      S.PDiag(diag::note_namespace_defined_here));
9394     } else {
9395       S.diagnoseTypo(Corrected,
9396                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9397                      S.PDiag(diag::note_namespace_defined_here));
9398     }
9399     R.addDecl(Corrected.getFoundDecl());
9400     return true;
9401   }
9402   return false;
9403 }
9404 
9405 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9406                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9407                                 SourceLocation IdentLoc,
9408                                 IdentifierInfo *NamespcName,
9409                                 const ParsedAttributesView &AttrList) {
9410   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9411   assert(NamespcName && "Invalid NamespcName.");
9412   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9413 
9414   // This can only happen along a recovery path.
9415   while (S->isTemplateParamScope())
9416     S = S->getParent();
9417   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9418 
9419   UsingDirectiveDecl *UDir = nullptr;
9420   NestedNameSpecifier *Qualifier = nullptr;
9421   if (SS.isSet())
9422     Qualifier = SS.getScopeRep();
9423 
9424   // Lookup namespace name.
9425   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9426   LookupParsedName(R, S, &SS);
9427   if (R.isAmbiguous())
9428     return nullptr;
9429 
9430   if (R.empty()) {
9431     R.clear();
9432     // Allow "using namespace std;" or "using namespace ::std;" even if
9433     // "std" hasn't been defined yet, for GCC compatibility.
9434     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9435         NamespcName->isStr("std")) {
9436       Diag(IdentLoc, diag::ext_using_undefined_std);
9437       R.addDecl(getOrCreateStdNamespace());
9438       R.resolveKind();
9439     }
9440     // Otherwise, attempt typo correction.
9441     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9442   }
9443 
9444   if (!R.empty()) {
9445     NamedDecl *Named = R.getRepresentativeDecl();
9446     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9447     assert(NS && "expected namespace decl");
9448 
9449     // The use of a nested name specifier may trigger deprecation warnings.
9450     DiagnoseUseOfDecl(Named, IdentLoc);
9451 
9452     // C++ [namespace.udir]p1:
9453     //   A using-directive specifies that the names in the nominated
9454     //   namespace can be used in the scope in which the
9455     //   using-directive appears after the using-directive. During
9456     //   unqualified name lookup (3.4.1), the names appear as if they
9457     //   were declared in the nearest enclosing namespace which
9458     //   contains both the using-directive and the nominated
9459     //   namespace. [Note: in this context, "contains" means "contains
9460     //   directly or indirectly". ]
9461 
9462     // Find enclosing context containing both using-directive and
9463     // nominated namespace.
9464     DeclContext *CommonAncestor = NS;
9465     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9466       CommonAncestor = CommonAncestor->getParent();
9467 
9468     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9469                                       SS.getWithLocInContext(Context),
9470                                       IdentLoc, Named, CommonAncestor);
9471 
9472     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9473         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9474       Diag(IdentLoc, diag::warn_using_directive_in_header);
9475     }
9476 
9477     PushUsingDirective(S, UDir);
9478   } else {
9479     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9480   }
9481 
9482   if (UDir)
9483     ProcessDeclAttributeList(S, UDir, AttrList);
9484 
9485   return UDir;
9486 }
9487 
9488 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9489   // If the scope has an associated entity and the using directive is at
9490   // namespace or translation unit scope, add the UsingDirectiveDecl into
9491   // its lookup structure so qualified name lookup can find it.
9492   DeclContext *Ctx = S->getEntity();
9493   if (Ctx && !Ctx->isFunctionOrMethod())
9494     Ctx->addDecl(UDir);
9495   else
9496     // Otherwise, it is at block scope. The using-directives will affect lookup
9497     // only to the end of the scope.
9498     S->PushUsingDirective(UDir);
9499 }
9500 
9501 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9502                                   SourceLocation UsingLoc,
9503                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
9504                                   UnqualifiedId &Name,
9505                                   SourceLocation EllipsisLoc,
9506                                   const ParsedAttributesView &AttrList) {
9507   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9508 
9509   if (SS.isEmpty()) {
9510     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9511     return nullptr;
9512   }
9513 
9514   switch (Name.getKind()) {
9515   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9516   case UnqualifiedIdKind::IK_Identifier:
9517   case UnqualifiedIdKind::IK_OperatorFunctionId:
9518   case UnqualifiedIdKind::IK_LiteralOperatorId:
9519   case UnqualifiedIdKind::IK_ConversionFunctionId:
9520     break;
9521 
9522   case UnqualifiedIdKind::IK_ConstructorName:
9523   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9524     // C++11 inheriting constructors.
9525     Diag(Name.getBeginLoc(),
9526          getLangOpts().CPlusPlus11
9527              ? diag::warn_cxx98_compat_using_decl_constructor
9528              : diag::err_using_decl_constructor)
9529         << SS.getRange();
9530 
9531     if (getLangOpts().CPlusPlus11) break;
9532 
9533     return nullptr;
9534 
9535   case UnqualifiedIdKind::IK_DestructorName:
9536     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9537     return nullptr;
9538 
9539   case UnqualifiedIdKind::IK_TemplateId:
9540     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9541         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9542     return nullptr;
9543 
9544   case UnqualifiedIdKind::IK_DeductionGuideName:
9545     llvm_unreachable("cannot parse qualified deduction guide name");
9546   }
9547 
9548   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9549   DeclarationName TargetName = TargetNameInfo.getName();
9550   if (!TargetName)
9551     return nullptr;
9552 
9553   // Warn about access declarations.
9554   if (UsingLoc.isInvalid()) {
9555     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9556                                  ? diag::err_access_decl
9557                                  : diag::warn_access_decl_deprecated)
9558         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9559   }
9560 
9561   if (EllipsisLoc.isInvalid()) {
9562     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9563         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9564       return nullptr;
9565   } else {
9566     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9567         !TargetNameInfo.containsUnexpandedParameterPack()) {
9568       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9569         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9570       EllipsisLoc = SourceLocation();
9571     }
9572   }
9573 
9574   NamedDecl *UD =
9575       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9576                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9577                             /*IsInstantiation*/false);
9578   if (UD)
9579     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9580 
9581   return UD;
9582 }
9583 
9584 /// Determine whether a using declaration considers the given
9585 /// declarations as "equivalent", e.g., if they are redeclarations of
9586 /// the same entity or are both typedefs of the same type.
9587 static bool
9588 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9589   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9590     return true;
9591 
9592   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9593     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9594       return Context.hasSameType(TD1->getUnderlyingType(),
9595                                  TD2->getUnderlyingType());
9596 
9597   return false;
9598 }
9599 
9600 
9601 /// Determines whether to create a using shadow decl for a particular
9602 /// decl, given the set of decls existing prior to this using lookup.
9603 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9604                                 const LookupResult &Previous,
9605                                 UsingShadowDecl *&PrevShadow) {
9606   // Diagnose finding a decl which is not from a base class of the
9607   // current class.  We do this now because there are cases where this
9608   // function will silently decide not to build a shadow decl, which
9609   // will pre-empt further diagnostics.
9610   //
9611   // We don't need to do this in C++11 because we do the check once on
9612   // the qualifier.
9613   //
9614   // FIXME: diagnose the following if we care enough:
9615   //   struct A { int foo; };
9616   //   struct B : A { using A::foo; };
9617   //   template <class T> struct C : A {};
9618   //   template <class T> struct D : C<T> { using B::foo; } // <---
9619   // This is invalid (during instantiation) in C++03 because B::foo
9620   // resolves to the using decl in B, which is not a base class of D<T>.
9621   // We can't diagnose it immediately because C<T> is an unknown
9622   // specialization.  The UsingShadowDecl in D<T> then points directly
9623   // to A::foo, which will look well-formed when we instantiate.
9624   // The right solution is to not collapse the shadow-decl chain.
9625   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9626     DeclContext *OrigDC = Orig->getDeclContext();
9627 
9628     // Handle enums and anonymous structs.
9629     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9630     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9631     while (OrigRec->isAnonymousStructOrUnion())
9632       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9633 
9634     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9635       if (OrigDC == CurContext) {
9636         Diag(Using->getLocation(),
9637              diag::err_using_decl_nested_name_specifier_is_current_class)
9638           << Using->getQualifierLoc().getSourceRange();
9639         Diag(Orig->getLocation(), diag::note_using_decl_target);
9640         Using->setInvalidDecl();
9641         return true;
9642       }
9643 
9644       Diag(Using->getQualifierLoc().getBeginLoc(),
9645            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9646         << Using->getQualifier()
9647         << cast<CXXRecordDecl>(CurContext)
9648         << Using->getQualifierLoc().getSourceRange();
9649       Diag(Orig->getLocation(), diag::note_using_decl_target);
9650       Using->setInvalidDecl();
9651       return true;
9652     }
9653   }
9654 
9655   if (Previous.empty()) return false;
9656 
9657   NamedDecl *Target = Orig;
9658   if (isa<UsingShadowDecl>(Target))
9659     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9660 
9661   // If the target happens to be one of the previous declarations, we
9662   // don't have a conflict.
9663   //
9664   // FIXME: but we might be increasing its access, in which case we
9665   // should redeclare it.
9666   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9667   bool FoundEquivalentDecl = false;
9668   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9669          I != E; ++I) {
9670     NamedDecl *D = (*I)->getUnderlyingDecl();
9671     // We can have UsingDecls in our Previous results because we use the same
9672     // LookupResult for checking whether the UsingDecl itself is a valid
9673     // redeclaration.
9674     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9675       continue;
9676 
9677     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9678       // C++ [class.mem]p19:
9679       //   If T is the name of a class, then [every named member other than
9680       //   a non-static data member] shall have a name different from T
9681       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9682           !isa<IndirectFieldDecl>(Target) &&
9683           !isa<UnresolvedUsingValueDecl>(Target) &&
9684           DiagnoseClassNameShadow(
9685               CurContext,
9686               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9687         return true;
9688     }
9689 
9690     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9691       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9692         PrevShadow = Shadow;
9693       FoundEquivalentDecl = true;
9694     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9695       // We don't conflict with an existing using shadow decl of an equivalent
9696       // declaration, but we're not a redeclaration of it.
9697       FoundEquivalentDecl = true;
9698     }
9699 
9700     if (isVisible(D))
9701       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9702   }
9703 
9704   if (FoundEquivalentDecl)
9705     return false;
9706 
9707   if (FunctionDecl *FD = Target->getAsFunction()) {
9708     NamedDecl *OldDecl = nullptr;
9709     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9710                           /*IsForUsingDecl*/ true)) {
9711     case Ovl_Overload:
9712       return false;
9713 
9714     case Ovl_NonFunction:
9715       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9716       break;
9717 
9718     // We found a decl with the exact signature.
9719     case Ovl_Match:
9720       // If we're in a record, we want to hide the target, so we
9721       // return true (without a diagnostic) to tell the caller not to
9722       // build a shadow decl.
9723       if (CurContext->isRecord())
9724         return true;
9725 
9726       // If we're not in a record, this is an error.
9727       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9728       break;
9729     }
9730 
9731     Diag(Target->getLocation(), diag::note_using_decl_target);
9732     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9733     Using->setInvalidDecl();
9734     return true;
9735   }
9736 
9737   // Target is not a function.
9738 
9739   if (isa<TagDecl>(Target)) {
9740     // No conflict between a tag and a non-tag.
9741     if (!Tag) return false;
9742 
9743     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9744     Diag(Target->getLocation(), diag::note_using_decl_target);
9745     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9746     Using->setInvalidDecl();
9747     return true;
9748   }
9749 
9750   // No conflict between a tag and a non-tag.
9751   if (!NonTag) return false;
9752 
9753   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9754   Diag(Target->getLocation(), diag::note_using_decl_target);
9755   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9756   Using->setInvalidDecl();
9757   return true;
9758 }
9759 
9760 /// Determine whether a direct base class is a virtual base class.
9761 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9762   if (!Derived->getNumVBases())
9763     return false;
9764   for (auto &B : Derived->bases())
9765     if (B.getType()->getAsCXXRecordDecl() == Base)
9766       return B.isVirtual();
9767   llvm_unreachable("not a direct base class");
9768 }
9769 
9770 /// Builds a shadow declaration corresponding to a 'using' declaration.
9771 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9772                                             UsingDecl *UD,
9773                                             NamedDecl *Orig,
9774                                             UsingShadowDecl *PrevDecl) {
9775   // If we resolved to another shadow declaration, just coalesce them.
9776   NamedDecl *Target = Orig;
9777   if (isa<UsingShadowDecl>(Target)) {
9778     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9779     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9780   }
9781 
9782   NamedDecl *NonTemplateTarget = Target;
9783   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9784     NonTemplateTarget = TargetTD->getTemplatedDecl();
9785 
9786   UsingShadowDecl *Shadow;
9787   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9788     bool IsVirtualBase =
9789         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9790                             UD->getQualifier()->getAsRecordDecl());
9791     Shadow = ConstructorUsingShadowDecl::Create(
9792         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9793   } else {
9794     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9795                                      Target);
9796   }
9797   UD->addShadowDecl(Shadow);
9798 
9799   Shadow->setAccess(UD->getAccess());
9800   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9801     Shadow->setInvalidDecl();
9802 
9803   Shadow->setPreviousDecl(PrevDecl);
9804 
9805   if (S)
9806     PushOnScopeChains(Shadow, S);
9807   else
9808     CurContext->addDecl(Shadow);
9809 
9810 
9811   return Shadow;
9812 }
9813 
9814 /// Hides a using shadow declaration.  This is required by the current
9815 /// using-decl implementation when a resolvable using declaration in a
9816 /// class is followed by a declaration which would hide or override
9817 /// one or more of the using decl's targets; for example:
9818 ///
9819 ///   struct Base { void foo(int); };
9820 ///   struct Derived : Base {
9821 ///     using Base::foo;
9822 ///     void foo(int);
9823 ///   };
9824 ///
9825 /// The governing language is C++03 [namespace.udecl]p12:
9826 ///
9827 ///   When a using-declaration brings names from a base class into a
9828 ///   derived class scope, member functions in the derived class
9829 ///   override and/or hide member functions with the same name and
9830 ///   parameter types in a base class (rather than conflicting).
9831 ///
9832 /// There are two ways to implement this:
9833 ///   (1) optimistically create shadow decls when they're not hidden
9834 ///       by existing declarations, or
9835 ///   (2) don't create any shadow decls (or at least don't make them
9836 ///       visible) until we've fully parsed/instantiated the class.
9837 /// The problem with (1) is that we might have to retroactively remove
9838 /// a shadow decl, which requires several O(n) operations because the
9839 /// decl structures are (very reasonably) not designed for removal.
9840 /// (2) avoids this but is very fiddly and phase-dependent.
9841 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9842   if (Shadow->getDeclName().getNameKind() ==
9843         DeclarationName::CXXConversionFunctionName)
9844     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9845 
9846   // Remove it from the DeclContext...
9847   Shadow->getDeclContext()->removeDecl(Shadow);
9848 
9849   // ...and the scope, if applicable...
9850   if (S) {
9851     S->RemoveDecl(Shadow);
9852     IdResolver.RemoveDecl(Shadow);
9853   }
9854 
9855   // ...and the using decl.
9856   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9857 
9858   // TODO: complain somehow if Shadow was used.  It shouldn't
9859   // be possible for this to happen, because...?
9860 }
9861 
9862 /// Find the base specifier for a base class with the given type.
9863 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9864                                                 QualType DesiredBase,
9865                                                 bool &AnyDependentBases) {
9866   // Check whether the named type is a direct base class.
9867   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9868   for (auto &Base : Derived->bases()) {
9869     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9870     if (CanonicalDesiredBase == BaseType)
9871       return &Base;
9872     if (BaseType->isDependentType())
9873       AnyDependentBases = true;
9874   }
9875   return nullptr;
9876 }
9877 
9878 namespace {
9879 class UsingValidatorCCC final : public CorrectionCandidateCallback {
9880 public:
9881   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9882                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9883       : HasTypenameKeyword(HasTypenameKeyword),
9884         IsInstantiation(IsInstantiation), OldNNS(NNS),
9885         RequireMemberOf(RequireMemberOf) {}
9886 
9887   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9888     NamedDecl *ND = Candidate.getCorrectionDecl();
9889 
9890     // Keywords are not valid here.
9891     if (!ND || isa<NamespaceDecl>(ND))
9892       return false;
9893 
9894     // Completely unqualified names are invalid for a 'using' declaration.
9895     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9896       return false;
9897 
9898     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9899     // reject.
9900 
9901     if (RequireMemberOf) {
9902       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9903       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9904         // No-one ever wants a using-declaration to name an injected-class-name
9905         // of a base class, unless they're declaring an inheriting constructor.
9906         ASTContext &Ctx = ND->getASTContext();
9907         if (!Ctx.getLangOpts().CPlusPlus11)
9908           return false;
9909         QualType FoundType = Ctx.getRecordType(FoundRecord);
9910 
9911         // Check that the injected-class-name is named as a member of its own
9912         // type; we don't want to suggest 'using Derived::Base;', since that
9913         // means something else.
9914         NestedNameSpecifier *Specifier =
9915             Candidate.WillReplaceSpecifier()
9916                 ? Candidate.getCorrectionSpecifier()
9917                 : OldNNS;
9918         if (!Specifier->getAsType() ||
9919             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9920           return false;
9921 
9922         // Check that this inheriting constructor declaration actually names a
9923         // direct base class of the current class.
9924         bool AnyDependentBases = false;
9925         if (!findDirectBaseWithType(RequireMemberOf,
9926                                     Ctx.getRecordType(FoundRecord),
9927                                     AnyDependentBases) &&
9928             !AnyDependentBases)
9929           return false;
9930       } else {
9931         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9932         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9933           return false;
9934 
9935         // FIXME: Check that the base class member is accessible?
9936       }
9937     } else {
9938       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9939       if (FoundRecord && FoundRecord->isInjectedClassName())
9940         return false;
9941     }
9942 
9943     if (isa<TypeDecl>(ND))
9944       return HasTypenameKeyword || !IsInstantiation;
9945 
9946     return !HasTypenameKeyword;
9947   }
9948 
9949   std::unique_ptr<CorrectionCandidateCallback> clone() override {
9950     return llvm::make_unique<UsingValidatorCCC>(*this);
9951   }
9952 
9953 private:
9954   bool HasTypenameKeyword;
9955   bool IsInstantiation;
9956   NestedNameSpecifier *OldNNS;
9957   CXXRecordDecl *RequireMemberOf;
9958 };
9959 } // end anonymous namespace
9960 
9961 /// Builds a using declaration.
9962 ///
9963 /// \param IsInstantiation - Whether this call arises from an
9964 ///   instantiation of an unresolved using declaration.  We treat
9965 ///   the lookup differently for these declarations.
9966 NamedDecl *Sema::BuildUsingDeclaration(
9967     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9968     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9969     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9970     const ParsedAttributesView &AttrList, bool IsInstantiation) {
9971   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9972   SourceLocation IdentLoc = NameInfo.getLoc();
9973   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9974 
9975   // FIXME: We ignore attributes for now.
9976 
9977   // For an inheriting constructor declaration, the name of the using
9978   // declaration is the name of a constructor in this class, not in the
9979   // base class.
9980   DeclarationNameInfo UsingName = NameInfo;
9981   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9982     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9983       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9984           Context.getCanonicalType(Context.getRecordType(RD))));
9985 
9986   // Do the redeclaration lookup in the current scope.
9987   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9988                         ForVisibleRedeclaration);
9989   Previous.setHideTags(false);
9990   if (S) {
9991     LookupName(Previous, S);
9992 
9993     // It is really dumb that we have to do this.
9994     LookupResult::Filter F = Previous.makeFilter();
9995     while (F.hasNext()) {
9996       NamedDecl *D = F.next();
9997       if (!isDeclInScope(D, CurContext, S))
9998         F.erase();
9999       // If we found a local extern declaration that's not ordinarily visible,
10000       // and this declaration is being added to a non-block scope, ignore it.
10001       // We're only checking for scope conflicts here, not also for violations
10002       // of the linkage rules.
10003       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
10004                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
10005         F.erase();
10006     }
10007     F.done();
10008   } else {
10009     assert(IsInstantiation && "no scope in non-instantiation");
10010     if (CurContext->isRecord())
10011       LookupQualifiedName(Previous, CurContext);
10012     else {
10013       // No redeclaration check is needed here; in non-member contexts we
10014       // diagnosed all possible conflicts with other using-declarations when
10015       // building the template:
10016       //
10017       // For a dependent non-type using declaration, the only valid case is
10018       // if we instantiate to a single enumerator. We check for conflicts
10019       // between shadow declarations we introduce, and we check in the template
10020       // definition for conflicts between a non-type using declaration and any
10021       // other declaration, which together covers all cases.
10022       //
10023       // A dependent typename using declaration will never successfully
10024       // instantiate, since it will always name a class member, so we reject
10025       // that in the template definition.
10026     }
10027   }
10028 
10029   // Check for invalid redeclarations.
10030   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
10031                                   SS, IdentLoc, Previous))
10032     return nullptr;
10033 
10034   // Check for bad qualifiers.
10035   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
10036                               IdentLoc))
10037     return nullptr;
10038 
10039   DeclContext *LookupContext = computeDeclContext(SS);
10040   NamedDecl *D;
10041   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10042   if (!LookupContext || EllipsisLoc.isValid()) {
10043     if (HasTypenameKeyword) {
10044       // FIXME: not all declaration name kinds are legal here
10045       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
10046                                               UsingLoc, TypenameLoc,
10047                                               QualifierLoc,
10048                                               IdentLoc, NameInfo.getName(),
10049                                               EllipsisLoc);
10050     } else {
10051       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
10052                                            QualifierLoc, NameInfo, EllipsisLoc);
10053     }
10054     D->setAccess(AS);
10055     CurContext->addDecl(D);
10056     return D;
10057   }
10058 
10059   auto Build = [&](bool Invalid) {
10060     UsingDecl *UD =
10061         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10062                           UsingName, HasTypenameKeyword);
10063     UD->setAccess(AS);
10064     CurContext->addDecl(UD);
10065     UD->setInvalidDecl(Invalid);
10066     return UD;
10067   };
10068   auto BuildInvalid = [&]{ return Build(true); };
10069   auto BuildValid = [&]{ return Build(false); };
10070 
10071   if (RequireCompleteDeclContext(SS, LookupContext))
10072     return BuildInvalid();
10073 
10074   // Look up the target name.
10075   LookupResult R(*this, NameInfo, LookupOrdinaryName);
10076 
10077   // Unlike most lookups, we don't always want to hide tag
10078   // declarations: tag names are visible through the using declaration
10079   // even if hidden by ordinary names, *except* in a dependent context
10080   // where it's important for the sanity of two-phase lookup.
10081   if (!IsInstantiation)
10082     R.setHideTags(false);
10083 
10084   // For the purposes of this lookup, we have a base object type
10085   // equal to that of the current context.
10086   if (CurContext->isRecord()) {
10087     R.setBaseObjectType(
10088                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10089   }
10090 
10091   LookupQualifiedName(R, LookupContext);
10092 
10093   // Try to correct typos if possible. If constructor name lookup finds no
10094   // results, that means the named class has no explicit constructors, and we
10095   // suppressed declaring implicit ones (probably because it's dependent or
10096   // invalid).
10097   if (R.empty() &&
10098       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10099     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10100     // it will believe that glibc provides a ::gets in cases where it does not,
10101     // and will try to pull it into namespace std with a using-declaration.
10102     // Just ignore the using-declaration in that case.
10103     auto *II = NameInfo.getName().getAsIdentifierInfo();
10104     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10105         CurContext->isStdNamespace() &&
10106         isa<TranslationUnitDecl>(LookupContext) &&
10107         getSourceManager().isInSystemHeader(UsingLoc))
10108       return nullptr;
10109     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10110                           dyn_cast<CXXRecordDecl>(CurContext));
10111     if (TypoCorrection Corrected =
10112             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
10113                         CTK_ErrorRecovery)) {
10114       // We reject candidates where DroppedSpecifier == true, hence the
10115       // literal '0' below.
10116       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10117                                 << NameInfo.getName() << LookupContext << 0
10118                                 << SS.getRange());
10119 
10120       // If we picked a correction with no attached Decl we can't do anything
10121       // useful with it, bail out.
10122       NamedDecl *ND = Corrected.getCorrectionDecl();
10123       if (!ND)
10124         return BuildInvalid();
10125 
10126       // If we corrected to an inheriting constructor, handle it as one.
10127       auto *RD = dyn_cast<CXXRecordDecl>(ND);
10128       if (RD && RD->isInjectedClassName()) {
10129         // The parent of the injected class name is the class itself.
10130         RD = cast<CXXRecordDecl>(RD->getParent());
10131 
10132         // Fix up the information we'll use to build the using declaration.
10133         if (Corrected.WillReplaceSpecifier()) {
10134           NestedNameSpecifierLocBuilder Builder;
10135           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10136                               QualifierLoc.getSourceRange());
10137           QualifierLoc = Builder.getWithLocInContext(Context);
10138         }
10139 
10140         // In this case, the name we introduce is the name of a derived class
10141         // constructor.
10142         auto *CurClass = cast<CXXRecordDecl>(CurContext);
10143         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10144             Context.getCanonicalType(Context.getRecordType(CurClass))));
10145         UsingName.setNamedTypeInfo(nullptr);
10146         for (auto *Ctor : LookupConstructors(RD))
10147           R.addDecl(Ctor);
10148         R.resolveKind();
10149       } else {
10150         // FIXME: Pick up all the declarations if we found an overloaded
10151         // function.
10152         UsingName.setName(ND->getDeclName());
10153         R.addDecl(ND);
10154       }
10155     } else {
10156       Diag(IdentLoc, diag::err_no_member)
10157         << NameInfo.getName() << LookupContext << SS.getRange();
10158       return BuildInvalid();
10159     }
10160   }
10161 
10162   if (R.isAmbiguous())
10163     return BuildInvalid();
10164 
10165   if (HasTypenameKeyword) {
10166     // If we asked for a typename and got a non-type decl, error out.
10167     if (!R.getAsSingle<TypeDecl>()) {
10168       Diag(IdentLoc, diag::err_using_typename_non_type);
10169       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10170         Diag((*I)->getUnderlyingDecl()->getLocation(),
10171              diag::note_using_decl_target);
10172       return BuildInvalid();
10173     }
10174   } else {
10175     // If we asked for a non-typename and we got a type, error out,
10176     // but only if this is an instantiation of an unresolved using
10177     // decl.  Otherwise just silently find the type name.
10178     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10179       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10180       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10181       return BuildInvalid();
10182     }
10183   }
10184 
10185   // C++14 [namespace.udecl]p6:
10186   // A using-declaration shall not name a namespace.
10187   if (R.getAsSingle<NamespaceDecl>()) {
10188     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10189       << SS.getRange();
10190     return BuildInvalid();
10191   }
10192 
10193   // C++14 [namespace.udecl]p7:
10194   // A using-declaration shall not name a scoped enumerator.
10195   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10196     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10197       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10198         << SS.getRange();
10199       return BuildInvalid();
10200     }
10201   }
10202 
10203   UsingDecl *UD = BuildValid();
10204 
10205   // Some additional rules apply to inheriting constructors.
10206   if (UsingName.getName().getNameKind() ==
10207         DeclarationName::CXXConstructorName) {
10208     // Suppress access diagnostics; the access check is instead performed at the
10209     // point of use for an inheriting constructor.
10210     R.suppressDiagnostics();
10211     if (CheckInheritingConstructorUsingDecl(UD))
10212       return UD;
10213   }
10214 
10215   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10216     UsingShadowDecl *PrevDecl = nullptr;
10217     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10218       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10219   }
10220 
10221   return UD;
10222 }
10223 
10224 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10225                                     ArrayRef<NamedDecl *> Expansions) {
10226   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10227          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10228          isa<UsingPackDecl>(InstantiatedFrom));
10229 
10230   auto *UPD =
10231       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10232   UPD->setAccess(InstantiatedFrom->getAccess());
10233   CurContext->addDecl(UPD);
10234   return UPD;
10235 }
10236 
10237 /// Additional checks for a using declaration referring to a constructor name.
10238 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10239   assert(!UD->hasTypename() && "expecting a constructor name");
10240 
10241   const Type *SourceType = UD->getQualifier()->getAsType();
10242   assert(SourceType &&
10243          "Using decl naming constructor doesn't have type in scope spec.");
10244   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10245 
10246   // Check whether the named type is a direct base class.
10247   bool AnyDependentBases = false;
10248   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10249                                       AnyDependentBases);
10250   if (!Base && !AnyDependentBases) {
10251     Diag(UD->getUsingLoc(),
10252          diag::err_using_decl_constructor_not_in_direct_base)
10253       << UD->getNameInfo().getSourceRange()
10254       << QualType(SourceType, 0) << TargetClass;
10255     UD->setInvalidDecl();
10256     return true;
10257   }
10258 
10259   if (Base)
10260     Base->setInheritConstructors();
10261 
10262   return false;
10263 }
10264 
10265 /// Checks that the given using declaration is not an invalid
10266 /// redeclaration.  Note that this is checking only for the using decl
10267 /// itself, not for any ill-formedness among the UsingShadowDecls.
10268 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10269                                        bool HasTypenameKeyword,
10270                                        const CXXScopeSpec &SS,
10271                                        SourceLocation NameLoc,
10272                                        const LookupResult &Prev) {
10273   NestedNameSpecifier *Qual = SS.getScopeRep();
10274 
10275   // C++03 [namespace.udecl]p8:
10276   // C++0x [namespace.udecl]p10:
10277   //   A using-declaration is a declaration and can therefore be used
10278   //   repeatedly where (and only where) multiple declarations are
10279   //   allowed.
10280   //
10281   // That's in non-member contexts.
10282   if (!CurContext->getRedeclContext()->isRecord()) {
10283     // A dependent qualifier outside a class can only ever resolve to an
10284     // enumeration type. Therefore it conflicts with any other non-type
10285     // declaration in the same scope.
10286     // FIXME: How should we check for dependent type-type conflicts at block
10287     // scope?
10288     if (Qual->isDependent() && !HasTypenameKeyword) {
10289       for (auto *D : Prev) {
10290         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10291           bool OldCouldBeEnumerator =
10292               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10293           Diag(NameLoc,
10294                OldCouldBeEnumerator ? diag::err_redefinition
10295                                     : diag::err_redefinition_different_kind)
10296               << Prev.getLookupName();
10297           Diag(D->getLocation(), diag::note_previous_definition);
10298           return true;
10299         }
10300       }
10301     }
10302     return false;
10303   }
10304 
10305   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10306     NamedDecl *D = *I;
10307 
10308     bool DTypename;
10309     NestedNameSpecifier *DQual;
10310     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10311       DTypename = UD->hasTypename();
10312       DQual = UD->getQualifier();
10313     } else if (UnresolvedUsingValueDecl *UD
10314                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10315       DTypename = false;
10316       DQual = UD->getQualifier();
10317     } else if (UnresolvedUsingTypenameDecl *UD
10318                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10319       DTypename = true;
10320       DQual = UD->getQualifier();
10321     } else continue;
10322 
10323     // using decls differ if one says 'typename' and the other doesn't.
10324     // FIXME: non-dependent using decls?
10325     if (HasTypenameKeyword != DTypename) continue;
10326 
10327     // using decls differ if they name different scopes (but note that
10328     // template instantiation can cause this check to trigger when it
10329     // didn't before instantiation).
10330     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10331         Context.getCanonicalNestedNameSpecifier(DQual))
10332       continue;
10333 
10334     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10335     Diag(D->getLocation(), diag::note_using_decl) << 1;
10336     return true;
10337   }
10338 
10339   return false;
10340 }
10341 
10342 
10343 /// Checks that the given nested-name qualifier used in a using decl
10344 /// in the current context is appropriately related to the current
10345 /// scope.  If an error is found, diagnoses it and returns true.
10346 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10347                                    bool HasTypename,
10348                                    const CXXScopeSpec &SS,
10349                                    const DeclarationNameInfo &NameInfo,
10350                                    SourceLocation NameLoc) {
10351   DeclContext *NamedContext = computeDeclContext(SS);
10352 
10353   if (!CurContext->isRecord()) {
10354     // C++03 [namespace.udecl]p3:
10355     // C++0x [namespace.udecl]p8:
10356     //   A using-declaration for a class member shall be a member-declaration.
10357 
10358     // If we weren't able to compute a valid scope, it might validly be a
10359     // dependent class scope or a dependent enumeration unscoped scope. If
10360     // we have a 'typename' keyword, the scope must resolve to a class type.
10361     if ((HasTypename && !NamedContext) ||
10362         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10363       auto *RD = NamedContext
10364                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10365                      : nullptr;
10366       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10367         RD = nullptr;
10368 
10369       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10370         << SS.getRange();
10371 
10372       // If we have a complete, non-dependent source type, try to suggest a
10373       // way to get the same effect.
10374       if (!RD)
10375         return true;
10376 
10377       // Find what this using-declaration was referring to.
10378       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10379       R.setHideTags(false);
10380       R.suppressDiagnostics();
10381       LookupQualifiedName(R, RD);
10382 
10383       if (R.getAsSingle<TypeDecl>()) {
10384         if (getLangOpts().CPlusPlus11) {
10385           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10386           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10387             << 0 // alias declaration
10388             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10389                                           NameInfo.getName().getAsString() +
10390                                               " = ");
10391         } else {
10392           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10393           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10394           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10395             << 1 // typedef declaration
10396             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10397             << FixItHint::CreateInsertion(
10398                    InsertLoc, " " + NameInfo.getName().getAsString());
10399         }
10400       } else if (R.getAsSingle<VarDecl>()) {
10401         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10402         // repeating the type of the static data member here.
10403         FixItHint FixIt;
10404         if (getLangOpts().CPlusPlus11) {
10405           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10406           FixIt = FixItHint::CreateReplacement(
10407               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10408         }
10409 
10410         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10411           << 2 // reference declaration
10412           << FixIt;
10413       } else if (R.getAsSingle<EnumConstantDecl>()) {
10414         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10415         // repeating the type of the enumeration here, and we can't do so if
10416         // the type is anonymous.
10417         FixItHint FixIt;
10418         if (getLangOpts().CPlusPlus11) {
10419           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10420           FixIt = FixItHint::CreateReplacement(
10421               UsingLoc,
10422               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10423         }
10424 
10425         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10426           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10427           << FixIt;
10428       }
10429       return true;
10430     }
10431 
10432     // Otherwise, this might be valid.
10433     return false;
10434   }
10435 
10436   // The current scope is a record.
10437 
10438   // If the named context is dependent, we can't decide much.
10439   if (!NamedContext) {
10440     // FIXME: in C++0x, we can diagnose if we can prove that the
10441     // nested-name-specifier does not refer to a base class, which is
10442     // still possible in some cases.
10443 
10444     // Otherwise we have to conservatively report that things might be
10445     // okay.
10446     return false;
10447   }
10448 
10449   if (!NamedContext->isRecord()) {
10450     // Ideally this would point at the last name in the specifier,
10451     // but we don't have that level of source info.
10452     Diag(SS.getRange().getBegin(),
10453          diag::err_using_decl_nested_name_specifier_is_not_class)
10454       << SS.getScopeRep() << SS.getRange();
10455     return true;
10456   }
10457 
10458   if (!NamedContext->isDependentContext() &&
10459       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10460     return true;
10461 
10462   if (getLangOpts().CPlusPlus11) {
10463     // C++11 [namespace.udecl]p3:
10464     //   In a using-declaration used as a member-declaration, the
10465     //   nested-name-specifier shall name a base class of the class
10466     //   being defined.
10467 
10468     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10469                                  cast<CXXRecordDecl>(NamedContext))) {
10470       if (CurContext == NamedContext) {
10471         Diag(NameLoc,
10472              diag::err_using_decl_nested_name_specifier_is_current_class)
10473           << SS.getRange();
10474         return true;
10475       }
10476 
10477       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10478         Diag(SS.getRange().getBegin(),
10479              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10480           << SS.getScopeRep()
10481           << cast<CXXRecordDecl>(CurContext)
10482           << SS.getRange();
10483       }
10484       return true;
10485     }
10486 
10487     return false;
10488   }
10489 
10490   // C++03 [namespace.udecl]p4:
10491   //   A using-declaration used as a member-declaration shall refer
10492   //   to a member of a base class of the class being defined [etc.].
10493 
10494   // Salient point: SS doesn't have to name a base class as long as
10495   // lookup only finds members from base classes.  Therefore we can
10496   // diagnose here only if we can prove that that can't happen,
10497   // i.e. if the class hierarchies provably don't intersect.
10498 
10499   // TODO: it would be nice if "definitely valid" results were cached
10500   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10501   // need to be repeated.
10502 
10503   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10504   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10505     Bases.insert(Base);
10506     return true;
10507   };
10508 
10509   // Collect all bases. Return false if we find a dependent base.
10510   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10511     return false;
10512 
10513   // Returns true if the base is dependent or is one of the accumulated base
10514   // classes.
10515   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10516     return !Bases.count(Base);
10517   };
10518 
10519   // Return false if the class has a dependent base or if it or one
10520   // of its bases is present in the base set of the current context.
10521   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10522       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10523     return false;
10524 
10525   Diag(SS.getRange().getBegin(),
10526        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10527     << SS.getScopeRep()
10528     << cast<CXXRecordDecl>(CurContext)
10529     << SS.getRange();
10530 
10531   return true;
10532 }
10533 
10534 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10535                                   MultiTemplateParamsArg TemplateParamLists,
10536                                   SourceLocation UsingLoc, UnqualifiedId &Name,
10537                                   const ParsedAttributesView &AttrList,
10538                                   TypeResult Type, Decl *DeclFromDeclSpec) {
10539   // Skip up to the relevant declaration scope.
10540   while (S->isTemplateParamScope())
10541     S = S->getParent();
10542   assert((S->getFlags() & Scope::DeclScope) &&
10543          "got alias-declaration outside of declaration scope");
10544 
10545   if (Type.isInvalid())
10546     return nullptr;
10547 
10548   bool Invalid = false;
10549   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10550   TypeSourceInfo *TInfo = nullptr;
10551   GetTypeFromParser(Type.get(), &TInfo);
10552 
10553   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10554     return nullptr;
10555 
10556   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10557                                       UPPC_DeclarationType)) {
10558     Invalid = true;
10559     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10560                                              TInfo->getTypeLoc().getBeginLoc());
10561   }
10562 
10563   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10564                         TemplateParamLists.size()
10565                             ? forRedeclarationInCurContext()
10566                             : ForVisibleRedeclaration);
10567   LookupName(Previous, S);
10568 
10569   // Warn about shadowing the name of a template parameter.
10570   if (Previous.isSingleResult() &&
10571       Previous.getFoundDecl()->isTemplateParameter()) {
10572     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10573     Previous.clear();
10574   }
10575 
10576   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10577          "name in alias declaration must be an identifier");
10578   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10579                                                Name.StartLocation,
10580                                                Name.Identifier, TInfo);
10581 
10582   NewTD->setAccess(AS);
10583 
10584   if (Invalid)
10585     NewTD->setInvalidDecl();
10586 
10587   ProcessDeclAttributeList(S, NewTD, AttrList);
10588   AddPragmaAttributes(S, NewTD);
10589 
10590   CheckTypedefForVariablyModifiedType(S, NewTD);
10591   Invalid |= NewTD->isInvalidDecl();
10592 
10593   bool Redeclaration = false;
10594 
10595   NamedDecl *NewND;
10596   if (TemplateParamLists.size()) {
10597     TypeAliasTemplateDecl *OldDecl = nullptr;
10598     TemplateParameterList *OldTemplateParams = nullptr;
10599 
10600     if (TemplateParamLists.size() != 1) {
10601       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10602         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10603          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10604     }
10605     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10606 
10607     // Check that we can declare a template here.
10608     if (CheckTemplateDeclScope(S, TemplateParams))
10609       return nullptr;
10610 
10611     // Only consider previous declarations in the same scope.
10612     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10613                          /*ExplicitInstantiationOrSpecialization*/false);
10614     if (!Previous.empty()) {
10615       Redeclaration = true;
10616 
10617       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10618       if (!OldDecl && !Invalid) {
10619         Diag(UsingLoc, diag::err_redefinition_different_kind)
10620           << Name.Identifier;
10621 
10622         NamedDecl *OldD = Previous.getRepresentativeDecl();
10623         if (OldD->getLocation().isValid())
10624           Diag(OldD->getLocation(), diag::note_previous_definition);
10625 
10626         Invalid = true;
10627       }
10628 
10629       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10630         if (TemplateParameterListsAreEqual(TemplateParams,
10631                                            OldDecl->getTemplateParameters(),
10632                                            /*Complain=*/true,
10633                                            TPL_TemplateMatch))
10634           OldTemplateParams =
10635               OldDecl->getMostRecentDecl()->getTemplateParameters();
10636         else
10637           Invalid = true;
10638 
10639         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10640         if (!Invalid &&
10641             !Context.hasSameType(OldTD->getUnderlyingType(),
10642                                  NewTD->getUnderlyingType())) {
10643           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10644           // but we can't reasonably accept it.
10645           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10646             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10647           if (OldTD->getLocation().isValid())
10648             Diag(OldTD->getLocation(), diag::note_previous_definition);
10649           Invalid = true;
10650         }
10651       }
10652     }
10653 
10654     // Merge any previous default template arguments into our parameters,
10655     // and check the parameter list.
10656     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10657                                    TPC_TypeAliasTemplate))
10658       return nullptr;
10659 
10660     TypeAliasTemplateDecl *NewDecl =
10661       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10662                                     Name.Identifier, TemplateParams,
10663                                     NewTD);
10664     NewTD->setDescribedAliasTemplate(NewDecl);
10665 
10666     NewDecl->setAccess(AS);
10667 
10668     if (Invalid)
10669       NewDecl->setInvalidDecl();
10670     else if (OldDecl) {
10671       NewDecl->setPreviousDecl(OldDecl);
10672       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10673     }
10674 
10675     NewND = NewDecl;
10676   } else {
10677     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10678       setTagNameForLinkagePurposes(TD, NewTD);
10679       handleTagNumbering(TD, S);
10680     }
10681     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10682     NewND = NewTD;
10683   }
10684 
10685   PushOnScopeChains(NewND, S);
10686   ActOnDocumentableDecl(NewND);
10687   return NewND;
10688 }
10689 
10690 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10691                                    SourceLocation AliasLoc,
10692                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10693                                    SourceLocation IdentLoc,
10694                                    IdentifierInfo *Ident) {
10695 
10696   // Lookup the namespace name.
10697   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10698   LookupParsedName(R, S, &SS);
10699 
10700   if (R.isAmbiguous())
10701     return nullptr;
10702 
10703   if (R.empty()) {
10704     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10705       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10706       return nullptr;
10707     }
10708   }
10709   assert(!R.isAmbiguous() && !R.empty());
10710   NamedDecl *ND = R.getRepresentativeDecl();
10711 
10712   // Check if we have a previous declaration with the same name.
10713   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10714                      ForVisibleRedeclaration);
10715   LookupName(PrevR, S);
10716 
10717   // Check we're not shadowing a template parameter.
10718   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10719     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10720     PrevR.clear();
10721   }
10722 
10723   // Filter out any other lookup result from an enclosing scope.
10724   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10725                        /*AllowInlineNamespace*/false);
10726 
10727   // Find the previous declaration and check that we can redeclare it.
10728   NamespaceAliasDecl *Prev = nullptr;
10729   if (PrevR.isSingleResult()) {
10730     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10731     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10732       // We already have an alias with the same name that points to the same
10733       // namespace; check that it matches.
10734       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10735         Prev = AD;
10736       } else if (isVisible(PrevDecl)) {
10737         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10738           << Alias;
10739         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10740           << AD->getNamespace();
10741         return nullptr;
10742       }
10743     } else if (isVisible(PrevDecl)) {
10744       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10745                             ? diag::err_redefinition
10746                             : diag::err_redefinition_different_kind;
10747       Diag(AliasLoc, DiagID) << Alias;
10748       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10749       return nullptr;
10750     }
10751   }
10752 
10753   // The use of a nested name specifier may trigger deprecation warnings.
10754   DiagnoseUseOfDecl(ND, IdentLoc);
10755 
10756   NamespaceAliasDecl *AliasDecl =
10757     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10758                                Alias, SS.getWithLocInContext(Context),
10759                                IdentLoc, ND);
10760   if (Prev)
10761     AliasDecl->setPreviousDecl(Prev);
10762 
10763   PushOnScopeChains(AliasDecl, S);
10764   return AliasDecl;
10765 }
10766 
10767 namespace {
10768 struct SpecialMemberExceptionSpecInfo
10769     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10770   SourceLocation Loc;
10771   Sema::ImplicitExceptionSpecification ExceptSpec;
10772 
10773   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10774                                  Sema::CXXSpecialMember CSM,
10775                                  Sema::InheritedConstructorInfo *ICI,
10776                                  SourceLocation Loc)
10777       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10778 
10779   bool visitBase(CXXBaseSpecifier *Base);
10780   bool visitField(FieldDecl *FD);
10781 
10782   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10783                            unsigned Quals);
10784 
10785   void visitSubobjectCall(Subobject Subobj,
10786                           Sema::SpecialMemberOverloadResult SMOR);
10787 };
10788 }
10789 
10790 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10791   auto *RT = Base->getType()->getAs<RecordType>();
10792   if (!RT)
10793     return false;
10794 
10795   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10796   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10797   if (auto *BaseCtor = SMOR.getMethod()) {
10798     visitSubobjectCall(Base, BaseCtor);
10799     return false;
10800   }
10801 
10802   visitClassSubobject(BaseClass, Base, 0);
10803   return false;
10804 }
10805 
10806 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10807   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10808     Expr *E = FD->getInClassInitializer();
10809     if (!E)
10810       // FIXME: It's a little wasteful to build and throw away a
10811       // CXXDefaultInitExpr here.
10812       // FIXME: We should have a single context note pointing at Loc, and
10813       // this location should be MD->getLocation() instead, since that's
10814       // the location where we actually use the default init expression.
10815       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10816     if (E)
10817       ExceptSpec.CalledExpr(E);
10818   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10819                             ->getAs<RecordType>()) {
10820     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10821                         FD->getType().getCVRQualifiers());
10822   }
10823   return false;
10824 }
10825 
10826 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10827                                                          Subobject Subobj,
10828                                                          unsigned Quals) {
10829   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10830   bool IsMutable = Field && Field->isMutable();
10831   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10832 }
10833 
10834 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10835     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10836   // Note, if lookup fails, it doesn't matter what exception specification we
10837   // choose because the special member will be deleted.
10838   if (CXXMethodDecl *MD = SMOR.getMethod())
10839     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10840 }
10841 
10842 namespace {
10843 /// RAII object to register a special member as being currently declared.
10844 struct ComputingExceptionSpec {
10845   Sema &S;
10846 
10847   ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
10848       : S(S) {
10849     Sema::CodeSynthesisContext Ctx;
10850     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
10851     Ctx.PointOfInstantiation = Loc;
10852     Ctx.Entity = MD;
10853     S.pushCodeSynthesisContext(Ctx);
10854   }
10855   ~ComputingExceptionSpec() {
10856     S.popCodeSynthesisContext();
10857   }
10858 };
10859 }
10860 
10861 static Sema::ImplicitExceptionSpecification
10862 ComputeDefaultedSpecialMemberExceptionSpec(
10863     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10864     Sema::InheritedConstructorInfo *ICI) {
10865   ComputingExceptionSpec CES(S, MD, Loc);
10866 
10867   CXXRecordDecl *ClassDecl = MD->getParent();
10868 
10869   // C++ [except.spec]p14:
10870   //   An implicitly declared special member function (Clause 12) shall have an
10871   //   exception-specification. [...]
10872   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
10873   if (ClassDecl->isInvalidDecl())
10874     return Info.ExceptSpec;
10875 
10876   // FIXME: If this diagnostic fires, we're probably missing a check for
10877   // attempting to resolve an exception specification before it's known
10878   // at a higher level.
10879   if (S.RequireCompleteType(MD->getLocation(),
10880                             S.Context.getRecordType(ClassDecl),
10881                             diag::err_exception_spec_incomplete_type))
10882     return Info.ExceptSpec;
10883 
10884   // C++1z [except.spec]p7:
10885   //   [Look for exceptions thrown by] a constructor selected [...] to
10886   //   initialize a potentially constructed subobject,
10887   // C++1z [except.spec]p8:
10888   //   The exception specification for an implicitly-declared destructor, or a
10889   //   destructor without a noexcept-specifier, is potentially-throwing if and
10890   //   only if any of the destructors for any of its potentially constructed
10891   //   subojects is potentially throwing.
10892   // FIXME: We respect the first rule but ignore the "potentially constructed"
10893   // in the second rule to resolve a core issue (no number yet) that would have
10894   // us reject:
10895   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10896   //   struct B : A {};
10897   //   struct C : B { void f(); };
10898   // ... due to giving B::~B() a non-throwing exception specification.
10899   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10900                                 : Info.VisitAllBases);
10901 
10902   return Info.ExceptSpec;
10903 }
10904 
10905 namespace {
10906 /// RAII object to register a special member as being currently declared.
10907 struct DeclaringSpecialMember {
10908   Sema &S;
10909   Sema::SpecialMemberDecl D;
10910   Sema::ContextRAII SavedContext;
10911   bool WasAlreadyBeingDeclared;
10912 
10913   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10914       : S(S), D(RD, CSM), SavedContext(S, RD) {
10915     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10916     if (WasAlreadyBeingDeclared)
10917       // This almost never happens, but if it does, ensure that our cache
10918       // doesn't contain a stale result.
10919       S.SpecialMemberCache.clear();
10920     else {
10921       // Register a note to be produced if we encounter an error while
10922       // declaring the special member.
10923       Sema::CodeSynthesisContext Ctx;
10924       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10925       // FIXME: We don't have a location to use here. Using the class's
10926       // location maintains the fiction that we declare all special members
10927       // with the class, but (1) it's not clear that lying about that helps our
10928       // users understand what's going on, and (2) there may be outer contexts
10929       // on the stack (some of which are relevant) and printing them exposes
10930       // our lies.
10931       Ctx.PointOfInstantiation = RD->getLocation();
10932       Ctx.Entity = RD;
10933       Ctx.SpecialMember = CSM;
10934       S.pushCodeSynthesisContext(Ctx);
10935     }
10936   }
10937   ~DeclaringSpecialMember() {
10938     if (!WasAlreadyBeingDeclared) {
10939       S.SpecialMembersBeingDeclared.erase(D);
10940       S.popCodeSynthesisContext();
10941     }
10942   }
10943 
10944   /// Are we already trying to declare this special member?
10945   bool isAlreadyBeingDeclared() const {
10946     return WasAlreadyBeingDeclared;
10947   }
10948 };
10949 }
10950 
10951 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10952   // Look up any existing declarations, but don't trigger declaration of all
10953   // implicit special members with this name.
10954   DeclarationName Name = FD->getDeclName();
10955   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10956                  ForExternalRedeclaration);
10957   for (auto *D : FD->getParent()->lookup(Name))
10958     if (auto *Acceptable = R.getAcceptableDecl(D))
10959       R.addDecl(Acceptable);
10960   R.resolveKind();
10961   R.suppressDiagnostics();
10962 
10963   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10964 }
10965 
10966 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
10967                                           QualType ResultTy,
10968                                           ArrayRef<QualType> Args) {
10969   // Build an exception specification pointing back at this constructor.
10970   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
10971 
10972   if (getLangOpts().OpenCLCPlusPlus) {
10973     // OpenCL: Implicitly defaulted special member are of the generic address
10974     // space.
10975     EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
10976   }
10977 
10978   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
10979   SpecialMem->setType(QT);
10980 }
10981 
10982 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10983                                                      CXXRecordDecl *ClassDecl) {
10984   // C++ [class.ctor]p5:
10985   //   A default constructor for a class X is a constructor of class X
10986   //   that can be called without an argument. If there is no
10987   //   user-declared constructor for class X, a default constructor is
10988   //   implicitly declared. An implicitly-declared default constructor
10989   //   is an inline public member of its class.
10990   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10991          "Should not build implicit default constructor!");
10992 
10993   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10994   if (DSM.isAlreadyBeingDeclared())
10995     return nullptr;
10996 
10997   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10998                                                      CXXDefaultConstructor,
10999                                                      false);
11000 
11001   // Create the actual constructor declaration.
11002   CanQualType ClassType
11003     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11004   SourceLocation ClassLoc = ClassDecl->getLocation();
11005   DeclarationName Name
11006     = Context.DeclarationNames.getCXXConstructorName(ClassType);
11007   DeclarationNameInfo NameInfo(Name, ClassLoc);
11008   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
11009       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
11010       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
11011       /*isImplicitlyDeclared=*/true, Constexpr);
11012   DefaultCon->setAccess(AS_public);
11013   DefaultCon->setDefaulted();
11014 
11015   if (getLangOpts().CUDA) {
11016     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
11017                                             DefaultCon,
11018                                             /* ConstRHS */ false,
11019                                             /* Diagnose */ false);
11020   }
11021 
11022   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
11023 
11024   // We don't need to use SpecialMemberIsTrivial here; triviality for default
11025   // constructors is easy to compute.
11026   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
11027 
11028   // Note that we have declared this constructor.
11029   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
11030 
11031   Scope *S = getScopeForContext(ClassDecl);
11032   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
11033 
11034   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
11035     SetDeclDeleted(DefaultCon, ClassLoc);
11036 
11037   if (S)
11038     PushOnScopeChains(DefaultCon, S, false);
11039   ClassDecl->addDecl(DefaultCon);
11040 
11041   return DefaultCon;
11042 }
11043 
11044 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
11045                                             CXXConstructorDecl *Constructor) {
11046   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
11047           !Constructor->doesThisDeclarationHaveABody() &&
11048           !Constructor->isDeleted()) &&
11049     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
11050   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11051     return;
11052 
11053   CXXRecordDecl *ClassDecl = Constructor->getParent();
11054   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
11055 
11056   SynthesizedFunctionScope Scope(*this, Constructor);
11057 
11058   // The exception specification is needed because we are defining the
11059   // function.
11060   ResolveExceptionSpec(CurrentLocation,
11061                        Constructor->getType()->castAs<FunctionProtoType>());
11062   MarkVTableUsed(CurrentLocation, ClassDecl);
11063 
11064   // Add a context note for diagnostics produced after this point.
11065   Scope.addContextNote(CurrentLocation);
11066 
11067   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11068     Constructor->setInvalidDecl();
11069     return;
11070   }
11071 
11072   SourceLocation Loc = Constructor->getEndLoc().isValid()
11073                            ? Constructor->getEndLoc()
11074                            : Constructor->getLocation();
11075   Constructor->setBody(new (Context) CompoundStmt(Loc));
11076   Constructor->markUsed(Context);
11077 
11078   if (ASTMutationListener *L = getASTMutationListener()) {
11079     L->CompletedImplicitDefinition(Constructor);
11080   }
11081 
11082   DiagnoseUninitializedFields(*this, Constructor);
11083 }
11084 
11085 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
11086   // Perform any delayed checks on exception specifications.
11087   CheckDelayedMemberExceptionSpecs();
11088 }
11089 
11090 /// Find or create the fake constructor we synthesize to model constructing an
11091 /// object of a derived class via a constructor of a base class.
11092 CXXConstructorDecl *
11093 Sema::findInheritingConstructor(SourceLocation Loc,
11094                                 CXXConstructorDecl *BaseCtor,
11095                                 ConstructorUsingShadowDecl *Shadow) {
11096   CXXRecordDecl *Derived = Shadow->getParent();
11097   SourceLocation UsingLoc = Shadow->getLocation();
11098 
11099   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11100   // For now we use the name of the base class constructor as a member of the
11101   // derived class to indicate a (fake) inherited constructor name.
11102   DeclarationName Name = BaseCtor->getDeclName();
11103 
11104   // Check to see if we already have a fake constructor for this inherited
11105   // constructor call.
11106   for (NamedDecl *Ctor : Derived->lookup(Name))
11107     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11108                                ->getInheritedConstructor()
11109                                .getConstructor(),
11110                            BaseCtor))
11111       return cast<CXXConstructorDecl>(Ctor);
11112 
11113   DeclarationNameInfo NameInfo(Name, UsingLoc);
11114   TypeSourceInfo *TInfo =
11115       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11116   FunctionProtoTypeLoc ProtoLoc =
11117       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11118 
11119   // Check the inherited constructor is valid and find the list of base classes
11120   // from which it was inherited.
11121   InheritedConstructorInfo ICI(*this, Loc, Shadow);
11122 
11123   bool Constexpr =
11124       BaseCtor->isConstexpr() &&
11125       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11126                                         false, BaseCtor, &ICI);
11127 
11128   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11129       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11130       BaseCtor->isExplicit(), /*Inline=*/true,
11131       /*ImplicitlyDeclared=*/true, Constexpr,
11132       InheritedConstructor(Shadow, BaseCtor));
11133   if (Shadow->isInvalidDecl())
11134     DerivedCtor->setInvalidDecl();
11135 
11136   // Build an unevaluated exception specification for this fake constructor.
11137   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11138   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11139   EPI.ExceptionSpec.Type = EST_Unevaluated;
11140   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11141   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11142                                                FPT->getParamTypes(), EPI));
11143 
11144   // Build the parameter declarations.
11145   SmallVector<ParmVarDecl *, 16> ParamDecls;
11146   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11147     TypeSourceInfo *TInfo =
11148         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11149     ParmVarDecl *PD = ParmVarDecl::Create(
11150         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11151         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
11152     PD->setScopeInfo(0, I);
11153     PD->setImplicit();
11154     // Ensure attributes are propagated onto parameters (this matters for
11155     // format, pass_object_size, ...).
11156     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11157     ParamDecls.push_back(PD);
11158     ProtoLoc.setParam(I, PD);
11159   }
11160 
11161   // Set up the new constructor.
11162   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11163   DerivedCtor->setAccess(BaseCtor->getAccess());
11164   DerivedCtor->setParams(ParamDecls);
11165   Derived->addDecl(DerivedCtor);
11166 
11167   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11168     SetDeclDeleted(DerivedCtor, UsingLoc);
11169 
11170   return DerivedCtor;
11171 }
11172 
11173 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11174   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11175                                Ctor->getInheritedConstructor().getShadowDecl());
11176   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11177                             /*Diagnose*/true);
11178 }
11179 
11180 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11181                                        CXXConstructorDecl *Constructor) {
11182   CXXRecordDecl *ClassDecl = Constructor->getParent();
11183   assert(Constructor->getInheritedConstructor() &&
11184          !Constructor->doesThisDeclarationHaveABody() &&
11185          !Constructor->isDeleted());
11186   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11187     return;
11188 
11189   // Initializations are performed "as if by a defaulted default constructor",
11190   // so enter the appropriate scope.
11191   SynthesizedFunctionScope Scope(*this, Constructor);
11192 
11193   // The exception specification is needed because we are defining the
11194   // function.
11195   ResolveExceptionSpec(CurrentLocation,
11196                        Constructor->getType()->castAs<FunctionProtoType>());
11197   MarkVTableUsed(CurrentLocation, ClassDecl);
11198 
11199   // Add a context note for diagnostics produced after this point.
11200   Scope.addContextNote(CurrentLocation);
11201 
11202   ConstructorUsingShadowDecl *Shadow =
11203       Constructor->getInheritedConstructor().getShadowDecl();
11204   CXXConstructorDecl *InheritedCtor =
11205       Constructor->getInheritedConstructor().getConstructor();
11206 
11207   // [class.inhctor.init]p1:
11208   //   initialization proceeds as if a defaulted default constructor is used to
11209   //   initialize the D object and each base class subobject from which the
11210   //   constructor was inherited
11211 
11212   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11213   CXXRecordDecl *RD = Shadow->getParent();
11214   SourceLocation InitLoc = Shadow->getLocation();
11215 
11216   // Build explicit initializers for all base classes from which the
11217   // constructor was inherited.
11218   SmallVector<CXXCtorInitializer*, 8> Inits;
11219   for (bool VBase : {false, true}) {
11220     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11221       if (B.isVirtual() != VBase)
11222         continue;
11223 
11224       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11225       if (!BaseRD)
11226         continue;
11227 
11228       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11229       if (!BaseCtor.first)
11230         continue;
11231 
11232       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11233       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11234           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11235 
11236       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11237       Inits.push_back(new (Context) CXXCtorInitializer(
11238           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11239           SourceLocation()));
11240     }
11241   }
11242 
11243   // We now proceed as if for a defaulted default constructor, with the relevant
11244   // initializers replaced.
11245 
11246   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11247     Constructor->setInvalidDecl();
11248     return;
11249   }
11250 
11251   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11252   Constructor->markUsed(Context);
11253 
11254   if (ASTMutationListener *L = getASTMutationListener()) {
11255     L->CompletedImplicitDefinition(Constructor);
11256   }
11257 
11258   DiagnoseUninitializedFields(*this, Constructor);
11259 }
11260 
11261 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11262   // C++ [class.dtor]p2:
11263   //   If a class has no user-declared destructor, a destructor is
11264   //   declared implicitly. An implicitly-declared destructor is an
11265   //   inline public member of its class.
11266   assert(ClassDecl->needsImplicitDestructor());
11267 
11268   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11269   if (DSM.isAlreadyBeingDeclared())
11270     return nullptr;
11271 
11272   // Create the actual destructor declaration.
11273   CanQualType ClassType
11274     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11275   SourceLocation ClassLoc = ClassDecl->getLocation();
11276   DeclarationName Name
11277     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11278   DeclarationNameInfo NameInfo(Name, ClassLoc);
11279   CXXDestructorDecl *Destructor
11280       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11281                                   QualType(), nullptr, /*isInline=*/true,
11282                                   /*isImplicitlyDeclared=*/true);
11283   Destructor->setAccess(AS_public);
11284   Destructor->setDefaulted();
11285 
11286   if (getLangOpts().CUDA) {
11287     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11288                                             Destructor,
11289                                             /* ConstRHS */ false,
11290                                             /* Diagnose */ false);
11291   }
11292 
11293   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
11294 
11295   // We don't need to use SpecialMemberIsTrivial here; triviality for
11296   // destructors is easy to compute.
11297   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11298   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11299                                 ClassDecl->hasTrivialDestructorForCall());
11300 
11301   // Note that we have declared this destructor.
11302   ++getASTContext().NumImplicitDestructorsDeclared;
11303 
11304   Scope *S = getScopeForContext(ClassDecl);
11305   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11306 
11307   // We can't check whether an implicit destructor is deleted before we complete
11308   // the definition of the class, because its validity depends on the alignment
11309   // of the class. We'll check this from ActOnFields once the class is complete.
11310   if (ClassDecl->isCompleteDefinition() &&
11311       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11312     SetDeclDeleted(Destructor, ClassLoc);
11313 
11314   // Introduce this destructor into its scope.
11315   if (S)
11316     PushOnScopeChains(Destructor, S, false);
11317   ClassDecl->addDecl(Destructor);
11318 
11319   return Destructor;
11320 }
11321 
11322 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11323                                     CXXDestructorDecl *Destructor) {
11324   assert((Destructor->isDefaulted() &&
11325           !Destructor->doesThisDeclarationHaveABody() &&
11326           !Destructor->isDeleted()) &&
11327          "DefineImplicitDestructor - call it for implicit default dtor");
11328   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11329     return;
11330 
11331   CXXRecordDecl *ClassDecl = Destructor->getParent();
11332   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11333 
11334   SynthesizedFunctionScope Scope(*this, Destructor);
11335 
11336   // The exception specification is needed because we are defining the
11337   // function.
11338   ResolveExceptionSpec(CurrentLocation,
11339                        Destructor->getType()->castAs<FunctionProtoType>());
11340   MarkVTableUsed(CurrentLocation, ClassDecl);
11341 
11342   // Add a context note for diagnostics produced after this point.
11343   Scope.addContextNote(CurrentLocation);
11344 
11345   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11346                                          Destructor->getParent());
11347 
11348   if (CheckDestructor(Destructor)) {
11349     Destructor->setInvalidDecl();
11350     return;
11351   }
11352 
11353   SourceLocation Loc = Destructor->getEndLoc().isValid()
11354                            ? Destructor->getEndLoc()
11355                            : Destructor->getLocation();
11356   Destructor->setBody(new (Context) CompoundStmt(Loc));
11357   Destructor->markUsed(Context);
11358 
11359   if (ASTMutationListener *L = getASTMutationListener()) {
11360     L->CompletedImplicitDefinition(Destructor);
11361   }
11362 }
11363 
11364 /// Perform any semantic analysis which needs to be delayed until all
11365 /// pending class member declarations have been parsed.
11366 void Sema::ActOnFinishCXXMemberDecls() {
11367   // If the context is an invalid C++ class, just suppress these checks.
11368   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11369     if (Record->isInvalidDecl()) {
11370       DelayedOverridingExceptionSpecChecks.clear();
11371       DelayedEquivalentExceptionSpecChecks.clear();
11372       DelayedDefaultedMemberExceptionSpecs.clear();
11373       return;
11374     }
11375     checkForMultipleExportedDefaultConstructors(*this, Record);
11376   }
11377 }
11378 
11379 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11380   referenceDLLExportedClassMethods();
11381 }
11382 
11383 void Sema::referenceDLLExportedClassMethods() {
11384   if (!DelayedDllExportClasses.empty()) {
11385     // Calling ReferenceDllExportedMembers might cause the current function to
11386     // be called again, so use a local copy of DelayedDllExportClasses.
11387     SmallVector<CXXRecordDecl *, 4> WorkList;
11388     std::swap(DelayedDllExportClasses, WorkList);
11389     for (CXXRecordDecl *Class : WorkList)
11390       ReferenceDllExportedMembers(*this, Class);
11391   }
11392 }
11393 
11394 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11395   assert(getLangOpts().CPlusPlus11 &&
11396          "adjusting dtor exception specs was introduced in c++11");
11397 
11398   if (Destructor->isDependentContext())
11399     return;
11400 
11401   // C++11 [class.dtor]p3:
11402   //   A declaration of a destructor that does not have an exception-
11403   //   specification is implicitly considered to have the same exception-
11404   //   specification as an implicit declaration.
11405   const FunctionProtoType *DtorType = Destructor->getType()->
11406                                         getAs<FunctionProtoType>();
11407   if (DtorType->hasExceptionSpec())
11408     return;
11409 
11410   // Replace the destructor's type, building off the existing one. Fortunately,
11411   // the only thing of interest in the destructor type is its extended info.
11412   // The return and arguments are fixed.
11413   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11414   EPI.ExceptionSpec.Type = EST_Unevaluated;
11415   EPI.ExceptionSpec.SourceDecl = Destructor;
11416   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11417 
11418   // FIXME: If the destructor has a body that could throw, and the newly created
11419   // spec doesn't allow exceptions, we should emit a warning, because this
11420   // change in behavior can break conforming C++03 programs at runtime.
11421   // However, we don't have a body or an exception specification yet, so it
11422   // needs to be done somewhere else.
11423 }
11424 
11425 namespace {
11426 /// An abstract base class for all helper classes used in building the
11427 //  copy/move operators. These classes serve as factory functions and help us
11428 //  avoid using the same Expr* in the AST twice.
11429 class ExprBuilder {
11430   ExprBuilder(const ExprBuilder&) = delete;
11431   ExprBuilder &operator=(const ExprBuilder&) = delete;
11432 
11433 protected:
11434   static Expr *assertNotNull(Expr *E) {
11435     assert(E && "Expression construction must not fail.");
11436     return E;
11437   }
11438 
11439 public:
11440   ExprBuilder() {}
11441   virtual ~ExprBuilder() {}
11442 
11443   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11444 };
11445 
11446 class RefBuilder: public ExprBuilder {
11447   VarDecl *Var;
11448   QualType VarType;
11449 
11450 public:
11451   Expr *build(Sema &S, SourceLocation Loc) const override {
11452     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11453   }
11454 
11455   RefBuilder(VarDecl *Var, QualType VarType)
11456       : Var(Var), VarType(VarType) {}
11457 };
11458 
11459 class ThisBuilder: public ExprBuilder {
11460 public:
11461   Expr *build(Sema &S, SourceLocation Loc) const override {
11462     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11463   }
11464 };
11465 
11466 class CastBuilder: public ExprBuilder {
11467   const ExprBuilder &Builder;
11468   QualType Type;
11469   ExprValueKind Kind;
11470   const CXXCastPath &Path;
11471 
11472 public:
11473   Expr *build(Sema &S, SourceLocation Loc) const override {
11474     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11475                                              CK_UncheckedDerivedToBase, Kind,
11476                                              &Path).get());
11477   }
11478 
11479   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11480               const CXXCastPath &Path)
11481       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11482 };
11483 
11484 class DerefBuilder: public ExprBuilder {
11485   const ExprBuilder &Builder;
11486 
11487 public:
11488   Expr *build(Sema &S, SourceLocation Loc) const override {
11489     return assertNotNull(
11490         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11491   }
11492 
11493   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11494 };
11495 
11496 class MemberBuilder: public ExprBuilder {
11497   const ExprBuilder &Builder;
11498   QualType Type;
11499   CXXScopeSpec SS;
11500   bool IsArrow;
11501   LookupResult &MemberLookup;
11502 
11503 public:
11504   Expr *build(Sema &S, SourceLocation Loc) const override {
11505     return assertNotNull(S.BuildMemberReferenceExpr(
11506         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11507         nullptr, MemberLookup, nullptr, nullptr).get());
11508   }
11509 
11510   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11511                 LookupResult &MemberLookup)
11512       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11513         MemberLookup(MemberLookup) {}
11514 };
11515 
11516 class MoveCastBuilder: public ExprBuilder {
11517   const ExprBuilder &Builder;
11518 
11519 public:
11520   Expr *build(Sema &S, SourceLocation Loc) const override {
11521     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11522   }
11523 
11524   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11525 };
11526 
11527 class LvalueConvBuilder: public ExprBuilder {
11528   const ExprBuilder &Builder;
11529 
11530 public:
11531   Expr *build(Sema &S, SourceLocation Loc) const override {
11532     return assertNotNull(
11533         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11534   }
11535 
11536   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11537 };
11538 
11539 class SubscriptBuilder: public ExprBuilder {
11540   const ExprBuilder &Base;
11541   const ExprBuilder &Index;
11542 
11543 public:
11544   Expr *build(Sema &S, SourceLocation Loc) const override {
11545     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11546         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11547   }
11548 
11549   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11550       : Base(Base), Index(Index) {}
11551 };
11552 
11553 } // end anonymous namespace
11554 
11555 /// When generating a defaulted copy or move assignment operator, if a field
11556 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11557 /// do so. This optimization only applies for arrays of scalars, and for arrays
11558 /// of class type where the selected copy/move-assignment operator is trivial.
11559 static StmtResult
11560 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11561                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11562   // Compute the size of the memory buffer to be copied.
11563   QualType SizeType = S.Context.getSizeType();
11564   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11565                    S.Context.getTypeSizeInChars(T).getQuantity());
11566 
11567   // Take the address of the field references for "from" and "to". We
11568   // directly construct UnaryOperators here because semantic analysis
11569   // does not permit us to take the address of an xvalue.
11570   Expr *From = FromB.build(S, Loc);
11571   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11572                          S.Context.getPointerType(From->getType()),
11573                          VK_RValue, OK_Ordinary, Loc, false);
11574   Expr *To = ToB.build(S, Loc);
11575   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11576                        S.Context.getPointerType(To->getType()),
11577                        VK_RValue, OK_Ordinary, Loc, false);
11578 
11579   const Type *E = T->getBaseElementTypeUnsafe();
11580   bool NeedsCollectableMemCpy =
11581     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11582 
11583   // Create a reference to the __builtin_objc_memmove_collectable function
11584   StringRef MemCpyName = NeedsCollectableMemCpy ?
11585     "__builtin_objc_memmove_collectable" :
11586     "__builtin_memcpy";
11587   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11588                  Sema::LookupOrdinaryName);
11589   S.LookupName(R, S.TUScope, true);
11590 
11591   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11592   if (!MemCpy)
11593     // Something went horribly wrong earlier, and we will have complained
11594     // about it.
11595     return StmtError();
11596 
11597   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11598                                             VK_RValue, Loc, nullptr);
11599   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11600 
11601   Expr *CallArgs[] = {
11602     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11603   };
11604   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11605                                     Loc, CallArgs, Loc);
11606 
11607   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11608   return Call.getAs<Stmt>();
11609 }
11610 
11611 /// Builds a statement that copies/moves the given entity from \p From to
11612 /// \c To.
11613 ///
11614 /// This routine is used to copy/move the members of a class with an
11615 /// implicitly-declared copy/move assignment operator. When the entities being
11616 /// copied are arrays, this routine builds for loops to copy them.
11617 ///
11618 /// \param S The Sema object used for type-checking.
11619 ///
11620 /// \param Loc The location where the implicit copy/move is being generated.
11621 ///
11622 /// \param T The type of the expressions being copied/moved. Both expressions
11623 /// must have this type.
11624 ///
11625 /// \param To The expression we are copying/moving to.
11626 ///
11627 /// \param From The expression we are copying/moving from.
11628 ///
11629 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11630 /// Otherwise, it's a non-static member subobject.
11631 ///
11632 /// \param Copying Whether we're copying or moving.
11633 ///
11634 /// \param Depth Internal parameter recording the depth of the recursion.
11635 ///
11636 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11637 /// if a memcpy should be used instead.
11638 static StmtResult
11639 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11640                                  const ExprBuilder &To, const ExprBuilder &From,
11641                                  bool CopyingBaseSubobject, bool Copying,
11642                                  unsigned Depth = 0) {
11643   // C++11 [class.copy]p28:
11644   //   Each subobject is assigned in the manner appropriate to its type:
11645   //
11646   //     - if the subobject is of class type, as if by a call to operator= with
11647   //       the subobject as the object expression and the corresponding
11648   //       subobject of x as a single function argument (as if by explicit
11649   //       qualification; that is, ignoring any possible virtual overriding
11650   //       functions in more derived classes);
11651   //
11652   // C++03 [class.copy]p13:
11653   //     - if the subobject is of class type, the copy assignment operator for
11654   //       the class is used (as if by explicit qualification; that is,
11655   //       ignoring any possible virtual overriding functions in more derived
11656   //       classes);
11657   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11658     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11659 
11660     // Look for operator=.
11661     DeclarationName Name
11662       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11663     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11664     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11665 
11666     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11667     // operator.
11668     if (!S.getLangOpts().CPlusPlus11) {
11669       LookupResult::Filter F = OpLookup.makeFilter();
11670       while (F.hasNext()) {
11671         NamedDecl *D = F.next();
11672         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11673           if (Method->isCopyAssignmentOperator() ||
11674               (!Copying && Method->isMoveAssignmentOperator()))
11675             continue;
11676 
11677         F.erase();
11678       }
11679       F.done();
11680     }
11681 
11682     // Suppress the protected check (C++ [class.protected]) for each of the
11683     // assignment operators we found. This strange dance is required when
11684     // we're assigning via a base classes's copy-assignment operator. To
11685     // ensure that we're getting the right base class subobject (without
11686     // ambiguities), we need to cast "this" to that subobject type; to
11687     // ensure that we don't go through the virtual call mechanism, we need
11688     // to qualify the operator= name with the base class (see below). However,
11689     // this means that if the base class has a protected copy assignment
11690     // operator, the protected member access check will fail. So, we
11691     // rewrite "protected" access to "public" access in this case, since we
11692     // know by construction that we're calling from a derived class.
11693     if (CopyingBaseSubobject) {
11694       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11695            L != LEnd; ++L) {
11696         if (L.getAccess() == AS_protected)
11697           L.setAccess(AS_public);
11698       }
11699     }
11700 
11701     // Create the nested-name-specifier that will be used to qualify the
11702     // reference to operator=; this is required to suppress the virtual
11703     // call mechanism.
11704     CXXScopeSpec SS;
11705     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11706     SS.MakeTrivial(S.Context,
11707                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11708                                                CanonicalT),
11709                    Loc);
11710 
11711     // Create the reference to operator=.
11712     ExprResult OpEqualRef
11713       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11714                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11715                                    /*FirstQualifierInScope=*/nullptr,
11716                                    OpLookup,
11717                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11718                                    /*SuppressQualifierCheck=*/true);
11719     if (OpEqualRef.isInvalid())
11720       return StmtError();
11721 
11722     // Build the call to the assignment operator.
11723 
11724     Expr *FromInst = From.build(S, Loc);
11725     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11726                                                   OpEqualRef.getAs<Expr>(),
11727                                                   Loc, FromInst, Loc);
11728     if (Call.isInvalid())
11729       return StmtError();
11730 
11731     // If we built a call to a trivial 'operator=' while copying an array,
11732     // bail out. We'll replace the whole shebang with a memcpy.
11733     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11734     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11735       return StmtResult((Stmt*)nullptr);
11736 
11737     // Convert to an expression-statement, and clean up any produced
11738     // temporaries.
11739     return S.ActOnExprStmt(Call);
11740   }
11741 
11742   //     - if the subobject is of scalar type, the built-in assignment
11743   //       operator is used.
11744   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11745   if (!ArrayTy) {
11746     ExprResult Assignment = S.CreateBuiltinBinOp(
11747         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11748     if (Assignment.isInvalid())
11749       return StmtError();
11750     return S.ActOnExprStmt(Assignment);
11751   }
11752 
11753   //     - if the subobject is an array, each element is assigned, in the
11754   //       manner appropriate to the element type;
11755 
11756   // Construct a loop over the array bounds, e.g.,
11757   //
11758   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11759   //
11760   // that will copy each of the array elements.
11761   QualType SizeType = S.Context.getSizeType();
11762 
11763   // Create the iteration variable.
11764   IdentifierInfo *IterationVarName = nullptr;
11765   {
11766     SmallString<8> Str;
11767     llvm::raw_svector_ostream OS(Str);
11768     OS << "__i" << Depth;
11769     IterationVarName = &S.Context.Idents.get(OS.str());
11770   }
11771   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11772                                           IterationVarName, SizeType,
11773                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11774                                           SC_None);
11775 
11776   // Initialize the iteration variable to zero.
11777   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11778   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11779 
11780   // Creates a reference to the iteration variable.
11781   RefBuilder IterationVarRef(IterationVar, SizeType);
11782   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11783 
11784   // Create the DeclStmt that holds the iteration variable.
11785   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11786 
11787   // Subscript the "from" and "to" expressions with the iteration variable.
11788   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11789   MoveCastBuilder FromIndexMove(FromIndexCopy);
11790   const ExprBuilder *FromIndex;
11791   if (Copying)
11792     FromIndex = &FromIndexCopy;
11793   else
11794     FromIndex = &FromIndexMove;
11795 
11796   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11797 
11798   // Build the copy/move for an individual element of the array.
11799   StmtResult Copy =
11800     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11801                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11802                                      Copying, Depth + 1);
11803   // Bail out if copying fails or if we determined that we should use memcpy.
11804   if (Copy.isInvalid() || !Copy.get())
11805     return Copy;
11806 
11807   // Create the comparison against the array bound.
11808   llvm::APInt Upper
11809     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11810   Expr *Comparison
11811     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11812                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11813                                      BO_NE, S.Context.BoolTy,
11814                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11815 
11816   // Create the pre-increment of the iteration variable. We can determine
11817   // whether the increment will overflow based on the value of the array
11818   // bound.
11819   Expr *Increment = new (S.Context)
11820       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11821                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11822 
11823   // Construct the loop that copies all elements of this array.
11824   return S.ActOnForStmt(
11825       Loc, Loc, InitStmt,
11826       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11827       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11828 }
11829 
11830 static StmtResult
11831 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11832                       const ExprBuilder &To, const ExprBuilder &From,
11833                       bool CopyingBaseSubobject, bool Copying) {
11834   // Maybe we should use a memcpy?
11835   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11836       T.isTriviallyCopyableType(S.Context))
11837     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11838 
11839   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11840                                                      CopyingBaseSubobject,
11841                                                      Copying, 0));
11842 
11843   // If we ended up picking a trivial assignment operator for an array of a
11844   // non-trivially-copyable class type, just emit a memcpy.
11845   if (!Result.isInvalid() && !Result.get())
11846     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11847 
11848   return Result;
11849 }
11850 
11851 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11852   // Note: The following rules are largely analoguous to the copy
11853   // constructor rules. Note that virtual bases are not taken into account
11854   // for determining the argument type of the operator. Note also that
11855   // operators taking an object instead of a reference are allowed.
11856   assert(ClassDecl->needsImplicitCopyAssignment());
11857 
11858   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11859   if (DSM.isAlreadyBeingDeclared())
11860     return nullptr;
11861 
11862   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11863   if (Context.getLangOpts().OpenCLCPlusPlus)
11864     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
11865   QualType RetType = Context.getLValueReferenceType(ArgType);
11866   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11867   if (Const)
11868     ArgType = ArgType.withConst();
11869 
11870   ArgType = Context.getLValueReferenceType(ArgType);
11871 
11872   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11873                                                      CXXCopyAssignment,
11874                                                      Const);
11875 
11876   //   An implicitly-declared copy assignment operator is an inline public
11877   //   member of its class.
11878   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11879   SourceLocation ClassLoc = ClassDecl->getLocation();
11880   DeclarationNameInfo NameInfo(Name, ClassLoc);
11881   CXXMethodDecl *CopyAssignment =
11882       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11883                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11884                             /*isInline=*/true, Constexpr, SourceLocation());
11885   CopyAssignment->setAccess(AS_public);
11886   CopyAssignment->setDefaulted();
11887   CopyAssignment->setImplicit();
11888 
11889   if (getLangOpts().CUDA) {
11890     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11891                                             CopyAssignment,
11892                                             /* ConstRHS */ Const,
11893                                             /* Diagnose */ false);
11894   }
11895 
11896   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
11897 
11898   // Add the parameter to the operator.
11899   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11900                                                ClassLoc, ClassLoc,
11901                                                /*Id=*/nullptr, ArgType,
11902                                                /*TInfo=*/nullptr, SC_None,
11903                                                nullptr);
11904   CopyAssignment->setParams(FromParam);
11905 
11906   CopyAssignment->setTrivial(
11907     ClassDecl->needsOverloadResolutionForCopyAssignment()
11908       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11909       : ClassDecl->hasTrivialCopyAssignment());
11910 
11911   // Note that we have added this copy-assignment operator.
11912   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
11913 
11914   Scope *S = getScopeForContext(ClassDecl);
11915   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11916 
11917   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11918     SetDeclDeleted(CopyAssignment, ClassLoc);
11919 
11920   if (S)
11921     PushOnScopeChains(CopyAssignment, S, false);
11922   ClassDecl->addDecl(CopyAssignment);
11923 
11924   return CopyAssignment;
11925 }
11926 
11927 /// Diagnose an implicit copy operation for a class which is odr-used, but
11928 /// which is deprecated because the class has a user-declared copy constructor,
11929 /// copy assignment operator, or destructor.
11930 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11931   assert(CopyOp->isImplicit());
11932 
11933   CXXRecordDecl *RD = CopyOp->getParent();
11934   CXXMethodDecl *UserDeclaredOperation = nullptr;
11935 
11936   // In Microsoft mode, assignment operations don't affect constructors and
11937   // vice versa.
11938   if (RD->hasUserDeclaredDestructor()) {
11939     UserDeclaredOperation = RD->getDestructor();
11940   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11941              RD->hasUserDeclaredCopyConstructor() &&
11942              !S.getLangOpts().MSVCCompat) {
11943     // Find any user-declared copy constructor.
11944     for (auto *I : RD->ctors()) {
11945       if (I->isCopyConstructor()) {
11946         UserDeclaredOperation = I;
11947         break;
11948       }
11949     }
11950     assert(UserDeclaredOperation);
11951   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11952              RD->hasUserDeclaredCopyAssignment() &&
11953              !S.getLangOpts().MSVCCompat) {
11954     // Find any user-declared move assignment operator.
11955     for (auto *I : RD->methods()) {
11956       if (I->isCopyAssignmentOperator()) {
11957         UserDeclaredOperation = I;
11958         break;
11959       }
11960     }
11961     assert(UserDeclaredOperation);
11962   }
11963 
11964   if (UserDeclaredOperation) {
11965     S.Diag(UserDeclaredOperation->getLocation(),
11966          diag::warn_deprecated_copy_operation)
11967       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11968       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11969   }
11970 }
11971 
11972 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11973                                         CXXMethodDecl *CopyAssignOperator) {
11974   assert((CopyAssignOperator->isDefaulted() &&
11975           CopyAssignOperator->isOverloadedOperator() &&
11976           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11977           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11978           !CopyAssignOperator->isDeleted()) &&
11979          "DefineImplicitCopyAssignment called for wrong function");
11980   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11981     return;
11982 
11983   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11984   if (ClassDecl->isInvalidDecl()) {
11985     CopyAssignOperator->setInvalidDecl();
11986     return;
11987   }
11988 
11989   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11990 
11991   // The exception specification is needed because we are defining the
11992   // function.
11993   ResolveExceptionSpec(CurrentLocation,
11994                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11995 
11996   // Add a context note for diagnostics produced after this point.
11997   Scope.addContextNote(CurrentLocation);
11998 
11999   // C++11 [class.copy]p18:
12000   //   The [definition of an implicitly declared copy assignment operator] is
12001   //   deprecated if the class has a user-declared copy constructor or a
12002   //   user-declared destructor.
12003   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
12004     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
12005 
12006   // C++0x [class.copy]p30:
12007   //   The implicitly-defined or explicitly-defaulted copy assignment operator
12008   //   for a non-union class X performs memberwise copy assignment of its
12009   //   subobjects. The direct base classes of X are assigned first, in the
12010   //   order of their declaration in the base-specifier-list, and then the
12011   //   immediate non-static data members of X are assigned, in the order in
12012   //   which they were declared in the class definition.
12013 
12014   // The statements that form the synthesized function body.
12015   SmallVector<Stmt*, 8> Statements;
12016 
12017   // The parameter for the "other" object, which we are copying from.
12018   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
12019   Qualifiers OtherQuals = Other->getType().getQualifiers();
12020   QualType OtherRefType = Other->getType();
12021   if (const LValueReferenceType *OtherRef
12022                                 = OtherRefType->getAs<LValueReferenceType>()) {
12023     OtherRefType = OtherRef->getPointeeType();
12024     OtherQuals = OtherRefType.getQualifiers();
12025   }
12026 
12027   // Our location for everything implicitly-generated.
12028   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
12029                            ? CopyAssignOperator->getEndLoc()
12030                            : CopyAssignOperator->getLocation();
12031 
12032   // Builds a DeclRefExpr for the "other" object.
12033   RefBuilder OtherRef(Other, OtherRefType);
12034 
12035   // Builds the "this" pointer.
12036   ThisBuilder This;
12037 
12038   // Assign base classes.
12039   bool Invalid = false;
12040   for (auto &Base : ClassDecl->bases()) {
12041     // Form the assignment:
12042     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
12043     QualType BaseType = Base.getType().getUnqualifiedType();
12044     if (!BaseType->isRecordType()) {
12045       Invalid = true;
12046       continue;
12047     }
12048 
12049     CXXCastPath BasePath;
12050     BasePath.push_back(&Base);
12051 
12052     // Construct the "from" expression, which is an implicit cast to the
12053     // appropriately-qualified base type.
12054     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
12055                      VK_LValue, BasePath);
12056 
12057     // Dereference "this".
12058     DerefBuilder DerefThis(This);
12059     CastBuilder To(DerefThis,
12060                    Context.getQualifiedType(
12061                        BaseType, CopyAssignOperator->getMethodQualifiers()),
12062                    VK_LValue, BasePath);
12063 
12064     // Build the copy.
12065     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12066                                             To, From,
12067                                             /*CopyingBaseSubobject=*/true,
12068                                             /*Copying=*/true);
12069     if (Copy.isInvalid()) {
12070       CopyAssignOperator->setInvalidDecl();
12071       return;
12072     }
12073 
12074     // Success! Record the copy.
12075     Statements.push_back(Copy.getAs<Expr>());
12076   }
12077 
12078   // Assign non-static members.
12079   for (auto *Field : ClassDecl->fields()) {
12080     // FIXME: We should form some kind of AST representation for the implied
12081     // memcpy in a union copy operation.
12082     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12083       continue;
12084 
12085     if (Field->isInvalidDecl()) {
12086       Invalid = true;
12087       continue;
12088     }
12089 
12090     // Check for members of reference type; we can't copy those.
12091     if (Field->getType()->isReferenceType()) {
12092       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12093         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12094       Diag(Field->getLocation(), diag::note_declared_at);
12095       Invalid = true;
12096       continue;
12097     }
12098 
12099     // Check for members of const-qualified, non-class type.
12100     QualType BaseType = Context.getBaseElementType(Field->getType());
12101     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12102       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12103         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12104       Diag(Field->getLocation(), diag::note_declared_at);
12105       Invalid = true;
12106       continue;
12107     }
12108 
12109     // Suppress assigning zero-width bitfields.
12110     if (Field->isZeroLengthBitField(Context))
12111       continue;
12112 
12113     QualType FieldType = Field->getType().getNonReferenceType();
12114     if (FieldType->isIncompleteArrayType()) {
12115       assert(ClassDecl->hasFlexibleArrayMember() &&
12116              "Incomplete array type is not valid");
12117       continue;
12118     }
12119 
12120     // Build references to the field in the object we're copying from and to.
12121     CXXScopeSpec SS; // Intentionally empty
12122     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12123                               LookupMemberName);
12124     MemberLookup.addDecl(Field);
12125     MemberLookup.resolveKind();
12126 
12127     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12128 
12129     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12130 
12131     // Build the copy of this field.
12132     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12133                                             To, From,
12134                                             /*CopyingBaseSubobject=*/false,
12135                                             /*Copying=*/true);
12136     if (Copy.isInvalid()) {
12137       CopyAssignOperator->setInvalidDecl();
12138       return;
12139     }
12140 
12141     // Success! Record the copy.
12142     Statements.push_back(Copy.getAs<Stmt>());
12143   }
12144 
12145   if (!Invalid) {
12146     // Add a "return *this;"
12147     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12148 
12149     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12150     if (Return.isInvalid())
12151       Invalid = true;
12152     else
12153       Statements.push_back(Return.getAs<Stmt>());
12154   }
12155 
12156   if (Invalid) {
12157     CopyAssignOperator->setInvalidDecl();
12158     return;
12159   }
12160 
12161   StmtResult Body;
12162   {
12163     CompoundScopeRAII CompoundScope(*this);
12164     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12165                              /*isStmtExpr=*/false);
12166     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12167   }
12168   CopyAssignOperator->setBody(Body.getAs<Stmt>());
12169   CopyAssignOperator->markUsed(Context);
12170 
12171   if (ASTMutationListener *L = getASTMutationListener()) {
12172     L->CompletedImplicitDefinition(CopyAssignOperator);
12173   }
12174 }
12175 
12176 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12177   assert(ClassDecl->needsImplicitMoveAssignment());
12178 
12179   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12180   if (DSM.isAlreadyBeingDeclared())
12181     return nullptr;
12182 
12183   // Note: The following rules are largely analoguous to the move
12184   // constructor rules.
12185 
12186   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12187   if (Context.getLangOpts().OpenCLCPlusPlus)
12188     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12189   QualType RetType = Context.getLValueReferenceType(ArgType);
12190   ArgType = Context.getRValueReferenceType(ArgType);
12191 
12192   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12193                                                      CXXMoveAssignment,
12194                                                      false);
12195 
12196   //   An implicitly-declared move assignment operator is an inline public
12197   //   member of its class.
12198   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12199   SourceLocation ClassLoc = ClassDecl->getLocation();
12200   DeclarationNameInfo NameInfo(Name, ClassLoc);
12201   CXXMethodDecl *MoveAssignment =
12202       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12203                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12204                             /*isInline=*/true, Constexpr, SourceLocation());
12205   MoveAssignment->setAccess(AS_public);
12206   MoveAssignment->setDefaulted();
12207   MoveAssignment->setImplicit();
12208 
12209   if (getLangOpts().CUDA) {
12210     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12211                                             MoveAssignment,
12212                                             /* ConstRHS */ false,
12213                                             /* Diagnose */ false);
12214   }
12215 
12216   // Build an exception specification pointing back at this member.
12217   FunctionProtoType::ExtProtoInfo EPI =
12218       getImplicitMethodEPI(*this, MoveAssignment);
12219   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12220 
12221   // Add the parameter to the operator.
12222   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12223                                                ClassLoc, ClassLoc,
12224                                                /*Id=*/nullptr, ArgType,
12225                                                /*TInfo=*/nullptr, SC_None,
12226                                                nullptr);
12227   MoveAssignment->setParams(FromParam);
12228 
12229   MoveAssignment->setTrivial(
12230     ClassDecl->needsOverloadResolutionForMoveAssignment()
12231       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12232       : ClassDecl->hasTrivialMoveAssignment());
12233 
12234   // Note that we have added this copy-assignment operator.
12235   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
12236 
12237   Scope *S = getScopeForContext(ClassDecl);
12238   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12239 
12240   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12241     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12242     SetDeclDeleted(MoveAssignment, ClassLoc);
12243   }
12244 
12245   if (S)
12246     PushOnScopeChains(MoveAssignment, S, false);
12247   ClassDecl->addDecl(MoveAssignment);
12248 
12249   return MoveAssignment;
12250 }
12251 
12252 /// Check if we're implicitly defining a move assignment operator for a class
12253 /// with virtual bases. Such a move assignment might move-assign the virtual
12254 /// base multiple times.
12255 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12256                                                SourceLocation CurrentLocation) {
12257   assert(!Class->isDependentContext() && "should not define dependent move");
12258 
12259   // Only a virtual base could get implicitly move-assigned multiple times.
12260   // Only a non-trivial move assignment can observe this. We only want to
12261   // diagnose if we implicitly define an assignment operator that assigns
12262   // two base classes, both of which move-assign the same virtual base.
12263   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12264       Class->getNumBases() < 2)
12265     return;
12266 
12267   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12268   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12269   VBaseMap VBases;
12270 
12271   for (auto &BI : Class->bases()) {
12272     Worklist.push_back(&BI);
12273     while (!Worklist.empty()) {
12274       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12275       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12276 
12277       // If the base has no non-trivial move assignment operators,
12278       // we don't care about moves from it.
12279       if (!Base->hasNonTrivialMoveAssignment())
12280         continue;
12281 
12282       // If there's nothing virtual here, skip it.
12283       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12284         continue;
12285 
12286       // If we're not actually going to call a move assignment for this base,
12287       // or the selected move assignment is trivial, skip it.
12288       Sema::SpecialMemberOverloadResult SMOR =
12289         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12290                               /*ConstArg*/false, /*VolatileArg*/false,
12291                               /*RValueThis*/true, /*ConstThis*/false,
12292                               /*VolatileThis*/false);
12293       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12294           !SMOR.getMethod()->isMoveAssignmentOperator())
12295         continue;
12296 
12297       if (BaseSpec->isVirtual()) {
12298         // We're going to move-assign this virtual base, and its move
12299         // assignment operator is not trivial. If this can happen for
12300         // multiple distinct direct bases of Class, diagnose it. (If it
12301         // only happens in one base, we'll diagnose it when synthesizing
12302         // that base class's move assignment operator.)
12303         CXXBaseSpecifier *&Existing =
12304             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12305                 .first->second;
12306         if (Existing && Existing != &BI) {
12307           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12308             << Class << Base;
12309           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12310               << (Base->getCanonicalDecl() ==
12311                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12312               << Base << Existing->getType() << Existing->getSourceRange();
12313           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12314               << (Base->getCanonicalDecl() ==
12315                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12316               << Base << BI.getType() << BaseSpec->getSourceRange();
12317 
12318           // Only diagnose each vbase once.
12319           Existing = nullptr;
12320         }
12321       } else {
12322         // Only walk over bases that have defaulted move assignment operators.
12323         // We assume that any user-provided move assignment operator handles
12324         // the multiple-moves-of-vbase case itself somehow.
12325         if (!SMOR.getMethod()->isDefaulted())
12326           continue;
12327 
12328         // We're going to move the base classes of Base. Add them to the list.
12329         for (auto &BI : Base->bases())
12330           Worklist.push_back(&BI);
12331       }
12332     }
12333   }
12334 }
12335 
12336 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12337                                         CXXMethodDecl *MoveAssignOperator) {
12338   assert((MoveAssignOperator->isDefaulted() &&
12339           MoveAssignOperator->isOverloadedOperator() &&
12340           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12341           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12342           !MoveAssignOperator->isDeleted()) &&
12343          "DefineImplicitMoveAssignment called for wrong function");
12344   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12345     return;
12346 
12347   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12348   if (ClassDecl->isInvalidDecl()) {
12349     MoveAssignOperator->setInvalidDecl();
12350     return;
12351   }
12352 
12353   // C++0x [class.copy]p28:
12354   //   The implicitly-defined or move assignment operator for a non-union class
12355   //   X performs memberwise move assignment of its subobjects. The direct base
12356   //   classes of X are assigned first, in the order of their declaration in the
12357   //   base-specifier-list, and then the immediate non-static data members of X
12358   //   are assigned, in the order in which they were declared in the class
12359   //   definition.
12360 
12361   // Issue a warning if our implicit move assignment operator will move
12362   // from a virtual base more than once.
12363   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12364 
12365   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12366 
12367   // The exception specification is needed because we are defining the
12368   // function.
12369   ResolveExceptionSpec(CurrentLocation,
12370                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12371 
12372   // Add a context note for diagnostics produced after this point.
12373   Scope.addContextNote(CurrentLocation);
12374 
12375   // The statements that form the synthesized function body.
12376   SmallVector<Stmt*, 8> Statements;
12377 
12378   // The parameter for the "other" object, which we are move from.
12379   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12380   QualType OtherRefType = Other->getType()->
12381       getAs<RValueReferenceType>()->getPointeeType();
12382 
12383   // Our location for everything implicitly-generated.
12384   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12385                            ? MoveAssignOperator->getEndLoc()
12386                            : MoveAssignOperator->getLocation();
12387 
12388   // Builds a reference to the "other" object.
12389   RefBuilder OtherRef(Other, OtherRefType);
12390   // Cast to rvalue.
12391   MoveCastBuilder MoveOther(OtherRef);
12392 
12393   // Builds the "this" pointer.
12394   ThisBuilder This;
12395 
12396   // Assign base classes.
12397   bool Invalid = false;
12398   for (auto &Base : ClassDecl->bases()) {
12399     // C++11 [class.copy]p28:
12400     //   It is unspecified whether subobjects representing virtual base classes
12401     //   are assigned more than once by the implicitly-defined copy assignment
12402     //   operator.
12403     // FIXME: Do not assign to a vbase that will be assigned by some other base
12404     // class. For a move-assignment, this can result in the vbase being moved
12405     // multiple times.
12406 
12407     // Form the assignment:
12408     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12409     QualType BaseType = Base.getType().getUnqualifiedType();
12410     if (!BaseType->isRecordType()) {
12411       Invalid = true;
12412       continue;
12413     }
12414 
12415     CXXCastPath BasePath;
12416     BasePath.push_back(&Base);
12417 
12418     // Construct the "from" expression, which is an implicit cast to the
12419     // appropriately-qualified base type.
12420     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12421 
12422     // Dereference "this".
12423     DerefBuilder DerefThis(This);
12424 
12425     // Implicitly cast "this" to the appropriately-qualified base type.
12426     CastBuilder To(DerefThis,
12427                    Context.getQualifiedType(
12428                        BaseType, MoveAssignOperator->getMethodQualifiers()),
12429                    VK_LValue, BasePath);
12430 
12431     // Build the move.
12432     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12433                                             To, From,
12434                                             /*CopyingBaseSubobject=*/true,
12435                                             /*Copying=*/false);
12436     if (Move.isInvalid()) {
12437       MoveAssignOperator->setInvalidDecl();
12438       return;
12439     }
12440 
12441     // Success! Record the move.
12442     Statements.push_back(Move.getAs<Expr>());
12443   }
12444 
12445   // Assign non-static members.
12446   for (auto *Field : ClassDecl->fields()) {
12447     // FIXME: We should form some kind of AST representation for the implied
12448     // memcpy in a union copy operation.
12449     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12450       continue;
12451 
12452     if (Field->isInvalidDecl()) {
12453       Invalid = true;
12454       continue;
12455     }
12456 
12457     // Check for members of reference type; we can't move those.
12458     if (Field->getType()->isReferenceType()) {
12459       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12460         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12461       Diag(Field->getLocation(), diag::note_declared_at);
12462       Invalid = true;
12463       continue;
12464     }
12465 
12466     // Check for members of const-qualified, non-class type.
12467     QualType BaseType = Context.getBaseElementType(Field->getType());
12468     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12469       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12470         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12471       Diag(Field->getLocation(), diag::note_declared_at);
12472       Invalid = true;
12473       continue;
12474     }
12475 
12476     // Suppress assigning zero-width bitfields.
12477     if (Field->isZeroLengthBitField(Context))
12478       continue;
12479 
12480     QualType FieldType = Field->getType().getNonReferenceType();
12481     if (FieldType->isIncompleteArrayType()) {
12482       assert(ClassDecl->hasFlexibleArrayMember() &&
12483              "Incomplete array type is not valid");
12484       continue;
12485     }
12486 
12487     // Build references to the field in the object we're copying from and to.
12488     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12489                               LookupMemberName);
12490     MemberLookup.addDecl(Field);
12491     MemberLookup.resolveKind();
12492     MemberBuilder From(MoveOther, OtherRefType,
12493                        /*IsArrow=*/false, MemberLookup);
12494     MemberBuilder To(This, getCurrentThisType(),
12495                      /*IsArrow=*/true, MemberLookup);
12496 
12497     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12498         "Member reference with rvalue base must be rvalue except for reference "
12499         "members, which aren't allowed for move assignment.");
12500 
12501     // Build the move of this field.
12502     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12503                                             To, From,
12504                                             /*CopyingBaseSubobject=*/false,
12505                                             /*Copying=*/false);
12506     if (Move.isInvalid()) {
12507       MoveAssignOperator->setInvalidDecl();
12508       return;
12509     }
12510 
12511     // Success! Record the copy.
12512     Statements.push_back(Move.getAs<Stmt>());
12513   }
12514 
12515   if (!Invalid) {
12516     // Add a "return *this;"
12517     ExprResult ThisObj =
12518         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12519 
12520     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12521     if (Return.isInvalid())
12522       Invalid = true;
12523     else
12524       Statements.push_back(Return.getAs<Stmt>());
12525   }
12526 
12527   if (Invalid) {
12528     MoveAssignOperator->setInvalidDecl();
12529     return;
12530   }
12531 
12532   StmtResult Body;
12533   {
12534     CompoundScopeRAII CompoundScope(*this);
12535     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12536                              /*isStmtExpr=*/false);
12537     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12538   }
12539   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12540   MoveAssignOperator->markUsed(Context);
12541 
12542   if (ASTMutationListener *L = getASTMutationListener()) {
12543     L->CompletedImplicitDefinition(MoveAssignOperator);
12544   }
12545 }
12546 
12547 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12548                                                     CXXRecordDecl *ClassDecl) {
12549   // C++ [class.copy]p4:
12550   //   If the class definition does not explicitly declare a copy
12551   //   constructor, one is declared implicitly.
12552   assert(ClassDecl->needsImplicitCopyConstructor());
12553 
12554   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12555   if (DSM.isAlreadyBeingDeclared())
12556     return nullptr;
12557 
12558   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12559   QualType ArgType = ClassType;
12560   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12561   if (Const)
12562     ArgType = ArgType.withConst();
12563 
12564   if (Context.getLangOpts().OpenCLCPlusPlus)
12565     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12566 
12567   ArgType = Context.getLValueReferenceType(ArgType);
12568 
12569   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12570                                                      CXXCopyConstructor,
12571                                                      Const);
12572 
12573   DeclarationName Name
12574     = Context.DeclarationNames.getCXXConstructorName(
12575                                            Context.getCanonicalType(ClassType));
12576   SourceLocation ClassLoc = ClassDecl->getLocation();
12577   DeclarationNameInfo NameInfo(Name, ClassLoc);
12578 
12579   //   An implicitly-declared copy constructor is an inline public
12580   //   member of its class.
12581   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12582       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12583       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12584       Constexpr);
12585   CopyConstructor->setAccess(AS_public);
12586   CopyConstructor->setDefaulted();
12587 
12588   if (getLangOpts().CUDA) {
12589     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12590                                             CopyConstructor,
12591                                             /* ConstRHS */ Const,
12592                                             /* Diagnose */ false);
12593   }
12594 
12595   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
12596 
12597   // Add the parameter to the constructor.
12598   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12599                                                ClassLoc, ClassLoc,
12600                                                /*IdentifierInfo=*/nullptr,
12601                                                ArgType, /*TInfo=*/nullptr,
12602                                                SC_None, nullptr);
12603   CopyConstructor->setParams(FromParam);
12604 
12605   CopyConstructor->setTrivial(
12606       ClassDecl->needsOverloadResolutionForCopyConstructor()
12607           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12608           : ClassDecl->hasTrivialCopyConstructor());
12609 
12610   CopyConstructor->setTrivialForCall(
12611       ClassDecl->hasAttr<TrivialABIAttr>() ||
12612       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12613            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12614              TAH_ConsiderTrivialABI)
12615            : ClassDecl->hasTrivialCopyConstructorForCall()));
12616 
12617   // Note that we have declared this constructor.
12618   ++getASTContext().NumImplicitCopyConstructorsDeclared;
12619 
12620   Scope *S = getScopeForContext(ClassDecl);
12621   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12622 
12623   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12624     ClassDecl->setImplicitCopyConstructorIsDeleted();
12625     SetDeclDeleted(CopyConstructor, ClassLoc);
12626   }
12627 
12628   if (S)
12629     PushOnScopeChains(CopyConstructor, S, false);
12630   ClassDecl->addDecl(CopyConstructor);
12631 
12632   return CopyConstructor;
12633 }
12634 
12635 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12636                                          CXXConstructorDecl *CopyConstructor) {
12637   assert((CopyConstructor->isDefaulted() &&
12638           CopyConstructor->isCopyConstructor() &&
12639           !CopyConstructor->doesThisDeclarationHaveABody() &&
12640           !CopyConstructor->isDeleted()) &&
12641          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12642   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12643     return;
12644 
12645   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12646   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12647 
12648   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12649 
12650   // The exception specification is needed because we are defining the
12651   // function.
12652   ResolveExceptionSpec(CurrentLocation,
12653                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12654   MarkVTableUsed(CurrentLocation, ClassDecl);
12655 
12656   // Add a context note for diagnostics produced after this point.
12657   Scope.addContextNote(CurrentLocation);
12658 
12659   // C++11 [class.copy]p7:
12660   //   The [definition of an implicitly declared copy constructor] is
12661   //   deprecated if the class has a user-declared copy assignment operator
12662   //   or a user-declared destructor.
12663   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12664     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12665 
12666   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12667     CopyConstructor->setInvalidDecl();
12668   }  else {
12669     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12670                              ? CopyConstructor->getEndLoc()
12671                              : CopyConstructor->getLocation();
12672     Sema::CompoundScopeRAII CompoundScope(*this);
12673     CopyConstructor->setBody(
12674         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12675     CopyConstructor->markUsed(Context);
12676   }
12677 
12678   if (ASTMutationListener *L = getASTMutationListener()) {
12679     L->CompletedImplicitDefinition(CopyConstructor);
12680   }
12681 }
12682 
12683 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12684                                                     CXXRecordDecl *ClassDecl) {
12685   assert(ClassDecl->needsImplicitMoveConstructor());
12686 
12687   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12688   if (DSM.isAlreadyBeingDeclared())
12689     return nullptr;
12690 
12691   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12692 
12693   QualType ArgType = ClassType;
12694   if (Context.getLangOpts().OpenCLCPlusPlus)
12695     ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
12696   ArgType = Context.getRValueReferenceType(ArgType);
12697 
12698   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12699                                                      CXXMoveConstructor,
12700                                                      false);
12701 
12702   DeclarationName Name
12703     = Context.DeclarationNames.getCXXConstructorName(
12704                                            Context.getCanonicalType(ClassType));
12705   SourceLocation ClassLoc = ClassDecl->getLocation();
12706   DeclarationNameInfo NameInfo(Name, ClassLoc);
12707 
12708   // C++11 [class.copy]p11:
12709   //   An implicitly-declared copy/move constructor is an inline public
12710   //   member of its class.
12711   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12712       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12713       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12714       Constexpr);
12715   MoveConstructor->setAccess(AS_public);
12716   MoveConstructor->setDefaulted();
12717 
12718   if (getLangOpts().CUDA) {
12719     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12720                                             MoveConstructor,
12721                                             /* ConstRHS */ false,
12722                                             /* Diagnose */ false);
12723   }
12724 
12725   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
12726 
12727   // Add the parameter to the constructor.
12728   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12729                                                ClassLoc, ClassLoc,
12730                                                /*IdentifierInfo=*/nullptr,
12731                                                ArgType, /*TInfo=*/nullptr,
12732                                                SC_None, nullptr);
12733   MoveConstructor->setParams(FromParam);
12734 
12735   MoveConstructor->setTrivial(
12736       ClassDecl->needsOverloadResolutionForMoveConstructor()
12737           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12738           : ClassDecl->hasTrivialMoveConstructor());
12739 
12740   MoveConstructor->setTrivialForCall(
12741       ClassDecl->hasAttr<TrivialABIAttr>() ||
12742       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12743            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12744                                     TAH_ConsiderTrivialABI)
12745            : ClassDecl->hasTrivialMoveConstructorForCall()));
12746 
12747   // Note that we have declared this constructor.
12748   ++getASTContext().NumImplicitMoveConstructorsDeclared;
12749 
12750   Scope *S = getScopeForContext(ClassDecl);
12751   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12752 
12753   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12754     ClassDecl->setImplicitMoveConstructorIsDeleted();
12755     SetDeclDeleted(MoveConstructor, ClassLoc);
12756   }
12757 
12758   if (S)
12759     PushOnScopeChains(MoveConstructor, S, false);
12760   ClassDecl->addDecl(MoveConstructor);
12761 
12762   return MoveConstructor;
12763 }
12764 
12765 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12766                                          CXXConstructorDecl *MoveConstructor) {
12767   assert((MoveConstructor->isDefaulted() &&
12768           MoveConstructor->isMoveConstructor() &&
12769           !MoveConstructor->doesThisDeclarationHaveABody() &&
12770           !MoveConstructor->isDeleted()) &&
12771          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12772   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12773     return;
12774 
12775   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12776   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12777 
12778   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12779 
12780   // The exception specification is needed because we are defining the
12781   // function.
12782   ResolveExceptionSpec(CurrentLocation,
12783                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12784   MarkVTableUsed(CurrentLocation, ClassDecl);
12785 
12786   // Add a context note for diagnostics produced after this point.
12787   Scope.addContextNote(CurrentLocation);
12788 
12789   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12790     MoveConstructor->setInvalidDecl();
12791   } else {
12792     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12793                              ? MoveConstructor->getEndLoc()
12794                              : MoveConstructor->getLocation();
12795     Sema::CompoundScopeRAII CompoundScope(*this);
12796     MoveConstructor->setBody(ActOnCompoundStmt(
12797         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12798     MoveConstructor->markUsed(Context);
12799   }
12800 
12801   if (ASTMutationListener *L = getASTMutationListener()) {
12802     L->CompletedImplicitDefinition(MoveConstructor);
12803   }
12804 }
12805 
12806 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12807   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12808 }
12809 
12810 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12811                             SourceLocation CurrentLocation,
12812                             CXXConversionDecl *Conv) {
12813   SynthesizedFunctionScope Scope(*this, Conv);
12814   assert(!Conv->getReturnType()->isUndeducedType());
12815 
12816   CXXRecordDecl *Lambda = Conv->getParent();
12817   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12818   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12819 
12820   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12821     CallOp = InstantiateFunctionDeclaration(
12822         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12823     if (!CallOp)
12824       return;
12825 
12826     Invoker = InstantiateFunctionDeclaration(
12827         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12828     if (!Invoker)
12829       return;
12830   }
12831 
12832   if (CallOp->isInvalidDecl())
12833     return;
12834 
12835   // Mark the call operator referenced (and add to pending instantiations
12836   // if necessary).
12837   // For both the conversion and static-invoker template specializations
12838   // we construct their body's in this function, so no need to add them
12839   // to the PendingInstantiations.
12840   MarkFunctionReferenced(CurrentLocation, CallOp);
12841 
12842   // Fill in the __invoke function with a dummy implementation. IR generation
12843   // will fill in the actual details. Update its type in case it contained
12844   // an 'auto'.
12845   Invoker->markUsed(Context);
12846   Invoker->setReferenced();
12847   Invoker->setType(Conv->getReturnType()->getPointeeType());
12848   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12849 
12850   // Construct the body of the conversion function { return __invoke; }.
12851   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12852                                        VK_LValue, Conv->getLocation()).get();
12853   assert(FunctionRef && "Can't refer to __invoke function?");
12854   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12855   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12856                                      Conv->getLocation()));
12857   Conv->markUsed(Context);
12858   Conv->setReferenced();
12859 
12860   if (ASTMutationListener *L = getASTMutationListener()) {
12861     L->CompletedImplicitDefinition(Conv);
12862     L->CompletedImplicitDefinition(Invoker);
12863   }
12864 }
12865 
12866 
12867 
12868 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12869        SourceLocation CurrentLocation,
12870        CXXConversionDecl *Conv)
12871 {
12872   assert(!Conv->getParent()->isGenericLambda());
12873 
12874   SynthesizedFunctionScope Scope(*this, Conv);
12875 
12876   // Copy-initialize the lambda object as needed to capture it.
12877   Expr *This = ActOnCXXThis(CurrentLocation).get();
12878   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12879 
12880   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12881                                                         Conv->getLocation(),
12882                                                         Conv, DerefThis);
12883 
12884   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12885   // behavior.  Note that only the general conversion function does this
12886   // (since it's unusable otherwise); in the case where we inline the
12887   // block literal, it has block literal lifetime semantics.
12888   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12889     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12890                                           CK_CopyAndAutoreleaseBlockObject,
12891                                           BuildBlock.get(), nullptr, VK_RValue);
12892 
12893   if (BuildBlock.isInvalid()) {
12894     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12895     Conv->setInvalidDecl();
12896     return;
12897   }
12898 
12899   // Create the return statement that returns the block from the conversion
12900   // function.
12901   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12902   if (Return.isInvalid()) {
12903     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12904     Conv->setInvalidDecl();
12905     return;
12906   }
12907 
12908   // Set the body of the conversion function.
12909   Stmt *ReturnS = Return.get();
12910   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12911                                      Conv->getLocation()));
12912   Conv->markUsed(Context);
12913 
12914   // We're done; notify the mutation listener, if any.
12915   if (ASTMutationListener *L = getASTMutationListener()) {
12916     L->CompletedImplicitDefinition(Conv);
12917   }
12918 }
12919 
12920 /// Determine whether the given list arguments contains exactly one
12921 /// "real" (non-default) argument.
12922 static bool hasOneRealArgument(MultiExprArg Args) {
12923   switch (Args.size()) {
12924   case 0:
12925     return false;
12926 
12927   default:
12928     if (!Args[1]->isDefaultArgument())
12929       return false;
12930 
12931     LLVM_FALLTHROUGH;
12932   case 1:
12933     return !Args[0]->isDefaultArgument();
12934   }
12935 
12936   return false;
12937 }
12938 
12939 ExprResult
12940 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12941                             NamedDecl *FoundDecl,
12942                             CXXConstructorDecl *Constructor,
12943                             MultiExprArg ExprArgs,
12944                             bool HadMultipleCandidates,
12945                             bool IsListInitialization,
12946                             bool IsStdInitListInitialization,
12947                             bool RequiresZeroInit,
12948                             unsigned ConstructKind,
12949                             SourceRange ParenRange) {
12950   bool Elidable = false;
12951 
12952   // C++0x [class.copy]p34:
12953   //   When certain criteria are met, an implementation is allowed to
12954   //   omit the copy/move construction of a class object, even if the
12955   //   copy/move constructor and/or destructor for the object have
12956   //   side effects. [...]
12957   //     - when a temporary class object that has not been bound to a
12958   //       reference (12.2) would be copied/moved to a class object
12959   //       with the same cv-unqualified type, the copy/move operation
12960   //       can be omitted by constructing the temporary object
12961   //       directly into the target of the omitted copy/move
12962   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12963       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12964     Expr *SubExpr = ExprArgs[0];
12965     Elidable = SubExpr->isTemporaryObject(
12966         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12967   }
12968 
12969   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12970                                FoundDecl, Constructor,
12971                                Elidable, ExprArgs, HadMultipleCandidates,
12972                                IsListInitialization,
12973                                IsStdInitListInitialization, RequiresZeroInit,
12974                                ConstructKind, ParenRange);
12975 }
12976 
12977 ExprResult
12978 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12979                             NamedDecl *FoundDecl,
12980                             CXXConstructorDecl *Constructor,
12981                             bool Elidable,
12982                             MultiExprArg ExprArgs,
12983                             bool HadMultipleCandidates,
12984                             bool IsListInitialization,
12985                             bool IsStdInitListInitialization,
12986                             bool RequiresZeroInit,
12987                             unsigned ConstructKind,
12988                             SourceRange ParenRange) {
12989   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12990     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12991     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12992       return ExprError();
12993   }
12994 
12995   return BuildCXXConstructExpr(
12996       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12997       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12998       RequiresZeroInit, ConstructKind, ParenRange);
12999 }
13000 
13001 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
13002 /// including handling of its default argument expressions.
13003 ExprResult
13004 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13005                             CXXConstructorDecl *Constructor,
13006                             bool Elidable,
13007                             MultiExprArg ExprArgs,
13008                             bool HadMultipleCandidates,
13009                             bool IsListInitialization,
13010                             bool IsStdInitListInitialization,
13011                             bool RequiresZeroInit,
13012                             unsigned ConstructKind,
13013                             SourceRange ParenRange) {
13014   assert(declaresSameEntity(
13015              Constructor->getParent(),
13016              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
13017          "given constructor for wrong type");
13018   MarkFunctionReferenced(ConstructLoc, Constructor);
13019   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
13020     return ExprError();
13021 
13022   return CXXConstructExpr::Create(
13023       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
13024       ExprArgs, HadMultipleCandidates, IsListInitialization,
13025       IsStdInitListInitialization, RequiresZeroInit,
13026       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
13027       ParenRange);
13028 }
13029 
13030 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
13031   assert(Field->hasInClassInitializer());
13032 
13033   // If we already have the in-class initializer nothing needs to be done.
13034   if (Field->getInClassInitializer())
13035     return CXXDefaultInitExpr::Create(Context, Loc, Field);
13036 
13037   // If we might have already tried and failed to instantiate, don't try again.
13038   if (Field->isInvalidDecl())
13039     return ExprError();
13040 
13041   // Maybe we haven't instantiated the in-class initializer. Go check the
13042   // pattern FieldDecl to see if it has one.
13043   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
13044 
13045   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
13046     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
13047     DeclContext::lookup_result Lookup =
13048         ClassPattern->lookup(Field->getDeclName());
13049 
13050     // Lookup can return at most two results: the pattern for the field, or the
13051     // injected class name of the parent record. No other member can have the
13052     // same name as the field.
13053     // In modules mode, lookup can return multiple results (coming from
13054     // different modules).
13055     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
13056            "more than two lookup results for field name");
13057     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
13058     if (!Pattern) {
13059       assert(isa<CXXRecordDecl>(Lookup[0]) &&
13060              "cannot have other non-field member with same name");
13061       for (auto L : Lookup)
13062         if (isa<FieldDecl>(L)) {
13063           Pattern = cast<FieldDecl>(L);
13064           break;
13065         }
13066       assert(Pattern && "We must have set the Pattern!");
13067     }
13068 
13069     if (!Pattern->hasInClassInitializer() ||
13070         InstantiateInClassInitializer(Loc, Field, Pattern,
13071                                       getTemplateInstantiationArgs(Field))) {
13072       // Don't diagnose this again.
13073       Field->setInvalidDecl();
13074       return ExprError();
13075     }
13076     return CXXDefaultInitExpr::Create(Context, Loc, Field);
13077   }
13078 
13079   // DR1351:
13080   //   If the brace-or-equal-initializer of a non-static data member
13081   //   invokes a defaulted default constructor of its class or of an
13082   //   enclosing class in a potentially evaluated subexpression, the
13083   //   program is ill-formed.
13084   //
13085   // This resolution is unworkable: the exception specification of the
13086   // default constructor can be needed in an unevaluated context, in
13087   // particular, in the operand of a noexcept-expression, and we can be
13088   // unable to compute an exception specification for an enclosed class.
13089   //
13090   // Any attempt to resolve the exception specification of a defaulted default
13091   // constructor before the initializer is lexically complete will ultimately
13092   // come here at which point we can diagnose it.
13093   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13094   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13095       << OutermostClass << Field;
13096   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13097   // Recover by marking the field invalid, unless we're in a SFINAE context.
13098   if (!isSFINAEContext())
13099     Field->setInvalidDecl();
13100   return ExprError();
13101 }
13102 
13103 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13104   if (VD->isInvalidDecl()) return;
13105 
13106   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13107   if (ClassDecl->isInvalidDecl()) return;
13108   if (ClassDecl->hasIrrelevantDestructor()) return;
13109   if (ClassDecl->isDependentContext()) return;
13110 
13111   if (VD->isNoDestroy(getASTContext()))
13112     return;
13113 
13114   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13115   MarkFunctionReferenced(VD->getLocation(), Destructor);
13116   CheckDestructorAccess(VD->getLocation(), Destructor,
13117                         PDiag(diag::err_access_dtor_var)
13118                         << VD->getDeclName()
13119                         << VD->getType());
13120   DiagnoseUseOfDecl(Destructor, VD->getLocation());
13121 
13122   if (Destructor->isTrivial()) return;
13123   if (!VD->hasGlobalStorage()) return;
13124 
13125   // Emit warning for non-trivial dtor in global scope (a real global,
13126   // class-static, function-static).
13127   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13128 
13129   // TODO: this should be re-enabled for static locals by !CXAAtExit
13130   if (!VD->isStaticLocal())
13131     Diag(VD->getLocation(), diag::warn_global_destructor);
13132 }
13133 
13134 /// Given a constructor and the set of arguments provided for the
13135 /// constructor, convert the arguments and add any required default arguments
13136 /// to form a proper call to this constructor.
13137 ///
13138 /// \returns true if an error occurred, false otherwise.
13139 bool
13140 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13141                               MultiExprArg ArgsPtr,
13142                               SourceLocation Loc,
13143                               SmallVectorImpl<Expr*> &ConvertedArgs,
13144                               bool AllowExplicit,
13145                               bool IsListInitialization) {
13146   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13147   unsigned NumArgs = ArgsPtr.size();
13148   Expr **Args = ArgsPtr.data();
13149 
13150   const FunctionProtoType *Proto
13151     = Constructor->getType()->getAs<FunctionProtoType>();
13152   assert(Proto && "Constructor without a prototype?");
13153   unsigned NumParams = Proto->getNumParams();
13154 
13155   // If too few arguments are available, we'll fill in the rest with defaults.
13156   if (NumArgs < NumParams)
13157     ConvertedArgs.reserve(NumParams);
13158   else
13159     ConvertedArgs.reserve(NumArgs);
13160 
13161   VariadicCallType CallType =
13162     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13163   SmallVector<Expr *, 8> AllArgs;
13164   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13165                                         Proto, 0,
13166                                         llvm::makeArrayRef(Args, NumArgs),
13167                                         AllArgs,
13168                                         CallType, AllowExplicit,
13169                                         IsListInitialization);
13170   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13171 
13172   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13173 
13174   CheckConstructorCall(Constructor,
13175                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13176                        Proto, Loc);
13177 
13178   return Invalid;
13179 }
13180 
13181 static inline bool
13182 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13183                                        const FunctionDecl *FnDecl) {
13184   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13185   if (isa<NamespaceDecl>(DC)) {
13186     return SemaRef.Diag(FnDecl->getLocation(),
13187                         diag::err_operator_new_delete_declared_in_namespace)
13188       << FnDecl->getDeclName();
13189   }
13190 
13191   if (isa<TranslationUnitDecl>(DC) &&
13192       FnDecl->getStorageClass() == SC_Static) {
13193     return SemaRef.Diag(FnDecl->getLocation(),
13194                         diag::err_operator_new_delete_declared_static)
13195       << FnDecl->getDeclName();
13196   }
13197 
13198   return false;
13199 }
13200 
13201 static QualType
13202 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13203   QualType QTy = PtrTy->getPointeeType();
13204   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13205   return SemaRef.Context.getPointerType(QTy);
13206 }
13207 
13208 static inline bool
13209 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13210                             CanQualType ExpectedResultType,
13211                             CanQualType ExpectedFirstParamType,
13212                             unsigned DependentParamTypeDiag,
13213                             unsigned InvalidParamTypeDiag) {
13214   QualType ResultType =
13215       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13216 
13217   // Check that the result type is not dependent.
13218   if (ResultType->isDependentType())
13219     return SemaRef.Diag(FnDecl->getLocation(),
13220                         diag::err_operator_new_delete_dependent_result_type)
13221     << FnDecl->getDeclName() << ExpectedResultType;
13222 
13223   // OpenCL C++: the operator is valid on any address space.
13224   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13225     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13226       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13227     }
13228   }
13229 
13230   // Check that the result type is what we expect.
13231   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13232     return SemaRef.Diag(FnDecl->getLocation(),
13233                         diag::err_operator_new_delete_invalid_result_type)
13234     << FnDecl->getDeclName() << ExpectedResultType;
13235 
13236   // A function template must have at least 2 parameters.
13237   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13238     return SemaRef.Diag(FnDecl->getLocation(),
13239                       diag::err_operator_new_delete_template_too_few_parameters)
13240         << FnDecl->getDeclName();
13241 
13242   // The function decl must have at least 1 parameter.
13243   if (FnDecl->getNumParams() == 0)
13244     return SemaRef.Diag(FnDecl->getLocation(),
13245                         diag::err_operator_new_delete_too_few_parameters)
13246       << FnDecl->getDeclName();
13247 
13248   // Check the first parameter type is not dependent.
13249   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13250   if (FirstParamType->isDependentType())
13251     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13252       << FnDecl->getDeclName() << ExpectedFirstParamType;
13253 
13254   // Check that the first parameter type is what we expect.
13255   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13256     // OpenCL C++: the operator is valid on any address space.
13257     if (auto *PtrTy =
13258             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13259       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13260     }
13261   }
13262   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13263       ExpectedFirstParamType)
13264     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13265     << FnDecl->getDeclName() << ExpectedFirstParamType;
13266 
13267   return false;
13268 }
13269 
13270 static bool
13271 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13272   // C++ [basic.stc.dynamic.allocation]p1:
13273   //   A program is ill-formed if an allocation function is declared in a
13274   //   namespace scope other than global scope or declared static in global
13275   //   scope.
13276   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13277     return true;
13278 
13279   CanQualType SizeTy =
13280     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13281 
13282   // C++ [basic.stc.dynamic.allocation]p1:
13283   //  The return type shall be void*. The first parameter shall have type
13284   //  std::size_t.
13285   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13286                                   SizeTy,
13287                                   diag::err_operator_new_dependent_param_type,
13288                                   diag::err_operator_new_param_type))
13289     return true;
13290 
13291   // C++ [basic.stc.dynamic.allocation]p1:
13292   //  The first parameter shall not have an associated default argument.
13293   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13294     return SemaRef.Diag(FnDecl->getLocation(),
13295                         diag::err_operator_new_default_arg)
13296       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13297 
13298   return false;
13299 }
13300 
13301 static bool
13302 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13303   // C++ [basic.stc.dynamic.deallocation]p1:
13304   //   A program is ill-formed if deallocation functions are declared in a
13305   //   namespace scope other than global scope or declared static in global
13306   //   scope.
13307   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13308     return true;
13309 
13310   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13311 
13312   // C++ P0722:
13313   //   Within a class C, the first parameter of a destroying operator delete
13314   //   shall be of type C *. The first parameter of any other deallocation
13315   //   function shall be of type void *.
13316   CanQualType ExpectedFirstParamType =
13317       MD && MD->isDestroyingOperatorDelete()
13318           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13319                 SemaRef.Context.getRecordType(MD->getParent())))
13320           : SemaRef.Context.VoidPtrTy;
13321 
13322   // C++ [basic.stc.dynamic.deallocation]p2:
13323   //   Each deallocation function shall return void
13324   if (CheckOperatorNewDeleteTypes(
13325           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13326           diag::err_operator_delete_dependent_param_type,
13327           diag::err_operator_delete_param_type))
13328     return true;
13329 
13330   // C++ P0722:
13331   //   A destroying operator delete shall be a usual deallocation function.
13332   if (MD && !MD->getParent()->isDependentContext() &&
13333       MD->isDestroyingOperatorDelete() &&
13334       !SemaRef.isUsualDeallocationFunction(MD)) {
13335     SemaRef.Diag(MD->getLocation(),
13336                  diag::err_destroying_operator_delete_not_usual);
13337     return true;
13338   }
13339 
13340   return false;
13341 }
13342 
13343 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13344 /// of this overloaded operator is well-formed. If so, returns false;
13345 /// otherwise, emits appropriate diagnostics and returns true.
13346 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13347   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13348          "Expected an overloaded operator declaration");
13349 
13350   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13351 
13352   // C++ [over.oper]p5:
13353   //   The allocation and deallocation functions, operator new,
13354   //   operator new[], operator delete and operator delete[], are
13355   //   described completely in 3.7.3. The attributes and restrictions
13356   //   found in the rest of this subclause do not apply to them unless
13357   //   explicitly stated in 3.7.3.
13358   if (Op == OO_Delete || Op == OO_Array_Delete)
13359     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13360 
13361   if (Op == OO_New || Op == OO_Array_New)
13362     return CheckOperatorNewDeclaration(*this, FnDecl);
13363 
13364   // C++ [over.oper]p6:
13365   //   An operator function shall either be a non-static member
13366   //   function or be a non-member function and have at least one
13367   //   parameter whose type is a class, a reference to a class, an
13368   //   enumeration, or a reference to an enumeration.
13369   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13370     if (MethodDecl->isStatic())
13371       return Diag(FnDecl->getLocation(),
13372                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13373   } else {
13374     bool ClassOrEnumParam = false;
13375     for (auto Param : FnDecl->parameters()) {
13376       QualType ParamType = Param->getType().getNonReferenceType();
13377       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13378           ParamType->isEnumeralType()) {
13379         ClassOrEnumParam = true;
13380         break;
13381       }
13382     }
13383 
13384     if (!ClassOrEnumParam)
13385       return Diag(FnDecl->getLocation(),
13386                   diag::err_operator_overload_needs_class_or_enum)
13387         << FnDecl->getDeclName();
13388   }
13389 
13390   // C++ [over.oper]p8:
13391   //   An operator function cannot have default arguments (8.3.6),
13392   //   except where explicitly stated below.
13393   //
13394   // Only the function-call operator allows default arguments
13395   // (C++ [over.call]p1).
13396   if (Op != OO_Call) {
13397     for (auto Param : FnDecl->parameters()) {
13398       if (Param->hasDefaultArg())
13399         return Diag(Param->getLocation(),
13400                     diag::err_operator_overload_default_arg)
13401           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13402     }
13403   }
13404 
13405   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13406     { false, false, false }
13407 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13408     , { Unary, Binary, MemberOnly }
13409 #include "clang/Basic/OperatorKinds.def"
13410   };
13411 
13412   bool CanBeUnaryOperator = OperatorUses[Op][0];
13413   bool CanBeBinaryOperator = OperatorUses[Op][1];
13414   bool MustBeMemberOperator = OperatorUses[Op][2];
13415 
13416   // C++ [over.oper]p8:
13417   //   [...] Operator functions cannot have more or fewer parameters
13418   //   than the number required for the corresponding operator, as
13419   //   described in the rest of this subclause.
13420   unsigned NumParams = FnDecl->getNumParams()
13421                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13422   if (Op != OO_Call &&
13423       ((NumParams == 1 && !CanBeUnaryOperator) ||
13424        (NumParams == 2 && !CanBeBinaryOperator) ||
13425        (NumParams < 1) || (NumParams > 2))) {
13426     // We have the wrong number of parameters.
13427     unsigned ErrorKind;
13428     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13429       ErrorKind = 2;  // 2 -> unary or binary.
13430     } else if (CanBeUnaryOperator) {
13431       ErrorKind = 0;  // 0 -> unary
13432     } else {
13433       assert(CanBeBinaryOperator &&
13434              "All non-call overloaded operators are unary or binary!");
13435       ErrorKind = 1;  // 1 -> binary
13436     }
13437 
13438     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13439       << FnDecl->getDeclName() << NumParams << ErrorKind;
13440   }
13441 
13442   // Overloaded operators other than operator() cannot be variadic.
13443   if (Op != OO_Call &&
13444       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13445     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13446       << FnDecl->getDeclName();
13447   }
13448 
13449   // Some operators must be non-static member functions.
13450   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13451     return Diag(FnDecl->getLocation(),
13452                 diag::err_operator_overload_must_be_member)
13453       << FnDecl->getDeclName();
13454   }
13455 
13456   // C++ [over.inc]p1:
13457   //   The user-defined function called operator++ implements the
13458   //   prefix and postfix ++ operator. If this function is a member
13459   //   function with no parameters, or a non-member function with one
13460   //   parameter of class or enumeration type, it defines the prefix
13461   //   increment operator ++ for objects of that type. If the function
13462   //   is a member function with one parameter (which shall be of type
13463   //   int) or a non-member function with two parameters (the second
13464   //   of which shall be of type int), it defines the postfix
13465   //   increment operator ++ for objects of that type.
13466   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13467     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13468     QualType ParamType = LastParam->getType();
13469 
13470     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13471         !ParamType->isDependentType())
13472       return Diag(LastParam->getLocation(),
13473                   diag::err_operator_overload_post_incdec_must_be_int)
13474         << LastParam->getType() << (Op == OO_MinusMinus);
13475   }
13476 
13477   return false;
13478 }
13479 
13480 static bool
13481 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13482                                           FunctionTemplateDecl *TpDecl) {
13483   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13484 
13485   // Must have one or two template parameters.
13486   if (TemplateParams->size() == 1) {
13487     NonTypeTemplateParmDecl *PmDecl =
13488         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13489 
13490     // The template parameter must be a char parameter pack.
13491     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13492         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13493       return false;
13494 
13495   } else if (TemplateParams->size() == 2) {
13496     TemplateTypeParmDecl *PmType =
13497         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13498     NonTypeTemplateParmDecl *PmArgs =
13499         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13500 
13501     // The second template parameter must be a parameter pack with the
13502     // first template parameter as its type.
13503     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13504         PmArgs->isTemplateParameterPack()) {
13505       const TemplateTypeParmType *TArgs =
13506           PmArgs->getType()->getAs<TemplateTypeParmType>();
13507       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13508           TArgs->getIndex() == PmType->getIndex()) {
13509         if (!SemaRef.inTemplateInstantiation())
13510           SemaRef.Diag(TpDecl->getLocation(),
13511                        diag::ext_string_literal_operator_template);
13512         return false;
13513       }
13514     }
13515   }
13516 
13517   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13518                diag::err_literal_operator_template)
13519       << TpDecl->getTemplateParameters()->getSourceRange();
13520   return true;
13521 }
13522 
13523 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13524 /// of this literal operator function is well-formed. If so, returns
13525 /// false; otherwise, emits appropriate diagnostics and returns true.
13526 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13527   if (isa<CXXMethodDecl>(FnDecl)) {
13528     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13529       << FnDecl->getDeclName();
13530     return true;
13531   }
13532 
13533   if (FnDecl->isExternC()) {
13534     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13535     if (const LinkageSpecDecl *LSD =
13536             FnDecl->getDeclContext()->getExternCContext())
13537       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13538     return true;
13539   }
13540 
13541   // This might be the definition of a literal operator template.
13542   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13543 
13544   // This might be a specialization of a literal operator template.
13545   if (!TpDecl)
13546     TpDecl = FnDecl->getPrimaryTemplate();
13547 
13548   // template <char...> type operator "" name() and
13549   // template <class T, T...> type operator "" name() are the only valid
13550   // template signatures, and the only valid signatures with no parameters.
13551   if (TpDecl) {
13552     if (FnDecl->param_size() != 0) {
13553       Diag(FnDecl->getLocation(),
13554            diag::err_literal_operator_template_with_params);
13555       return true;
13556     }
13557 
13558     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13559       return true;
13560 
13561   } else if (FnDecl->param_size() == 1) {
13562     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13563 
13564     QualType ParamType = Param->getType().getUnqualifiedType();
13565 
13566     // Only unsigned long long int, long double, any character type, and const
13567     // char * are allowed as the only parameters.
13568     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13569         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13570         Context.hasSameType(ParamType, Context.CharTy) ||
13571         Context.hasSameType(ParamType, Context.WideCharTy) ||
13572         Context.hasSameType(ParamType, Context.Char8Ty) ||
13573         Context.hasSameType(ParamType, Context.Char16Ty) ||
13574         Context.hasSameType(ParamType, Context.Char32Ty)) {
13575     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13576       QualType InnerType = Ptr->getPointeeType();
13577 
13578       // Pointer parameter must be a const char *.
13579       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13580                                 Context.CharTy) &&
13581             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13582         Diag(Param->getSourceRange().getBegin(),
13583              diag::err_literal_operator_param)
13584             << ParamType << "'const char *'" << Param->getSourceRange();
13585         return true;
13586       }
13587 
13588     } else if (ParamType->isRealFloatingType()) {
13589       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13590           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13591       return true;
13592 
13593     } else if (ParamType->isIntegerType()) {
13594       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13595           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13596       return true;
13597 
13598     } else {
13599       Diag(Param->getSourceRange().getBegin(),
13600            diag::err_literal_operator_invalid_param)
13601           << ParamType << Param->getSourceRange();
13602       return true;
13603     }
13604 
13605   } else if (FnDecl->param_size() == 2) {
13606     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13607 
13608     // First, verify that the first parameter is correct.
13609 
13610     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13611 
13612     // Two parameter function must have a pointer to const as a
13613     // first parameter; let's strip those qualifiers.
13614     const PointerType *PT = FirstParamType->getAs<PointerType>();
13615 
13616     if (!PT) {
13617       Diag((*Param)->getSourceRange().getBegin(),
13618            diag::err_literal_operator_param)
13619           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13620       return true;
13621     }
13622 
13623     QualType PointeeType = PT->getPointeeType();
13624     // First parameter must be const
13625     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13626       Diag((*Param)->getSourceRange().getBegin(),
13627            diag::err_literal_operator_param)
13628           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13629       return true;
13630     }
13631 
13632     QualType InnerType = PointeeType.getUnqualifiedType();
13633     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13634     // const char32_t* are allowed as the first parameter to a two-parameter
13635     // function
13636     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13637           Context.hasSameType(InnerType, Context.WideCharTy) ||
13638           Context.hasSameType(InnerType, Context.Char8Ty) ||
13639           Context.hasSameType(InnerType, Context.Char16Ty) ||
13640           Context.hasSameType(InnerType, Context.Char32Ty))) {
13641       Diag((*Param)->getSourceRange().getBegin(),
13642            diag::err_literal_operator_param)
13643           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13644       return true;
13645     }
13646 
13647     // Move on to the second and final parameter.
13648     ++Param;
13649 
13650     // The second parameter must be a std::size_t.
13651     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13652     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13653       Diag((*Param)->getSourceRange().getBegin(),
13654            diag::err_literal_operator_param)
13655           << SecondParamType << Context.getSizeType()
13656           << (*Param)->getSourceRange();
13657       return true;
13658     }
13659   } else {
13660     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13661     return true;
13662   }
13663 
13664   // Parameters are good.
13665 
13666   // A parameter-declaration-clause containing a default argument is not
13667   // equivalent to any of the permitted forms.
13668   for (auto Param : FnDecl->parameters()) {
13669     if (Param->hasDefaultArg()) {
13670       Diag(Param->getDefaultArgRange().getBegin(),
13671            diag::err_literal_operator_default_argument)
13672         << Param->getDefaultArgRange();
13673       break;
13674     }
13675   }
13676 
13677   StringRef LiteralName
13678     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13679   if (LiteralName[0] != '_' &&
13680       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13681     // C++11 [usrlit.suffix]p1:
13682     //   Literal suffix identifiers that do not start with an underscore
13683     //   are reserved for future standardization.
13684     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13685       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13686   }
13687 
13688   return false;
13689 }
13690 
13691 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13692 /// linkage specification, including the language and (if present)
13693 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13694 /// language string literal. LBraceLoc, if valid, provides the location of
13695 /// the '{' brace. Otherwise, this linkage specification does not
13696 /// have any braces.
13697 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13698                                            Expr *LangStr,
13699                                            SourceLocation LBraceLoc) {
13700   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13701   if (!Lit->isAscii()) {
13702     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13703       << LangStr->getSourceRange();
13704     return nullptr;
13705   }
13706 
13707   StringRef Lang = Lit->getString();
13708   LinkageSpecDecl::LanguageIDs Language;
13709   if (Lang == "C")
13710     Language = LinkageSpecDecl::lang_c;
13711   else if (Lang == "C++")
13712     Language = LinkageSpecDecl::lang_cxx;
13713   else {
13714     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13715       << LangStr->getSourceRange();
13716     return nullptr;
13717   }
13718 
13719   // FIXME: Add all the various semantics of linkage specifications
13720 
13721   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13722                                                LangStr->getExprLoc(), Language,
13723                                                LBraceLoc.isValid());
13724   CurContext->addDecl(D);
13725   PushDeclContext(S, D);
13726   return D;
13727 }
13728 
13729 /// ActOnFinishLinkageSpecification - Complete the definition of
13730 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13731 /// valid, it's the position of the closing '}' brace in a linkage
13732 /// specification that uses braces.
13733 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13734                                             Decl *LinkageSpec,
13735                                             SourceLocation RBraceLoc) {
13736   if (RBraceLoc.isValid()) {
13737     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13738     LSDecl->setRBraceLoc(RBraceLoc);
13739   }
13740   PopDeclContext();
13741   return LinkageSpec;
13742 }
13743 
13744 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13745                                   const ParsedAttributesView &AttrList,
13746                                   SourceLocation SemiLoc) {
13747   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13748   // Attribute declarations appertain to empty declaration so we handle
13749   // them here.
13750   ProcessDeclAttributeList(S, ED, AttrList);
13751 
13752   CurContext->addDecl(ED);
13753   return ED;
13754 }
13755 
13756 /// Perform semantic analysis for the variable declaration that
13757 /// occurs within a C++ catch clause, returning the newly-created
13758 /// variable.
13759 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13760                                          TypeSourceInfo *TInfo,
13761                                          SourceLocation StartLoc,
13762                                          SourceLocation Loc,
13763                                          IdentifierInfo *Name) {
13764   bool Invalid = false;
13765   QualType ExDeclType = TInfo->getType();
13766 
13767   // Arrays and functions decay.
13768   if (ExDeclType->isArrayType())
13769     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13770   else if (ExDeclType->isFunctionType())
13771     ExDeclType = Context.getPointerType(ExDeclType);
13772 
13773   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13774   // The exception-declaration shall not denote a pointer or reference to an
13775   // incomplete type, other than [cv] void*.
13776   // N2844 forbids rvalue references.
13777   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13778     Diag(Loc, diag::err_catch_rvalue_ref);
13779     Invalid = true;
13780   }
13781 
13782   if (ExDeclType->isVariablyModifiedType()) {
13783     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13784     Invalid = true;
13785   }
13786 
13787   QualType BaseType = ExDeclType;
13788   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13789   unsigned DK = diag::err_catch_incomplete;
13790   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13791     BaseType = Ptr->getPointeeType();
13792     Mode = 1;
13793     DK = diag::err_catch_incomplete_ptr;
13794   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13795     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13796     BaseType = Ref->getPointeeType();
13797     Mode = 2;
13798     DK = diag::err_catch_incomplete_ref;
13799   }
13800   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13801       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13802     Invalid = true;
13803 
13804   if (!Invalid && !ExDeclType->isDependentType() &&
13805       RequireNonAbstractType(Loc, ExDeclType,
13806                              diag::err_abstract_type_in_decl,
13807                              AbstractVariableType))
13808     Invalid = true;
13809 
13810   // Only the non-fragile NeXT runtime currently supports C++ catches
13811   // of ObjC types, and no runtime supports catching ObjC types by value.
13812   if (!Invalid && getLangOpts().ObjC) {
13813     QualType T = ExDeclType;
13814     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13815       T = RT->getPointeeType();
13816 
13817     if (T->isObjCObjectType()) {
13818       Diag(Loc, diag::err_objc_object_catch);
13819       Invalid = true;
13820     } else if (T->isObjCObjectPointerType()) {
13821       // FIXME: should this be a test for macosx-fragile specifically?
13822       if (getLangOpts().ObjCRuntime.isFragile())
13823         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13824     }
13825   }
13826 
13827   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13828                                     ExDeclType, TInfo, SC_None);
13829   ExDecl->setExceptionVariable(true);
13830 
13831   // In ARC, infer 'retaining' for variables of retainable type.
13832   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13833     Invalid = true;
13834 
13835   if (!Invalid && !ExDeclType->isDependentType()) {
13836     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13837       // Insulate this from anything else we might currently be parsing.
13838       EnterExpressionEvaluationContext scope(
13839           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13840 
13841       // C++ [except.handle]p16:
13842       //   The object declared in an exception-declaration or, if the
13843       //   exception-declaration does not specify a name, a temporary (12.2) is
13844       //   copy-initialized (8.5) from the exception object. [...]
13845       //   The object is destroyed when the handler exits, after the destruction
13846       //   of any automatic objects initialized within the handler.
13847       //
13848       // We just pretend to initialize the object with itself, then make sure
13849       // it can be destroyed later.
13850       QualType initType = Context.getExceptionObjectType(ExDeclType);
13851 
13852       InitializedEntity entity =
13853         InitializedEntity::InitializeVariable(ExDecl);
13854       InitializationKind initKind =
13855         InitializationKind::CreateCopy(Loc, SourceLocation());
13856 
13857       Expr *opaqueValue =
13858         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13859       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13860       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13861       if (result.isInvalid())
13862         Invalid = true;
13863       else {
13864         // If the constructor used was non-trivial, set this as the
13865         // "initializer".
13866         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13867         if (!construct->getConstructor()->isTrivial()) {
13868           Expr *init = MaybeCreateExprWithCleanups(construct);
13869           ExDecl->setInit(init);
13870         }
13871 
13872         // And make sure it's destructable.
13873         FinalizeVarWithDestructor(ExDecl, recordType);
13874       }
13875     }
13876   }
13877 
13878   if (Invalid)
13879     ExDecl->setInvalidDecl();
13880 
13881   return ExDecl;
13882 }
13883 
13884 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13885 /// handler.
13886 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13887   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13888   bool Invalid = D.isInvalidType();
13889 
13890   // Check for unexpanded parameter packs.
13891   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13892                                       UPPC_ExceptionType)) {
13893     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13894                                              D.getIdentifierLoc());
13895     Invalid = true;
13896   }
13897 
13898   IdentifierInfo *II = D.getIdentifier();
13899   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13900                                              LookupOrdinaryName,
13901                                              ForVisibleRedeclaration)) {
13902     // The scope should be freshly made just for us. There is just no way
13903     // it contains any previous declaration, except for function parameters in
13904     // a function-try-block's catch statement.
13905     assert(!S->isDeclScope(PrevDecl));
13906     if (isDeclInScope(PrevDecl, CurContext, S)) {
13907       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13908         << D.getIdentifier();
13909       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13910       Invalid = true;
13911     } else if (PrevDecl->isTemplateParameter())
13912       // Maybe we will complain about the shadowed template parameter.
13913       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13914   }
13915 
13916   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13917     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13918       << D.getCXXScopeSpec().getRange();
13919     Invalid = true;
13920   }
13921 
13922   VarDecl *ExDecl = BuildExceptionDeclaration(
13923       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
13924   if (Invalid)
13925     ExDecl->setInvalidDecl();
13926 
13927   // Add the exception declaration into this scope.
13928   if (II)
13929     PushOnScopeChains(ExDecl, S);
13930   else
13931     CurContext->addDecl(ExDecl);
13932 
13933   ProcessDeclAttributes(S, ExDecl, D);
13934   return ExDecl;
13935 }
13936 
13937 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13938                                          Expr *AssertExpr,
13939                                          Expr *AssertMessageExpr,
13940                                          SourceLocation RParenLoc) {
13941   StringLiteral *AssertMessage =
13942       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13943 
13944   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13945     return nullptr;
13946 
13947   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13948                                       AssertMessage, RParenLoc, false);
13949 }
13950 
13951 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13952                                          Expr *AssertExpr,
13953                                          StringLiteral *AssertMessage,
13954                                          SourceLocation RParenLoc,
13955                                          bool Failed) {
13956   assert(AssertExpr != nullptr && "Expected non-null condition");
13957   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13958       !Failed) {
13959     // In a static_assert-declaration, the constant-expression shall be a
13960     // constant expression that can be contextually converted to bool.
13961     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13962     if (Converted.isInvalid())
13963       Failed = true;
13964     else
13965       Converted = ConstantExpr::Create(Context, Converted.get());
13966 
13967     llvm::APSInt Cond;
13968     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13969           diag::err_static_assert_expression_is_not_constant,
13970           /*AllowFold=*/false).isInvalid())
13971       Failed = true;
13972 
13973     if (!Failed && !Cond) {
13974       SmallString<256> MsgBuffer;
13975       llvm::raw_svector_ostream Msg(MsgBuffer);
13976       if (AssertMessage)
13977         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13978 
13979       Expr *InnerCond = nullptr;
13980       std::string InnerCondDescription;
13981       std::tie(InnerCond, InnerCondDescription) =
13982         findFailedBooleanCondition(Converted.get());
13983       if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
13984                     && !isa<IntegerLiteral>(InnerCond)) {
13985         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13986           << InnerCondDescription << !AssertMessage
13987           << Msg.str() << InnerCond->getSourceRange();
13988       } else {
13989         Diag(StaticAssertLoc, diag::err_static_assert_failed)
13990           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13991       }
13992       Failed = true;
13993     }
13994   }
13995 
13996   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13997                                                   /*DiscardedValue*/false,
13998                                                   /*IsConstexpr*/true);
13999   if (FullAssertExpr.isInvalid())
14000     Failed = true;
14001   else
14002     AssertExpr = FullAssertExpr.get();
14003 
14004   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
14005                                         AssertExpr, AssertMessage, RParenLoc,
14006                                         Failed);
14007 
14008   CurContext->addDecl(Decl);
14009   return Decl;
14010 }
14011 
14012 /// Perform semantic analysis of the given friend type declaration.
14013 ///
14014 /// \returns A friend declaration that.
14015 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
14016                                       SourceLocation FriendLoc,
14017                                       TypeSourceInfo *TSInfo) {
14018   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
14019 
14020   QualType T = TSInfo->getType();
14021   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
14022 
14023   // C++03 [class.friend]p2:
14024   //   An elaborated-type-specifier shall be used in a friend declaration
14025   //   for a class.*
14026   //
14027   //   * The class-key of the elaborated-type-specifier is required.
14028   if (!CodeSynthesisContexts.empty()) {
14029     // Do not complain about the form of friend template types during any kind
14030     // of code synthesis. For template instantiation, we will have complained
14031     // when the template was defined.
14032   } else {
14033     if (!T->isElaboratedTypeSpecifier()) {
14034       // If we evaluated the type to a record type, suggest putting
14035       // a tag in front.
14036       if (const RecordType *RT = T->getAs<RecordType>()) {
14037         RecordDecl *RD = RT->getDecl();
14038 
14039         SmallString<16> InsertionText(" ");
14040         InsertionText += RD->getKindName();
14041 
14042         Diag(TypeRange.getBegin(),
14043              getLangOpts().CPlusPlus11 ?
14044                diag::warn_cxx98_compat_unelaborated_friend_type :
14045                diag::ext_unelaborated_friend_type)
14046           << (unsigned) RD->getTagKind()
14047           << T
14048           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
14049                                         InsertionText);
14050       } else {
14051         Diag(FriendLoc,
14052              getLangOpts().CPlusPlus11 ?
14053                diag::warn_cxx98_compat_nonclass_type_friend :
14054                diag::ext_nonclass_type_friend)
14055           << T
14056           << TypeRange;
14057       }
14058     } else if (T->getAs<EnumType>()) {
14059       Diag(FriendLoc,
14060            getLangOpts().CPlusPlus11 ?
14061              diag::warn_cxx98_compat_enum_friend :
14062              diag::ext_enum_friend)
14063         << T
14064         << TypeRange;
14065     }
14066 
14067     // C++11 [class.friend]p3:
14068     //   A friend declaration that does not declare a function shall have one
14069     //   of the following forms:
14070     //     friend elaborated-type-specifier ;
14071     //     friend simple-type-specifier ;
14072     //     friend typename-specifier ;
14073     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14074       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14075   }
14076 
14077   //   If the type specifier in a friend declaration designates a (possibly
14078   //   cv-qualified) class type, that class is declared as a friend; otherwise,
14079   //   the friend declaration is ignored.
14080   return FriendDecl::Create(Context, CurContext,
14081                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14082                             FriendLoc);
14083 }
14084 
14085 /// Handle a friend tag declaration where the scope specifier was
14086 /// templated.
14087 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
14088                                     unsigned TagSpec, SourceLocation TagLoc,
14089                                     CXXScopeSpec &SS, IdentifierInfo *Name,
14090                                     SourceLocation NameLoc,
14091                                     const ParsedAttributesView &Attr,
14092                                     MultiTemplateParamsArg TempParamLists) {
14093   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14094 
14095   bool IsMemberSpecialization = false;
14096   bool Invalid = false;
14097 
14098   if (TemplateParameterList *TemplateParams =
14099           MatchTemplateParametersToScopeSpecifier(
14100               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14101               IsMemberSpecialization, Invalid)) {
14102     if (TemplateParams->size() > 0) {
14103       // This is a declaration of a class template.
14104       if (Invalid)
14105         return nullptr;
14106 
14107       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14108                                 NameLoc, Attr, TemplateParams, AS_public,
14109                                 /*ModulePrivateLoc=*/SourceLocation(),
14110                                 FriendLoc, TempParamLists.size() - 1,
14111                                 TempParamLists.data()).get();
14112     } else {
14113       // The "template<>" header is extraneous.
14114       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14115         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14116       IsMemberSpecialization = true;
14117     }
14118   }
14119 
14120   if (Invalid) return nullptr;
14121 
14122   bool isAllExplicitSpecializations = true;
14123   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14124     if (TempParamLists[I]->size()) {
14125       isAllExplicitSpecializations = false;
14126       break;
14127     }
14128   }
14129 
14130   // FIXME: don't ignore attributes.
14131 
14132   // If it's explicit specializations all the way down, just forget
14133   // about the template header and build an appropriate non-templated
14134   // friend.  TODO: for source fidelity, remember the headers.
14135   if (isAllExplicitSpecializations) {
14136     if (SS.isEmpty()) {
14137       bool Owned = false;
14138       bool IsDependent = false;
14139       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14140                       Attr, AS_public,
14141                       /*ModulePrivateLoc=*/SourceLocation(),
14142                       MultiTemplateParamsArg(), Owned, IsDependent,
14143                       /*ScopedEnumKWLoc=*/SourceLocation(),
14144                       /*ScopedEnumUsesClassTag=*/false,
14145                       /*UnderlyingType=*/TypeResult(),
14146                       /*IsTypeSpecifier=*/false,
14147                       /*IsTemplateParamOrArg=*/false);
14148     }
14149 
14150     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14151     ElaboratedTypeKeyword Keyword
14152       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14153     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14154                                    *Name, NameLoc);
14155     if (T.isNull())
14156       return nullptr;
14157 
14158     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14159     if (isa<DependentNameType>(T)) {
14160       DependentNameTypeLoc TL =
14161           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14162       TL.setElaboratedKeywordLoc(TagLoc);
14163       TL.setQualifierLoc(QualifierLoc);
14164       TL.setNameLoc(NameLoc);
14165     } else {
14166       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14167       TL.setElaboratedKeywordLoc(TagLoc);
14168       TL.setQualifierLoc(QualifierLoc);
14169       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14170     }
14171 
14172     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14173                                             TSI, FriendLoc, TempParamLists);
14174     Friend->setAccess(AS_public);
14175     CurContext->addDecl(Friend);
14176     return Friend;
14177   }
14178 
14179   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14180 
14181 
14182 
14183   // Handle the case of a templated-scope friend class.  e.g.
14184   //   template <class T> class A<T>::B;
14185   // FIXME: we don't support these right now.
14186   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14187     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14188   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14189   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14190   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14191   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14192   TL.setElaboratedKeywordLoc(TagLoc);
14193   TL.setQualifierLoc(SS.getWithLocInContext(Context));
14194   TL.setNameLoc(NameLoc);
14195 
14196   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14197                                           TSI, FriendLoc, TempParamLists);
14198   Friend->setAccess(AS_public);
14199   Friend->setUnsupportedFriend(true);
14200   CurContext->addDecl(Friend);
14201   return Friend;
14202 }
14203 
14204 /// Handle a friend type declaration.  This works in tandem with
14205 /// ActOnTag.
14206 ///
14207 /// Notes on friend class templates:
14208 ///
14209 /// We generally treat friend class declarations as if they were
14210 /// declaring a class.  So, for example, the elaborated type specifier
14211 /// in a friend declaration is required to obey the restrictions of a
14212 /// class-head (i.e. no typedefs in the scope chain), template
14213 /// parameters are required to match up with simple template-ids, &c.
14214 /// However, unlike when declaring a template specialization, it's
14215 /// okay to refer to a template specialization without an empty
14216 /// template parameter declaration, e.g.
14217 ///   friend class A<T>::B<unsigned>;
14218 /// We permit this as a special case; if there are any template
14219 /// parameters present at all, require proper matching, i.e.
14220 ///   template <> template \<class T> friend class A<int>::B;
14221 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14222                                 MultiTemplateParamsArg TempParams) {
14223   SourceLocation Loc = DS.getBeginLoc();
14224 
14225   assert(DS.isFriendSpecified());
14226   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14227 
14228   // C++ [class.friend]p3:
14229   // A friend declaration that does not declare a function shall have one of
14230   // the following forms:
14231   //     friend elaborated-type-specifier ;
14232   //     friend simple-type-specifier ;
14233   //     friend typename-specifier ;
14234   //
14235   // Any declaration with a type qualifier does not have that form. (It's
14236   // legal to specify a qualified type as a friend, you just can't write the
14237   // keywords.)
14238   if (DS.getTypeQualifiers()) {
14239     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14240       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14241     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14242       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14243     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14244       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14245     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14246       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14247     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14248       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14249   }
14250 
14251   // Try to convert the decl specifier to a type.  This works for
14252   // friend templates because ActOnTag never produces a ClassTemplateDecl
14253   // for a TUK_Friend.
14254   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14255   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14256   QualType T = TSI->getType();
14257   if (TheDeclarator.isInvalidType())
14258     return nullptr;
14259 
14260   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14261     return nullptr;
14262 
14263   // This is definitely an error in C++98.  It's probably meant to
14264   // be forbidden in C++0x, too, but the specification is just
14265   // poorly written.
14266   //
14267   // The problem is with declarations like the following:
14268   //   template <T> friend A<T>::foo;
14269   // where deciding whether a class C is a friend or not now hinges
14270   // on whether there exists an instantiation of A that causes
14271   // 'foo' to equal C.  There are restrictions on class-heads
14272   // (which we declare (by fiat) elaborated friend declarations to
14273   // be) that makes this tractable.
14274   //
14275   // FIXME: handle "template <> friend class A<T>;", which
14276   // is possibly well-formed?  Who even knows?
14277   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14278     Diag(Loc, diag::err_tagless_friend_type_template)
14279       << DS.getSourceRange();
14280     return nullptr;
14281   }
14282 
14283   // C++98 [class.friend]p1: A friend of a class is a function
14284   //   or class that is not a member of the class . . .
14285   // This is fixed in DR77, which just barely didn't make the C++03
14286   // deadline.  It's also a very silly restriction that seriously
14287   // affects inner classes and which nobody else seems to implement;
14288   // thus we never diagnose it, not even in -pedantic.
14289   //
14290   // But note that we could warn about it: it's always useless to
14291   // friend one of your own members (it's not, however, worthless to
14292   // friend a member of an arbitrary specialization of your template).
14293 
14294   Decl *D;
14295   if (!TempParams.empty())
14296     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14297                                    TempParams,
14298                                    TSI,
14299                                    DS.getFriendSpecLoc());
14300   else
14301     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14302 
14303   if (!D)
14304     return nullptr;
14305 
14306   D->setAccess(AS_public);
14307   CurContext->addDecl(D);
14308 
14309   return D;
14310 }
14311 
14312 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14313                                         MultiTemplateParamsArg TemplateParams) {
14314   const DeclSpec &DS = D.getDeclSpec();
14315 
14316   assert(DS.isFriendSpecified());
14317   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14318 
14319   SourceLocation Loc = D.getIdentifierLoc();
14320   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14321 
14322   // C++ [class.friend]p1
14323   //   A friend of a class is a function or class....
14324   // Note that this sees through typedefs, which is intended.
14325   // It *doesn't* see through dependent types, which is correct
14326   // according to [temp.arg.type]p3:
14327   //   If a declaration acquires a function type through a
14328   //   type dependent on a template-parameter and this causes
14329   //   a declaration that does not use the syntactic form of a
14330   //   function declarator to have a function type, the program
14331   //   is ill-formed.
14332   if (!TInfo->getType()->isFunctionType()) {
14333     Diag(Loc, diag::err_unexpected_friend);
14334 
14335     // It might be worthwhile to try to recover by creating an
14336     // appropriate declaration.
14337     return nullptr;
14338   }
14339 
14340   // C++ [namespace.memdef]p3
14341   //  - If a friend declaration in a non-local class first declares a
14342   //    class or function, the friend class or function is a member
14343   //    of the innermost enclosing namespace.
14344   //  - The name of the friend is not found by simple name lookup
14345   //    until a matching declaration is provided in that namespace
14346   //    scope (either before or after the class declaration granting
14347   //    friendship).
14348   //  - If a friend function is called, its name may be found by the
14349   //    name lookup that considers functions from namespaces and
14350   //    classes associated with the types of the function arguments.
14351   //  - When looking for a prior declaration of a class or a function
14352   //    declared as a friend, scopes outside the innermost enclosing
14353   //    namespace scope are not considered.
14354 
14355   CXXScopeSpec &SS = D.getCXXScopeSpec();
14356   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14357   assert(NameInfo.getName());
14358 
14359   // Check for unexpanded parameter packs.
14360   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14361       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14362       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14363     return nullptr;
14364 
14365   // The context we found the declaration in, or in which we should
14366   // create the declaration.
14367   DeclContext *DC;
14368   Scope *DCScope = S;
14369   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14370                         ForExternalRedeclaration);
14371 
14372   // There are five cases here.
14373   //   - There's no scope specifier and we're in a local class. Only look
14374   //     for functions declared in the immediately-enclosing block scope.
14375   // We recover from invalid scope qualifiers as if they just weren't there.
14376   FunctionDecl *FunctionContainingLocalClass = nullptr;
14377   if ((SS.isInvalid() || !SS.isSet()) &&
14378       (FunctionContainingLocalClass =
14379            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14380     // C++11 [class.friend]p11:
14381     //   If a friend declaration appears in a local class and the name
14382     //   specified is an unqualified name, a prior declaration is
14383     //   looked up without considering scopes that are outside the
14384     //   innermost enclosing non-class scope. For a friend function
14385     //   declaration, if there is no prior declaration, the program is
14386     //   ill-formed.
14387 
14388     // Find the innermost enclosing non-class scope. This is the block
14389     // scope containing the local class definition (or for a nested class,
14390     // the outer local class).
14391     DCScope = S->getFnParent();
14392 
14393     // Look up the function name in the scope.
14394     Previous.clear(LookupLocalFriendName);
14395     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14396 
14397     if (!Previous.empty()) {
14398       // All possible previous declarations must have the same context:
14399       // either they were declared at block scope or they are members of
14400       // one of the enclosing local classes.
14401       DC = Previous.getRepresentativeDecl()->getDeclContext();
14402     } else {
14403       // This is ill-formed, but provide the context that we would have
14404       // declared the function in, if we were permitted to, for error recovery.
14405       DC = FunctionContainingLocalClass;
14406     }
14407     adjustContextForLocalExternDecl(DC);
14408 
14409     // C++ [class.friend]p6:
14410     //   A function can be defined in a friend declaration of a class if and
14411     //   only if the class is a non-local class (9.8), the function name is
14412     //   unqualified, and the function has namespace scope.
14413     if (D.isFunctionDefinition()) {
14414       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14415     }
14416 
14417   //   - There's no scope specifier, in which case we just go to the
14418   //     appropriate scope and look for a function or function template
14419   //     there as appropriate.
14420   } else if (SS.isInvalid() || !SS.isSet()) {
14421     // C++11 [namespace.memdef]p3:
14422     //   If the name in a friend declaration is neither qualified nor
14423     //   a template-id and the declaration is a function or an
14424     //   elaborated-type-specifier, the lookup to determine whether
14425     //   the entity has been previously declared shall not consider
14426     //   any scopes outside the innermost enclosing namespace.
14427     bool isTemplateId =
14428         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14429 
14430     // Find the appropriate context according to the above.
14431     DC = CurContext;
14432 
14433     // Skip class contexts.  If someone can cite chapter and verse
14434     // for this behavior, that would be nice --- it's what GCC and
14435     // EDG do, and it seems like a reasonable intent, but the spec
14436     // really only says that checks for unqualified existing
14437     // declarations should stop at the nearest enclosing namespace,
14438     // not that they should only consider the nearest enclosing
14439     // namespace.
14440     while (DC->isRecord())
14441       DC = DC->getParent();
14442 
14443     DeclContext *LookupDC = DC;
14444     while (LookupDC->isTransparentContext())
14445       LookupDC = LookupDC->getParent();
14446 
14447     while (true) {
14448       LookupQualifiedName(Previous, LookupDC);
14449 
14450       if (!Previous.empty()) {
14451         DC = LookupDC;
14452         break;
14453       }
14454 
14455       if (isTemplateId) {
14456         if (isa<TranslationUnitDecl>(LookupDC)) break;
14457       } else {
14458         if (LookupDC->isFileContext()) break;
14459       }
14460       LookupDC = LookupDC->getParent();
14461     }
14462 
14463     DCScope = getScopeForDeclContext(S, DC);
14464 
14465   //   - There's a non-dependent scope specifier, in which case we
14466   //     compute it and do a previous lookup there for a function
14467   //     or function template.
14468   } else if (!SS.getScopeRep()->isDependent()) {
14469     DC = computeDeclContext(SS);
14470     if (!DC) return nullptr;
14471 
14472     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14473 
14474     LookupQualifiedName(Previous, DC);
14475 
14476     // C++ [class.friend]p1: A friend of a class is a function or
14477     //   class that is not a member of the class . . .
14478     if (DC->Equals(CurContext))
14479       Diag(DS.getFriendSpecLoc(),
14480            getLangOpts().CPlusPlus11 ?
14481              diag::warn_cxx98_compat_friend_is_member :
14482              diag::err_friend_is_member);
14483 
14484     if (D.isFunctionDefinition()) {
14485       // C++ [class.friend]p6:
14486       //   A function can be defined in a friend declaration of a class if and
14487       //   only if the class is a non-local class (9.8), the function name is
14488       //   unqualified, and the function has namespace scope.
14489       //
14490       // FIXME: We should only do this if the scope specifier names the
14491       // innermost enclosing namespace; otherwise the fixit changes the
14492       // meaning of the code.
14493       SemaDiagnosticBuilder DB
14494         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14495 
14496       DB << SS.getScopeRep();
14497       if (DC->isFileContext())
14498         DB << FixItHint::CreateRemoval(SS.getRange());
14499       SS.clear();
14500     }
14501 
14502   //   - There's a scope specifier that does not match any template
14503   //     parameter lists, in which case we use some arbitrary context,
14504   //     create a method or method template, and wait for instantiation.
14505   //   - There's a scope specifier that does match some template
14506   //     parameter lists, which we don't handle right now.
14507   } else {
14508     if (D.isFunctionDefinition()) {
14509       // C++ [class.friend]p6:
14510       //   A function can be defined in a friend declaration of a class if and
14511       //   only if the class is a non-local class (9.8), the function name is
14512       //   unqualified, and the function has namespace scope.
14513       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14514         << SS.getScopeRep();
14515     }
14516 
14517     DC = CurContext;
14518     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14519   }
14520 
14521   if (!DC->isRecord()) {
14522     int DiagArg = -1;
14523     switch (D.getName().getKind()) {
14524     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14525     case UnqualifiedIdKind::IK_ConstructorName:
14526       DiagArg = 0;
14527       break;
14528     case UnqualifiedIdKind::IK_DestructorName:
14529       DiagArg = 1;
14530       break;
14531     case UnqualifiedIdKind::IK_ConversionFunctionId:
14532       DiagArg = 2;
14533       break;
14534     case UnqualifiedIdKind::IK_DeductionGuideName:
14535       DiagArg = 3;
14536       break;
14537     case UnqualifiedIdKind::IK_Identifier:
14538     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14539     case UnqualifiedIdKind::IK_LiteralOperatorId:
14540     case UnqualifiedIdKind::IK_OperatorFunctionId:
14541     case UnqualifiedIdKind::IK_TemplateId:
14542       break;
14543     }
14544     // This implies that it has to be an operator or function.
14545     if (DiagArg >= 0) {
14546       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14547       return nullptr;
14548     }
14549   }
14550 
14551   // FIXME: This is an egregious hack to cope with cases where the scope stack
14552   // does not contain the declaration context, i.e., in an out-of-line
14553   // definition of a class.
14554   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14555   if (!DCScope) {
14556     FakeDCScope.setEntity(DC);
14557     DCScope = &FakeDCScope;
14558   }
14559 
14560   bool AddToScope = true;
14561   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14562                                           TemplateParams, AddToScope);
14563   if (!ND) return nullptr;
14564 
14565   assert(ND->getLexicalDeclContext() == CurContext);
14566 
14567   // If we performed typo correction, we might have added a scope specifier
14568   // and changed the decl context.
14569   DC = ND->getDeclContext();
14570 
14571   // Add the function declaration to the appropriate lookup tables,
14572   // adjusting the redeclarations list as necessary.  We don't
14573   // want to do this yet if the friending class is dependent.
14574   //
14575   // Also update the scope-based lookup if the target context's
14576   // lookup context is in lexical scope.
14577   if (!CurContext->isDependentContext()) {
14578     DC = DC->getRedeclContext();
14579     DC->makeDeclVisibleInContext(ND);
14580     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14581       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14582   }
14583 
14584   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14585                                        D.getIdentifierLoc(), ND,
14586                                        DS.getFriendSpecLoc());
14587   FrD->setAccess(AS_public);
14588   CurContext->addDecl(FrD);
14589 
14590   if (ND->isInvalidDecl()) {
14591     FrD->setInvalidDecl();
14592   } else {
14593     if (DC->isRecord()) CheckFriendAccess(ND);
14594 
14595     FunctionDecl *FD;
14596     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14597       FD = FTD->getTemplatedDecl();
14598     else
14599       FD = cast<FunctionDecl>(ND);
14600 
14601     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14602     // default argument expression, that declaration shall be a definition
14603     // and shall be the only declaration of the function or function
14604     // template in the translation unit.
14605     if (functionDeclHasDefaultArgument(FD)) {
14606       // We can't look at FD->getPreviousDecl() because it may not have been set
14607       // if we're in a dependent context. If the function is known to be a
14608       // redeclaration, we will have narrowed Previous down to the right decl.
14609       if (D.isRedeclaration()) {
14610         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14611         Diag(Previous.getRepresentativeDecl()->getLocation(),
14612              diag::note_previous_declaration);
14613       } else if (!D.isFunctionDefinition())
14614         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14615     }
14616 
14617     // Mark templated-scope function declarations as unsupported.
14618     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14619       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14620         << SS.getScopeRep() << SS.getRange()
14621         << cast<CXXRecordDecl>(CurContext);
14622       FrD->setUnsupportedFriend(true);
14623     }
14624   }
14625 
14626   return ND;
14627 }
14628 
14629 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14630   AdjustDeclIfTemplate(Dcl);
14631 
14632   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14633   if (!Fn) {
14634     Diag(DelLoc, diag::err_deleted_non_function);
14635     return;
14636   }
14637 
14638   // Deleted function does not have a body.
14639   Fn->setWillHaveBody(false);
14640 
14641   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14642     // Don't consider the implicit declaration we generate for explicit
14643     // specializations. FIXME: Do not generate these implicit declarations.
14644     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14645          Prev->getPreviousDecl()) &&
14646         !Prev->isDefined()) {
14647       Diag(DelLoc, diag::err_deleted_decl_not_first);
14648       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14649            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14650                               : diag::note_previous_declaration);
14651     }
14652     // If the declaration wasn't the first, we delete the function anyway for
14653     // recovery.
14654     Fn = Fn->getCanonicalDecl();
14655   }
14656 
14657   // dllimport/dllexport cannot be deleted.
14658   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14659     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14660     Fn->setInvalidDecl();
14661   }
14662 
14663   if (Fn->isDeleted())
14664     return;
14665 
14666   // See if we're deleting a function which is already known to override a
14667   // non-deleted virtual function.
14668   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14669     bool IssuedDiagnostic = false;
14670     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14671       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14672         if (!IssuedDiagnostic) {
14673           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14674           IssuedDiagnostic = true;
14675         }
14676         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14677       }
14678     }
14679     // If this function was implicitly deleted because it was defaulted,
14680     // explain why it was deleted.
14681     if (IssuedDiagnostic && MD->isDefaulted())
14682       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14683                                 /*Diagnose*/true);
14684   }
14685 
14686   // C++11 [basic.start.main]p3:
14687   //   A program that defines main as deleted [...] is ill-formed.
14688   if (Fn->isMain())
14689     Diag(DelLoc, diag::err_deleted_main);
14690 
14691   // C++11 [dcl.fct.def.delete]p4:
14692   //  A deleted function is implicitly inline.
14693   Fn->setImplicitlyInline();
14694   Fn->setDeletedAsWritten();
14695 }
14696 
14697 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14698   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14699 
14700   if (MD) {
14701     if (MD->getParent()->isDependentType()) {
14702       MD->setDefaulted();
14703       MD->setExplicitlyDefaulted();
14704       return;
14705     }
14706 
14707     CXXSpecialMember Member = getSpecialMember(MD);
14708     if (Member == CXXInvalid) {
14709       if (!MD->isInvalidDecl())
14710         Diag(DefaultLoc, diag::err_default_special_members);
14711       return;
14712     }
14713 
14714     MD->setDefaulted();
14715     MD->setExplicitlyDefaulted();
14716 
14717     // Unset that we will have a body for this function. We might not,
14718     // if it turns out to be trivial, and we don't need this marking now
14719     // that we've marked it as defaulted.
14720     MD->setWillHaveBody(false);
14721 
14722     // If this definition appears within the record, do the checking when
14723     // the record is complete.
14724     const FunctionDecl *Primary = MD;
14725     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14726       // Ask the template instantiation pattern that actually had the
14727       // '= default' on it.
14728       Primary = Pattern;
14729 
14730     // If the method was defaulted on its first declaration, we will have
14731     // already performed the checking in CheckCompletedCXXClass. Such a
14732     // declaration doesn't trigger an implicit definition.
14733     if (Primary->getCanonicalDecl()->isDefaulted())
14734       return;
14735 
14736     CheckExplicitlyDefaultedSpecialMember(MD);
14737 
14738     if (!MD->isInvalidDecl())
14739       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14740   } else {
14741     Diag(DefaultLoc, diag::err_default_special_members);
14742   }
14743 }
14744 
14745 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14746   for (Stmt *SubStmt : S->children()) {
14747     if (!SubStmt)
14748       continue;
14749     if (isa<ReturnStmt>(SubStmt))
14750       Self.Diag(SubStmt->getBeginLoc(),
14751                 diag::err_return_in_constructor_handler);
14752     if (!isa<Expr>(SubStmt))
14753       SearchForReturnInStmt(Self, SubStmt);
14754   }
14755 }
14756 
14757 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14758   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14759     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14760     SearchForReturnInStmt(*this, Handler);
14761   }
14762 }
14763 
14764 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14765                                              const CXXMethodDecl *Old) {
14766   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14767   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14768 
14769   if (OldFT->hasExtParameterInfos()) {
14770     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14771       // A parameter of the overriding method should be annotated with noescape
14772       // if the corresponding parameter of the overridden method is annotated.
14773       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14774           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14775         Diag(New->getParamDecl(I)->getLocation(),
14776              diag::warn_overriding_method_missing_noescape);
14777         Diag(Old->getParamDecl(I)->getLocation(),
14778              diag::note_overridden_marked_noescape);
14779       }
14780   }
14781 
14782   // Virtual overrides must have the same code_seg.
14783   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14784   const auto *NewCSA = New->getAttr<CodeSegAttr>();
14785   if ((NewCSA || OldCSA) &&
14786       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14787     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14788     Diag(Old->getLocation(), diag::note_previous_declaration);
14789     return true;
14790   }
14791 
14792   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14793 
14794   // If the calling conventions match, everything is fine
14795   if (NewCC == OldCC)
14796     return false;
14797 
14798   // If the calling conventions mismatch because the new function is static,
14799   // suppress the calling convention mismatch error; the error about static
14800   // function override (err_static_overrides_virtual from
14801   // Sema::CheckFunctionDeclaration) is more clear.
14802   if (New->getStorageClass() == SC_Static)
14803     return false;
14804 
14805   Diag(New->getLocation(),
14806        diag::err_conflicting_overriding_cc_attributes)
14807     << New->getDeclName() << New->getType() << Old->getType();
14808   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14809   return true;
14810 }
14811 
14812 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14813                                              const CXXMethodDecl *Old) {
14814   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14815   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14816 
14817   if (Context.hasSameType(NewTy, OldTy) ||
14818       NewTy->isDependentType() || OldTy->isDependentType())
14819     return false;
14820 
14821   // Check if the return types are covariant
14822   QualType NewClassTy, OldClassTy;
14823 
14824   /// Both types must be pointers or references to classes.
14825   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14826     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14827       NewClassTy = NewPT->getPointeeType();
14828       OldClassTy = OldPT->getPointeeType();
14829     }
14830   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14831     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14832       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14833         NewClassTy = NewRT->getPointeeType();
14834         OldClassTy = OldRT->getPointeeType();
14835       }
14836     }
14837   }
14838 
14839   // The return types aren't either both pointers or references to a class type.
14840   if (NewClassTy.isNull()) {
14841     Diag(New->getLocation(),
14842          diag::err_different_return_type_for_overriding_virtual_function)
14843         << New->getDeclName() << NewTy << OldTy
14844         << New->getReturnTypeSourceRange();
14845     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14846         << Old->getReturnTypeSourceRange();
14847 
14848     return true;
14849   }
14850 
14851   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14852     // C++14 [class.virtual]p8:
14853     //   If the class type in the covariant return type of D::f differs from
14854     //   that of B::f, the class type in the return type of D::f shall be
14855     //   complete at the point of declaration of D::f or shall be the class
14856     //   type D.
14857     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14858       if (!RT->isBeingDefined() &&
14859           RequireCompleteType(New->getLocation(), NewClassTy,
14860                               diag::err_covariant_return_incomplete,
14861                               New->getDeclName()))
14862         return true;
14863     }
14864 
14865     // Check if the new class derives from the old class.
14866     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14867       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14868           << New->getDeclName() << NewTy << OldTy
14869           << New->getReturnTypeSourceRange();
14870       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14871           << Old->getReturnTypeSourceRange();
14872       return true;
14873     }
14874 
14875     // Check if we the conversion from derived to base is valid.
14876     if (CheckDerivedToBaseConversion(
14877             NewClassTy, OldClassTy,
14878             diag::err_covariant_return_inaccessible_base,
14879             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14880             New->getLocation(), New->getReturnTypeSourceRange(),
14881             New->getDeclName(), nullptr)) {
14882       // FIXME: this note won't trigger for delayed access control
14883       // diagnostics, and it's impossible to get an undelayed error
14884       // here from access control during the original parse because
14885       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14886       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14887           << Old->getReturnTypeSourceRange();
14888       return true;
14889     }
14890   }
14891 
14892   // The qualifiers of the return types must be the same.
14893   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14894     Diag(New->getLocation(),
14895          diag::err_covariant_return_type_different_qualifications)
14896         << New->getDeclName() << NewTy << OldTy
14897         << New->getReturnTypeSourceRange();
14898     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14899         << Old->getReturnTypeSourceRange();
14900     return true;
14901   }
14902 
14903 
14904   // The new class type must have the same or less qualifiers as the old type.
14905   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14906     Diag(New->getLocation(),
14907          diag::err_covariant_return_type_class_type_more_qualified)
14908         << New->getDeclName() << NewTy << OldTy
14909         << New->getReturnTypeSourceRange();
14910     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14911         << Old->getReturnTypeSourceRange();
14912     return true;
14913   }
14914 
14915   return false;
14916 }
14917 
14918 /// Mark the given method pure.
14919 ///
14920 /// \param Method the method to be marked pure.
14921 ///
14922 /// \param InitRange the source range that covers the "0" initializer.
14923 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14924   SourceLocation EndLoc = InitRange.getEnd();
14925   if (EndLoc.isValid())
14926     Method->setRangeEnd(EndLoc);
14927 
14928   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14929     Method->setPure();
14930     return false;
14931   }
14932 
14933   if (!Method->isInvalidDecl())
14934     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14935       << Method->getDeclName() << InitRange;
14936   return true;
14937 }
14938 
14939 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14940   if (D->getFriendObjectKind())
14941     Diag(D->getLocation(), diag::err_pure_friend);
14942   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14943     CheckPureMethod(M, ZeroLoc);
14944   else
14945     Diag(D->getLocation(), diag::err_illegal_initializer);
14946 }
14947 
14948 /// Determine whether the given declaration is a global variable or
14949 /// static data member.
14950 static bool isNonlocalVariable(const Decl *D) {
14951   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14952     return Var->hasGlobalStorage();
14953 
14954   return false;
14955 }
14956 
14957 /// Invoked when we are about to parse an initializer for the declaration
14958 /// 'Dcl'.
14959 ///
14960 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14961 /// static data member of class X, names should be looked up in the scope of
14962 /// class X. If the declaration had a scope specifier, a scope will have
14963 /// been created and passed in for this purpose. Otherwise, S will be null.
14964 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14965   // If there is no declaration, there was an error parsing it.
14966   if (!D || D->isInvalidDecl())
14967     return;
14968 
14969   // We will always have a nested name specifier here, but this declaration
14970   // might not be out of line if the specifier names the current namespace:
14971   //   extern int n;
14972   //   int ::n = 0;
14973   if (S && D->isOutOfLine())
14974     EnterDeclaratorContext(S, D->getDeclContext());
14975 
14976   // If we are parsing the initializer for a static data member, push a
14977   // new expression evaluation context that is associated with this static
14978   // data member.
14979   if (isNonlocalVariable(D))
14980     PushExpressionEvaluationContext(
14981         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14982 }
14983 
14984 /// Invoked after we are finished parsing an initializer for the declaration D.
14985 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14986   // If there is no declaration, there was an error parsing it.
14987   if (!D || D->isInvalidDecl())
14988     return;
14989 
14990   if (isNonlocalVariable(D))
14991     PopExpressionEvaluationContext();
14992 
14993   if (S && D->isOutOfLine())
14994     ExitDeclaratorContext(S);
14995 }
14996 
14997 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14998 /// C++ if/switch/while/for statement.
14999 /// e.g: "if (int x = f()) {...}"
15000 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
15001   // C++ 6.4p2:
15002   // The declarator shall not specify a function or an array.
15003   // The type-specifier-seq shall not contain typedef and shall not declare a
15004   // new class or enumeration.
15005   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
15006          "Parser allowed 'typedef' as storage class of condition decl.");
15007 
15008   Decl *Dcl = ActOnDeclarator(S, D);
15009   if (!Dcl)
15010     return true;
15011 
15012   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
15013     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
15014       << D.getSourceRange();
15015     return true;
15016   }
15017 
15018   return Dcl;
15019 }
15020 
15021 void Sema::LoadExternalVTableUses() {
15022   if (!ExternalSource)
15023     return;
15024 
15025   SmallVector<ExternalVTableUse, 4> VTables;
15026   ExternalSource->ReadUsedVTables(VTables);
15027   SmallVector<VTableUse, 4> NewUses;
15028   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
15029     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
15030       = VTablesUsed.find(VTables[I].Record);
15031     // Even if a definition wasn't required before, it may be required now.
15032     if (Pos != VTablesUsed.end()) {
15033       if (!Pos->second && VTables[I].DefinitionRequired)
15034         Pos->second = true;
15035       continue;
15036     }
15037 
15038     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
15039     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
15040   }
15041 
15042   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
15043 }
15044 
15045 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
15046                           bool DefinitionRequired) {
15047   // Ignore any vtable uses in unevaluated operands or for classes that do
15048   // not have a vtable.
15049   if (!Class->isDynamicClass() || Class->isDependentContext() ||
15050       CurContext->isDependentContext() || isUnevaluatedContext())
15051     return;
15052   // Do not mark as used if compiling for the device outside of the target
15053   // region.
15054   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15055       !isInOpenMPDeclareTargetContext() &&
15056       !isInOpenMPTargetExecutionDirective()) {
15057     if (!DefinitionRequired)
15058       MarkVirtualMembersReferenced(Loc, Class);
15059     return;
15060   }
15061 
15062   // Try to insert this class into the map.
15063   LoadExternalVTableUses();
15064   Class = Class->getCanonicalDecl();
15065   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15066     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15067   if (!Pos.second) {
15068     // If we already had an entry, check to see if we are promoting this vtable
15069     // to require a definition. If so, we need to reappend to the VTableUses
15070     // list, since we may have already processed the first entry.
15071     if (DefinitionRequired && !Pos.first->second) {
15072       Pos.first->second = true;
15073     } else {
15074       // Otherwise, we can early exit.
15075       return;
15076     }
15077   } else {
15078     // The Microsoft ABI requires that we perform the destructor body
15079     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15080     // the deleting destructor is emitted with the vtable, not with the
15081     // destructor definition as in the Itanium ABI.
15082     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15083       CXXDestructorDecl *DD = Class->getDestructor();
15084       if (DD && DD->isVirtual() && !DD->isDeleted()) {
15085         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15086           // If this is an out-of-line declaration, marking it referenced will
15087           // not do anything. Manually call CheckDestructor to look up operator
15088           // delete().
15089           ContextRAII SavedContext(*this, DD);
15090           CheckDestructor(DD);
15091         } else {
15092           MarkFunctionReferenced(Loc, Class->getDestructor());
15093         }
15094       }
15095     }
15096   }
15097 
15098   // Local classes need to have their virtual members marked
15099   // immediately. For all other classes, we mark their virtual members
15100   // at the end of the translation unit.
15101   if (Class->isLocalClass())
15102     MarkVirtualMembersReferenced(Loc, Class);
15103   else
15104     VTableUses.push_back(std::make_pair(Class, Loc));
15105 }
15106 
15107 bool Sema::DefineUsedVTables() {
15108   LoadExternalVTableUses();
15109   if (VTableUses.empty())
15110     return false;
15111 
15112   // Note: The VTableUses vector could grow as a result of marking
15113   // the members of a class as "used", so we check the size each
15114   // time through the loop and prefer indices (which are stable) to
15115   // iterators (which are not).
15116   bool DefinedAnything = false;
15117   for (unsigned I = 0; I != VTableUses.size(); ++I) {
15118     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15119     if (!Class)
15120       continue;
15121     TemplateSpecializationKind ClassTSK =
15122         Class->getTemplateSpecializationKind();
15123 
15124     SourceLocation Loc = VTableUses[I].second;
15125 
15126     bool DefineVTable = true;
15127 
15128     // If this class has a key function, but that key function is
15129     // defined in another translation unit, we don't need to emit the
15130     // vtable even though we're using it.
15131     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15132     if (KeyFunction && !KeyFunction->hasBody()) {
15133       // The key function is in another translation unit.
15134       DefineVTable = false;
15135       TemplateSpecializationKind TSK =
15136           KeyFunction->getTemplateSpecializationKind();
15137       assert(TSK != TSK_ExplicitInstantiationDefinition &&
15138              TSK != TSK_ImplicitInstantiation &&
15139              "Instantiations don't have key functions");
15140       (void)TSK;
15141     } else if (!KeyFunction) {
15142       // If we have a class with no key function that is the subject
15143       // of an explicit instantiation declaration, suppress the
15144       // vtable; it will live with the explicit instantiation
15145       // definition.
15146       bool IsExplicitInstantiationDeclaration =
15147           ClassTSK == TSK_ExplicitInstantiationDeclaration;
15148       for (auto R : Class->redecls()) {
15149         TemplateSpecializationKind TSK
15150           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15151         if (TSK == TSK_ExplicitInstantiationDeclaration)
15152           IsExplicitInstantiationDeclaration = true;
15153         else if (TSK == TSK_ExplicitInstantiationDefinition) {
15154           IsExplicitInstantiationDeclaration = false;
15155           break;
15156         }
15157       }
15158 
15159       if (IsExplicitInstantiationDeclaration)
15160         DefineVTable = false;
15161     }
15162 
15163     // The exception specifications for all virtual members may be needed even
15164     // if we are not providing an authoritative form of the vtable in this TU.
15165     // We may choose to emit it available_externally anyway.
15166     if (!DefineVTable) {
15167       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15168       continue;
15169     }
15170 
15171     // Mark all of the virtual members of this class as referenced, so
15172     // that we can build a vtable. Then, tell the AST consumer that a
15173     // vtable for this class is required.
15174     DefinedAnything = true;
15175     MarkVirtualMembersReferenced(Loc, Class);
15176     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15177     if (VTablesUsed[Canonical])
15178       Consumer.HandleVTable(Class);
15179 
15180     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15181     // no key function or the key function is inlined. Don't warn in C++ ABIs
15182     // that lack key functions, since the user won't be able to make one.
15183     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15184         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15185       const FunctionDecl *KeyFunctionDef = nullptr;
15186       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15187                            KeyFunctionDef->isInlined())) {
15188         Diag(Class->getLocation(),
15189              ClassTSK == TSK_ExplicitInstantiationDefinition
15190                  ? diag::warn_weak_template_vtable
15191                  : diag::warn_weak_vtable)
15192             << Class;
15193       }
15194     }
15195   }
15196   VTableUses.clear();
15197 
15198   return DefinedAnything;
15199 }
15200 
15201 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15202                                                  const CXXRecordDecl *RD) {
15203   for (const auto *I : RD->methods())
15204     if (I->isVirtual() && !I->isPure())
15205       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15206 }
15207 
15208 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15209                                         const CXXRecordDecl *RD) {
15210   // Mark all functions which will appear in RD's vtable as used.
15211   CXXFinalOverriderMap FinalOverriders;
15212   RD->getFinalOverriders(FinalOverriders);
15213   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15214                                             E = FinalOverriders.end();
15215        I != E; ++I) {
15216     for (OverridingMethods::const_iterator OI = I->second.begin(),
15217                                            OE = I->second.end();
15218          OI != OE; ++OI) {
15219       assert(OI->second.size() > 0 && "no final overrider");
15220       CXXMethodDecl *Overrider = OI->second.front().Method;
15221 
15222       // C++ [basic.def.odr]p2:
15223       //   [...] A virtual member function is used if it is not pure. [...]
15224       if (!Overrider->isPure())
15225         MarkFunctionReferenced(Loc, Overrider);
15226     }
15227   }
15228 
15229   // Only classes that have virtual bases need a VTT.
15230   if (RD->getNumVBases() == 0)
15231     return;
15232 
15233   for (const auto &I : RD->bases()) {
15234     const CXXRecordDecl *Base =
15235         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15236     if (Base->getNumVBases() == 0)
15237       continue;
15238     MarkVirtualMembersReferenced(Loc, Base);
15239   }
15240 }
15241 
15242 /// SetIvarInitializers - This routine builds initialization ASTs for the
15243 /// Objective-C implementation whose ivars need be initialized.
15244 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15245   if (!getLangOpts().CPlusPlus)
15246     return;
15247   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15248     SmallVector<ObjCIvarDecl*, 8> ivars;
15249     CollectIvarsToConstructOrDestruct(OID, ivars);
15250     if (ivars.empty())
15251       return;
15252     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15253     for (unsigned i = 0; i < ivars.size(); i++) {
15254       FieldDecl *Field = ivars[i];
15255       if (Field->isInvalidDecl())
15256         continue;
15257 
15258       CXXCtorInitializer *Member;
15259       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15260       InitializationKind InitKind =
15261         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15262 
15263       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15264       ExprResult MemberInit =
15265         InitSeq.Perform(*this, InitEntity, InitKind, None);
15266       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15267       // Note, MemberInit could actually come back empty if no initialization
15268       // is required (e.g., because it would call a trivial default constructor)
15269       if (!MemberInit.get() || MemberInit.isInvalid())
15270         continue;
15271 
15272       Member =
15273         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15274                                          SourceLocation(),
15275                                          MemberInit.getAs<Expr>(),
15276                                          SourceLocation());
15277       AllToInit.push_back(Member);
15278 
15279       // Be sure that the destructor is accessible and is marked as referenced.
15280       if (const RecordType *RecordTy =
15281               Context.getBaseElementType(Field->getType())
15282                   ->getAs<RecordType>()) {
15283         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15284         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15285           MarkFunctionReferenced(Field->getLocation(), Destructor);
15286           CheckDestructorAccess(Field->getLocation(), Destructor,
15287                             PDiag(diag::err_access_dtor_ivar)
15288                               << Context.getBaseElementType(Field->getType()));
15289         }
15290       }
15291     }
15292     ObjCImplementation->setIvarInitializers(Context,
15293                                             AllToInit.data(), AllToInit.size());
15294   }
15295 }
15296 
15297 static
15298 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15299                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15300                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15301                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15302                            Sema &S) {
15303   if (Ctor->isInvalidDecl())
15304     return;
15305 
15306   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15307 
15308   // Target may not be determinable yet, for instance if this is a dependent
15309   // call in an uninstantiated template.
15310   if (Target) {
15311     const FunctionDecl *FNTarget = nullptr;
15312     (void)Target->hasBody(FNTarget);
15313     Target = const_cast<CXXConstructorDecl*>(
15314       cast_or_null<CXXConstructorDecl>(FNTarget));
15315   }
15316 
15317   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15318                      // Avoid dereferencing a null pointer here.
15319                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15320 
15321   if (!Current.insert(Canonical).second)
15322     return;
15323 
15324   // We know that beyond here, we aren't chaining into a cycle.
15325   if (!Target || !Target->isDelegatingConstructor() ||
15326       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15327     Valid.insert(Current.begin(), Current.end());
15328     Current.clear();
15329   // We've hit a cycle.
15330   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15331              Current.count(TCanonical)) {
15332     // If we haven't diagnosed this cycle yet, do so now.
15333     if (!Invalid.count(TCanonical)) {
15334       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15335              diag::warn_delegating_ctor_cycle)
15336         << Ctor;
15337 
15338       // Don't add a note for a function delegating directly to itself.
15339       if (TCanonical != Canonical)
15340         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15341 
15342       CXXConstructorDecl *C = Target;
15343       while (C->getCanonicalDecl() != Canonical) {
15344         const FunctionDecl *FNTarget = nullptr;
15345         (void)C->getTargetConstructor()->hasBody(FNTarget);
15346         assert(FNTarget && "Ctor cycle through bodiless function");
15347 
15348         C = const_cast<CXXConstructorDecl*>(
15349           cast<CXXConstructorDecl>(FNTarget));
15350         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15351       }
15352     }
15353 
15354     Invalid.insert(Current.begin(), Current.end());
15355     Current.clear();
15356   } else {
15357     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15358   }
15359 }
15360 
15361 
15362 void Sema::CheckDelegatingCtorCycles() {
15363   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15364 
15365   for (DelegatingCtorDeclsType::iterator
15366          I = DelegatingCtorDecls.begin(ExternalSource),
15367          E = DelegatingCtorDecls.end();
15368        I != E; ++I)
15369     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15370 
15371   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15372     (*CI)->setInvalidDecl();
15373 }
15374 
15375 namespace {
15376   /// AST visitor that finds references to the 'this' expression.
15377   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15378     Sema &S;
15379 
15380   public:
15381     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15382 
15383     bool VisitCXXThisExpr(CXXThisExpr *E) {
15384       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15385         << E->isImplicit();
15386       return false;
15387     }
15388   };
15389 }
15390 
15391 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15392   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15393   if (!TSInfo)
15394     return false;
15395 
15396   TypeLoc TL = TSInfo->getTypeLoc();
15397   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15398   if (!ProtoTL)
15399     return false;
15400 
15401   // C++11 [expr.prim.general]p3:
15402   //   [The expression this] shall not appear before the optional
15403   //   cv-qualifier-seq and it shall not appear within the declaration of a
15404   //   static member function (although its type and value category are defined
15405   //   within a static member function as they are within a non-static member
15406   //   function). [ Note: this is because declaration matching does not occur
15407   //  until the complete declarator is known. - end note ]
15408   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15409   FindCXXThisExpr Finder(*this);
15410 
15411   // If the return type came after the cv-qualifier-seq, check it now.
15412   if (Proto->hasTrailingReturn() &&
15413       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15414     return true;
15415 
15416   // Check the exception specification.
15417   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15418     return true;
15419 
15420   return checkThisInStaticMemberFunctionAttributes(Method);
15421 }
15422 
15423 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15424   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15425   if (!TSInfo)
15426     return false;
15427 
15428   TypeLoc TL = TSInfo->getTypeLoc();
15429   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15430   if (!ProtoTL)
15431     return false;
15432 
15433   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15434   FindCXXThisExpr Finder(*this);
15435 
15436   switch (Proto->getExceptionSpecType()) {
15437   case EST_Unparsed:
15438   case EST_Uninstantiated:
15439   case EST_Unevaluated:
15440   case EST_BasicNoexcept:
15441   case EST_DynamicNone:
15442   case EST_MSAny:
15443   case EST_None:
15444     break;
15445 
15446   case EST_DependentNoexcept:
15447   case EST_NoexceptFalse:
15448   case EST_NoexceptTrue:
15449     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15450       return true;
15451     LLVM_FALLTHROUGH;
15452 
15453   case EST_Dynamic:
15454     for (const auto &E : Proto->exceptions()) {
15455       if (!Finder.TraverseType(E))
15456         return true;
15457     }
15458     break;
15459   }
15460 
15461   return false;
15462 }
15463 
15464 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15465   FindCXXThisExpr Finder(*this);
15466 
15467   // Check attributes.
15468   for (const auto *A : Method->attrs()) {
15469     // FIXME: This should be emitted by tblgen.
15470     Expr *Arg = nullptr;
15471     ArrayRef<Expr *> Args;
15472     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15473       Arg = G->getArg();
15474     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15475       Arg = G->getArg();
15476     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15477       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15478     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15479       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15480     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15481       Arg = ETLF->getSuccessValue();
15482       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15483     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15484       Arg = STLF->getSuccessValue();
15485       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15486     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15487       Arg = LR->getArg();
15488     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15489       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15490     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15491       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15492     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15493       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15494     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15495       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15496     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15497       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15498 
15499     if (Arg && !Finder.TraverseStmt(Arg))
15500       return true;
15501 
15502     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15503       if (!Finder.TraverseStmt(Args[I]))
15504         return true;
15505     }
15506   }
15507 
15508   return false;
15509 }
15510 
15511 void Sema::checkExceptionSpecification(
15512     bool IsTopLevel, ExceptionSpecificationType EST,
15513     ArrayRef<ParsedType> DynamicExceptions,
15514     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15515     SmallVectorImpl<QualType> &Exceptions,
15516     FunctionProtoType::ExceptionSpecInfo &ESI) {
15517   Exceptions.clear();
15518   ESI.Type = EST;
15519   if (EST == EST_Dynamic) {
15520     Exceptions.reserve(DynamicExceptions.size());
15521     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15522       // FIXME: Preserve type source info.
15523       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15524 
15525       if (IsTopLevel) {
15526         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15527         collectUnexpandedParameterPacks(ET, Unexpanded);
15528         if (!Unexpanded.empty()) {
15529           DiagnoseUnexpandedParameterPacks(
15530               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15531               Unexpanded);
15532           continue;
15533         }
15534       }
15535 
15536       // Check that the type is valid for an exception spec, and
15537       // drop it if not.
15538       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15539         Exceptions.push_back(ET);
15540     }
15541     ESI.Exceptions = Exceptions;
15542     return;
15543   }
15544 
15545   if (isComputedNoexcept(EST)) {
15546     assert((NoexceptExpr->isTypeDependent() ||
15547             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15548             Context.BoolTy) &&
15549            "Parser should have made sure that the expression is boolean");
15550     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15551       ESI.Type = EST_BasicNoexcept;
15552       return;
15553     }
15554 
15555     ESI.NoexceptExpr = NoexceptExpr;
15556     return;
15557   }
15558 }
15559 
15560 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15561              ExceptionSpecificationType EST,
15562              SourceRange SpecificationRange,
15563              ArrayRef<ParsedType> DynamicExceptions,
15564              ArrayRef<SourceRange> DynamicExceptionRanges,
15565              Expr *NoexceptExpr) {
15566   if (!MethodD)
15567     return;
15568 
15569   // Dig out the method we're referring to.
15570   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15571     MethodD = FunTmpl->getTemplatedDecl();
15572 
15573   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15574   if (!Method)
15575     return;
15576 
15577   // Check the exception specification.
15578   llvm::SmallVector<QualType, 4> Exceptions;
15579   FunctionProtoType::ExceptionSpecInfo ESI;
15580   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15581                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15582                               ESI);
15583 
15584   // Update the exception specification on the function type.
15585   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15586 
15587   if (Method->isStatic())
15588     checkThisInStaticMemberFunctionExceptionSpec(Method);
15589 
15590   if (Method->isVirtual()) {
15591     // Check overrides, which we previously had to delay.
15592     for (const CXXMethodDecl *O : Method->overridden_methods())
15593       CheckOverridingFunctionExceptionSpec(Method, O);
15594   }
15595 }
15596 
15597 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15598 ///
15599 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15600                                        SourceLocation DeclStart, Declarator &D,
15601                                        Expr *BitWidth,
15602                                        InClassInitStyle InitStyle,
15603                                        AccessSpecifier AS,
15604                                        const ParsedAttr &MSPropertyAttr) {
15605   IdentifierInfo *II = D.getIdentifier();
15606   if (!II) {
15607     Diag(DeclStart, diag::err_anonymous_property);
15608     return nullptr;
15609   }
15610   SourceLocation Loc = D.getIdentifierLoc();
15611 
15612   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15613   QualType T = TInfo->getType();
15614   if (getLangOpts().CPlusPlus) {
15615     CheckExtraCXXDefaultArguments(D);
15616 
15617     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15618                                         UPPC_DataMemberType)) {
15619       D.setInvalidType();
15620       T = Context.IntTy;
15621       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15622     }
15623   }
15624 
15625   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15626 
15627   if (D.getDeclSpec().isInlineSpecified())
15628     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15629         << getLangOpts().CPlusPlus17;
15630   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15631     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15632          diag::err_invalid_thread)
15633       << DeclSpec::getSpecifierName(TSCS);
15634 
15635   // Check to see if this name was declared as a member previously
15636   NamedDecl *PrevDecl = nullptr;
15637   LookupResult Previous(*this, II, Loc, LookupMemberName,
15638                         ForVisibleRedeclaration);
15639   LookupName(Previous, S);
15640   switch (Previous.getResultKind()) {
15641   case LookupResult::Found:
15642   case LookupResult::FoundUnresolvedValue:
15643     PrevDecl = Previous.getAsSingle<NamedDecl>();
15644     break;
15645 
15646   case LookupResult::FoundOverloaded:
15647     PrevDecl = Previous.getRepresentativeDecl();
15648     break;
15649 
15650   case LookupResult::NotFound:
15651   case LookupResult::NotFoundInCurrentInstantiation:
15652   case LookupResult::Ambiguous:
15653     break;
15654   }
15655 
15656   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15657     // Maybe we will complain about the shadowed template parameter.
15658     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15659     // Just pretend that we didn't see the previous declaration.
15660     PrevDecl = nullptr;
15661   }
15662 
15663   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15664     PrevDecl = nullptr;
15665 
15666   SourceLocation TSSL = D.getBeginLoc();
15667   MSPropertyDecl *NewPD =
15668       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15669                              MSPropertyAttr.getPropertyDataGetter(),
15670                              MSPropertyAttr.getPropertyDataSetter());
15671   ProcessDeclAttributes(TUScope, NewPD, D);
15672   NewPD->setAccess(AS);
15673 
15674   if (NewPD->isInvalidDecl())
15675     Record->setInvalidDecl();
15676 
15677   if (D.getDeclSpec().isModulePrivateSpecified())
15678     NewPD->setModulePrivate();
15679 
15680   if (NewPD->isInvalidDecl() && PrevDecl) {
15681     // Don't introduce NewFD into scope; there's already something
15682     // with the same name in the same scope.
15683   } else if (II) {
15684     PushOnScopeChains(NewPD, S);
15685   } else
15686     Record->addDecl(NewPD);
15687 
15688   return NewPD;
15689 }
15690