]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm-project / clang / lib / Sema / SemaDeclCXX.cpp
1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for C++ declarations.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ComparisonCategories.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/LiteralSupport.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/CXXFieldCollector.h"
32 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/Initialization.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/ParsedTemplate.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaInternal.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include <map>
44 #include <set>
45
46 using namespace clang;
47
48 //===----------------------------------------------------------------------===//
49 // CheckDefaultArgumentVisitor
50 //===----------------------------------------------------------------------===//
51
52 namespace {
53   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54   /// the default argument of a parameter to determine whether it
55   /// contains any ill-formed subexpressions. For example, this will
56   /// diagnose the use of local variables or parameters within the
57   /// default argument expression.
58   class CheckDefaultArgumentVisitor
59     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
60     Expr *DefaultArg;
61     Sema *S;
62
63   public:
64     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
65         : DefaultArg(defarg), S(s) {}
66
67     bool VisitExpr(Expr *Node);
68     bool VisitDeclRefExpr(DeclRefExpr *DRE);
69     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
70     bool VisitLambdaExpr(LambdaExpr *Lambda);
71     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
72   };
73
74   /// VisitExpr - Visit all of the children of this expression.
75   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76     bool IsInvalid = false;
77     for (Stmt *SubStmt : Node->children())
78       IsInvalid |= Visit(SubStmt);
79     return IsInvalid;
80   }
81
82   /// VisitDeclRefExpr - Visit a reference to a declaration, to
83   /// determine whether this declaration can be used in the default
84   /// argument expression.
85   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
86     NamedDecl *Decl = DRE->getDecl();
87     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88       // C++ [dcl.fct.default]p9
89       //   Default arguments are evaluated each time the function is
90       //   called. The order of evaluation of function arguments is
91       //   unspecified. Consequently, parameters of a function shall not
92       //   be used in default argument expressions, even if they are not
93       //   evaluated. Parameters of a function declared before a default
94       //   argument expression are in scope and can hide namespace and
95       //   class member names.
96       return S->Diag(DRE->getBeginLoc(),
97                      diag::err_param_default_argument_references_param)
98              << Param->getDeclName() << DefaultArg->getSourceRange();
99     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
100       // C++ [dcl.fct.default]p7
101       //   Local variables shall not be used in default argument
102       //   expressions.
103       if (VDecl->isLocalVarDecl())
104         return S->Diag(DRE->getBeginLoc(),
105                        diag::err_param_default_argument_references_local)
106                << VDecl->getDeclName() << DefaultArg->getSourceRange();
107     }
108
109     return false;
110   }
111
112   /// VisitCXXThisExpr - Visit a C++ "this" expression.
113   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114     // C++ [dcl.fct.default]p8:
115     //   The keyword this shall not be used in a default argument of a
116     //   member function.
117     return S->Diag(ThisE->getBeginLoc(),
118                    diag::err_param_default_argument_references_this)
119            << ThisE->getSourceRange();
120   }
121
122   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123     bool Invalid = false;
124     for (PseudoObjectExpr::semantics_iterator
125            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126       Expr *E = *i;
127
128       // Look through bindings.
129       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130         E = OVE->getSourceExpr();
131         assert(E && "pseudo-object binding without source expression?");
132       }
133
134       Invalid |= Visit(E);
135     }
136     return Invalid;
137   }
138
139   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140     // C++11 [expr.lambda.prim]p13:
141     //   A lambda-expression appearing in a default argument shall not
142     //   implicitly or explicitly capture any entity.
143     if (Lambda->capture_begin() == Lambda->capture_end())
144       return false;
145
146     return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
147   }
148 }
149
150 void
151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152                                                  const CXXMethodDecl *Method) {
153   // If we have an MSAny spec already, don't bother.
154   if (!Method || ComputedEST == EST_MSAny)
155     return;
156
157   const FunctionProtoType *Proto
158     = Method->getType()->getAs<FunctionProtoType>();
159   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160   if (!Proto)
161     return;
162
163   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
165   // If we have a throw-all spec at this point, ignore the function.
166   if (ComputedEST == EST_None)
167     return;
168
169   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
170     EST = EST_BasicNoexcept;
171
172   switch (EST) {
173   case EST_Unparsed:
174   case EST_Uninstantiated:
175   case EST_Unevaluated:
176     llvm_unreachable("should not see unresolved exception specs here");
177
178   // If this function can throw any exceptions, make a note of that.
179   case EST_MSAny:
180   case EST_None:
181     // FIXME: Whichever we see last of MSAny and None determines our result.
182     // We should make a consistent, order-independent choice here.
183     ClearExceptions();
184     ComputedEST = EST;
185     return;
186   case EST_NoexceptFalse:
187     ClearExceptions();
188     ComputedEST = EST_None;
189     return;
190   // FIXME: If the call to this decl is using any of its default arguments, we
191   // need to search them for potentially-throwing calls.
192   // If this function has a basic noexcept, it doesn't affect the outcome.
193   case EST_BasicNoexcept:
194   case EST_NoexceptTrue:
195   case EST_NoThrow:
196     return;
197   // If we're still at noexcept(true) and there's a throw() callee,
198   // change to that specification.
199   case EST_DynamicNone:
200     if (ComputedEST == EST_BasicNoexcept)
201       ComputedEST = EST_DynamicNone;
202     return;
203   case EST_DependentNoexcept:
204     llvm_unreachable(
205         "should not generate implicit declarations for dependent cases");
206   case EST_Dynamic:
207     break;
208   }
209   assert(EST == EST_Dynamic && "EST case not considered earlier.");
210   assert(ComputedEST != EST_None &&
211          "Shouldn't collect exceptions when throw-all is guaranteed.");
212   ComputedEST = EST_Dynamic;
213   // Record the exceptions in this function's exception specification.
214   for (const auto &E : Proto->exceptions())
215     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
216       Exceptions.push_back(E);
217 }
218
219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
220   if (!E || ComputedEST == EST_MSAny)
221     return;
222
223   // FIXME:
224   //
225   // C++0x [except.spec]p14:
226   //   [An] implicit exception-specification specifies the type-id T if and
227   // only if T is allowed by the exception-specification of a function directly
228   // invoked by f's implicit definition; f shall allow all exceptions if any
229   // function it directly invokes allows all exceptions, and f shall allow no
230   // exceptions if every function it directly invokes allows no exceptions.
231   //
232   // Note in particular that if an implicit exception-specification is generated
233   // for a function containing a throw-expression, that specification can still
234   // be noexcept(true).
235   //
236   // Note also that 'directly invoked' is not defined in the standard, and there
237   // is no indication that we should only consider potentially-evaluated calls.
238   //
239   // Ultimately we should implement the intent of the standard: the exception
240   // specification should be the set of exceptions which can be thrown by the
241   // implicit definition. For now, we assume that any non-nothrow expression can
242   // throw any exception.
243
244   if (Self->canThrow(E))
245     ComputedEST = EST_None;
246 }
247
248 bool
249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
250                               SourceLocation EqualLoc) {
251   if (RequireCompleteType(Param->getLocation(), Param->getType(),
252                           diag::err_typecheck_decl_incomplete_type)) {
253     Param->setInvalidDecl();
254     return true;
255   }
256
257   // C++ [dcl.fct.default]p5
258   //   A default argument expression is implicitly converted (clause
259   //   4) to the parameter type. The default argument expression has
260   //   the same semantic constraints as the initializer expression in
261   //   a declaration of a variable of the parameter type, using the
262   //   copy-initialization semantics (8.5).
263   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264                                                                     Param);
265   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266                                                            EqualLoc);
267   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269   if (Result.isInvalid())
270     return true;
271   Arg = Result.getAs<Expr>();
272
273   CheckCompletedExpr(Arg, EqualLoc);
274   Arg = MaybeCreateExprWithCleanups(Arg);
275
276   // Okay: add the default argument to the parameter
277   Param->setDefaultArg(Arg);
278
279   // We have already instantiated this parameter; provide each of the
280   // instantiations with the uninstantiated default argument.
281   UnparsedDefaultArgInstantiationsMap::iterator InstPos
282     = UnparsedDefaultArgInstantiations.find(Param);
283   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286
287     // We're done tracking this parameter's instantiations.
288     UnparsedDefaultArgInstantiations.erase(InstPos);
289   }
290
291   return false;
292 }
293
294 /// ActOnParamDefaultArgument - Check whether the default argument
295 /// provided for a function parameter is well-formed. If so, attach it
296 /// to the parameter declaration.
297 void
298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
299                                 Expr *DefaultArg) {
300   if (!param || !DefaultArg)
301     return;
302
303   ParmVarDecl *Param = cast<ParmVarDecl>(param);
304   UnparsedDefaultArgLocs.erase(Param);
305
306   // Default arguments are only permitted in C++
307   if (!getLangOpts().CPlusPlus) {
308     Diag(EqualLoc, diag::err_param_default_argument)
309       << DefaultArg->getSourceRange();
310     Param->setInvalidDecl();
311     return;
312   }
313
314   // Check for unexpanded parameter packs.
315   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316     Param->setInvalidDecl();
317     return;
318   }
319
320   // C++11 [dcl.fct.default]p3
321   //   A default argument expression [...] shall not be specified for a
322   //   parameter pack.
323   if (Param->isParameterPack()) {
324     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325         << DefaultArg->getSourceRange();
326     return;
327   }
328
329   // Check that the default argument is well-formed
330   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331   if (DefaultArgChecker.Visit(DefaultArg)) {
332     Param->setInvalidDecl();
333     return;
334   }
335
336   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
337 }
338
339 /// ActOnParamUnparsedDefaultArgument - We've seen a default
340 /// argument for a function parameter, but we can't parse it yet
341 /// because we're inside a class definition. Note that this default
342 /// argument will be parsed later.
343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
344                                              SourceLocation EqualLoc,
345                                              SourceLocation ArgLoc) {
346   if (!param)
347     return;
348
349   ParmVarDecl *Param = cast<ParmVarDecl>(param);
350   Param->setUnparsedDefaultArg();
351   UnparsedDefaultArgLocs[Param] = ArgLoc;
352 }
353
354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355 /// the default argument for the parameter param failed.
356 void Sema::ActOnParamDefaultArgumentError(Decl *param,
357                                           SourceLocation EqualLoc) {
358   if (!param)
359     return;
360
361   ParmVarDecl *Param = cast<ParmVarDecl>(param);
362   Param->setInvalidDecl();
363   UnparsedDefaultArgLocs.erase(Param);
364   Param->setDefaultArg(new(Context)
365                        OpaqueValueExpr(EqualLoc,
366                                        Param->getType().getNonReferenceType(),
367                                        VK_RValue));
368 }
369
370 /// CheckExtraCXXDefaultArguments - Check for any extra default
371 /// arguments in the declarator, which is not a function declaration
372 /// or definition and therefore is not permitted to have default
373 /// arguments. This routine should be invoked for every declarator
374 /// that is not a function declaration or definition.
375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
376   // C++ [dcl.fct.default]p3
377   //   A default argument expression shall be specified only in the
378   //   parameter-declaration-clause of a function declaration or in a
379   //   template-parameter (14.1). It shall not be specified for a
380   //   parameter pack. If it is specified in a
381   //   parameter-declaration-clause, it shall not occur within a
382   //   declarator or abstract-declarator of a parameter-declaration.
383   bool MightBeFunction = D.isFunctionDeclarationContext();
384   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
385     DeclaratorChunk &chunk = D.getTypeObject(i);
386     if (chunk.Kind == DeclaratorChunk::Function) {
387       if (MightBeFunction) {
388         // This is a function declaration. It can have default arguments, but
389         // keep looking in case its return type is a function type with default
390         // arguments.
391         MightBeFunction = false;
392         continue;
393       }
394       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395            ++argIdx) {
396         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
397         if (Param->hasUnparsedDefaultArg()) {
398           std::unique_ptr<CachedTokens> Toks =
399               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
400           SourceRange SR;
401           if (Toks->size() > 1)
402             SR = SourceRange((*Toks)[1].getLocation(),
403                              Toks->back().getLocation());
404           else
405             SR = UnparsedDefaultArgLocs[Param];
406           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
407             << SR;
408         } else if (Param->getDefaultArg()) {
409           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410             << Param->getDefaultArg()->getSourceRange();
411           Param->setDefaultArg(nullptr);
412         }
413       }
414     } else if (chunk.Kind != DeclaratorChunk::Paren) {
415       MightBeFunction = false;
416     }
417   }
418 }
419
420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423     if (!PVD->hasDefaultArg())
424       return false;
425     if (!PVD->hasInheritedDefaultArg())
426       return true;
427   }
428   return false;
429 }
430
431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
432 /// function, once we already know that they have the same
433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434 /// error, false otherwise.
435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
436                                 Scope *S) {
437   bool Invalid = false;
438
439   // The declaration context corresponding to the scope is the semantic
440   // parent, unless this is a local function declaration, in which case
441   // it is that surrounding function.
442   DeclContext *ScopeDC = New->isLocalExternDecl()
443                              ? New->getLexicalDeclContext()
444                              : New->getDeclContext();
445
446   // Find the previous declaration for the purpose of default arguments.
447   FunctionDecl *PrevForDefaultArgs = Old;
448   for (/**/; PrevForDefaultArgs;
449        // Don't bother looking back past the latest decl if this is a local
450        // extern declaration; nothing else could work.
451        PrevForDefaultArgs = New->isLocalExternDecl()
452                                 ? nullptr
453                                 : PrevForDefaultArgs->getPreviousDecl()) {
454     // Ignore hidden declarations.
455     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456       continue;
457
458     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459         !New->isCXXClassMember()) {
460       // Ignore default arguments of old decl if they are not in
461       // the same scope and this is not an out-of-line definition of
462       // a member function.
463       continue;
464     }
465
466     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467       // If only one of these is a local function declaration, then they are
468       // declared in different scopes, even though isDeclInScope may think
469       // they're in the same scope. (If both are local, the scope check is
470       // sufficient, and if neither is local, then they are in the same scope.)
471       continue;
472     }
473
474     // We found the right previous declaration.
475     break;
476   }
477
478   // C++ [dcl.fct.default]p4:
479   //   For non-template functions, default arguments can be added in
480   //   later declarations of a function in the same
481   //   scope. Declarations in different scopes have completely
482   //   distinct sets of default arguments. That is, declarations in
483   //   inner scopes do not acquire default arguments from
484   //   declarations in outer scopes, and vice versa. In a given
485   //   function declaration, all parameters subsequent to a
486   //   parameter with a default argument shall have default
487   //   arguments supplied in this or previous declarations. A
488   //   default argument shall not be redefined by a later
489   //   declaration (not even to the same value).
490   //
491   // C++ [dcl.fct.default]p6:
492   //   Except for member functions of class templates, the default arguments
493   //   in a member function definition that appears outside of the class
494   //   definition are added to the set of default arguments provided by the
495   //   member function declaration in the class definition.
496   for (unsigned p = 0, NumParams = PrevForDefaultArgs
497                                        ? PrevForDefaultArgs->getNumParams()
498                                        : 0;
499        p < NumParams; ++p) {
500     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
501     ParmVarDecl *NewParam = New->getParamDecl(p);
502
503     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
504     bool NewParamHasDfl = NewParam->hasDefaultArg();
505
506     if (OldParamHasDfl && NewParamHasDfl) {
507       unsigned DiagDefaultParamID =
508         diag::err_param_default_argument_redefinition;
509
510       // MSVC accepts that default parameters be redefined for member functions
511       // of template class. The new default parameter's value is ignored.
512       Invalid = true;
513       if (getLangOpts().MicrosoftExt) {
514         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
515         if (MD && MD->getParent()->getDescribedClassTemplate()) {
516           // Merge the old default argument into the new parameter.
517           NewParam->setHasInheritedDefaultArg();
518           if (OldParam->hasUninstantiatedDefaultArg())
519             NewParam->setUninstantiatedDefaultArg(
520                                       OldParam->getUninstantiatedDefaultArg());
521           else
522             NewParam->setDefaultArg(OldParam->getInit());
523           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
524           Invalid = false;
525         }
526       }
527
528       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529       // hint here. Alternatively, we could walk the type-source information
530       // for NewParam to find the last source location in the type... but it
531       // isn't worth the effort right now. This is the kind of test case that
532       // is hard to get right:
533       //   int f(int);
534       //   void g(int (*fp)(int) = f);
535       //   void g(int (*fp)(int) = &f);
536       Diag(NewParam->getLocation(), DiagDefaultParamID)
537         << NewParam->getDefaultArgRange();
538
539       // Look for the function declaration where the default argument was
540       // actually written, which may be a declaration prior to Old.
541       for (auto Older = PrevForDefaultArgs;
542            OldParam->hasInheritedDefaultArg(); /**/) {
543         Older = Older->getPreviousDecl();
544         OldParam = Older->getParamDecl(p);
545       }
546
547       Diag(OldParam->getLocation(), diag::note_previous_definition)
548         << OldParam->getDefaultArgRange();
549     } else if (OldParamHasDfl) {
550       // Merge the old default argument into the new parameter unless the new
551       // function is a friend declaration in a template class. In the latter
552       // case the default arguments will be inherited when the friend
553       // declaration will be instantiated.
554       if (New->getFriendObjectKind() == Decl::FOK_None ||
555           !New->getLexicalDeclContext()->isDependentContext()) {
556         // It's important to use getInit() here;  getDefaultArg()
557         // strips off any top-level ExprWithCleanups.
558         NewParam->setHasInheritedDefaultArg();
559         if (OldParam->hasUnparsedDefaultArg())
560           NewParam->setUnparsedDefaultArg();
561         else if (OldParam->hasUninstantiatedDefaultArg())
562           NewParam->setUninstantiatedDefaultArg(
563                                        OldParam->getUninstantiatedDefaultArg());
564         else
565           NewParam->setDefaultArg(OldParam->getInit());
566       }
567     } else if (NewParamHasDfl) {
568       if (New->getDescribedFunctionTemplate()) {
569         // Paragraph 4, quoted above, only applies to non-template functions.
570         Diag(NewParam->getLocation(),
571              diag::err_param_default_argument_template_redecl)
572           << NewParam->getDefaultArgRange();
573         Diag(PrevForDefaultArgs->getLocation(),
574              diag::note_template_prev_declaration)
575             << false;
576       } else if (New->getTemplateSpecializationKind()
577                    != TSK_ImplicitInstantiation &&
578                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
579         // C++ [temp.expr.spec]p21:
580         //   Default function arguments shall not be specified in a declaration
581         //   or a definition for one of the following explicit specializations:
582         //     - the explicit specialization of a function template;
583         //     - the explicit specialization of a member function template;
584         //     - the explicit specialization of a member function of a class
585         //       template where the class template specialization to which the
586         //       member function specialization belongs is implicitly
587         //       instantiated.
588         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
589           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
590           << New->getDeclName()
591           << NewParam->getDefaultArgRange();
592       } else if (New->getDeclContext()->isDependentContext()) {
593         // C++ [dcl.fct.default]p6 (DR217):
594         //   Default arguments for a member function of a class template shall
595         //   be specified on the initial declaration of the member function
596         //   within the class template.
597         //
598         // Reading the tea leaves a bit in DR217 and its reference to DR205
599         // leads me to the conclusion that one cannot add default function
600         // arguments for an out-of-line definition of a member function of a
601         // dependent type.
602         int WhichKind = 2;
603         if (CXXRecordDecl *Record
604               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
605           if (Record->getDescribedClassTemplate())
606             WhichKind = 0;
607           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
608             WhichKind = 1;
609           else
610             WhichKind = 2;
611         }
612
613         Diag(NewParam->getLocation(),
614              diag::err_param_default_argument_member_template_redecl)
615           << WhichKind
616           << NewParam->getDefaultArgRange();
617       }
618     }
619   }
620
621   // DR1344: If a default argument is added outside a class definition and that
622   // default argument makes the function a special member function, the program
623   // is ill-formed. This can only happen for constructors.
624   if (isa<CXXConstructorDecl>(New) &&
625       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
626     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
627                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
628     if (NewSM != OldSM) {
629       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
630       assert(NewParam->hasDefaultArg());
631       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
632         << NewParam->getDefaultArgRange() << NewSM;
633       Diag(Old->getLocation(), diag::note_previous_declaration);
634     }
635   }
636
637   const FunctionDecl *Def;
638   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
639   // template has a constexpr specifier then all its declarations shall
640   // contain the constexpr specifier.
641   if (New->getConstexprKind() != Old->getConstexprKind()) {
642     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
643         << New << New->getConstexprKind() << Old->getConstexprKind();
644     Diag(Old->getLocation(), diag::note_previous_declaration);
645     Invalid = true;
646   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
647              Old->isDefined(Def) &&
648              // If a friend function is inlined but does not have 'inline'
649              // specifier, it is a definition. Do not report attribute conflict
650              // in this case, redefinition will be diagnosed later.
651              (New->isInlineSpecified() ||
652               New->getFriendObjectKind() == Decl::FOK_None)) {
653     // C++11 [dcl.fcn.spec]p4:
654     //   If the definition of a function appears in a translation unit before its
655     //   first declaration as inline, the program is ill-formed.
656     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
657     Diag(Def->getLocation(), diag::note_previous_definition);
658     Invalid = true;
659   }
660
661   // C++17 [temp.deduct.guide]p3:
662   //   Two deduction guide declarations in the same translation unit
663   //   for the same class template shall not have equivalent
664   //   parameter-declaration-clauses.
665   if (isa<CXXDeductionGuideDecl>(New) &&
666       !New->isFunctionTemplateSpecialization()) {
667     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
668     Diag(Old->getLocation(), diag::note_previous_declaration);
669   }
670
671   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
672   // argument expression, that declaration shall be a definition and shall be
673   // the only declaration of the function or function template in the
674   // translation unit.
675   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
676       functionDeclHasDefaultArgument(Old)) {
677     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
678     Diag(Old->getLocation(), diag::note_previous_declaration);
679     Invalid = true;
680   }
681
682   return Invalid;
683 }
684
685 NamedDecl *
686 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
687                                    MultiTemplateParamsArg TemplateParamLists) {
688   assert(D.isDecompositionDeclarator());
689   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
690
691   // The syntax only allows a decomposition declarator as a simple-declaration,
692   // a for-range-declaration, or a condition in Clang, but we parse it in more
693   // cases than that.
694   if (!D.mayHaveDecompositionDeclarator()) {
695     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
696       << Decomp.getSourceRange();
697     return nullptr;
698   }
699
700   if (!TemplateParamLists.empty()) {
701     // FIXME: There's no rule against this, but there are also no rules that
702     // would actually make it usable, so we reject it for now.
703     Diag(TemplateParamLists.front()->getTemplateLoc(),
704          diag::err_decomp_decl_template);
705     return nullptr;
706   }
707
708   Diag(Decomp.getLSquareLoc(),
709        !getLangOpts().CPlusPlus17
710            ? diag::ext_decomp_decl
711            : D.getContext() == DeclaratorContext::ConditionContext
712                  ? diag::ext_decomp_decl_cond
713                  : diag::warn_cxx14_compat_decomp_decl)
714       << Decomp.getSourceRange();
715
716   // The semantic context is always just the current context.
717   DeclContext *const DC = CurContext;
718
719   // C++17 [dcl.dcl]/8:
720   //   The decl-specifier-seq shall contain only the type-specifier auto
721   //   and cv-qualifiers.
722   // C++2a [dcl.dcl]/8:
723   //   If decl-specifier-seq contains any decl-specifier other than static,
724   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
725   auto &DS = D.getDeclSpec();
726   {
727     SmallVector<StringRef, 8> BadSpecifiers;
728     SmallVector<SourceLocation, 8> BadSpecifierLocs;
729     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
730     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
731     if (auto SCS = DS.getStorageClassSpec()) {
732       if (SCS == DeclSpec::SCS_static) {
733         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
734         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
735       } else {
736         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
737         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
738       }
739     }
740     if (auto TSCS = DS.getThreadStorageClassSpec()) {
741       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
742       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
743     }
744     if (DS.hasConstexprSpecifier()) {
745       BadSpecifiers.push_back(
746           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
747       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
748     }
749     if (DS.isInlineSpecified()) {
750       BadSpecifiers.push_back("inline");
751       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
752     }
753     if (!BadSpecifiers.empty()) {
754       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
755       Err << (int)BadSpecifiers.size()
756           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
757       // Don't add FixItHints to remove the specifiers; we do still respect
758       // them when building the underlying variable.
759       for (auto Loc : BadSpecifierLocs)
760         Err << SourceRange(Loc, Loc);
761     } else if (!CPlusPlus20Specifiers.empty()) {
762       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
763                          getLangOpts().CPlusPlus2a
764                              ? diag::warn_cxx17_compat_decomp_decl_spec
765                              : diag::ext_decomp_decl_spec);
766       Warn << (int)CPlusPlus20Specifiers.size()
767            << llvm::join(CPlusPlus20Specifiers.begin(),
768                          CPlusPlus20Specifiers.end(), " ");
769       for (auto Loc : CPlusPlus20SpecifierLocs)
770         Warn << SourceRange(Loc, Loc);
771     }
772     // We can't recover from it being declared as a typedef.
773     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
774       return nullptr;
775   }
776
777   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
778   QualType R = TInfo->getType();
779
780   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
781                                       UPPC_DeclarationType))
782     D.setInvalidType();
783
784   // The syntax only allows a single ref-qualifier prior to the decomposition
785   // declarator. No other declarator chunks are permitted. Also check the type
786   // specifier here.
787   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
788       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
789       (D.getNumTypeObjects() == 1 &&
790        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
791     Diag(Decomp.getLSquareLoc(),
792          (D.hasGroupingParens() ||
793           (D.getNumTypeObjects() &&
794            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
795              ? diag::err_decomp_decl_parens
796              : diag::err_decomp_decl_type)
797         << R;
798
799     // In most cases, there's no actual problem with an explicitly-specified
800     // type, but a function type won't work here, and ActOnVariableDeclarator
801     // shouldn't be called for such a type.
802     if (R->isFunctionType())
803       D.setInvalidType();
804   }
805
806   // Build the BindingDecls.
807   SmallVector<BindingDecl*, 8> Bindings;
808
809   // Build the BindingDecls.
810   for (auto &B : D.getDecompositionDeclarator().bindings()) {
811     // Check for name conflicts.
812     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
813     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
814                           ForVisibleRedeclaration);
815     LookupName(Previous, S,
816                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
817
818     // It's not permitted to shadow a template parameter name.
819     if (Previous.isSingleResult() &&
820         Previous.getFoundDecl()->isTemplateParameter()) {
821       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
822                                       Previous.getFoundDecl());
823       Previous.clear();
824     }
825
826     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
827                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
828     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
829                          /*AllowInlineNamespace*/false);
830     if (!Previous.empty()) {
831       auto *Old = Previous.getRepresentativeDecl();
832       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
833       Diag(Old->getLocation(), diag::note_previous_definition);
834     }
835
836     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
837     PushOnScopeChains(BD, S, true);
838     Bindings.push_back(BD);
839     ParsingInitForAutoVars.insert(BD);
840   }
841
842   // There are no prior lookup results for the variable itself, because it
843   // is unnamed.
844   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
845                                Decomp.getLSquareLoc());
846   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
847                         ForVisibleRedeclaration);
848
849   // Build the variable that holds the non-decomposed object.
850   bool AddToScope = true;
851   NamedDecl *New =
852       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
853                               MultiTemplateParamsArg(), AddToScope, Bindings);
854   if (AddToScope) {
855     S->AddDecl(New);
856     CurContext->addHiddenDecl(New);
857   }
858
859   if (isInOpenMPDeclareTargetContext())
860     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
861
862   return New;
863 }
864
865 static bool checkSimpleDecomposition(
866     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
867     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
868     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
869   if ((int64_t)Bindings.size() != NumElems) {
870     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
871         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
872         << (NumElems < Bindings.size());
873     return true;
874   }
875
876   unsigned I = 0;
877   for (auto *B : Bindings) {
878     SourceLocation Loc = B->getLocation();
879     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
880     if (E.isInvalid())
881       return true;
882     E = GetInit(Loc, E.get(), I++);
883     if (E.isInvalid())
884       return true;
885     B->setBinding(ElemType, E.get());
886   }
887
888   return false;
889 }
890
891 static bool checkArrayLikeDecomposition(Sema &S,
892                                         ArrayRef<BindingDecl *> Bindings,
893                                         ValueDecl *Src, QualType DecompType,
894                                         const llvm::APSInt &NumElems,
895                                         QualType ElemType) {
896   return checkSimpleDecomposition(
897       S, Bindings, Src, DecompType, NumElems, ElemType,
898       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
899         ExprResult E = S.ActOnIntegerConstant(Loc, I);
900         if (E.isInvalid())
901           return ExprError();
902         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
903       });
904 }
905
906 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
907                                     ValueDecl *Src, QualType DecompType,
908                                     const ConstantArrayType *CAT) {
909   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
910                                      llvm::APSInt(CAT->getSize()),
911                                      CAT->getElementType());
912 }
913
914 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
915                                      ValueDecl *Src, QualType DecompType,
916                                      const VectorType *VT) {
917   return checkArrayLikeDecomposition(
918       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
919       S.Context.getQualifiedType(VT->getElementType(),
920                                  DecompType.getQualifiers()));
921 }
922
923 static bool checkComplexDecomposition(Sema &S,
924                                       ArrayRef<BindingDecl *> Bindings,
925                                       ValueDecl *Src, QualType DecompType,
926                                       const ComplexType *CT) {
927   return checkSimpleDecomposition(
928       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
929       S.Context.getQualifiedType(CT->getElementType(),
930                                  DecompType.getQualifiers()),
931       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
932         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
933       });
934 }
935
936 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
937                                      TemplateArgumentListInfo &Args) {
938   SmallString<128> SS;
939   llvm::raw_svector_ostream OS(SS);
940   bool First = true;
941   for (auto &Arg : Args.arguments()) {
942     if (!First)
943       OS << ", ";
944     Arg.getArgument().print(PrintingPolicy, OS);
945     First = false;
946   }
947   return OS.str();
948 }
949
950 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
951                                      SourceLocation Loc, StringRef Trait,
952                                      TemplateArgumentListInfo &Args,
953                                      unsigned DiagID) {
954   auto DiagnoseMissing = [&] {
955     if (DiagID)
956       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
957                                                Args);
958     return true;
959   };
960
961   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
962   NamespaceDecl *Std = S.getStdNamespace();
963   if (!Std)
964     return DiagnoseMissing();
965
966   // Look up the trait itself, within namespace std. We can diagnose various
967   // problems with this lookup even if we've been asked to not diagnose a
968   // missing specialization, because this can only fail if the user has been
969   // declaring their own names in namespace std or we don't support the
970   // standard library implementation in use.
971   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
972                       Loc, Sema::LookupOrdinaryName);
973   if (!S.LookupQualifiedName(Result, Std))
974     return DiagnoseMissing();
975   if (Result.isAmbiguous())
976     return true;
977
978   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
979   if (!TraitTD) {
980     Result.suppressDiagnostics();
981     NamedDecl *Found = *Result.begin();
982     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
983     S.Diag(Found->getLocation(), diag::note_declared_at);
984     return true;
985   }
986
987   // Build the template-id.
988   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
989   if (TraitTy.isNull())
990     return true;
991   if (!S.isCompleteType(Loc, TraitTy)) {
992     if (DiagID)
993       S.RequireCompleteType(
994           Loc, TraitTy, DiagID,
995           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
996     return true;
997   }
998
999   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1000   assert(RD && "specialization of class template is not a class?");
1001
1002   // Look up the member of the trait type.
1003   S.LookupQualifiedName(TraitMemberLookup, RD);
1004   return TraitMemberLookup.isAmbiguous();
1005 }
1006
1007 static TemplateArgumentLoc
1008 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1009                                    uint64_t I) {
1010   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1011   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1012 }
1013
1014 static TemplateArgumentLoc
1015 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1016   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1017 }
1018
1019 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1020
1021 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1022                                llvm::APSInt &Size) {
1023   EnterExpressionEvaluationContext ContextRAII(
1024       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1025
1026   DeclarationName Value = S.PP.getIdentifierInfo("value");
1027   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1028
1029   // Form template argument list for tuple_size<T>.
1030   TemplateArgumentListInfo Args(Loc, Loc);
1031   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1032
1033   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1034   // it's not tuple-like.
1035   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1036       R.empty())
1037     return IsTupleLike::NotTupleLike;
1038
1039   // If we get this far, we've committed to the tuple interpretation, but
1040   // we can still fail if there actually isn't a usable ::value.
1041
1042   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1043     LookupResult &R;
1044     TemplateArgumentListInfo &Args;
1045     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1046         : R(R), Args(Args) {}
1047     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1048       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1049           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1050     }
1051   } Diagnoser(R, Args);
1052
1053   ExprResult E =
1054       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1055   if (E.isInvalid())
1056     return IsTupleLike::Error;
1057
1058   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1059   if (E.isInvalid())
1060     return IsTupleLike::Error;
1061
1062   return IsTupleLike::TupleLike;
1063 }
1064
1065 /// \return std::tuple_element<I, T>::type.
1066 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1067                                         unsigned I, QualType T) {
1068   // Form template argument list for tuple_element<I, T>.
1069   TemplateArgumentListInfo Args(Loc, Loc);
1070   Args.addArgument(
1071       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1072   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1073
1074   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1075   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1076   if (lookupStdTypeTraitMember(
1077           S, R, Loc, "tuple_element", Args,
1078           diag::err_decomp_decl_std_tuple_element_not_specialized))
1079     return QualType();
1080
1081   auto *TD = R.getAsSingle<TypeDecl>();
1082   if (!TD) {
1083     R.suppressDiagnostics();
1084     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1085       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1086     if (!R.empty())
1087       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1088     return QualType();
1089   }
1090
1091   return S.Context.getTypeDeclType(TD);
1092 }
1093
1094 namespace {
1095 struct BindingDiagnosticTrap {
1096   Sema &S;
1097   DiagnosticErrorTrap Trap;
1098   BindingDecl *BD;
1099
1100   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1101       : S(S), Trap(S.Diags), BD(BD) {}
1102   ~BindingDiagnosticTrap() {
1103     if (Trap.hasErrorOccurred())
1104       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1105   }
1106 };
1107 }
1108
1109 static bool checkTupleLikeDecomposition(Sema &S,
1110                                         ArrayRef<BindingDecl *> Bindings,
1111                                         VarDecl *Src, QualType DecompType,
1112                                         const llvm::APSInt &TupleSize) {
1113   if ((int64_t)Bindings.size() != TupleSize) {
1114     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1115         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1116         << (TupleSize < Bindings.size());
1117     return true;
1118   }
1119
1120   if (Bindings.empty())
1121     return false;
1122
1123   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1124
1125   // [dcl.decomp]p3:
1126   //   The unqualified-id get is looked up in the scope of E by class member
1127   //   access lookup ...
1128   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1129   bool UseMemberGet = false;
1130   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1131     if (auto *RD = DecompType->getAsCXXRecordDecl())
1132       S.LookupQualifiedName(MemberGet, RD);
1133     if (MemberGet.isAmbiguous())
1134       return true;
1135     //   ... and if that finds at least one declaration that is a function
1136     //   template whose first template parameter is a non-type parameter ...
1137     for (NamedDecl *D : MemberGet) {
1138       if (FunctionTemplateDecl *FTD =
1139               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1140         TemplateParameterList *TPL = FTD->getTemplateParameters();
1141         if (TPL->size() != 0 &&
1142             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1143           //   ... the initializer is e.get<i>().
1144           UseMemberGet = true;
1145           break;
1146         }
1147       }
1148     }
1149   }
1150
1151   unsigned I = 0;
1152   for (auto *B : Bindings) {
1153     BindingDiagnosticTrap Trap(S, B);
1154     SourceLocation Loc = B->getLocation();
1155
1156     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1157     if (E.isInvalid())
1158       return true;
1159
1160     //   e is an lvalue if the type of the entity is an lvalue reference and
1161     //   an xvalue otherwise
1162     if (!Src->getType()->isLValueReferenceType())
1163       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1164                                    E.get(), nullptr, VK_XValue);
1165
1166     TemplateArgumentListInfo Args(Loc, Loc);
1167     Args.addArgument(
1168         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1169
1170     if (UseMemberGet) {
1171       //   if [lookup of member get] finds at least one declaration, the
1172       //   initializer is e.get<i-1>().
1173       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1174                                      CXXScopeSpec(), SourceLocation(), nullptr,
1175                                      MemberGet, &Args, nullptr);
1176       if (E.isInvalid())
1177         return true;
1178
1179       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1180     } else {
1181       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1182       //   in the associated namespaces.
1183       Expr *Get = UnresolvedLookupExpr::Create(
1184           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1185           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1186           UnresolvedSetIterator(), UnresolvedSetIterator());
1187
1188       Expr *Arg = E.get();
1189       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1190     }
1191     if (E.isInvalid())
1192       return true;
1193     Expr *Init = E.get();
1194
1195     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1196     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1197     if (T.isNull())
1198       return true;
1199
1200     //   each vi is a variable of type "reference to T" initialized with the
1201     //   initializer, where the reference is an lvalue reference if the
1202     //   initializer is an lvalue and an rvalue reference otherwise
1203     QualType RefType =
1204         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1205     if (RefType.isNull())
1206       return true;
1207     auto *RefVD = VarDecl::Create(
1208         S.Context, Src->getDeclContext(), Loc, Loc,
1209         B->getDeclName().getAsIdentifierInfo(), RefType,
1210         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1211     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1212     RefVD->setTSCSpec(Src->getTSCSpec());
1213     RefVD->setImplicit();
1214     if (Src->isInlineSpecified())
1215       RefVD->setInlineSpecified();
1216     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1217
1218     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1219     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1220     InitializationSequence Seq(S, Entity, Kind, Init);
1221     E = Seq.Perform(S, Entity, Kind, Init);
1222     if (E.isInvalid())
1223       return true;
1224     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1225     if (E.isInvalid())
1226       return true;
1227     RefVD->setInit(E.get());
1228     if (!E.get()->isValueDependent())
1229       RefVD->checkInitIsICE();
1230
1231     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1232                                    DeclarationNameInfo(B->getDeclName(), Loc),
1233                                    RefVD);
1234     if (E.isInvalid())
1235       return true;
1236
1237     B->setBinding(T, E.get());
1238     I++;
1239   }
1240
1241   return false;
1242 }
1243
1244 /// Find the base class to decompose in a built-in decomposition of a class type.
1245 /// This base class search is, unfortunately, not quite like any other that we
1246 /// perform anywhere else in C++.
1247 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1248                                                 const CXXRecordDecl *RD,
1249                                                 CXXCastPath &BasePath) {
1250   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1251                           CXXBasePath &Path) {
1252     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1253   };
1254
1255   const CXXRecordDecl *ClassWithFields = nullptr;
1256   AccessSpecifier AS = AS_public;
1257   if (RD->hasDirectFields())
1258     // [dcl.decomp]p4:
1259     //   Otherwise, all of E's non-static data members shall be public direct
1260     //   members of E ...
1261     ClassWithFields = RD;
1262   else {
1263     //   ... or of ...
1264     CXXBasePaths Paths;
1265     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1266     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1267       // If no classes have fields, just decompose RD itself. (This will work
1268       // if and only if zero bindings were provided.)
1269       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1270     }
1271
1272     CXXBasePath *BestPath = nullptr;
1273     for (auto &P : Paths) {
1274       if (!BestPath)
1275         BestPath = &P;
1276       else if (!S.Context.hasSameType(P.back().Base->getType(),
1277                                       BestPath->back().Base->getType())) {
1278         //   ... the same ...
1279         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1280           << false << RD << BestPath->back().Base->getType()
1281           << P.back().Base->getType();
1282         return DeclAccessPair();
1283       } else if (P.Access < BestPath->Access) {
1284         BestPath = &P;
1285       }
1286     }
1287
1288     //   ... unambiguous ...
1289     QualType BaseType = BestPath->back().Base->getType();
1290     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1291       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1292         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1293       return DeclAccessPair();
1294     }
1295
1296     //   ... [accessible, implied by other rules] base class of E.
1297     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1298                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1299     AS = BestPath->Access;
1300
1301     ClassWithFields = BaseType->getAsCXXRecordDecl();
1302     S.BuildBasePathArray(Paths, BasePath);
1303   }
1304
1305   // The above search did not check whether the selected class itself has base
1306   // classes with fields, so check that now.
1307   CXXBasePaths Paths;
1308   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1309     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1310       << (ClassWithFields == RD) << RD << ClassWithFields
1311       << Paths.front().back().Base->getType();
1312     return DeclAccessPair();
1313   }
1314
1315   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1316 }
1317
1318 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1319                                      ValueDecl *Src, QualType DecompType,
1320                                      const CXXRecordDecl *OrigRD) {
1321   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1322                             diag::err_incomplete_type))
1323     return true;
1324
1325   CXXCastPath BasePath;
1326   DeclAccessPair BasePair =
1327       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1328   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1329   if (!RD)
1330     return true;
1331   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1332                                                  DecompType.getQualifiers());
1333
1334   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1335     unsigned NumFields =
1336         std::count_if(RD->field_begin(), RD->field_end(),
1337                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1338     assert(Bindings.size() != NumFields);
1339     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1340         << DecompType << (unsigned)Bindings.size() << NumFields
1341         << (NumFields < Bindings.size());
1342     return true;
1343   };
1344
1345   //   all of E's non-static data members shall be [...] well-formed
1346   //   when named as e.name in the context of the structured binding,
1347   //   E shall not have an anonymous union member, ...
1348   unsigned I = 0;
1349   for (auto *FD : RD->fields()) {
1350     if (FD->isUnnamedBitfield())
1351       continue;
1352
1353     if (FD->isAnonymousStructOrUnion()) {
1354       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1355         << DecompType << FD->getType()->isUnionType();
1356       S.Diag(FD->getLocation(), diag::note_declared_at);
1357       return true;
1358     }
1359
1360     // We have a real field to bind.
1361     if (I >= Bindings.size())
1362       return DiagnoseBadNumberOfBindings();
1363     auto *B = Bindings[I++];
1364     SourceLocation Loc = B->getLocation();
1365
1366     // The field must be accessible in the context of the structured binding.
1367     // We already checked that the base class is accessible.
1368     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1369     // const_cast here.
1370     S.CheckStructuredBindingMemberAccess(
1371         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1372         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1373                                      BasePair.getAccess(), FD->getAccess())));
1374
1375     // Initialize the binding to Src.FD.
1376     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1377     if (E.isInvalid())
1378       return true;
1379     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1380                             VK_LValue, &BasePath);
1381     if (E.isInvalid())
1382       return true;
1383     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1384                                   CXXScopeSpec(), FD,
1385                                   DeclAccessPair::make(FD, FD->getAccess()),
1386                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1387     if (E.isInvalid())
1388       return true;
1389
1390     // If the type of the member is T, the referenced type is cv T, where cv is
1391     // the cv-qualification of the decomposition expression.
1392     //
1393     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1394     // 'const' to the type of the field.
1395     Qualifiers Q = DecompType.getQualifiers();
1396     if (FD->isMutable())
1397       Q.removeConst();
1398     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1399   }
1400
1401   if (I != Bindings.size())
1402     return DiagnoseBadNumberOfBindings();
1403
1404   return false;
1405 }
1406
1407 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1408   QualType DecompType = DD->getType();
1409
1410   // If the type of the decomposition is dependent, then so is the type of
1411   // each binding.
1412   if (DecompType->isDependentType()) {
1413     for (auto *B : DD->bindings())
1414       B->setType(Context.DependentTy);
1415     return;
1416   }
1417
1418   DecompType = DecompType.getNonReferenceType();
1419   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1420
1421   // C++1z [dcl.decomp]/2:
1422   //   If E is an array type [...]
1423   // As an extension, we also support decomposition of built-in complex and
1424   // vector types.
1425   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1426     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1427       DD->setInvalidDecl();
1428     return;
1429   }
1430   if (auto *VT = DecompType->getAs<VectorType>()) {
1431     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1432       DD->setInvalidDecl();
1433     return;
1434   }
1435   if (auto *CT = DecompType->getAs<ComplexType>()) {
1436     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1437       DD->setInvalidDecl();
1438     return;
1439   }
1440
1441   // C++1z [dcl.decomp]/3:
1442   //   if the expression std::tuple_size<E>::value is a well-formed integral
1443   //   constant expression, [...]
1444   llvm::APSInt TupleSize(32);
1445   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1446   case IsTupleLike::Error:
1447     DD->setInvalidDecl();
1448     return;
1449
1450   case IsTupleLike::TupleLike:
1451     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1452       DD->setInvalidDecl();
1453     return;
1454
1455   case IsTupleLike::NotTupleLike:
1456     break;
1457   }
1458
1459   // C++1z [dcl.dcl]/8:
1460   //   [E shall be of array or non-union class type]
1461   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1462   if (!RD || RD->isUnion()) {
1463     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1464         << DD << !RD << DecompType;
1465     DD->setInvalidDecl();
1466     return;
1467   }
1468
1469   // C++1z [dcl.decomp]/4:
1470   //   all of E's non-static data members shall be [...] direct members of
1471   //   E or of the same unambiguous public base class of E, ...
1472   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1473     DD->setInvalidDecl();
1474 }
1475
1476 /// Merge the exception specifications of two variable declarations.
1477 ///
1478 /// This is called when there's a redeclaration of a VarDecl. The function
1479 /// checks if the redeclaration might have an exception specification and
1480 /// validates compatibility and merges the specs if necessary.
1481 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1482   // Shortcut if exceptions are disabled.
1483   if (!getLangOpts().CXXExceptions)
1484     return;
1485
1486   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1487          "Should only be called if types are otherwise the same.");
1488
1489   QualType NewType = New->getType();
1490   QualType OldType = Old->getType();
1491
1492   // We're only interested in pointers and references to functions, as well
1493   // as pointers to member functions.
1494   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1495     NewType = R->getPointeeType();
1496     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1497   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1498     NewType = P->getPointeeType();
1499     OldType = OldType->getAs<PointerType>()->getPointeeType();
1500   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1501     NewType = M->getPointeeType();
1502     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1503   }
1504
1505   if (!NewType->isFunctionProtoType())
1506     return;
1507
1508   // There's lots of special cases for functions. For function pointers, system
1509   // libraries are hopefully not as broken so that we don't need these
1510   // workarounds.
1511   if (CheckEquivalentExceptionSpec(
1512         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1513         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1514     New->setInvalidDecl();
1515   }
1516 }
1517
1518 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1519 /// function declaration are well-formed according to C++
1520 /// [dcl.fct.default].
1521 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1522   unsigned NumParams = FD->getNumParams();
1523   unsigned p;
1524
1525   // Find first parameter with a default argument
1526   for (p = 0; p < NumParams; ++p) {
1527     ParmVarDecl *Param = FD->getParamDecl(p);
1528     if (Param->hasDefaultArg())
1529       break;
1530   }
1531
1532   // C++11 [dcl.fct.default]p4:
1533   //   In a given function declaration, each parameter subsequent to a parameter
1534   //   with a default argument shall have a default argument supplied in this or
1535   //   a previous declaration or shall be a function parameter pack. A default
1536   //   argument shall not be redefined by a later declaration (not even to the
1537   //   same value).
1538   unsigned LastMissingDefaultArg = 0;
1539   for (; p < NumParams; ++p) {
1540     ParmVarDecl *Param = FD->getParamDecl(p);
1541     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1542       if (Param->isInvalidDecl())
1543         /* We already complained about this parameter. */;
1544       else if (Param->getIdentifier())
1545         Diag(Param->getLocation(),
1546              diag::err_param_default_argument_missing_name)
1547           << Param->getIdentifier();
1548       else
1549         Diag(Param->getLocation(),
1550              diag::err_param_default_argument_missing);
1551
1552       LastMissingDefaultArg = p;
1553     }
1554   }
1555
1556   if (LastMissingDefaultArg > 0) {
1557     // Some default arguments were missing. Clear out all of the
1558     // default arguments up to (and including) the last missing
1559     // default argument, so that we leave the function parameters
1560     // in a semantically valid state.
1561     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1562       ParmVarDecl *Param = FD->getParamDecl(p);
1563       if (Param->hasDefaultArg()) {
1564         Param->setDefaultArg(nullptr);
1565       }
1566     }
1567   }
1568 }
1569
1570 // CheckConstexprParameterTypes - Check whether a function's parameter types
1571 // are all literal types. If so, return true. If not, produce a suitable
1572 // diagnostic and return false.
1573 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1574                                          const FunctionDecl *FD) {
1575   unsigned ArgIndex = 0;
1576   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1577   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1578                                               e = FT->param_type_end();
1579        i != e; ++i, ++ArgIndex) {
1580     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1581     SourceLocation ParamLoc = PD->getLocation();
1582     if (!(*i)->isDependentType() &&
1583         SemaRef.RequireLiteralType(
1584             ParamLoc, *i, diag::err_constexpr_non_literal_param, ArgIndex + 1,
1585             PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1586             FD->isConsteval()))
1587       return false;
1588   }
1589   return true;
1590 }
1591
1592 /// Get diagnostic %select index for tag kind for
1593 /// record diagnostic message.
1594 /// WARNING: Indexes apply to particular diagnostics only!
1595 ///
1596 /// \returns diagnostic %select index.
1597 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1598   switch (Tag) {
1599   case TTK_Struct: return 0;
1600   case TTK_Interface: return 1;
1601   case TTK_Class:  return 2;
1602   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1603   }
1604 }
1605
1606 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1607 // the requirements of a constexpr function definition or a constexpr
1608 // constructor definition. If so, return true. If not, produce appropriate
1609 // diagnostics and return false.
1610 //
1611 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1612 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1613   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1614   if (MD && MD->isInstance()) {
1615     // C++11 [dcl.constexpr]p4:
1616     //  The definition of a constexpr constructor shall satisfy the following
1617     //  constraints:
1618     //  - the class shall not have any virtual base classes;
1619     //
1620     // FIXME: This only applies to constructors, not arbitrary member
1621     // functions.
1622     const CXXRecordDecl *RD = MD->getParent();
1623     if (RD->getNumVBases()) {
1624       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1625         << isa<CXXConstructorDecl>(NewFD)
1626         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1627       for (const auto &I : RD->vbases())
1628         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1629             << I.getSourceRange();
1630       return false;
1631     }
1632   }
1633
1634   if (!isa<CXXConstructorDecl>(NewFD)) {
1635     // C++11 [dcl.constexpr]p3:
1636     //  The definition of a constexpr function shall satisfy the following
1637     //  constraints:
1638     // - it shall not be virtual; (removed in C++20)
1639     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1640     if (Method && Method->isVirtual()) {
1641       if (getLangOpts().CPlusPlus2a) {
1642         Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1643       } else {
1644         Method = Method->getCanonicalDecl();
1645         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1646
1647         // If it's not obvious why this function is virtual, find an overridden
1648         // function which uses the 'virtual' keyword.
1649         const CXXMethodDecl *WrittenVirtual = Method;
1650         while (!WrittenVirtual->isVirtualAsWritten())
1651           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1652         if (WrittenVirtual != Method)
1653           Diag(WrittenVirtual->getLocation(),
1654                diag::note_overridden_virtual_function);
1655         return false;
1656       }
1657     }
1658
1659     // - its return type shall be a literal type;
1660     QualType RT = NewFD->getReturnType();
1661     if (!RT->isDependentType() &&
1662         RequireLiteralType(NewFD->getLocation(), RT,
1663                            diag::err_constexpr_non_literal_return,
1664                            NewFD->isConsteval()))
1665       return false;
1666   }
1667
1668   // - each of its parameter types shall be a literal type;
1669   if (!CheckConstexprParameterTypes(*this, NewFD))
1670     return false;
1671
1672   return true;
1673 }
1674
1675 /// Check the given declaration statement is legal within a constexpr function
1676 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1677 ///
1678 /// \return true if the body is OK (maybe only as an extension), false if we
1679 ///         have diagnosed a problem.
1680 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1681                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1682   // C++11 [dcl.constexpr]p3 and p4:
1683   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1684   //  contain only
1685   for (const auto *DclIt : DS->decls()) {
1686     switch (DclIt->getKind()) {
1687     case Decl::StaticAssert:
1688     case Decl::Using:
1689     case Decl::UsingShadow:
1690     case Decl::UsingDirective:
1691     case Decl::UnresolvedUsingTypename:
1692     case Decl::UnresolvedUsingValue:
1693       //   - static_assert-declarations
1694       //   - using-declarations,
1695       //   - using-directives,
1696       continue;
1697
1698     case Decl::Typedef:
1699     case Decl::TypeAlias: {
1700       //   - typedef declarations and alias-declarations that do not define
1701       //     classes or enumerations,
1702       const auto *TN = cast<TypedefNameDecl>(DclIt);
1703       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1704         // Don't allow variably-modified types in constexpr functions.
1705         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1706         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1707           << TL.getSourceRange() << TL.getType()
1708           << isa<CXXConstructorDecl>(Dcl);
1709         return false;
1710       }
1711       continue;
1712     }
1713
1714     case Decl::Enum:
1715     case Decl::CXXRecord:
1716       // C++1y allows types to be defined, not just declared.
1717       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1718         SemaRef.Diag(DS->getBeginLoc(),
1719                      SemaRef.getLangOpts().CPlusPlus14
1720                          ? diag::warn_cxx11_compat_constexpr_type_definition
1721                          : diag::ext_constexpr_type_definition)
1722             << isa<CXXConstructorDecl>(Dcl);
1723       continue;
1724
1725     case Decl::EnumConstant:
1726     case Decl::IndirectField:
1727     case Decl::ParmVar:
1728       // These can only appear with other declarations which are banned in
1729       // C++11 and permitted in C++1y, so ignore them.
1730       continue;
1731
1732     case Decl::Var:
1733     case Decl::Decomposition: {
1734       // C++1y [dcl.constexpr]p3 allows anything except:
1735       //   a definition of a variable of non-literal type or of static or
1736       //   thread storage duration or for which no initialization is performed.
1737       const auto *VD = cast<VarDecl>(DclIt);
1738       if (VD->isThisDeclarationADefinition()) {
1739         if (VD->isStaticLocal()) {
1740           SemaRef.Diag(VD->getLocation(),
1741                        diag::err_constexpr_local_var_static)
1742             << isa<CXXConstructorDecl>(Dcl)
1743             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1744           return false;
1745         }
1746         if (!VD->getType()->isDependentType() &&
1747             SemaRef.RequireLiteralType(
1748               VD->getLocation(), VD->getType(),
1749               diag::err_constexpr_local_var_non_literal_type,
1750               isa<CXXConstructorDecl>(Dcl)))
1751           return false;
1752         if (!VD->getType()->isDependentType() &&
1753             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1754           SemaRef.Diag(VD->getLocation(),
1755                        diag::err_constexpr_local_var_no_init)
1756             << isa<CXXConstructorDecl>(Dcl);
1757           return false;
1758         }
1759       }
1760       SemaRef.Diag(VD->getLocation(),
1761                    SemaRef.getLangOpts().CPlusPlus14
1762                     ? diag::warn_cxx11_compat_constexpr_local_var
1763                     : diag::ext_constexpr_local_var)
1764         << isa<CXXConstructorDecl>(Dcl);
1765       continue;
1766     }
1767
1768     case Decl::NamespaceAlias:
1769     case Decl::Function:
1770       // These are disallowed in C++11 and permitted in C++1y. Allow them
1771       // everywhere as an extension.
1772       if (!Cxx1yLoc.isValid())
1773         Cxx1yLoc = DS->getBeginLoc();
1774       continue;
1775
1776     default:
1777       SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1778           << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1779       return false;
1780     }
1781   }
1782
1783   return true;
1784 }
1785
1786 /// Check that the given field is initialized within a constexpr constructor.
1787 ///
1788 /// \param Dcl The constexpr constructor being checked.
1789 /// \param Field The field being checked. This may be a member of an anonymous
1790 ///        struct or union nested within the class being checked.
1791 /// \param Inits All declarations, including anonymous struct/union members and
1792 ///        indirect members, for which any initialization was provided.
1793 /// \param Diagnosed Set to true if an error is produced.
1794 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1795                                           const FunctionDecl *Dcl,
1796                                           FieldDecl *Field,
1797                                           llvm::SmallSet<Decl*, 16> &Inits,
1798                                           bool &Diagnosed) {
1799   if (Field->isInvalidDecl())
1800     return;
1801
1802   if (Field->isUnnamedBitfield())
1803     return;
1804
1805   // Anonymous unions with no variant members and empty anonymous structs do not
1806   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1807   // indirect fields don't need initializing.
1808   if (Field->isAnonymousStructOrUnion() &&
1809       (Field->getType()->isUnionType()
1810            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1811            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1812     return;
1813
1814   if (!Inits.count(Field)) {
1815     if (!Diagnosed) {
1816       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1817       Diagnosed = true;
1818     }
1819     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1820   } else if (Field->isAnonymousStructOrUnion()) {
1821     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1822     for (auto *I : RD->fields())
1823       // If an anonymous union contains an anonymous struct of which any member
1824       // is initialized, all members must be initialized.
1825       if (!RD->isUnion() || Inits.count(I))
1826         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1827   }
1828 }
1829
1830 /// Check the provided statement is allowed in a constexpr function
1831 /// definition.
1832 static bool
1833 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1834                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1835                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc) {
1836   // - its function-body shall be [...] a compound-statement that contains only
1837   switch (S->getStmtClass()) {
1838   case Stmt::NullStmtClass:
1839     //   - null statements,
1840     return true;
1841
1842   case Stmt::DeclStmtClass:
1843     //   - static_assert-declarations
1844     //   - using-declarations,
1845     //   - using-directives,
1846     //   - typedef declarations and alias-declarations that do not define
1847     //     classes or enumerations,
1848     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1849       return false;
1850     return true;
1851
1852   case Stmt::ReturnStmtClass:
1853     //   - and exactly one return statement;
1854     if (isa<CXXConstructorDecl>(Dcl)) {
1855       // C++1y allows return statements in constexpr constructors.
1856       if (!Cxx1yLoc.isValid())
1857         Cxx1yLoc = S->getBeginLoc();
1858       return true;
1859     }
1860
1861     ReturnStmts.push_back(S->getBeginLoc());
1862     return true;
1863
1864   case Stmt::CompoundStmtClass: {
1865     // C++1y allows compound-statements.
1866     if (!Cxx1yLoc.isValid())
1867       Cxx1yLoc = S->getBeginLoc();
1868
1869     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1870     for (auto *BodyIt : CompStmt->body()) {
1871       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1872                                       Cxx1yLoc, Cxx2aLoc))
1873         return false;
1874     }
1875     return true;
1876   }
1877
1878   case Stmt::AttributedStmtClass:
1879     if (!Cxx1yLoc.isValid())
1880       Cxx1yLoc = S->getBeginLoc();
1881     return true;
1882
1883   case Stmt::IfStmtClass: {
1884     // C++1y allows if-statements.
1885     if (!Cxx1yLoc.isValid())
1886       Cxx1yLoc = S->getBeginLoc();
1887
1888     IfStmt *If = cast<IfStmt>(S);
1889     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1890                                     Cxx1yLoc, Cxx2aLoc))
1891       return false;
1892     if (If->getElse() &&
1893         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1894                                     Cxx1yLoc, Cxx2aLoc))
1895       return false;
1896     return true;
1897   }
1898
1899   case Stmt::WhileStmtClass:
1900   case Stmt::DoStmtClass:
1901   case Stmt::ForStmtClass:
1902   case Stmt::CXXForRangeStmtClass:
1903   case Stmt::ContinueStmtClass:
1904     // C++1y allows all of these. We don't allow them as extensions in C++11,
1905     // because they don't make sense without variable mutation.
1906     if (!SemaRef.getLangOpts().CPlusPlus14)
1907       break;
1908     if (!Cxx1yLoc.isValid())
1909       Cxx1yLoc = S->getBeginLoc();
1910     for (Stmt *SubStmt : S->children())
1911       if (SubStmt &&
1912           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1913                                       Cxx1yLoc, Cxx2aLoc))
1914         return false;
1915     return true;
1916
1917   case Stmt::SwitchStmtClass:
1918   case Stmt::CaseStmtClass:
1919   case Stmt::DefaultStmtClass:
1920   case Stmt::BreakStmtClass:
1921     // C++1y allows switch-statements, and since they don't need variable
1922     // mutation, we can reasonably allow them in C++11 as an extension.
1923     if (!Cxx1yLoc.isValid())
1924       Cxx1yLoc = S->getBeginLoc();
1925     for (Stmt *SubStmt : S->children())
1926       if (SubStmt &&
1927           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1928                                       Cxx1yLoc, Cxx2aLoc))
1929         return false;
1930     return true;
1931
1932   case Stmt::CXXTryStmtClass:
1933     if (Cxx2aLoc.isInvalid())
1934       Cxx2aLoc = S->getBeginLoc();
1935     for (Stmt *SubStmt : S->children()) {
1936       if (SubStmt &&
1937           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1938                                       Cxx1yLoc, Cxx2aLoc))
1939         return false;
1940     }
1941     return true;
1942
1943   case Stmt::CXXCatchStmtClass:
1944     // Do not bother checking the language mode (already covered by the
1945     // try block check).
1946     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
1947                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
1948                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc))
1949       return false;
1950     return true;
1951
1952   default:
1953     if (!isa<Expr>(S))
1954       break;
1955
1956     // C++1y allows expression-statements.
1957     if (!Cxx1yLoc.isValid())
1958       Cxx1yLoc = S->getBeginLoc();
1959     return true;
1960   }
1961
1962   SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1963       << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1964   return false;
1965 }
1966
1967 /// Check the body for the given constexpr function declaration only contains
1968 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1969 ///
1970 /// \return true if the body is OK, false if we have diagnosed a problem.
1971 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1972   SmallVector<SourceLocation, 4> ReturnStmts;
1973
1974   if (isa<CXXTryStmt>(Body)) {
1975     // C++11 [dcl.constexpr]p3:
1976     //  The definition of a constexpr function shall satisfy the following
1977     //  constraints: [...]
1978     // - its function-body shall be = delete, = default, or a
1979     //   compound-statement
1980     //
1981     // C++11 [dcl.constexpr]p4:
1982     //  In the definition of a constexpr constructor, [...]
1983     // - its function-body shall not be a function-try-block;
1984     //
1985     // This restriction is lifted in C++2a, as long as inner statements also
1986     // apply the general constexpr rules.
1987     Diag(Body->getBeginLoc(),
1988          !getLangOpts().CPlusPlus2a
1989              ? diag::ext_constexpr_function_try_block_cxx2a
1990              : diag::warn_cxx17_compat_constexpr_function_try_block)
1991         << isa<CXXConstructorDecl>(Dcl);
1992   }
1993
1994   // - its function-body shall be [...] a compound-statement that contains only
1995   //   [... list of cases ...]
1996   //
1997   // Note that walking the children here is enough to properly check for
1998   // CompoundStmt and CXXTryStmt body.
1999   SourceLocation Cxx1yLoc, Cxx2aLoc;
2000   for (Stmt *SubStmt : Body->children()) {
2001     if (SubStmt &&
2002         !CheckConstexprFunctionStmt(*this, Dcl, SubStmt, ReturnStmts,
2003                                     Cxx1yLoc, Cxx2aLoc))
2004       return false;
2005   }
2006
2007   if (Cxx2aLoc.isValid())
2008     Diag(Cxx2aLoc,
2009          getLangOpts().CPlusPlus2a
2010            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2011            : diag::ext_constexpr_body_invalid_stmt_cxx2a)
2012       << isa<CXXConstructorDecl>(Dcl);
2013   if (Cxx1yLoc.isValid())
2014     Diag(Cxx1yLoc,
2015          getLangOpts().CPlusPlus14
2016            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2017            : diag::ext_constexpr_body_invalid_stmt)
2018       << isa<CXXConstructorDecl>(Dcl);
2019
2020   if (const CXXConstructorDecl *Constructor
2021         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2022     const CXXRecordDecl *RD = Constructor->getParent();
2023     // DR1359:
2024     // - every non-variant non-static data member and base class sub-object
2025     //   shall be initialized;
2026     // DR1460:
2027     // - if the class is a union having variant members, exactly one of them
2028     //   shall be initialized;
2029     if (RD->isUnion()) {
2030       if (Constructor->getNumCtorInitializers() == 0 &&
2031           RD->hasVariantMembers()) {
2032         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
2033         return false;
2034       }
2035     } else if (!Constructor->isDependentContext() &&
2036                !Constructor->isDelegatingConstructor()) {
2037       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2038
2039       // Skip detailed checking if we have enough initializers, and we would
2040       // allow at most one initializer per member.
2041       bool AnyAnonStructUnionMembers = false;
2042       unsigned Fields = 0;
2043       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2044            E = RD->field_end(); I != E; ++I, ++Fields) {
2045         if (I->isAnonymousStructOrUnion()) {
2046           AnyAnonStructUnionMembers = true;
2047           break;
2048         }
2049       }
2050       // DR1460:
2051       // - if the class is a union-like class, but is not a union, for each of
2052       //   its anonymous union members having variant members, exactly one of
2053       //   them shall be initialized;
2054       if (AnyAnonStructUnionMembers ||
2055           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2056         // Check initialization of non-static data members. Base classes are
2057         // always initialized so do not need to be checked. Dependent bases
2058         // might not have initializers in the member initializer list.
2059         llvm::SmallSet<Decl*, 16> Inits;
2060         for (const auto *I: Constructor->inits()) {
2061           if (FieldDecl *FD = I->getMember())
2062             Inits.insert(FD);
2063           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2064             Inits.insert(ID->chain_begin(), ID->chain_end());
2065         }
2066
2067         bool Diagnosed = false;
2068         for (auto *I : RD->fields())
2069           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2070         if (Diagnosed)
2071           return false;
2072       }
2073     }
2074   } else {
2075     if (ReturnStmts.empty()) {
2076       // C++1y doesn't require constexpr functions to contain a 'return'
2077       // statement. We still do, unless the return type might be void, because
2078       // otherwise if there's no return statement, the function cannot
2079       // be used in a core constant expression.
2080       bool OK = getLangOpts().CPlusPlus14 &&
2081                 (Dcl->getReturnType()->isVoidType() ||
2082                  Dcl->getReturnType()->isDependentType());
2083       Diag(Dcl->getLocation(),
2084            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2085               : diag::err_constexpr_body_no_return)
2086           << Dcl->isConsteval();
2087       if (!OK)
2088         return false;
2089     } else if (ReturnStmts.size() > 1) {
2090       Diag(ReturnStmts.back(),
2091            getLangOpts().CPlusPlus14
2092              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2093              : diag::ext_constexpr_body_multiple_return);
2094       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2095         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2096     }
2097   }
2098
2099   // C++11 [dcl.constexpr]p5:
2100   //   if no function argument values exist such that the function invocation
2101   //   substitution would produce a constant expression, the program is
2102   //   ill-formed; no diagnostic required.
2103   // C++11 [dcl.constexpr]p3:
2104   //   - every constructor call and implicit conversion used in initializing the
2105   //     return value shall be one of those allowed in a constant expression.
2106   // C++11 [dcl.constexpr]p4:
2107   //   - every constructor involved in initializing non-static data members and
2108   //     base class sub-objects shall be a constexpr constructor.
2109   SmallVector<PartialDiagnosticAt, 8> Diags;
2110   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2111     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2112       << isa<CXXConstructorDecl>(Dcl);
2113     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2114       Diag(Diags[I].first, Diags[I].second);
2115     // Don't return false here: we allow this for compatibility in
2116     // system headers.
2117   }
2118
2119   return true;
2120 }
2121
2122 /// Get the class that is directly named by the current context. This is the
2123 /// class for which an unqualified-id in this scope could name a constructor
2124 /// or destructor.
2125 ///
2126 /// If the scope specifier denotes a class, this will be that class.
2127 /// If the scope specifier is empty, this will be the class whose
2128 /// member-specification we are currently within. Otherwise, there
2129 /// is no such class.
2130 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2131   assert(getLangOpts().CPlusPlus && "No class names in C!");
2132
2133   if (SS && SS->isInvalid())
2134     return nullptr;
2135
2136   if (SS && SS->isNotEmpty()) {
2137     DeclContext *DC = computeDeclContext(*SS, true);
2138     return dyn_cast_or_null<CXXRecordDecl>(DC);
2139   }
2140
2141   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2142 }
2143
2144 /// isCurrentClassName - Determine whether the identifier II is the
2145 /// name of the class type currently being defined. In the case of
2146 /// nested classes, this will only return true if II is the name of
2147 /// the innermost class.
2148 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2149                               const CXXScopeSpec *SS) {
2150   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2151   return CurDecl && &II == CurDecl->getIdentifier();
2152 }
2153
2154 /// Determine whether the identifier II is a typo for the name of
2155 /// the class type currently being defined. If so, update it to the identifier
2156 /// that should have been used.
2157 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2158   assert(getLangOpts().CPlusPlus && "No class names in C!");
2159
2160   if (!getLangOpts().SpellChecking)
2161     return false;
2162
2163   CXXRecordDecl *CurDecl;
2164   if (SS && SS->isSet() && !SS->isInvalid()) {
2165     DeclContext *DC = computeDeclContext(*SS, true);
2166     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2167   } else
2168     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2169
2170   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2171       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2172           < II->getLength()) {
2173     II = CurDecl->getIdentifier();
2174     return true;
2175   }
2176
2177   return false;
2178 }
2179
2180 /// Determine whether the given class is a base class of the given
2181 /// class, including looking at dependent bases.
2182 static bool findCircularInheritance(const CXXRecordDecl *Class,
2183                                     const CXXRecordDecl *Current) {
2184   SmallVector<const CXXRecordDecl*, 8> Queue;
2185
2186   Class = Class->getCanonicalDecl();
2187   while (true) {
2188     for (const auto &I : Current->bases()) {
2189       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2190       if (!Base)
2191         continue;
2192
2193       Base = Base->getDefinition();
2194       if (!Base)
2195         continue;
2196
2197       if (Base->getCanonicalDecl() == Class)
2198         return true;
2199
2200       Queue.push_back(Base);
2201     }
2202
2203     if (Queue.empty())
2204       return false;
2205
2206     Current = Queue.pop_back_val();
2207   }
2208
2209   return false;
2210 }
2211
2212 /// Check the validity of a C++ base class specifier.
2213 ///
2214 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2215 /// and returns NULL otherwise.
2216 CXXBaseSpecifier *
2217 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2218                          SourceRange SpecifierRange,
2219                          bool Virtual, AccessSpecifier Access,
2220                          TypeSourceInfo *TInfo,
2221                          SourceLocation EllipsisLoc) {
2222   QualType BaseType = TInfo->getType();
2223
2224   // C++ [class.union]p1:
2225   //   A union shall not have base classes.
2226   if (Class->isUnion()) {
2227     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2228       << SpecifierRange;
2229     return nullptr;
2230   }
2231
2232   if (EllipsisLoc.isValid() &&
2233       !TInfo->getType()->containsUnexpandedParameterPack()) {
2234     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2235       << TInfo->getTypeLoc().getSourceRange();
2236     EllipsisLoc = SourceLocation();
2237   }
2238
2239   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2240
2241   if (BaseType->isDependentType()) {
2242     // Make sure that we don't have circular inheritance among our dependent
2243     // bases. For non-dependent bases, the check for completeness below handles
2244     // this.
2245     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2246       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2247           ((BaseDecl = BaseDecl->getDefinition()) &&
2248            findCircularInheritance(Class, BaseDecl))) {
2249         Diag(BaseLoc, diag::err_circular_inheritance)
2250           << BaseType << Context.getTypeDeclType(Class);
2251
2252         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2253           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2254             << BaseType;
2255
2256         return nullptr;
2257       }
2258     }
2259
2260     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2261                                           Class->getTagKind() == TTK_Class,
2262                                           Access, TInfo, EllipsisLoc);
2263   }
2264
2265   // Base specifiers must be record types.
2266   if (!BaseType->isRecordType()) {
2267     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2268     return nullptr;
2269   }
2270
2271   // C++ [class.union]p1:
2272   //   A union shall not be used as a base class.
2273   if (BaseType->isUnionType()) {
2274     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2275     return nullptr;
2276   }
2277
2278   // For the MS ABI, propagate DLL attributes to base class templates.
2279   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2280     if (Attr *ClassAttr = getDLLAttr(Class)) {
2281       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2282               BaseType->getAsCXXRecordDecl())) {
2283         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2284                                             BaseLoc);
2285       }
2286     }
2287   }
2288
2289   // C++ [class.derived]p2:
2290   //   The class-name in a base-specifier shall not be an incompletely
2291   //   defined class.
2292   if (RequireCompleteType(BaseLoc, BaseType,
2293                           diag::err_incomplete_base_class, SpecifierRange)) {
2294     Class->setInvalidDecl();
2295     return nullptr;
2296   }
2297
2298   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2299   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2300   assert(BaseDecl && "Record type has no declaration");
2301   BaseDecl = BaseDecl->getDefinition();
2302   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2303   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2304   assert(CXXBaseDecl && "Base type is not a C++ type");
2305
2306   // Microsoft docs say:
2307   // "If a base-class has a code_seg attribute, derived classes must have the
2308   // same attribute."
2309   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2310   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2311   if ((DerivedCSA || BaseCSA) &&
2312       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2313     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2314     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2315       << CXXBaseDecl;
2316     return nullptr;
2317   }
2318
2319   // A class which contains a flexible array member is not suitable for use as a
2320   // base class:
2321   //   - If the layout determines that a base comes before another base,
2322   //     the flexible array member would index into the subsequent base.
2323   //   - If the layout determines that base comes before the derived class,
2324   //     the flexible array member would index into the derived class.
2325   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2326     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2327       << CXXBaseDecl->getDeclName();
2328     return nullptr;
2329   }
2330
2331   // C++ [class]p3:
2332   //   If a class is marked final and it appears as a base-type-specifier in
2333   //   base-clause, the program is ill-formed.
2334   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2335     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2336       << CXXBaseDecl->getDeclName()
2337       << FA->isSpelledAsSealed();
2338     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2339         << CXXBaseDecl->getDeclName() << FA->getRange();
2340     return nullptr;
2341   }
2342
2343   if (BaseDecl->isInvalidDecl())
2344     Class->setInvalidDecl();
2345
2346   // Create the base specifier.
2347   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2348                                         Class->getTagKind() == TTK_Class,
2349                                         Access, TInfo, EllipsisLoc);
2350 }
2351
2352 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2353 /// one entry in the base class list of a class specifier, for
2354 /// example:
2355 ///    class foo : public bar, virtual private baz {
2356 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2357 BaseResult
2358 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2359                          ParsedAttributes &Attributes,
2360                          bool Virtual, AccessSpecifier Access,
2361                          ParsedType basetype, SourceLocation BaseLoc,
2362                          SourceLocation EllipsisLoc) {
2363   if (!classdecl)
2364     return true;
2365
2366   AdjustDeclIfTemplate(classdecl);
2367   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2368   if (!Class)
2369     return true;
2370
2371   // We haven't yet attached the base specifiers.
2372   Class->setIsParsingBaseSpecifiers();
2373
2374   // We do not support any C++11 attributes on base-specifiers yet.
2375   // Diagnose any attributes we see.
2376   for (const ParsedAttr &AL : Attributes) {
2377     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2378       continue;
2379     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2380                           ? (unsigned)diag::warn_unknown_attribute_ignored
2381                           : (unsigned)diag::err_base_specifier_attribute)
2382         << AL.getName();
2383   }
2384
2385   TypeSourceInfo *TInfo = nullptr;
2386   GetTypeFromParser(basetype, &TInfo);
2387
2388   if (EllipsisLoc.isInvalid() &&
2389       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2390                                       UPPC_BaseType))
2391     return true;
2392
2393   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2394                                                       Virtual, Access, TInfo,
2395                                                       EllipsisLoc))
2396     return BaseSpec;
2397   else
2398     Class->setInvalidDecl();
2399
2400   return true;
2401 }
2402
2403 /// Use small set to collect indirect bases.  As this is only used
2404 /// locally, there's no need to abstract the small size parameter.
2405 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2406
2407 /// Recursively add the bases of Type.  Don't add Type itself.
2408 static void
2409 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2410                   const QualType &Type)
2411 {
2412   // Even though the incoming type is a base, it might not be
2413   // a class -- it could be a template parm, for instance.
2414   if (auto Rec = Type->getAs<RecordType>()) {
2415     auto Decl = Rec->getAsCXXRecordDecl();
2416
2417     // Iterate over its bases.
2418     for (const auto &BaseSpec : Decl->bases()) {
2419       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2420         .getUnqualifiedType();
2421       if (Set.insert(Base).second)
2422         // If we've not already seen it, recurse.
2423         NoteIndirectBases(Context, Set, Base);
2424     }
2425   }
2426 }
2427
2428 /// Performs the actual work of attaching the given base class
2429 /// specifiers to a C++ class.
2430 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2431                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2432  if (Bases.empty())
2433     return false;
2434
2435   // Used to keep track of which base types we have already seen, so
2436   // that we can properly diagnose redundant direct base types. Note
2437   // that the key is always the unqualified canonical type of the base
2438   // class.
2439   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2440
2441   // Used to track indirect bases so we can see if a direct base is
2442   // ambiguous.
2443   IndirectBaseSet IndirectBaseTypes;
2444
2445   // Copy non-redundant base specifiers into permanent storage.
2446   unsigned NumGoodBases = 0;
2447   bool Invalid = false;
2448   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2449     QualType NewBaseType
2450       = Context.getCanonicalType(Bases[idx]->getType());
2451     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2452
2453     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2454     if (KnownBase) {
2455       // C++ [class.mi]p3:
2456       //   A class shall not be specified as a direct base class of a
2457       //   derived class more than once.
2458       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2459           << KnownBase->getType() << Bases[idx]->getSourceRange();
2460
2461       // Delete the duplicate base class specifier; we're going to
2462       // overwrite its pointer later.
2463       Context.Deallocate(Bases[idx]);
2464
2465       Invalid = true;
2466     } else {
2467       // Okay, add this new base class.
2468       KnownBase = Bases[idx];
2469       Bases[NumGoodBases++] = Bases[idx];
2470
2471       // Note this base's direct & indirect bases, if there could be ambiguity.
2472       if (Bases.size() > 1)
2473         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2474
2475       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2476         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2477         if (Class->isInterface() &&
2478               (!RD->isInterfaceLike() ||
2479                KnownBase->getAccessSpecifier() != AS_public)) {
2480           // The Microsoft extension __interface does not permit bases that
2481           // are not themselves public interfaces.
2482           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2483               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2484               << RD->getSourceRange();
2485           Invalid = true;
2486         }
2487         if (RD->hasAttr<WeakAttr>())
2488           Class->addAttr(WeakAttr::CreateImplicit(Context));
2489       }
2490     }
2491   }
2492
2493   // Attach the remaining base class specifiers to the derived class.
2494   Class->setBases(Bases.data(), NumGoodBases);
2495
2496   // Check that the only base classes that are duplicate are virtual.
2497   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2498     // Check whether this direct base is inaccessible due to ambiguity.
2499     QualType BaseType = Bases[idx]->getType();
2500
2501     // Skip all dependent types in templates being used as base specifiers.
2502     // Checks below assume that the base specifier is a CXXRecord.
2503     if (BaseType->isDependentType())
2504       continue;
2505
2506     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2507       .getUnqualifiedType();
2508
2509     if (IndirectBaseTypes.count(CanonicalBase)) {
2510       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2511                          /*DetectVirtual=*/true);
2512       bool found
2513         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2514       assert(found);
2515       (void)found;
2516
2517       if (Paths.isAmbiguous(CanonicalBase))
2518         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2519             << BaseType << getAmbiguousPathsDisplayString(Paths)
2520             << Bases[idx]->getSourceRange();
2521       else
2522         assert(Bases[idx]->isVirtual());
2523     }
2524
2525     // Delete the base class specifier, since its data has been copied
2526     // into the CXXRecordDecl.
2527     Context.Deallocate(Bases[idx]);
2528   }
2529
2530   return Invalid;
2531 }
2532
2533 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2534 /// class, after checking whether there are any duplicate base
2535 /// classes.
2536 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2537                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2538   if (!ClassDecl || Bases.empty())
2539     return;
2540
2541   AdjustDeclIfTemplate(ClassDecl);
2542   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2543 }
2544
2545 /// Determine whether the type \p Derived is a C++ class that is
2546 /// derived from the type \p Base.
2547 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
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 either the base or the derived type is invalid, don't try to
2560   // check whether one is derived from the other.
2561   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2562     return false;
2563
2564   // FIXME: In a modules build, do we need the entire path to be visible for us
2565   // to be able to use the inheritance relationship?
2566   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2567     return false;
2568
2569   return DerivedRD->isDerivedFrom(BaseRD);
2570 }
2571
2572 /// Determine whether the type \p Derived is a C++ class that is
2573 /// derived from the type \p Base.
2574 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2575                          CXXBasePaths &Paths) {
2576   if (!getLangOpts().CPlusPlus)
2577     return false;
2578
2579   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2580   if (!DerivedRD)
2581     return false;
2582
2583   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2584   if (!BaseRD)
2585     return false;
2586
2587   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2588     return false;
2589
2590   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2591 }
2592
2593 static void BuildBasePathArray(const CXXBasePath &Path,
2594                                CXXCastPath &BasePathArray) {
2595   // We first go backward and check if we have a virtual base.
2596   // FIXME: It would be better if CXXBasePath had the base specifier for
2597   // the nearest virtual base.
2598   unsigned Start = 0;
2599   for (unsigned I = Path.size(); I != 0; --I) {
2600     if (Path[I - 1].Base->isVirtual()) {
2601       Start = I - 1;
2602       break;
2603     }
2604   }
2605
2606   // Now add all bases.
2607   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2608     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2609 }
2610
2611
2612 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2613                               CXXCastPath &BasePathArray) {
2614   assert(BasePathArray.empty() && "Base path array must be empty!");
2615   assert(Paths.isRecordingPaths() && "Must record paths!");
2616   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2617 }
2618 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2619 /// conversion (where Derived and Base are class types) is
2620 /// well-formed, meaning that the conversion is unambiguous (and
2621 /// that all of the base classes are accessible). Returns true
2622 /// and emits a diagnostic if the code is ill-formed, returns false
2623 /// otherwise. Loc is the location where this routine should point to
2624 /// if there is an error, and Range is the source range to highlight
2625 /// if there is an error.
2626 ///
2627 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2628 /// diagnostic for the respective type of error will be suppressed, but the
2629 /// check for ill-formed code will still be performed.
2630 bool
2631 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2632                                    unsigned InaccessibleBaseID,
2633                                    unsigned AmbigiousBaseConvID,
2634                                    SourceLocation Loc, SourceRange Range,
2635                                    DeclarationName Name,
2636                                    CXXCastPath *BasePath,
2637                                    bool IgnoreAccess) {
2638   // First, determine whether the path from Derived to Base is
2639   // ambiguous. This is slightly more expensive than checking whether
2640   // the Derived to Base conversion exists, because here we need to
2641   // explore multiple paths to determine if there is an ambiguity.
2642   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2643                      /*DetectVirtual=*/false);
2644   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2645   if (!DerivationOkay)
2646     return true;
2647
2648   const CXXBasePath *Path = nullptr;
2649   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2650     Path = &Paths.front();
2651
2652   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2653   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2654   // user to access such bases.
2655   if (!Path && getLangOpts().MSVCCompat) {
2656     for (const CXXBasePath &PossiblePath : Paths) {
2657       if (PossiblePath.size() == 1) {
2658         Path = &PossiblePath;
2659         if (AmbigiousBaseConvID)
2660           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2661               << Base << Derived << Range;
2662         break;
2663       }
2664     }
2665   }
2666
2667   if (Path) {
2668     if (!IgnoreAccess) {
2669       // Check that the base class can be accessed.
2670       switch (
2671           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2672       case AR_inaccessible:
2673         return true;
2674       case AR_accessible:
2675       case AR_dependent:
2676       case AR_delayed:
2677         break;
2678       }
2679     }
2680
2681     // Build a base path if necessary.
2682     if (BasePath)
2683       ::BuildBasePathArray(*Path, *BasePath);
2684     return false;
2685   }
2686
2687   if (AmbigiousBaseConvID) {
2688     // We know that the derived-to-base conversion is ambiguous, and
2689     // we're going to produce a diagnostic. Perform the derived-to-base
2690     // search just one more time to compute all of the possible paths so
2691     // that we can print them out. This is more expensive than any of
2692     // the previous derived-to-base checks we've done, but at this point
2693     // performance isn't as much of an issue.
2694     Paths.clear();
2695     Paths.setRecordingPaths(true);
2696     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2697     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2698     (void)StillOkay;
2699
2700     // Build up a textual representation of the ambiguous paths, e.g.,
2701     // D -> B -> A, that will be used to illustrate the ambiguous
2702     // conversions in the diagnostic. We only print one of the paths
2703     // to each base class subobject.
2704     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2705
2706     Diag(Loc, AmbigiousBaseConvID)
2707     << Derived << Base << PathDisplayStr << Range << Name;
2708   }
2709   return true;
2710 }
2711
2712 bool
2713 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2714                                    SourceLocation Loc, SourceRange Range,
2715                                    CXXCastPath *BasePath,
2716                                    bool IgnoreAccess) {
2717   return CheckDerivedToBaseConversion(
2718       Derived, Base, diag::err_upcast_to_inaccessible_base,
2719       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2720       BasePath, IgnoreAccess);
2721 }
2722
2723
2724 /// Builds a string representing ambiguous paths from a
2725 /// specific derived class to different subobjects of the same base
2726 /// class.
2727 ///
2728 /// This function builds a string that can be used in error messages
2729 /// to show the different paths that one can take through the
2730 /// inheritance hierarchy to go from the derived class to different
2731 /// subobjects of a base class. The result looks something like this:
2732 /// @code
2733 /// struct D -> struct B -> struct A
2734 /// struct D -> struct C -> struct A
2735 /// @endcode
2736 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2737   std::string PathDisplayStr;
2738   std::set<unsigned> DisplayedPaths;
2739   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2740        Path != Paths.end(); ++Path) {
2741     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2742       // We haven't displayed a path to this particular base
2743       // class subobject yet.
2744       PathDisplayStr += "\n    ";
2745       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2746       for (CXXBasePath::const_iterator Element = Path->begin();
2747            Element != Path->end(); ++Element)
2748         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2749     }
2750   }
2751
2752   return PathDisplayStr;
2753 }
2754
2755 //===----------------------------------------------------------------------===//
2756 // C++ class member Handling
2757 //===----------------------------------------------------------------------===//
2758
2759 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2760 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2761                                 SourceLocation ColonLoc,
2762                                 const ParsedAttributesView &Attrs) {
2763   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2764   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2765                                                   ASLoc, ColonLoc);
2766   CurContext->addHiddenDecl(ASDecl);
2767   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2768 }
2769
2770 /// CheckOverrideControl - Check C++11 override control semantics.
2771 void Sema::CheckOverrideControl(NamedDecl *D) {
2772   if (D->isInvalidDecl())
2773     return;
2774
2775   // We only care about "override" and "final" declarations.
2776   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2777     return;
2778
2779   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2780
2781   // We can't check dependent instance methods.
2782   if (MD && MD->isInstance() &&
2783       (MD->getParent()->hasAnyDependentBases() ||
2784        MD->getType()->isDependentType()))
2785     return;
2786
2787   if (MD && !MD->isVirtual()) {
2788     // If we have a non-virtual method, check if if hides a virtual method.
2789     // (In that case, it's most likely the method has the wrong type.)
2790     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2791     FindHiddenVirtualMethods(MD, OverloadedMethods);
2792
2793     if (!OverloadedMethods.empty()) {
2794       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2795         Diag(OA->getLocation(),
2796              diag::override_keyword_hides_virtual_member_function)
2797           << "override" << (OverloadedMethods.size() > 1);
2798       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2799         Diag(FA->getLocation(),
2800              diag::override_keyword_hides_virtual_member_function)
2801           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2802           << (OverloadedMethods.size() > 1);
2803       }
2804       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2805       MD->setInvalidDecl();
2806       return;
2807     }
2808     // Fall through into the general case diagnostic.
2809     // FIXME: We might want to attempt typo correction here.
2810   }
2811
2812   if (!MD || !MD->isVirtual()) {
2813     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2814       Diag(OA->getLocation(),
2815            diag::override_keyword_only_allowed_on_virtual_member_functions)
2816         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2817       D->dropAttr<OverrideAttr>();
2818     }
2819     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2820       Diag(FA->getLocation(),
2821            diag::override_keyword_only_allowed_on_virtual_member_functions)
2822         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2823         << FixItHint::CreateRemoval(FA->getLocation());
2824       D->dropAttr<FinalAttr>();
2825     }
2826     return;
2827   }
2828
2829   // C++11 [class.virtual]p5:
2830   //   If a function is marked with the virt-specifier override and
2831   //   does not override a member function of a base class, the program is
2832   //   ill-formed.
2833   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2834   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2835     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2836       << MD->getDeclName();
2837 }
2838
2839 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2840   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2841     return;
2842   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2843   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2844     return;
2845
2846   SourceLocation Loc = MD->getLocation();
2847   SourceLocation SpellingLoc = Loc;
2848   if (getSourceManager().isMacroArgExpansion(Loc))
2849     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2850   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2851   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2852       return;
2853
2854   if (MD->size_overridden_methods() > 0) {
2855     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2856                           ? diag::warn_destructor_marked_not_override_overriding
2857                           : diag::warn_function_marked_not_override_overriding;
2858     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2859     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2860     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2861   }
2862 }
2863
2864 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2865 /// function overrides a virtual member function marked 'final', according to
2866 /// C++11 [class.virtual]p4.
2867 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2868                                                   const CXXMethodDecl *Old) {
2869   FinalAttr *FA = Old->getAttr<FinalAttr>();
2870   if (!FA)
2871     return false;
2872
2873   Diag(New->getLocation(), diag::err_final_function_overridden)
2874     << New->getDeclName()
2875     << FA->isSpelledAsSealed();
2876   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2877   return true;
2878 }
2879
2880 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2881   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2882   // FIXME: Destruction of ObjC lifetime types has side-effects.
2883   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2884     return !RD->isCompleteDefinition() ||
2885            !RD->hasTrivialDefaultConstructor() ||
2886            !RD->hasTrivialDestructor();
2887   return false;
2888 }
2889
2890 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
2891   ParsedAttributesView::const_iterator Itr =
2892       llvm::find_if(list, [](const ParsedAttr &AL) {
2893         return AL.isDeclspecPropertyAttribute();
2894       });
2895   if (Itr != list.end())
2896     return &*Itr;
2897   return nullptr;
2898 }
2899
2900 // Check if there is a field shadowing.
2901 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2902                                       DeclarationName FieldName,
2903                                       const CXXRecordDecl *RD,
2904                                       bool DeclIsField) {
2905   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2906     return;
2907
2908   // To record a shadowed field in a base
2909   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2910   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2911                            CXXBasePath &Path) {
2912     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2913     // Record an ambiguous path directly
2914     if (Bases.find(Base) != Bases.end())
2915       return true;
2916     for (const auto Field : Base->lookup(FieldName)) {
2917       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2918           Field->getAccess() != AS_private) {
2919         assert(Field->getAccess() != AS_none);
2920         assert(Bases.find(Base) == Bases.end());
2921         Bases[Base] = Field;
2922         return true;
2923       }
2924     }
2925     return false;
2926   };
2927
2928   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2929                      /*DetectVirtual=*/true);
2930   if (!RD->lookupInBases(FieldShadowed, Paths))
2931     return;
2932
2933   for (const auto &P : Paths) {
2934     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2935     auto It = Bases.find(Base);
2936     // Skip duplicated bases
2937     if (It == Bases.end())
2938       continue;
2939     auto BaseField = It->second;
2940     assert(BaseField->getAccess() != AS_private);
2941     if (AS_none !=
2942         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2943       Diag(Loc, diag::warn_shadow_field)
2944         << FieldName << RD << Base << DeclIsField;
2945       Diag(BaseField->getLocation(), diag::note_shadow_field);
2946       Bases.erase(It);
2947     }
2948   }
2949 }
2950
2951 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2952 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2953 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2954 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2955 /// present (but parsing it has been deferred).
2956 NamedDecl *
2957 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2958                                MultiTemplateParamsArg TemplateParameterLists,
2959                                Expr *BW, const VirtSpecifiers &VS,
2960                                InClassInitStyle InitStyle) {
2961   const DeclSpec &DS = D.getDeclSpec();
2962   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2963   DeclarationName Name = NameInfo.getName();
2964   SourceLocation Loc = NameInfo.getLoc();
2965
2966   // For anonymous bitfields, the location should point to the type.
2967   if (Loc.isInvalid())
2968     Loc = D.getBeginLoc();
2969
2970   Expr *BitWidth = static_cast<Expr*>(BW);
2971
2972   assert(isa<CXXRecordDecl>(CurContext));
2973   assert(!DS.isFriendSpecified());
2974
2975   bool isFunc = D.isDeclarationOfFunction();
2976   const ParsedAttr *MSPropertyAttr =
2977       getMSPropertyAttr(D.getDeclSpec().getAttributes());
2978
2979   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2980     // The Microsoft extension __interface only permits public member functions
2981     // and prohibits constructors, destructors, operators, non-public member
2982     // functions, static methods and data members.
2983     unsigned InvalidDecl;
2984     bool ShowDeclName = true;
2985     if (!isFunc &&
2986         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2987       InvalidDecl = 0;
2988     else if (!isFunc)
2989       InvalidDecl = 1;
2990     else if (AS != AS_public)
2991       InvalidDecl = 2;
2992     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2993       InvalidDecl = 3;
2994     else switch (Name.getNameKind()) {
2995       case DeclarationName::CXXConstructorName:
2996         InvalidDecl = 4;
2997         ShowDeclName = false;
2998         break;
2999
3000       case DeclarationName::CXXDestructorName:
3001         InvalidDecl = 5;
3002         ShowDeclName = false;
3003         break;
3004
3005       case DeclarationName::CXXOperatorName:
3006       case DeclarationName::CXXConversionFunctionName:
3007         InvalidDecl = 6;
3008         break;
3009
3010       default:
3011         InvalidDecl = 0;
3012         break;
3013     }
3014
3015     if (InvalidDecl) {
3016       if (ShowDeclName)
3017         Diag(Loc, diag::err_invalid_member_in_interface)
3018           << (InvalidDecl-1) << Name;
3019       else
3020         Diag(Loc, diag::err_invalid_member_in_interface)
3021           << (InvalidDecl-1) << "";
3022       return nullptr;
3023     }
3024   }
3025
3026   // C++ 9.2p6: A member shall not be declared to have automatic storage
3027   // duration (auto, register) or with the extern storage-class-specifier.
3028   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3029   // data members and cannot be applied to names declared const or static,
3030   // and cannot be applied to reference members.
3031   switch (DS.getStorageClassSpec()) {
3032   case DeclSpec::SCS_unspecified:
3033   case DeclSpec::SCS_typedef:
3034   case DeclSpec::SCS_static:
3035     break;
3036   case DeclSpec::SCS_mutable:
3037     if (isFunc) {
3038       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3039
3040       // FIXME: It would be nicer if the keyword was ignored only for this
3041       // declarator. Otherwise we could get follow-up errors.
3042       D.getMutableDeclSpec().ClearStorageClassSpecs();
3043     }
3044     break;
3045   default:
3046     Diag(DS.getStorageClassSpecLoc(),
3047          diag::err_storageclass_invalid_for_member);
3048     D.getMutableDeclSpec().ClearStorageClassSpecs();
3049     break;
3050   }
3051
3052   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3053                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3054                       !isFunc);
3055
3056   if (DS.hasConstexprSpecifier() && isInstField) {
3057     SemaDiagnosticBuilder B =
3058         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3059     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3060     if (InitStyle == ICIS_NoInit) {
3061       B << 0 << 0;
3062       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3063         B << FixItHint::CreateRemoval(ConstexprLoc);
3064       else {
3065         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3066         D.getMutableDeclSpec().ClearConstexprSpec();
3067         const char *PrevSpec;
3068         unsigned DiagID;
3069         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3070             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3071         (void)Failed;
3072         assert(!Failed && "Making a constexpr member const shouldn't fail");
3073       }
3074     } else {
3075       B << 1;
3076       const char *PrevSpec;
3077       unsigned DiagID;
3078       if (D.getMutableDeclSpec().SetStorageClassSpec(
3079           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3080           Context.getPrintingPolicy())) {
3081         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3082                "This is the only DeclSpec that should fail to be applied");
3083         B << 1;
3084       } else {
3085         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3086         isInstField = false;
3087       }
3088     }
3089   }
3090
3091   NamedDecl *Member;
3092   if (isInstField) {
3093     CXXScopeSpec &SS = D.getCXXScopeSpec();
3094
3095     // Data members must have identifiers for names.
3096     if (!Name.isIdentifier()) {
3097       Diag(Loc, diag::err_bad_variable_name)
3098         << Name;
3099       return nullptr;
3100     }
3101
3102     IdentifierInfo *II = Name.getAsIdentifierInfo();
3103
3104     // Member field could not be with "template" keyword.
3105     // So TemplateParameterLists should be empty in this case.
3106     if (TemplateParameterLists.size()) {
3107       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3108       if (TemplateParams->size()) {
3109         // There is no such thing as a member field template.
3110         Diag(D.getIdentifierLoc(), diag::err_template_member)
3111             << II
3112             << SourceRange(TemplateParams->getTemplateLoc(),
3113                 TemplateParams->getRAngleLoc());
3114       } else {
3115         // There is an extraneous 'template<>' for this member.
3116         Diag(TemplateParams->getTemplateLoc(),
3117             diag::err_template_member_noparams)
3118             << II
3119             << SourceRange(TemplateParams->getTemplateLoc(),
3120                 TemplateParams->getRAngleLoc());
3121       }
3122       return nullptr;
3123     }
3124
3125     if (SS.isSet() && !SS.isInvalid()) {
3126       // The user provided a superfluous scope specifier inside a class
3127       // definition:
3128       //
3129       // class X {
3130       //   int X::member;
3131       // };
3132       if (DeclContext *DC = computeDeclContext(SS, false))
3133         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3134                                      D.getName().getKind() ==
3135                                          UnqualifiedIdKind::IK_TemplateId);
3136       else
3137         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3138           << Name << SS.getRange();
3139
3140       SS.clear();
3141     }
3142
3143     if (MSPropertyAttr) {
3144       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3145                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3146       if (!Member)
3147         return nullptr;
3148       isInstField = false;
3149     } else {
3150       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3151                                 BitWidth, InitStyle, AS);
3152       if (!Member)
3153         return nullptr;
3154     }
3155
3156     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3157   } else {
3158     Member = HandleDeclarator(S, D, TemplateParameterLists);
3159     if (!Member)
3160       return nullptr;
3161
3162     // Non-instance-fields can't have a bitfield.
3163     if (BitWidth) {
3164       if (Member->isInvalidDecl()) {
3165         // don't emit another diagnostic.
3166       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3167         // C++ 9.6p3: A bit-field shall not be a static member.
3168         // "static member 'A' cannot be a bit-field"
3169         Diag(Loc, diag::err_static_not_bitfield)
3170           << Name << BitWidth->getSourceRange();
3171       } else if (isa<TypedefDecl>(Member)) {
3172         // "typedef member 'x' cannot be a bit-field"
3173         Diag(Loc, diag::err_typedef_not_bitfield)
3174           << Name << BitWidth->getSourceRange();
3175       } else {
3176         // A function typedef ("typedef int f(); f a;").
3177         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3178         Diag(Loc, diag::err_not_integral_type_bitfield)
3179           << Name << cast<ValueDecl>(Member)->getType()
3180           << BitWidth->getSourceRange();
3181       }
3182
3183       BitWidth = nullptr;
3184       Member->setInvalidDecl();
3185     }
3186
3187     NamedDecl *NonTemplateMember = Member;
3188     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3189       NonTemplateMember = FunTmpl->getTemplatedDecl();
3190     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3191       NonTemplateMember = VarTmpl->getTemplatedDecl();
3192
3193     Member->setAccess(AS);
3194
3195     // If we have declared a member function template or static data member
3196     // template, set the access of the templated declaration as well.
3197     if (NonTemplateMember != Member)
3198       NonTemplateMember->setAccess(AS);
3199
3200     // C++ [temp.deduct.guide]p3:
3201     //   A deduction guide [...] for a member class template [shall be
3202     //   declared] with the same access [as the template].
3203     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3204       auto *TD = DG->getDeducedTemplate();
3205       // Access specifiers are only meaningful if both the template and the
3206       // deduction guide are from the same scope.
3207       if (AS != TD->getAccess() &&
3208           TD->getDeclContext()->getRedeclContext()->Equals(
3209               DG->getDeclContext()->getRedeclContext())) {
3210         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3211         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3212             << TD->getAccess();
3213         const AccessSpecDecl *LastAccessSpec = nullptr;
3214         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3215           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3216             LastAccessSpec = AccessSpec;
3217         }
3218         assert(LastAccessSpec && "differing access with no access specifier");
3219         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3220             << AS;
3221       }
3222     }
3223   }
3224
3225   if (VS.isOverrideSpecified())
3226     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3227   if (VS.isFinalSpecified())
3228     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3229                                             VS.isFinalSpelledSealed()));
3230
3231   if (VS.getLastLocation().isValid()) {
3232     // Update the end location of a method that has a virt-specifiers.
3233     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3234       MD->setRangeEnd(VS.getLastLocation());
3235   }
3236
3237   CheckOverrideControl(Member);
3238
3239   assert((Name || isInstField) && "No identifier for non-field ?");
3240
3241   if (isInstField) {
3242     FieldDecl *FD = cast<FieldDecl>(Member);
3243     FieldCollector->Add(FD);
3244
3245     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3246       // Remember all explicit private FieldDecls that have a name, no side
3247       // effects and are not part of a dependent type declaration.
3248       if (!FD->isImplicit() && FD->getDeclName() &&
3249           FD->getAccess() == AS_private &&
3250           !FD->hasAttr<UnusedAttr>() &&
3251           !FD->getParent()->isDependentContext() &&
3252           !InitializationHasSideEffects(*FD))
3253         UnusedPrivateFields.insert(FD);
3254     }
3255   }
3256
3257   return Member;
3258 }
3259
3260 namespace {
3261   class UninitializedFieldVisitor
3262       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3263     Sema &S;
3264     // List of Decls to generate a warning on.  Also remove Decls that become
3265     // initialized.
3266     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3267     // List of base classes of the record.  Classes are removed after their
3268     // initializers.
3269     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3270     // Vector of decls to be removed from the Decl set prior to visiting the
3271     // nodes.  These Decls may have been initialized in the prior initializer.
3272     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3273     // If non-null, add a note to the warning pointing back to the constructor.
3274     const CXXConstructorDecl *Constructor;
3275     // Variables to hold state when processing an initializer list.  When
3276     // InitList is true, special case initialization of FieldDecls matching
3277     // InitListFieldDecl.
3278     bool InitList;
3279     FieldDecl *InitListFieldDecl;
3280     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3281
3282   public:
3283     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3284     UninitializedFieldVisitor(Sema &S,
3285                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3286                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3287       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3288         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3289
3290     // Returns true if the use of ME is not an uninitialized use.
3291     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3292                                          bool CheckReferenceOnly) {
3293       llvm::SmallVector<FieldDecl*, 4> Fields;
3294       bool ReferenceField = false;
3295       while (ME) {
3296         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3297         if (!FD)
3298           return false;
3299         Fields.push_back(FD);
3300         if (FD->getType()->isReferenceType())
3301           ReferenceField = true;
3302         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3303       }
3304
3305       // Binding a reference to an uninitialized field is not an
3306       // uninitialized use.
3307       if (CheckReferenceOnly && !ReferenceField)
3308         return true;
3309
3310       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3311       // Discard the first field since it is the field decl that is being
3312       // initialized.
3313       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3314         UsedFieldIndex.push_back((*I)->getFieldIndex());
3315       }
3316
3317       for (auto UsedIter = UsedFieldIndex.begin(),
3318                 UsedEnd = UsedFieldIndex.end(),
3319                 OrigIter = InitFieldIndex.begin(),
3320                 OrigEnd = InitFieldIndex.end();
3321            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3322         if (*UsedIter < *OrigIter)
3323           return true;
3324         if (*UsedIter > *OrigIter)
3325           break;
3326       }
3327
3328       return false;
3329     }
3330
3331     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3332                           bool AddressOf) {
3333       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3334         return;
3335
3336       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3337       // or union.
3338       MemberExpr *FieldME = ME;
3339
3340       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3341
3342       Expr *Base = ME;
3343       while (MemberExpr *SubME =
3344                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3345
3346         if (isa<VarDecl>(SubME->getMemberDecl()))
3347           return;
3348
3349         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3350           if (!FD->isAnonymousStructOrUnion())
3351             FieldME = SubME;
3352
3353         if (!FieldME->getType().isPODType(S.Context))
3354           AllPODFields = false;
3355
3356         Base = SubME->getBase();
3357       }
3358
3359       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3360         return;
3361
3362       if (AddressOf && AllPODFields)
3363         return;
3364
3365       ValueDecl* FoundVD = FieldME->getMemberDecl();
3366
3367       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3368         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3369           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3370         }
3371
3372         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3373           QualType T = BaseCast->getType();
3374           if (T->isPointerType() &&
3375               BaseClasses.count(T->getPointeeType())) {
3376             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3377                 << T->getPointeeType() << FoundVD;
3378           }
3379         }
3380       }
3381
3382       if (!Decls.count(FoundVD))
3383         return;
3384
3385       const bool IsReference = FoundVD->getType()->isReferenceType();
3386
3387       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3388         // Special checking for initializer lists.
3389         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3390           return;
3391         }
3392       } else {
3393         // Prevent double warnings on use of unbounded references.
3394         if (CheckReferenceOnly && !IsReference)
3395           return;
3396       }
3397
3398       unsigned diag = IsReference
3399           ? diag::warn_reference_field_is_uninit
3400           : diag::warn_field_is_uninit;
3401       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3402       if (Constructor)
3403         S.Diag(Constructor->getLocation(),
3404                diag::note_uninit_in_this_constructor)
3405           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3406
3407     }
3408
3409     void HandleValue(Expr *E, bool AddressOf) {
3410       E = E->IgnoreParens();
3411
3412       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3413         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3414                          AddressOf /*AddressOf*/);
3415         return;
3416       }
3417
3418       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3419         Visit(CO->getCond());
3420         HandleValue(CO->getTrueExpr(), AddressOf);
3421         HandleValue(CO->getFalseExpr(), AddressOf);
3422         return;
3423       }
3424
3425       if (BinaryConditionalOperator *BCO =
3426               dyn_cast<BinaryConditionalOperator>(E)) {
3427         Visit(BCO->getCond());
3428         HandleValue(BCO->getFalseExpr(), AddressOf);
3429         return;
3430       }
3431
3432       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3433         HandleValue(OVE->getSourceExpr(), AddressOf);
3434         return;
3435       }
3436
3437       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3438         switch (BO->getOpcode()) {
3439         default:
3440           break;
3441         case(BO_PtrMemD):
3442         case(BO_PtrMemI):
3443           HandleValue(BO->getLHS(), AddressOf);
3444           Visit(BO->getRHS());
3445           return;
3446         case(BO_Comma):
3447           Visit(BO->getLHS());
3448           HandleValue(BO->getRHS(), AddressOf);
3449           return;
3450         }
3451       }
3452
3453       Visit(E);
3454     }
3455
3456     void CheckInitListExpr(InitListExpr *ILE) {
3457       InitFieldIndex.push_back(0);
3458       for (auto Child : ILE->children()) {
3459         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3460           CheckInitListExpr(SubList);
3461         } else {
3462           Visit(Child);
3463         }
3464         ++InitFieldIndex.back();
3465       }
3466       InitFieldIndex.pop_back();
3467     }
3468
3469     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3470                           FieldDecl *Field, const Type *BaseClass) {
3471       // Remove Decls that may have been initialized in the previous
3472       // initializer.
3473       for (ValueDecl* VD : DeclsToRemove)
3474         Decls.erase(VD);
3475       DeclsToRemove.clear();
3476
3477       Constructor = FieldConstructor;
3478       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3479
3480       if (ILE && Field) {
3481         InitList = true;
3482         InitListFieldDecl = Field;
3483         InitFieldIndex.clear();
3484         CheckInitListExpr(ILE);
3485       } else {
3486         InitList = false;
3487         Visit(E);
3488       }
3489
3490       if (Field)
3491         Decls.erase(Field);
3492       if (BaseClass)
3493         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3494     }
3495
3496     void VisitMemberExpr(MemberExpr *ME) {
3497       // All uses of unbounded reference fields will warn.
3498       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3499     }
3500
3501     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3502       if (E->getCastKind() == CK_LValueToRValue) {
3503         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3504         return;
3505       }
3506
3507       Inherited::VisitImplicitCastExpr(E);
3508     }
3509
3510     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3511       if (E->getConstructor()->isCopyConstructor()) {
3512         Expr *ArgExpr = E->getArg(0);
3513         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3514           if (ILE->getNumInits() == 1)
3515             ArgExpr = ILE->getInit(0);
3516         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3517           if (ICE->getCastKind() == CK_NoOp)
3518             ArgExpr = ICE->getSubExpr();
3519         HandleValue(ArgExpr, false /*AddressOf*/);
3520         return;
3521       }
3522       Inherited::VisitCXXConstructExpr(E);
3523     }
3524
3525     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3526       Expr *Callee = E->getCallee();
3527       if (isa<MemberExpr>(Callee)) {
3528         HandleValue(Callee, false /*AddressOf*/);
3529         for (auto Arg : E->arguments())
3530           Visit(Arg);
3531         return;
3532       }
3533
3534       Inherited::VisitCXXMemberCallExpr(E);
3535     }
3536
3537     void VisitCallExpr(CallExpr *E) {
3538       // Treat std::move as a use.
3539       if (E->isCallToStdMove()) {
3540         HandleValue(E->getArg(0), /*AddressOf=*/false);
3541         return;
3542       }
3543
3544       Inherited::VisitCallExpr(E);
3545     }
3546
3547     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3548       Expr *Callee = E->getCallee();
3549
3550       if (isa<UnresolvedLookupExpr>(Callee))
3551         return Inherited::VisitCXXOperatorCallExpr(E);
3552
3553       Visit(Callee);
3554       for (auto Arg : E->arguments())
3555         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3556     }
3557
3558     void VisitBinaryOperator(BinaryOperator *E) {
3559       // If a field assignment is detected, remove the field from the
3560       // uninitiailized field set.
3561       if (E->getOpcode() == BO_Assign)
3562         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3563           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3564             if (!FD->getType()->isReferenceType())
3565               DeclsToRemove.push_back(FD);
3566
3567       if (E->isCompoundAssignmentOp()) {
3568         HandleValue(E->getLHS(), false /*AddressOf*/);
3569         Visit(E->getRHS());
3570         return;
3571       }
3572
3573       Inherited::VisitBinaryOperator(E);
3574     }
3575
3576     void VisitUnaryOperator(UnaryOperator *E) {
3577       if (E->isIncrementDecrementOp()) {
3578         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3579         return;
3580       }
3581       if (E->getOpcode() == UO_AddrOf) {
3582         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3583           HandleValue(ME->getBase(), true /*AddressOf*/);
3584           return;
3585         }
3586       }
3587
3588       Inherited::VisitUnaryOperator(E);
3589     }
3590   };
3591
3592   // Diagnose value-uses of fields to initialize themselves, e.g.
3593   //   foo(foo)
3594   // where foo is not also a parameter to the constructor.
3595   // Also diagnose across field uninitialized use such as
3596   //   x(y), y(x)
3597   // TODO: implement -Wuninitialized and fold this into that framework.
3598   static void DiagnoseUninitializedFields(
3599       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3600
3601     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3602                                            Constructor->getLocation())) {
3603       return;
3604     }
3605
3606     if (Constructor->isInvalidDecl())
3607       return;
3608
3609     const CXXRecordDecl *RD = Constructor->getParent();
3610
3611     if (RD->getDescribedClassTemplate())
3612       return;
3613
3614     // Holds fields that are uninitialized.
3615     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3616
3617     // At the beginning, all fields are uninitialized.
3618     for (auto *I : RD->decls()) {
3619       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3620         UninitializedFields.insert(FD);
3621       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3622         UninitializedFields.insert(IFD->getAnonField());
3623       }
3624     }
3625
3626     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3627     for (auto I : RD->bases())
3628       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3629
3630     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3631       return;
3632
3633     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3634                                                    UninitializedFields,
3635                                                    UninitializedBaseClasses);
3636
3637     for (const auto *FieldInit : Constructor->inits()) {
3638       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3639         break;
3640
3641       Expr *InitExpr = FieldInit->getInit();
3642       if (!InitExpr)
3643         continue;
3644
3645       if (CXXDefaultInitExpr *Default =
3646               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3647         InitExpr = Default->getExpr();
3648         if (!InitExpr)
3649           continue;
3650         // In class initializers will point to the constructor.
3651         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3652                                               FieldInit->getAnyMember(),
3653                                               FieldInit->getBaseClass());
3654       } else {
3655         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3656                                               FieldInit->getAnyMember(),
3657                                               FieldInit->getBaseClass());
3658       }
3659     }
3660   }
3661 } // namespace
3662
3663 /// Enter a new C++ default initializer scope. After calling this, the
3664 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3665 /// parsing or instantiating the initializer failed.
3666 void Sema::ActOnStartCXXInClassMemberInitializer() {
3667   // Create a synthetic function scope to represent the call to the constructor
3668   // that notionally surrounds a use of this initializer.
3669   PushFunctionScope();
3670 }
3671
3672 /// This is invoked after parsing an in-class initializer for a
3673 /// non-static C++ class member, and after instantiating an in-class initializer
3674 /// in a class template. Such actions are deferred until the class is complete.
3675 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3676                                                   SourceLocation InitLoc,
3677                                                   Expr *InitExpr) {
3678   // Pop the notional constructor scope we created earlier.
3679   PopFunctionScopeInfo(nullptr, D);
3680
3681   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3682   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3683          "must set init style when field is created");
3684
3685   if (!InitExpr) {
3686     D->setInvalidDecl();
3687     if (FD)
3688       FD->removeInClassInitializer();
3689     return;
3690   }
3691
3692   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3693     FD->setInvalidDecl();
3694     FD->removeInClassInitializer();
3695     return;
3696   }
3697
3698   ExprResult Init = InitExpr;
3699   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3700     InitializedEntity Entity =
3701         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3702     InitializationKind Kind =
3703         FD->getInClassInitStyle() == ICIS_ListInit
3704             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3705                                                    InitExpr->getBeginLoc(),
3706                                                    InitExpr->getEndLoc())
3707             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3708     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3709     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3710     if (Init.isInvalid()) {
3711       FD->setInvalidDecl();
3712       return;
3713     }
3714   }
3715
3716   // C++11 [class.base.init]p7:
3717   //   The initialization of each base and member constitutes a
3718   //   full-expression.
3719   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3720   if (Init.isInvalid()) {
3721     FD->setInvalidDecl();
3722     return;
3723   }
3724
3725   InitExpr = Init.get();
3726
3727   FD->setInClassInitializer(InitExpr);
3728 }
3729
3730 /// Find the direct and/or virtual base specifiers that
3731 /// correspond to the given base type, for use in base initialization
3732 /// within a constructor.
3733 static bool FindBaseInitializer(Sema &SemaRef,
3734                                 CXXRecordDecl *ClassDecl,
3735                                 QualType BaseType,
3736                                 const CXXBaseSpecifier *&DirectBaseSpec,
3737                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3738   // First, check for a direct base class.
3739   DirectBaseSpec = nullptr;
3740   for (const auto &Base : ClassDecl->bases()) {
3741     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3742       // We found a direct base of this type. That's what we're
3743       // initializing.
3744       DirectBaseSpec = &Base;
3745       break;
3746     }
3747   }
3748
3749   // Check for a virtual base class.
3750   // FIXME: We might be able to short-circuit this if we know in advance that
3751   // there are no virtual bases.
3752   VirtualBaseSpec = nullptr;
3753   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3754     // We haven't found a base yet; search the class hierarchy for a
3755     // virtual base class.
3756     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3757                        /*DetectVirtual=*/false);
3758     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3759                               SemaRef.Context.getTypeDeclType(ClassDecl),
3760                               BaseType, Paths)) {
3761       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3762            Path != Paths.end(); ++Path) {
3763         if (Path->back().Base->isVirtual()) {
3764           VirtualBaseSpec = Path->back().Base;
3765           break;
3766         }
3767       }
3768     }
3769   }
3770
3771   return DirectBaseSpec || VirtualBaseSpec;
3772 }
3773
3774 /// Handle a C++ member initializer using braced-init-list syntax.
3775 MemInitResult
3776 Sema::ActOnMemInitializer(Decl *ConstructorD,
3777                           Scope *S,
3778                           CXXScopeSpec &SS,
3779                           IdentifierInfo *MemberOrBase,
3780                           ParsedType TemplateTypeTy,
3781                           const DeclSpec &DS,
3782                           SourceLocation IdLoc,
3783                           Expr *InitList,
3784                           SourceLocation EllipsisLoc) {
3785   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3786                              DS, IdLoc, InitList,
3787                              EllipsisLoc);
3788 }
3789
3790 /// Handle a C++ member initializer using parentheses syntax.
3791 MemInitResult
3792 Sema::ActOnMemInitializer(Decl *ConstructorD,
3793                           Scope *S,
3794                           CXXScopeSpec &SS,
3795                           IdentifierInfo *MemberOrBase,
3796                           ParsedType TemplateTypeTy,
3797                           const DeclSpec &DS,
3798                           SourceLocation IdLoc,
3799                           SourceLocation LParenLoc,
3800                           ArrayRef<Expr *> Args,
3801                           SourceLocation RParenLoc,
3802                           SourceLocation EllipsisLoc) {
3803   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3804   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3805                              DS, IdLoc, List, EllipsisLoc);
3806 }
3807
3808 namespace {
3809
3810 // Callback to only accept typo corrections that can be a valid C++ member
3811 // intializer: either a non-static field member or a base class.
3812 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
3813 public:
3814   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3815       : ClassDecl(ClassDecl) {}
3816
3817   bool ValidateCandidate(const TypoCorrection &candidate) override {
3818     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3819       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3820         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3821       return isa<TypeDecl>(ND);
3822     }
3823     return false;
3824   }
3825
3826   std::unique_ptr<CorrectionCandidateCallback> clone() override {
3827     return llvm::make_unique<MemInitializerValidatorCCC>(*this);
3828   }
3829
3830 private:
3831   CXXRecordDecl *ClassDecl;
3832 };
3833
3834 }
3835
3836 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3837                                              CXXScopeSpec &SS,
3838                                              ParsedType TemplateTypeTy,
3839                                              IdentifierInfo *MemberOrBase) {
3840   if (SS.getScopeRep() || TemplateTypeTy)
3841     return nullptr;
3842   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3843   if (Result.empty())
3844     return nullptr;
3845   ValueDecl *Member;
3846   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3847       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3848     return Member;
3849   return nullptr;
3850 }
3851
3852 /// Handle a C++ member initializer.
3853 MemInitResult
3854 Sema::BuildMemInitializer(Decl *ConstructorD,
3855                           Scope *S,
3856                           CXXScopeSpec &SS,
3857                           IdentifierInfo *MemberOrBase,
3858                           ParsedType TemplateTypeTy,
3859                           const DeclSpec &DS,
3860                           SourceLocation IdLoc,
3861                           Expr *Init,
3862                           SourceLocation EllipsisLoc) {
3863   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3864   if (!Res.isUsable())
3865     return true;
3866   Init = Res.get();
3867
3868   if (!ConstructorD)
3869     return true;
3870
3871   AdjustDeclIfTemplate(ConstructorD);
3872
3873   CXXConstructorDecl *Constructor
3874     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3875   if (!Constructor) {
3876     // The user wrote a constructor initializer on a function that is
3877     // not a C++ constructor. Ignore the error for now, because we may
3878     // have more member initializers coming; we'll diagnose it just
3879     // once in ActOnMemInitializers.
3880     return true;
3881   }
3882
3883   CXXRecordDecl *ClassDecl = Constructor->getParent();
3884
3885   // C++ [class.base.init]p2:
3886   //   Names in a mem-initializer-id are looked up in the scope of the
3887   //   constructor's class and, if not found in that scope, are looked
3888   //   up in the scope containing the constructor's definition.
3889   //   [Note: if the constructor's class contains a member with the
3890   //   same name as a direct or virtual base class of the class, a
3891   //   mem-initializer-id naming the member or base class and composed
3892   //   of a single identifier refers to the class member. A
3893   //   mem-initializer-id for the hidden base class may be specified
3894   //   using a qualified name. ]
3895
3896   // Look for a member, first.
3897   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
3898           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
3899     if (EllipsisLoc.isValid())
3900       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3901           << MemberOrBase
3902           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3903
3904     return BuildMemberInitializer(Member, Init, IdLoc);
3905   }
3906   // It didn't name a member, so see if it names a class.
3907   QualType BaseType;
3908   TypeSourceInfo *TInfo = nullptr;
3909
3910   if (TemplateTypeTy) {
3911     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3912     if (BaseType.isNull())
3913       return true;
3914   } else if (DS.getTypeSpecType() == TST_decltype) {
3915     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3916   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3917     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3918     return true;
3919   } else {
3920     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3921     LookupParsedName(R, S, &SS);
3922
3923     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3924     if (!TyD) {
3925       if (R.isAmbiguous()) return true;
3926
3927       // We don't want access-control diagnostics here.
3928       R.suppressDiagnostics();
3929
3930       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3931         bool NotUnknownSpecialization = false;
3932         DeclContext *DC = computeDeclContext(SS, false);
3933         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3934           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3935
3936         if (!NotUnknownSpecialization) {
3937           // When the scope specifier can refer to a member of an unknown
3938           // specialization, we take it as a type name.
3939           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3940                                        SS.getWithLocInContext(Context),
3941                                        *MemberOrBase, IdLoc);
3942           if (BaseType.isNull())
3943             return true;
3944
3945           TInfo = Context.CreateTypeSourceInfo(BaseType);
3946           DependentNameTypeLoc TL =
3947               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3948           if (!TL.isNull()) {
3949             TL.setNameLoc(IdLoc);
3950             TL.setElaboratedKeywordLoc(SourceLocation());
3951             TL.setQualifierLoc(SS.getWithLocInContext(Context));
3952           }
3953
3954           R.clear();
3955           R.setLookupName(MemberOrBase);
3956         }
3957       }
3958
3959       // If no results were found, try to correct typos.
3960       TypoCorrection Corr;
3961       MemInitializerValidatorCCC CCC(ClassDecl);
3962       if (R.empty() && BaseType.isNull() &&
3963           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3964                               CCC, CTK_ErrorRecovery, ClassDecl))) {
3965         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3966           // We have found a non-static data member with a similar
3967           // name to what was typed; complain and initialize that
3968           // member.
3969           diagnoseTypo(Corr,
3970                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3971                          << MemberOrBase << true);
3972           return BuildMemberInitializer(Member, Init, IdLoc);
3973         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3974           const CXXBaseSpecifier *DirectBaseSpec;
3975           const CXXBaseSpecifier *VirtualBaseSpec;
3976           if (FindBaseInitializer(*this, ClassDecl,
3977                                   Context.getTypeDeclType(Type),
3978                                   DirectBaseSpec, VirtualBaseSpec)) {
3979             // We have found a direct or virtual base class with a
3980             // similar name to what was typed; complain and initialize
3981             // that base class.
3982             diagnoseTypo(Corr,
3983                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3984                            << MemberOrBase << false,
3985                          PDiag() /*Suppress note, we provide our own.*/);
3986
3987             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3988                                                               : VirtualBaseSpec;
3989             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
3990                 << BaseSpec->getType() << BaseSpec->getSourceRange();
3991
3992             TyD = Type;
3993           }
3994         }
3995       }
3996
3997       if (!TyD && BaseType.isNull()) {
3998         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3999           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4000         return true;
4001       }
4002     }
4003
4004     if (BaseType.isNull()) {
4005       BaseType = Context.getTypeDeclType(TyD);
4006       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4007       if (SS.isSet()) {
4008         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4009                                              BaseType);
4010         TInfo = Context.CreateTypeSourceInfo(BaseType);
4011         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4012         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4013         TL.setElaboratedKeywordLoc(SourceLocation());
4014         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4015       }
4016     }
4017   }
4018
4019   if (!TInfo)
4020     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4021
4022   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4023 }
4024
4025 MemInitResult
4026 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4027                              SourceLocation IdLoc) {
4028   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4029   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4030   assert((DirectMember || IndirectMember) &&
4031          "Member must be a FieldDecl or IndirectFieldDecl");
4032
4033   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4034     return true;
4035
4036   if (Member->isInvalidDecl())
4037     return true;
4038
4039   MultiExprArg Args;
4040   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4041     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4042   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4043     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4044   } else {
4045     // Template instantiation doesn't reconstruct ParenListExprs for us.
4046     Args = Init;
4047   }
4048
4049   SourceRange InitRange = Init->getSourceRange();
4050
4051   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4052     // Can't check initialization for a member of dependent type or when
4053     // any of the arguments are type-dependent expressions.
4054     DiscardCleanupsInEvaluationContext();
4055   } else {
4056     bool InitList = false;
4057     if (isa<InitListExpr>(Init)) {
4058       InitList = true;
4059       Args = Init;
4060     }
4061
4062     // Initialize the member.
4063     InitializedEntity MemberEntity =
4064       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4065                    : InitializedEntity::InitializeMember(IndirectMember,
4066                                                          nullptr);
4067     InitializationKind Kind =
4068         InitList ? InitializationKind::CreateDirectList(
4069                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4070                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4071                                                     InitRange.getEnd());
4072
4073     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4074     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4075                                             nullptr);
4076     if (MemberInit.isInvalid())
4077       return true;
4078
4079     // C++11 [class.base.init]p7:
4080     //   The initialization of each base and member constitutes a
4081     //   full-expression.
4082     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4083                                      /*DiscardedValue*/ false);
4084     if (MemberInit.isInvalid())
4085       return true;
4086
4087     Init = MemberInit.get();
4088   }
4089
4090   if (DirectMember) {
4091     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4092                                             InitRange.getBegin(), Init,
4093                                             InitRange.getEnd());
4094   } else {
4095     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4096                                             InitRange.getBegin(), Init,
4097                                             InitRange.getEnd());
4098   }
4099 }
4100
4101 MemInitResult
4102 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4103                                  CXXRecordDecl *ClassDecl) {
4104   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4105   if (!LangOpts.CPlusPlus11)
4106     return Diag(NameLoc, diag::err_delegating_ctor)
4107       << TInfo->getTypeLoc().getLocalSourceRange();
4108   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4109
4110   bool InitList = true;
4111   MultiExprArg Args = Init;
4112   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4113     InitList = false;
4114     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4115   }
4116
4117   SourceRange InitRange = Init->getSourceRange();
4118   // Initialize the object.
4119   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4120                                      QualType(ClassDecl->getTypeForDecl(), 0));
4121   InitializationKind Kind =
4122       InitList ? InitializationKind::CreateDirectList(
4123                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4124                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4125                                                   InitRange.getEnd());
4126   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4127   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4128                                               Args, nullptr);
4129   if (DelegationInit.isInvalid())
4130     return true;
4131
4132   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4133          "Delegating constructor with no target?");
4134
4135   // C++11 [class.base.init]p7:
4136   //   The initialization of each base and member constitutes a
4137   //   full-expression.
4138   DelegationInit = ActOnFinishFullExpr(
4139       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4140   if (DelegationInit.isInvalid())
4141     return true;
4142
4143   // If we are in a dependent context, template instantiation will
4144   // perform this type-checking again. Just save the arguments that we
4145   // received in a ParenListExpr.
4146   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4147   // of the information that we have about the base
4148   // initializer. However, deconstructing the ASTs is a dicey process,
4149   // and this approach is far more likely to get the corner cases right.
4150   if (CurContext->isDependentContext())
4151     DelegationInit = Init;
4152
4153   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4154                                           DelegationInit.getAs<Expr>(),
4155                                           InitRange.getEnd());
4156 }
4157
4158 MemInitResult
4159 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4160                            Expr *Init, CXXRecordDecl *ClassDecl,
4161                            SourceLocation EllipsisLoc) {
4162   SourceLocation BaseLoc
4163     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4164
4165   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4166     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4167              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4168
4169   // C++ [class.base.init]p2:
4170   //   [...] Unless the mem-initializer-id names a nonstatic data
4171   //   member of the constructor's class or a direct or virtual base
4172   //   of that class, the mem-initializer is ill-formed. A
4173   //   mem-initializer-list can initialize a base class using any
4174   //   name that denotes that base class type.
4175   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4176
4177   SourceRange InitRange = Init->getSourceRange();
4178   if (EllipsisLoc.isValid()) {
4179     // This is a pack expansion.
4180     if (!BaseType->containsUnexpandedParameterPack())  {
4181       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4182         << SourceRange(BaseLoc, InitRange.getEnd());
4183
4184       EllipsisLoc = SourceLocation();
4185     }
4186   } else {
4187     // Check for any unexpanded parameter packs.
4188     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4189       return true;
4190
4191     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4192       return true;
4193   }
4194
4195   // Check for direct and virtual base classes.
4196   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4197   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4198   if (!Dependent) {
4199     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4200                                        BaseType))
4201       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4202
4203     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4204                         VirtualBaseSpec);
4205
4206     // C++ [base.class.init]p2:
4207     // Unless the mem-initializer-id names a nonstatic data member of the
4208     // constructor's class or a direct or virtual base of that class, the
4209     // mem-initializer is ill-formed.
4210     if (!DirectBaseSpec && !VirtualBaseSpec) {
4211       // If the class has any dependent bases, then it's possible that
4212       // one of those types will resolve to the same type as
4213       // BaseType. Therefore, just treat this as a dependent base
4214       // class initialization.  FIXME: Should we try to check the
4215       // initialization anyway? It seems odd.
4216       if (ClassDecl->hasAnyDependentBases())
4217         Dependent = true;
4218       else
4219         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4220           << BaseType << Context.getTypeDeclType(ClassDecl)
4221           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4222     }
4223   }
4224
4225   if (Dependent) {
4226     DiscardCleanupsInEvaluationContext();
4227
4228     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4229                                             /*IsVirtual=*/false,
4230                                             InitRange.getBegin(), Init,
4231                                             InitRange.getEnd(), EllipsisLoc);
4232   }
4233
4234   // C++ [base.class.init]p2:
4235   //   If a mem-initializer-id is ambiguous because it designates both
4236   //   a direct non-virtual base class and an inherited virtual base
4237   //   class, the mem-initializer is ill-formed.
4238   if (DirectBaseSpec && VirtualBaseSpec)
4239     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4240       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4241
4242   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4243   if (!BaseSpec)
4244     BaseSpec = VirtualBaseSpec;
4245
4246   // Initialize the base.
4247   bool InitList = true;
4248   MultiExprArg Args = Init;
4249   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4250     InitList = false;
4251     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4252   }
4253
4254   InitializedEntity BaseEntity =
4255     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4256   InitializationKind Kind =
4257       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4258                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4259                                                   InitRange.getEnd());
4260   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4261   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4262   if (BaseInit.isInvalid())
4263     return true;
4264
4265   // C++11 [class.base.init]p7:
4266   //   The initialization of each base and member constitutes a
4267   //   full-expression.
4268   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4269                                  /*DiscardedValue*/ false);
4270   if (BaseInit.isInvalid())
4271     return true;
4272
4273   // If we are in a dependent context, template instantiation will
4274   // perform this type-checking again. Just save the arguments that we
4275   // received in a ParenListExpr.
4276   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4277   // of the information that we have about the base
4278   // initializer. However, deconstructing the ASTs is a dicey process,
4279   // and this approach is far more likely to get the corner cases right.
4280   if (CurContext->isDependentContext())
4281     BaseInit = Init;
4282
4283   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4284                                           BaseSpec->isVirtual(),
4285                                           InitRange.getBegin(),
4286                                           BaseInit.getAs<Expr>(),
4287                                           InitRange.getEnd(), EllipsisLoc);
4288 }
4289
4290 // Create a static_cast\<T&&>(expr).
4291 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4292   if (T.isNull()) T = E->getType();
4293   QualType TargetType = SemaRef.BuildReferenceType(
4294       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4295   SourceLocation ExprLoc = E->getBeginLoc();
4296   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4297       TargetType, ExprLoc);
4298
4299   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4300                                    SourceRange(ExprLoc, ExprLoc),
4301                                    E->getSourceRange()).get();
4302 }
4303
4304 /// ImplicitInitializerKind - How an implicit base or member initializer should
4305 /// initialize its base or member.
4306 enum ImplicitInitializerKind {
4307   IIK_Default,
4308   IIK_Copy,
4309   IIK_Move,
4310   IIK_Inherit
4311 };
4312
4313 static bool
4314 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4315                              ImplicitInitializerKind ImplicitInitKind,
4316                              CXXBaseSpecifier *BaseSpec,
4317                              bool IsInheritedVirtualBase,
4318                              CXXCtorInitializer *&CXXBaseInit) {
4319   InitializedEntity InitEntity
4320     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4321                                         IsInheritedVirtualBase);
4322
4323   ExprResult BaseInit;
4324
4325   switch (ImplicitInitKind) {
4326   case IIK_Inherit:
4327   case IIK_Default: {
4328     InitializationKind InitKind
4329       = InitializationKind::CreateDefault(Constructor->getLocation());
4330     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4331     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4332     break;
4333   }
4334
4335   case IIK_Move:
4336   case IIK_Copy: {
4337     bool Moving = ImplicitInitKind == IIK_Move;
4338     ParmVarDecl *Param = Constructor->getParamDecl(0);
4339     QualType ParamType = Param->getType().getNonReferenceType();
4340
4341     Expr *CopyCtorArg =
4342       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4343                           SourceLocation(), Param, false,
4344                           Constructor->getLocation(), ParamType,
4345                           VK_LValue, nullptr);
4346
4347     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4348
4349     // Cast to the base class to avoid ambiguities.
4350     QualType ArgTy =
4351       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4352                                        ParamType.getQualifiers());
4353
4354     if (Moving) {
4355       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4356     }
4357
4358     CXXCastPath BasePath;
4359     BasePath.push_back(BaseSpec);
4360     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4361                                             CK_UncheckedDerivedToBase,
4362                                             Moving ? VK_XValue : VK_LValue,
4363                                             &BasePath).get();
4364
4365     InitializationKind InitKind
4366       = InitializationKind::CreateDirect(Constructor->getLocation(),
4367                                          SourceLocation(), SourceLocation());
4368     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4369     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4370     break;
4371   }
4372   }
4373
4374   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4375   if (BaseInit.isInvalid())
4376     return true;
4377
4378   CXXBaseInit =
4379     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4380                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4381                                                         SourceLocation()),
4382                                              BaseSpec->isVirtual(),
4383                                              SourceLocation(),
4384                                              BaseInit.getAs<Expr>(),
4385                                              SourceLocation(),
4386                                              SourceLocation());
4387
4388   return false;
4389 }
4390
4391 static bool RefersToRValueRef(Expr *MemRef) {
4392   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4393   return Referenced->getType()->isRValueReferenceType();
4394 }
4395
4396 static bool
4397 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4398                                ImplicitInitializerKind ImplicitInitKind,
4399                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4400                                CXXCtorInitializer *&CXXMemberInit) {
4401   if (Field->isInvalidDecl())
4402     return true;
4403
4404   SourceLocation Loc = Constructor->getLocation();
4405
4406   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4407     bool Moving = ImplicitInitKind == IIK_Move;
4408     ParmVarDecl *Param = Constructor->getParamDecl(0);
4409     QualType ParamType = Param->getType().getNonReferenceType();
4410
4411     // Suppress copying zero-width bitfields.
4412     if (Field->isZeroLengthBitField(SemaRef.Context))
4413       return false;
4414
4415     Expr *MemberExprBase =
4416       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4417                           SourceLocation(), Param, false,
4418                           Loc, ParamType, VK_LValue, nullptr);
4419
4420     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4421
4422     if (Moving) {
4423       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4424     }
4425
4426     // Build a reference to this field within the parameter.
4427     CXXScopeSpec SS;
4428     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4429                               Sema::LookupMemberName);
4430     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4431                                   : cast<ValueDecl>(Field), AS_public);
4432     MemberLookup.resolveKind();
4433     ExprResult CtorArg
4434       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4435                                          ParamType, Loc,
4436                                          /*IsArrow=*/false,
4437                                          SS,
4438                                          /*TemplateKWLoc=*/SourceLocation(),
4439                                          /*FirstQualifierInScope=*/nullptr,
4440                                          MemberLookup,
4441                                          /*TemplateArgs=*/nullptr,
4442                                          /*S*/nullptr);
4443     if (CtorArg.isInvalid())
4444       return true;
4445
4446     // C++11 [class.copy]p15:
4447     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4448     //     with static_cast<T&&>(x.m);
4449     if (RefersToRValueRef(CtorArg.get())) {
4450       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4451     }
4452
4453     InitializedEntity Entity =
4454         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4455                                                        /*Implicit*/ true)
4456                  : InitializedEntity::InitializeMember(Field, nullptr,
4457                                                        /*Implicit*/ true);
4458
4459     // Direct-initialize to use the copy constructor.
4460     InitializationKind InitKind =
4461       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4462
4463     Expr *CtorArgE = CtorArg.getAs<Expr>();
4464     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4465     ExprResult MemberInit =
4466         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4467     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4468     if (MemberInit.isInvalid())
4469       return true;
4470
4471     if (Indirect)
4472       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4473           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4474     else
4475       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4476           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4477     return false;
4478   }
4479
4480   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4481          "Unhandled implicit init kind!");
4482
4483   QualType FieldBaseElementType =
4484     SemaRef.Context.getBaseElementType(Field->getType());
4485
4486   if (FieldBaseElementType->isRecordType()) {
4487     InitializedEntity InitEntity =
4488         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4489                                                        /*Implicit*/ true)
4490                  : InitializedEntity::InitializeMember(Field, nullptr,
4491                                                        /*Implicit*/ true);
4492     InitializationKind InitKind =
4493       InitializationKind::CreateDefault(Loc);
4494
4495     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4496     ExprResult MemberInit =
4497       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4498
4499     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4500     if (MemberInit.isInvalid())
4501       return true;
4502
4503     if (Indirect)
4504       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4505                                                                Indirect, Loc,
4506                                                                Loc,
4507                                                                MemberInit.get(),
4508                                                                Loc);
4509     else
4510       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4511                                                                Field, Loc, Loc,
4512                                                                MemberInit.get(),
4513                                                                Loc);
4514     return false;
4515   }
4516
4517   if (!Field->getParent()->isUnion()) {
4518     if (FieldBaseElementType->isReferenceType()) {
4519       SemaRef.Diag(Constructor->getLocation(),
4520                    diag::err_uninitialized_member_in_ctor)
4521       << (int)Constructor->isImplicit()
4522       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4523       << 0 << Field->getDeclName();
4524       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4525       return true;
4526     }
4527
4528     if (FieldBaseElementType.isConstQualified()) {
4529       SemaRef.Diag(Constructor->getLocation(),
4530                    diag::err_uninitialized_member_in_ctor)
4531       << (int)Constructor->isImplicit()
4532       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4533       << 1 << Field->getDeclName();
4534       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4535       return true;
4536     }
4537   }
4538
4539   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4540     // ARC and Weak:
4541     //   Default-initialize Objective-C pointers to NULL.
4542     CXXMemberInit
4543       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4544                                                  Loc, Loc,
4545                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4546                                                  Loc);
4547     return false;
4548   }
4549
4550   // Nothing to initialize.
4551   CXXMemberInit = nullptr;
4552   return false;
4553 }
4554
4555 namespace {
4556 struct BaseAndFieldInfo {
4557   Sema &S;
4558   CXXConstructorDecl *Ctor;
4559   bool AnyErrorsInInits;
4560   ImplicitInitializerKind IIK;
4561   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4562   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4563   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4564
4565   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4566     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4567     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4568     if (Ctor->getInheritedConstructor())
4569       IIK = IIK_Inherit;
4570     else if (Generated && Ctor->isCopyConstructor())
4571       IIK = IIK_Copy;
4572     else if (Generated && Ctor->isMoveConstructor())
4573       IIK = IIK_Move;
4574     else
4575       IIK = IIK_Default;
4576   }
4577
4578   bool isImplicitCopyOrMove() const {
4579     switch (IIK) {
4580     case IIK_Copy:
4581     case IIK_Move:
4582       return true;
4583
4584     case IIK_Default:
4585     case IIK_Inherit:
4586       return false;
4587     }
4588
4589     llvm_unreachable("Invalid ImplicitInitializerKind!");
4590   }
4591
4592   bool addFieldInitializer(CXXCtorInitializer *Init) {
4593     AllToInit.push_back(Init);
4594
4595     // Check whether this initializer makes the field "used".
4596     if (Init->getInit()->HasSideEffects(S.Context))
4597       S.UnusedPrivateFields.remove(Init->getAnyMember());
4598
4599     return false;
4600   }
4601
4602   bool isInactiveUnionMember(FieldDecl *Field) {
4603     RecordDecl *Record = Field->getParent();
4604     if (!Record->isUnion())
4605       return false;
4606
4607     if (FieldDecl *Active =
4608             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4609       return Active != Field->getCanonicalDecl();
4610
4611     // In an implicit copy or move constructor, ignore any in-class initializer.
4612     if (isImplicitCopyOrMove())
4613       return true;
4614
4615     // If there's no explicit initialization, the field is active only if it
4616     // has an in-class initializer...
4617     if (Field->hasInClassInitializer())
4618       return false;
4619     // ... or it's an anonymous struct or union whose class has an in-class
4620     // initializer.
4621     if (!Field->isAnonymousStructOrUnion())
4622       return true;
4623     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4624     return !FieldRD->hasInClassInitializer();
4625   }
4626
4627   /// Determine whether the given field is, or is within, a union member
4628   /// that is inactive (because there was an initializer given for a different
4629   /// member of the union, or because the union was not initialized at all).
4630   bool isWithinInactiveUnionMember(FieldDecl *Field,
4631                                    IndirectFieldDecl *Indirect) {
4632     if (!Indirect)
4633       return isInactiveUnionMember(Field);
4634
4635     for (auto *C : Indirect->chain()) {
4636       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4637       if (Field && isInactiveUnionMember(Field))
4638         return true;
4639     }
4640     return false;
4641   }
4642 };
4643 }
4644
4645 /// Determine whether the given type is an incomplete or zero-lenfgth
4646 /// array type.
4647 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4648   if (T->isIncompleteArrayType())
4649     return true;
4650
4651   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4652     if (!ArrayT->getSize())
4653       return true;
4654
4655     T = ArrayT->getElementType();
4656   }
4657
4658   return false;
4659 }
4660
4661 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4662                                     FieldDecl *Field,
4663                                     IndirectFieldDecl *Indirect = nullptr) {
4664   if (Field->isInvalidDecl())
4665     return false;
4666
4667   // Overwhelmingly common case: we have a direct initializer for this field.
4668   if (CXXCtorInitializer *Init =
4669           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4670     return Info.addFieldInitializer(Init);
4671
4672   // C++11 [class.base.init]p8:
4673   //   if the entity is a non-static data member that has a
4674   //   brace-or-equal-initializer and either
4675   //   -- the constructor's class is a union and no other variant member of that
4676   //      union is designated by a mem-initializer-id or
4677   //   -- the constructor's class is not a union, and, if the entity is a member
4678   //      of an anonymous union, no other member of that union is designated by
4679   //      a mem-initializer-id,
4680   //   the entity is initialized as specified in [dcl.init].
4681   //
4682   // We also apply the same rules to handle anonymous structs within anonymous
4683   // unions.
4684   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4685     return false;
4686
4687   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4688     ExprResult DIE =
4689         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4690     if (DIE.isInvalid())
4691       return true;
4692
4693     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4694     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4695
4696     CXXCtorInitializer *Init;
4697     if (Indirect)
4698       Init = new (SemaRef.Context)
4699           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4700                              SourceLocation(), DIE.get(), SourceLocation());
4701     else
4702       Init = new (SemaRef.Context)
4703           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4704                              SourceLocation(), DIE.get(), SourceLocation());
4705     return Info.addFieldInitializer(Init);
4706   }
4707
4708   // Don't initialize incomplete or zero-length arrays.
4709   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4710     return false;
4711
4712   // Don't try to build an implicit initializer if there were semantic
4713   // errors in any of the initializers (and therefore we might be
4714   // missing some that the user actually wrote).
4715   if (Info.AnyErrorsInInits)
4716     return false;
4717
4718   CXXCtorInitializer *Init = nullptr;
4719   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4720                                      Indirect, Init))
4721     return true;
4722
4723   if (!Init)
4724     return false;
4725
4726   return Info.addFieldInitializer(Init);
4727 }
4728
4729 bool
4730 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4731                                CXXCtorInitializer *Initializer) {
4732   assert(Initializer->isDelegatingInitializer());
4733   Constructor->setNumCtorInitializers(1);
4734   CXXCtorInitializer **initializer =
4735     new (Context) CXXCtorInitializer*[1];
4736   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4737   Constructor->setCtorInitializers(initializer);
4738
4739   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4740     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4741     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4742   }
4743
4744   DelegatingCtorDecls.push_back(Constructor);
4745
4746   DiagnoseUninitializedFields(*this, Constructor);
4747
4748   return false;
4749 }
4750
4751 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4752                                ArrayRef<CXXCtorInitializer *> Initializers) {
4753   if (Constructor->isDependentContext()) {
4754     // Just store the initializers as written, they will be checked during
4755     // instantiation.
4756     if (!Initializers.empty()) {
4757       Constructor->setNumCtorInitializers(Initializers.size());
4758       CXXCtorInitializer **baseOrMemberInitializers =
4759         new (Context) CXXCtorInitializer*[Initializers.size()];
4760       memcpy(baseOrMemberInitializers, Initializers.data(),
4761              Initializers.size() * sizeof(CXXCtorInitializer*));
4762       Constructor->setCtorInitializers(baseOrMemberInitializers);
4763     }
4764
4765     // Let template instantiation know whether we had errors.
4766     if (AnyErrors)
4767       Constructor->setInvalidDecl();
4768
4769     return false;
4770   }
4771
4772   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4773
4774   // We need to build the initializer AST according to order of construction
4775   // and not what user specified in the Initializers list.
4776   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4777   if (!ClassDecl)
4778     return true;
4779
4780   bool HadError = false;
4781
4782   for (unsigned i = 0; i < Initializers.size(); i++) {
4783     CXXCtorInitializer *Member = Initializers[i];
4784
4785     if (Member->isBaseInitializer())
4786       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4787     else {
4788       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4789
4790       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4791         for (auto *C : F->chain()) {
4792           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4793           if (FD && FD->getParent()->isUnion())
4794             Info.ActiveUnionMember.insert(std::make_pair(
4795                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4796         }
4797       } else if (FieldDecl *FD = Member->getMember()) {
4798         if (FD->getParent()->isUnion())
4799           Info.ActiveUnionMember.insert(std::make_pair(
4800               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4801       }
4802     }
4803   }
4804
4805   // Keep track of the direct virtual bases.
4806   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4807   for (auto &I : ClassDecl->bases()) {
4808     if (I.isVirtual())
4809       DirectVBases.insert(&I);
4810   }
4811
4812   // Push virtual bases before others.
4813   for (auto &VBase : ClassDecl->vbases()) {
4814     if (CXXCtorInitializer *Value
4815         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4816       // [class.base.init]p7, per DR257:
4817       //   A mem-initializer where the mem-initializer-id names a virtual base
4818       //   class is ignored during execution of a constructor of any class that
4819       //   is not the most derived class.
4820       if (ClassDecl->isAbstract()) {
4821         // FIXME: Provide a fixit to remove the base specifier. This requires
4822         // tracking the location of the associated comma for a base specifier.
4823         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4824           << VBase.getType() << ClassDecl;
4825         DiagnoseAbstractType(ClassDecl);
4826       }
4827
4828       Info.AllToInit.push_back(Value);
4829     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4830       // [class.base.init]p8, per DR257:
4831       //   If a given [...] base class is not named by a mem-initializer-id
4832       //   [...] and the entity is not a virtual base class of an abstract
4833       //   class, then [...] the entity is default-initialized.
4834       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4835       CXXCtorInitializer *CXXBaseInit;
4836       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4837                                        &VBase, IsInheritedVirtualBase,
4838                                        CXXBaseInit)) {
4839         HadError = true;
4840         continue;
4841       }
4842
4843       Info.AllToInit.push_back(CXXBaseInit);
4844     }
4845   }
4846
4847   // Non-virtual bases.
4848   for (auto &Base : ClassDecl->bases()) {
4849     // Virtuals are in the virtual base list and already constructed.
4850     if (Base.isVirtual())
4851       continue;
4852
4853     if (CXXCtorInitializer *Value
4854           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4855       Info.AllToInit.push_back(Value);
4856     } else if (!AnyErrors) {
4857       CXXCtorInitializer *CXXBaseInit;
4858       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4859                                        &Base, /*IsInheritedVirtualBase=*/false,
4860                                        CXXBaseInit)) {
4861         HadError = true;
4862         continue;
4863       }
4864
4865       Info.AllToInit.push_back(CXXBaseInit);
4866     }
4867   }
4868
4869   // Fields.
4870   for (auto *Mem : ClassDecl->decls()) {
4871     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4872       // C++ [class.bit]p2:
4873       //   A declaration for a bit-field that omits the identifier declares an
4874       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4875       //   initialized.
4876       if (F->isUnnamedBitfield())
4877         continue;
4878
4879       // If we're not generating the implicit copy/move constructor, then we'll
4880       // handle anonymous struct/union fields based on their individual
4881       // indirect fields.
4882       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4883         continue;
4884
4885       if (CollectFieldInitializer(*this, Info, F))
4886         HadError = true;
4887       continue;
4888     }
4889
4890     // Beyond this point, we only consider default initialization.
4891     if (Info.isImplicitCopyOrMove())
4892       continue;
4893
4894     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4895       if (F->getType()->isIncompleteArrayType()) {
4896         assert(ClassDecl->hasFlexibleArrayMember() &&
4897                "Incomplete array type is not valid");
4898         continue;
4899       }
4900
4901       // Initialize each field of an anonymous struct individually.
4902       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4903         HadError = true;
4904
4905       continue;
4906     }
4907   }
4908
4909   unsigned NumInitializers = Info.AllToInit.size();
4910   if (NumInitializers > 0) {
4911     Constructor->setNumCtorInitializers(NumInitializers);
4912     CXXCtorInitializer **baseOrMemberInitializers =
4913       new (Context) CXXCtorInitializer*[NumInitializers];
4914     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4915            NumInitializers * sizeof(CXXCtorInitializer*));
4916     Constructor->setCtorInitializers(baseOrMemberInitializers);
4917
4918     // Constructors implicitly reference the base and member
4919     // destructors.
4920     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4921                                            Constructor->getParent());
4922   }
4923
4924   return HadError;
4925 }
4926
4927 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4928   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4929     const RecordDecl *RD = RT->getDecl();
4930     if (RD->isAnonymousStructOrUnion()) {
4931       for (auto *Field : RD->fields())
4932         PopulateKeysForFields(Field, IdealInits);
4933       return;
4934     }
4935   }
4936   IdealInits.push_back(Field->getCanonicalDecl());
4937 }
4938
4939 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4940   return Context.getCanonicalType(BaseType).getTypePtr();
4941 }
4942
4943 static const void *GetKeyForMember(ASTContext &Context,
4944                                    CXXCtorInitializer *Member) {
4945   if (!Member->isAnyMemberInitializer())
4946     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4947
4948   return Member->getAnyMember()->getCanonicalDecl();
4949 }
4950
4951 static void DiagnoseBaseOrMemInitializerOrder(
4952     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4953     ArrayRef<CXXCtorInitializer *> Inits) {
4954   if (Constructor->getDeclContext()->isDependentContext())
4955     return;
4956
4957   // Don't check initializers order unless the warning is enabled at the
4958   // location of at least one initializer.
4959   bool ShouldCheckOrder = false;
4960   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4961     CXXCtorInitializer *Init = Inits[InitIndex];
4962     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4963                                  Init->getSourceLocation())) {
4964       ShouldCheckOrder = true;
4965       break;
4966     }
4967   }
4968   if (!ShouldCheckOrder)
4969     return;
4970
4971   // Build the list of bases and members in the order that they'll
4972   // actually be initialized.  The explicit initializers should be in
4973   // this same order but may be missing things.
4974   SmallVector<const void*, 32> IdealInitKeys;
4975
4976   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4977
4978   // 1. Virtual bases.
4979   for (const auto &VBase : ClassDecl->vbases())
4980     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4981
4982   // 2. Non-virtual bases.
4983   for (const auto &Base : ClassDecl->bases()) {
4984     if (Base.isVirtual())
4985       continue;
4986     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4987   }
4988
4989   // 3. Direct fields.
4990   for (auto *Field : ClassDecl->fields()) {
4991     if (Field->isUnnamedBitfield())
4992       continue;
4993
4994     PopulateKeysForFields(Field, IdealInitKeys);
4995   }
4996
4997   unsigned NumIdealInits = IdealInitKeys.size();
4998   unsigned IdealIndex = 0;
4999
5000   CXXCtorInitializer *PrevInit = nullptr;
5001   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5002     CXXCtorInitializer *Init = Inits[InitIndex];
5003     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5004
5005     // Scan forward to try to find this initializer in the idealized
5006     // initializers list.
5007     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5008       if (InitKey == IdealInitKeys[IdealIndex])
5009         break;
5010
5011     // If we didn't find this initializer, it must be because we
5012     // scanned past it on a previous iteration.  That can only
5013     // happen if we're out of order;  emit a warning.
5014     if (IdealIndex == NumIdealInits && PrevInit) {
5015       Sema::SemaDiagnosticBuilder D =
5016         SemaRef.Diag(PrevInit->getSourceLocation(),
5017                      diag::warn_initializer_out_of_order);
5018
5019       if (PrevInit->isAnyMemberInitializer())
5020         D << 0 << PrevInit->getAnyMember()->getDeclName();
5021       else
5022         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5023
5024       if (Init->isAnyMemberInitializer())
5025         D << 0 << Init->getAnyMember()->getDeclName();
5026       else
5027         D << 1 << Init->getTypeSourceInfo()->getType();
5028
5029       // Move back to the initializer's location in the ideal list.
5030       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5031         if (InitKey == IdealInitKeys[IdealIndex])
5032           break;
5033
5034       assert(IdealIndex < NumIdealInits &&
5035              "initializer not found in initializer list");
5036     }
5037
5038     PrevInit = Init;
5039   }
5040 }
5041
5042 namespace {
5043 bool CheckRedundantInit(Sema &S,
5044                         CXXCtorInitializer *Init,
5045                         CXXCtorInitializer *&PrevInit) {
5046   if (!PrevInit) {
5047     PrevInit = Init;
5048     return false;
5049   }
5050
5051   if (FieldDecl *Field = Init->getAnyMember())
5052     S.Diag(Init->getSourceLocation(),
5053            diag::err_multiple_mem_initialization)
5054       << Field->getDeclName()
5055       << Init->getSourceRange();
5056   else {
5057     const Type *BaseClass = Init->getBaseClass();
5058     assert(BaseClass && "neither field nor base");
5059     S.Diag(Init->getSourceLocation(),
5060            diag::err_multiple_base_initialization)
5061       << QualType(BaseClass, 0)
5062       << Init->getSourceRange();
5063   }
5064   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5065     << 0 << PrevInit->getSourceRange();
5066
5067   return true;
5068 }
5069
5070 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5071 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5072
5073 bool CheckRedundantUnionInit(Sema &S,
5074                              CXXCtorInitializer *Init,
5075                              RedundantUnionMap &Unions) {
5076   FieldDecl *Field = Init->getAnyMember();
5077   RecordDecl *Parent = Field->getParent();
5078   NamedDecl *Child = Field;
5079
5080   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5081     if (Parent->isUnion()) {
5082       UnionEntry &En = Unions[Parent];
5083       if (En.first && En.first != Child) {
5084         S.Diag(Init->getSourceLocation(),
5085                diag::err_multiple_mem_union_initialization)
5086           << Field->getDeclName()
5087           << Init->getSourceRange();
5088         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5089           << 0 << En.second->getSourceRange();
5090         return true;
5091       }
5092       if (!En.first) {
5093         En.first = Child;
5094         En.second = Init;
5095       }
5096       if (!Parent->isAnonymousStructOrUnion())
5097         return false;
5098     }
5099
5100     Child = Parent;
5101     Parent = cast<RecordDecl>(Parent->getDeclContext());
5102   }
5103
5104   return false;
5105 }
5106 }
5107
5108 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5109 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5110                                 SourceLocation ColonLoc,
5111                                 ArrayRef<CXXCtorInitializer*> MemInits,
5112                                 bool AnyErrors) {
5113   if (!ConstructorDecl)
5114     return;
5115
5116   AdjustDeclIfTemplate(ConstructorDecl);
5117
5118   CXXConstructorDecl *Constructor
5119     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5120
5121   if (!Constructor) {
5122     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5123     return;
5124   }
5125
5126   // Mapping for the duplicate initializers check.
5127   // For member initializers, this is keyed with a FieldDecl*.
5128   // For base initializers, this is keyed with a Type*.
5129   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5130
5131   // Mapping for the inconsistent anonymous-union initializers check.
5132   RedundantUnionMap MemberUnions;
5133
5134   bool HadError = false;
5135   for (unsigned i = 0; i < MemInits.size(); i++) {
5136     CXXCtorInitializer *Init = MemInits[i];
5137
5138     // Set the source order index.
5139     Init->setSourceOrder(i);
5140
5141     if (Init->isAnyMemberInitializer()) {
5142       const void *Key = GetKeyForMember(Context, Init);
5143       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5144           CheckRedundantUnionInit(*this, Init, MemberUnions))
5145         HadError = true;
5146     } else if (Init->isBaseInitializer()) {
5147       const void *Key = GetKeyForMember(Context, Init);
5148       if (CheckRedundantInit(*this, Init, Members[Key]))
5149         HadError = true;
5150     } else {
5151       assert(Init->isDelegatingInitializer());
5152       // This must be the only initializer
5153       if (MemInits.size() != 1) {
5154         Diag(Init->getSourceLocation(),
5155              diag::err_delegating_initializer_alone)
5156           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5157         // We will treat this as being the only initializer.
5158       }
5159       SetDelegatingInitializer(Constructor, MemInits[i]);
5160       // Return immediately as the initializer is set.
5161       return;
5162     }
5163   }
5164
5165   if (HadError)
5166     return;
5167
5168   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5169
5170   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5171
5172   DiagnoseUninitializedFields(*this, Constructor);
5173 }
5174
5175 void
5176 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5177                                              CXXRecordDecl *ClassDecl) {
5178   // Ignore dependent contexts. Also ignore unions, since their members never
5179   // have destructors implicitly called.
5180   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5181     return;
5182
5183   // FIXME: all the access-control diagnostics are positioned on the
5184   // field/base declaration.  That's probably good; that said, the
5185   // user might reasonably want to know why the destructor is being
5186   // emitted, and we currently don't say.
5187
5188   // Non-static data members.
5189   for (auto *Field : ClassDecl->fields()) {
5190     if (Field->isInvalidDecl())
5191       continue;
5192
5193     // Don't destroy incomplete or zero-length arrays.
5194     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5195       continue;
5196
5197     QualType FieldType = Context.getBaseElementType(Field->getType());
5198
5199     const RecordType* RT = FieldType->getAs<RecordType>();
5200     if (!RT)
5201       continue;
5202
5203     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5204     if (FieldClassDecl->isInvalidDecl())
5205       continue;
5206     if (FieldClassDecl->hasIrrelevantDestructor())
5207       continue;
5208     // The destructor for an implicit anonymous union member is never invoked.
5209     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5210       continue;
5211
5212     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5213     assert(Dtor && "No dtor found for FieldClassDecl!");
5214     CheckDestructorAccess(Field->getLocation(), Dtor,
5215                           PDiag(diag::err_access_dtor_field)
5216                             << Field->getDeclName()
5217                             << FieldType);
5218
5219     MarkFunctionReferenced(Location, Dtor);
5220     DiagnoseUseOfDecl(Dtor, Location);
5221   }
5222
5223   // We only potentially invoke the destructors of potentially constructed
5224   // subobjects.
5225   bool VisitVirtualBases = !ClassDecl->isAbstract();
5226
5227   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5228
5229   // Bases.
5230   for (const auto &Base : ClassDecl->bases()) {
5231     // Bases are always records in a well-formed non-dependent class.
5232     const RecordType *RT = Base.getType()->getAs<RecordType>();
5233
5234     // Remember direct virtual bases.
5235     if (Base.isVirtual()) {
5236       if (!VisitVirtualBases)
5237         continue;
5238       DirectVirtualBases.insert(RT);
5239     }
5240
5241     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5242     // If our base class is invalid, we probably can't get its dtor anyway.
5243     if (BaseClassDecl->isInvalidDecl())
5244       continue;
5245     if (BaseClassDecl->hasIrrelevantDestructor())
5246       continue;
5247
5248     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5249     assert(Dtor && "No dtor found for BaseClassDecl!");
5250
5251     // FIXME: caret should be on the start of the class name
5252     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5253                           PDiag(diag::err_access_dtor_base)
5254                               << Base.getType() << Base.getSourceRange(),
5255                           Context.getTypeDeclType(ClassDecl));
5256
5257     MarkFunctionReferenced(Location, Dtor);
5258     DiagnoseUseOfDecl(Dtor, Location);
5259   }
5260
5261   if (!VisitVirtualBases)
5262     return;
5263
5264   // Virtual bases.
5265   for (const auto &VBase : ClassDecl->vbases()) {
5266     // Bases are always records in a well-formed non-dependent class.
5267     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5268
5269     // Ignore direct virtual bases.
5270     if (DirectVirtualBases.count(RT))
5271       continue;
5272
5273     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5274     // If our base class is invalid, we probably can't get its dtor anyway.
5275     if (BaseClassDecl->isInvalidDecl())
5276       continue;
5277     if (BaseClassDecl->hasIrrelevantDestructor())
5278       continue;
5279
5280     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5281     assert(Dtor && "No dtor found for BaseClassDecl!");
5282     if (CheckDestructorAccess(
5283             ClassDecl->getLocation(), Dtor,
5284             PDiag(diag::err_access_dtor_vbase)
5285                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5286             Context.getTypeDeclType(ClassDecl)) ==
5287         AR_accessible) {
5288       CheckDerivedToBaseConversion(
5289           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5290           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5291           SourceRange(), DeclarationName(), nullptr);
5292     }
5293
5294     MarkFunctionReferenced(Location, Dtor);
5295     DiagnoseUseOfDecl(Dtor, Location);
5296   }
5297 }
5298
5299 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5300   if (!CDtorDecl)
5301     return;
5302
5303   if (CXXConstructorDecl *Constructor
5304       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5305     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5306     DiagnoseUninitializedFields(*this, Constructor);
5307   }
5308 }
5309
5310 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5311   if (!getLangOpts().CPlusPlus)
5312     return false;
5313
5314   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5315   if (!RD)
5316     return false;
5317
5318   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5319   // class template specialization here, but doing so breaks a lot of code.
5320
5321   // We can't answer whether something is abstract until it has a
5322   // definition. If it's currently being defined, we'll walk back
5323   // over all the declarations when we have a full definition.
5324   const CXXRecordDecl *Def = RD->getDefinition();
5325   if (!Def || Def->isBeingDefined())
5326     return false;
5327
5328   return RD->isAbstract();
5329 }
5330
5331 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5332                                   TypeDiagnoser &Diagnoser) {
5333   if (!isAbstractType(Loc, T))
5334     return false;
5335
5336   T = Context.getBaseElementType(T);
5337   Diagnoser.diagnose(*this, Loc, T);
5338   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5339   return true;
5340 }
5341
5342 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5343   // Check if we've already emitted the list of pure virtual functions
5344   // for this class.
5345   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5346     return;
5347
5348   // If the diagnostic is suppressed, don't emit the notes. We're only
5349   // going to emit them once, so try to attach them to a diagnostic we're
5350   // actually going to show.
5351   if (Diags.isLastDiagnosticIgnored())
5352     return;
5353
5354   CXXFinalOverriderMap FinalOverriders;
5355   RD->getFinalOverriders(FinalOverriders);
5356
5357   // Keep a set of seen pure methods so we won't diagnose the same method
5358   // more than once.
5359   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5360
5361   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5362                                    MEnd = FinalOverriders.end();
5363        M != MEnd;
5364        ++M) {
5365     for (OverridingMethods::iterator SO = M->second.begin(),
5366                                   SOEnd = M->second.end();
5367          SO != SOEnd; ++SO) {
5368       // C++ [class.abstract]p4:
5369       //   A class is abstract if it contains or inherits at least one
5370       //   pure virtual function for which the final overrider is pure
5371       //   virtual.
5372
5373       //
5374       if (SO->second.size() != 1)
5375         continue;
5376
5377       if (!SO->second.front().Method->isPure())
5378         continue;
5379
5380       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5381         continue;
5382
5383       Diag(SO->second.front().Method->getLocation(),
5384            diag::note_pure_virtual_function)
5385         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5386     }
5387   }
5388
5389   if (!PureVirtualClassDiagSet)
5390     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5391   PureVirtualClassDiagSet->insert(RD);
5392 }
5393
5394 namespace {
5395 struct AbstractUsageInfo {
5396   Sema &S;
5397   CXXRecordDecl *Record;
5398   CanQualType AbstractType;
5399   bool Invalid;
5400
5401   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5402     : S(S), Record(Record),
5403       AbstractType(S.Context.getCanonicalType(
5404                    S.Context.getTypeDeclType(Record))),
5405       Invalid(false) {}
5406
5407   void DiagnoseAbstractType() {
5408     if (Invalid) return;
5409     S.DiagnoseAbstractType(Record);
5410     Invalid = true;
5411   }
5412
5413   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5414 };
5415
5416 struct CheckAbstractUsage {
5417   AbstractUsageInfo &Info;
5418   const NamedDecl *Ctx;
5419
5420   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5421     : Info(Info), Ctx(Ctx) {}
5422
5423   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5424     switch (TL.getTypeLocClass()) {
5425 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5426 #define TYPELOC(CLASS, PARENT) \
5427     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5428 #include "clang/AST/TypeLocNodes.def"
5429     }
5430   }
5431
5432   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5433     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5434     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5435       if (!TL.getParam(I))
5436         continue;
5437
5438       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5439       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5440     }
5441   }
5442
5443   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5444     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5445   }
5446
5447   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5448     // Visit the type parameters from a permissive context.
5449     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5450       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5451       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5452         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5453           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5454       // TODO: other template argument types?
5455     }
5456   }
5457
5458   // Visit pointee types from a permissive context.
5459 #define CheckPolymorphic(Type) \
5460   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5461     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5462   }
5463   CheckPolymorphic(PointerTypeLoc)
5464   CheckPolymorphic(ReferenceTypeLoc)
5465   CheckPolymorphic(MemberPointerTypeLoc)
5466   CheckPolymorphic(BlockPointerTypeLoc)
5467   CheckPolymorphic(AtomicTypeLoc)
5468
5469   /// Handle all the types we haven't given a more specific
5470   /// implementation for above.
5471   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5472     // Every other kind of type that we haven't called out already
5473     // that has an inner type is either (1) sugar or (2) contains that
5474     // inner type in some way as a subobject.
5475     if (TypeLoc Next = TL.getNextTypeLoc())
5476       return Visit(Next, Sel);
5477
5478     // If there's no inner type and we're in a permissive context,
5479     // don't diagnose.
5480     if (Sel == Sema::AbstractNone) return;
5481
5482     // Check whether the type matches the abstract type.
5483     QualType T = TL.getType();
5484     if (T->isArrayType()) {
5485       Sel = Sema::AbstractArrayType;
5486       T = Info.S.Context.getBaseElementType(T);
5487     }
5488     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5489     if (CT != Info.AbstractType) return;
5490
5491     // It matched; do some magic.
5492     if (Sel == Sema::AbstractArrayType) {
5493       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5494         << T << TL.getSourceRange();
5495     } else {
5496       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5497         << Sel << T << TL.getSourceRange();
5498     }
5499     Info.DiagnoseAbstractType();
5500   }
5501 };
5502
5503 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5504                                   Sema::AbstractDiagSelID Sel) {
5505   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5506 }
5507
5508 }
5509
5510 /// Check for invalid uses of an abstract type in a method declaration.
5511 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5512                                     CXXMethodDecl *MD) {
5513   // No need to do the check on definitions, which require that
5514   // the return/param types be complete.
5515   if (MD->doesThisDeclarationHaveABody())
5516     return;
5517
5518   // For safety's sake, just ignore it if we don't have type source
5519   // information.  This should never happen for non-implicit methods,
5520   // but...
5521   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5522     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5523 }
5524
5525 /// Check for invalid uses of an abstract type within a class definition.
5526 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5527                                     CXXRecordDecl *RD) {
5528   for (auto *D : RD->decls()) {
5529     if (D->isImplicit()) continue;
5530
5531     // Methods and method templates.
5532     if (isa<CXXMethodDecl>(D)) {
5533       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5534     } else if (isa<FunctionTemplateDecl>(D)) {
5535       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5536       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5537
5538     // Fields and static variables.
5539     } else if (isa<FieldDecl>(D)) {
5540       FieldDecl *FD = cast<FieldDecl>(D);
5541       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5542         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5543     } else if (isa<VarDecl>(D)) {
5544       VarDecl *VD = cast<VarDecl>(D);
5545       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5546         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5547
5548     // Nested classes and class templates.
5549     } else if (isa<CXXRecordDecl>(D)) {
5550       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5551     } else if (isa<ClassTemplateDecl>(D)) {
5552       CheckAbstractClassUsage(Info,
5553                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5554     }
5555   }
5556 }
5557
5558 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5559   Attr *ClassAttr = getDLLAttr(Class);
5560   if (!ClassAttr)
5561     return;
5562
5563   assert(ClassAttr->getKind() == attr::DLLExport);
5564
5565   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5566
5567   if (TSK == TSK_ExplicitInstantiationDeclaration)
5568     // Don't go any further if this is just an explicit instantiation
5569     // declaration.
5570     return;
5571
5572   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5573     S.MarkVTableUsed(Class->getLocation(), Class, true);
5574
5575   for (Decl *Member : Class->decls()) {
5576     // Defined static variables that are members of an exported base
5577     // class must be marked export too.
5578     auto *VD = dyn_cast<VarDecl>(Member);
5579     if (VD && Member->getAttr<DLLExportAttr>() &&
5580         VD->getStorageClass() == SC_Static &&
5581         TSK == TSK_ImplicitInstantiation)
5582       S.MarkVariableReferenced(VD->getLocation(), VD);
5583
5584     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5585     if (!MD)
5586       continue;
5587
5588     if (Member->getAttr<DLLExportAttr>()) {
5589       if (MD->isUserProvided()) {
5590         // Instantiate non-default class member functions ...
5591
5592         // .. except for certain kinds of template specializations.
5593         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5594           continue;
5595
5596         S.MarkFunctionReferenced(Class->getLocation(), MD);
5597
5598         // The function will be passed to the consumer when its definition is
5599         // encountered.
5600       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5601                  MD->isCopyAssignmentOperator() ||
5602                  MD->isMoveAssignmentOperator()) {
5603         // Synthesize and instantiate non-trivial implicit methods, explicitly
5604         // defaulted methods, and the copy and move assignment operators. The
5605         // latter are exported even if they are trivial, because the address of
5606         // an operator can be taken and should compare equal across libraries.
5607         DiagnosticErrorTrap Trap(S.Diags);
5608         S.MarkFunctionReferenced(Class->getLocation(), MD);
5609         if (Trap.hasErrorOccurred()) {
5610           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5611               << Class << !S.getLangOpts().CPlusPlus11;
5612           break;
5613         }
5614
5615         // There is no later point when we will see the definition of this
5616         // function, so pass it to the consumer now.
5617         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5618       }
5619     }
5620   }
5621 }
5622
5623 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5624                                                         CXXRecordDecl *Class) {
5625   // Only the MS ABI has default constructor closures, so we don't need to do
5626   // this semantic checking anywhere else.
5627   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5628     return;
5629
5630   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5631   for (Decl *Member : Class->decls()) {
5632     // Look for exported default constructors.
5633     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5634     if (!CD || !CD->isDefaultConstructor())
5635       continue;
5636     auto *Attr = CD->getAttr<DLLExportAttr>();
5637     if (!Attr)
5638       continue;
5639
5640     // If the class is non-dependent, mark the default arguments as ODR-used so
5641     // that we can properly codegen the constructor closure.
5642     if (!Class->isDependentContext()) {
5643       for (ParmVarDecl *PD : CD->parameters()) {
5644         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5645         S.DiscardCleanupsInEvaluationContext();
5646       }
5647     }
5648
5649     if (LastExportedDefaultCtor) {
5650       S.Diag(LastExportedDefaultCtor->getLocation(),
5651              diag::err_attribute_dll_ambiguous_default_ctor)
5652           << Class;
5653       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5654           << CD->getDeclName();
5655       return;
5656     }
5657     LastExportedDefaultCtor = CD;
5658   }
5659 }
5660
5661 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5662   // Mark any compiler-generated routines with the implicit code_seg attribute.
5663   for (auto *Method : Class->methods()) {
5664     if (Method->isUserProvided())
5665       continue;
5666     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5667       Method->addAttr(A);
5668   }
5669 }
5670
5671 /// Check class-level dllimport/dllexport attribute.
5672 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5673   Attr *ClassAttr = getDLLAttr(Class);
5674
5675   // MSVC inherits DLL attributes to partial class template specializations.
5676   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5677     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5678       if (Attr *TemplateAttr =
5679               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5680         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5681         A->setInherited(true);
5682         ClassAttr = A;
5683       }
5684     }
5685   }
5686
5687   if (!ClassAttr)
5688     return;
5689
5690   if (!Class->isExternallyVisible()) {
5691     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5692         << Class << ClassAttr;
5693     return;
5694   }
5695
5696   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5697       !ClassAttr->isInherited()) {
5698     // Diagnose dll attributes on members of class with dll attribute.
5699     for (Decl *Member : Class->decls()) {
5700       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5701         continue;
5702       InheritableAttr *MemberAttr = getDLLAttr(Member);
5703       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5704         continue;
5705
5706       Diag(MemberAttr->getLocation(),
5707              diag::err_attribute_dll_member_of_dll_class)
5708           << MemberAttr << ClassAttr;
5709       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5710       Member->setInvalidDecl();
5711     }
5712   }
5713
5714   if (Class->getDescribedClassTemplate())
5715     // Don't inherit dll attribute until the template is instantiated.
5716     return;
5717
5718   // The class is either imported or exported.
5719   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5720
5721   // Check if this was a dllimport attribute propagated from a derived class to
5722   // a base class template specialization. We don't apply these attributes to
5723   // static data members.
5724   const bool PropagatedImport =
5725       !ClassExported &&
5726       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5727
5728   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5729
5730   // Ignore explicit dllexport on explicit class template instantiation
5731   // declarations, except in MinGW mode.
5732   if (ClassExported && !ClassAttr->isInherited() &&
5733       TSK == TSK_ExplicitInstantiationDeclaration &&
5734       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
5735     Class->dropAttr<DLLExportAttr>();
5736     return;
5737   }
5738
5739   // Force declaration of implicit members so they can inherit the attribute.
5740   ForceDeclarationOfImplicitMembers(Class);
5741
5742   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5743   // seem to be true in practice?
5744
5745   for (Decl *Member : Class->decls()) {
5746     VarDecl *VD = dyn_cast<VarDecl>(Member);
5747     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5748
5749     // Only methods and static fields inherit the attributes.
5750     if (!VD && !MD)
5751       continue;
5752
5753     if (MD) {
5754       // Don't process deleted methods.
5755       if (MD->isDeleted())
5756         continue;
5757
5758       if (MD->isInlined()) {
5759         // MinGW does not import or export inline methods. But do it for
5760         // template instantiations.
5761         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5762             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
5763             TSK != TSK_ExplicitInstantiationDeclaration &&
5764             TSK != TSK_ExplicitInstantiationDefinition)
5765           continue;
5766
5767         // MSVC versions before 2015 don't export the move assignment operators
5768         // and move constructor, so don't attempt to import/export them if
5769         // we have a definition.
5770         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5771         if ((MD->isMoveAssignmentOperator() ||
5772              (Ctor && Ctor->isMoveConstructor())) &&
5773             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5774           continue;
5775
5776         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5777         // operator is exported anyway.
5778         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5779             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5780           continue;
5781       }
5782     }
5783
5784     // Don't apply dllimport attributes to static data members of class template
5785     // instantiations when the attribute is propagated from a derived class.
5786     if (VD && PropagatedImport)
5787       continue;
5788
5789     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5790       continue;
5791
5792     if (!getDLLAttr(Member)) {
5793       InheritableAttr *NewAttr = nullptr;
5794
5795       // Do not export/import inline function when -fno-dllexport-inlines is
5796       // passed. But add attribute for later local static var check.
5797       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5798           TSK != TSK_ExplicitInstantiationDeclaration &&
5799           TSK != TSK_ExplicitInstantiationDefinition) {
5800         if (ClassExported) {
5801           NewAttr = ::new (getASTContext())
5802             DLLExportStaticLocalAttr(ClassAttr->getRange(),
5803                                      getASTContext(),
5804                                      ClassAttr->getSpellingListIndex());
5805         } else {
5806           NewAttr = ::new (getASTContext())
5807             DLLImportStaticLocalAttr(ClassAttr->getRange(),
5808                                      getASTContext(),
5809                                      ClassAttr->getSpellingListIndex());
5810         }
5811       } else {
5812         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5813       }
5814
5815       NewAttr->setInherited(true);
5816       Member->addAttr(NewAttr);
5817
5818       if (MD) {
5819         // Propagate DLLAttr to friend re-declarations of MD that have already
5820         // been constructed.
5821         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5822              FD = FD->getPreviousDecl()) {
5823           if (FD->getFriendObjectKind() == Decl::FOK_None)
5824             continue;
5825           assert(!getDLLAttr(FD) &&
5826                  "friend re-decl should not already have a DLLAttr");
5827           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5828           NewAttr->setInherited(true);
5829           FD->addAttr(NewAttr);
5830         }
5831       }
5832     }
5833   }
5834
5835   if (ClassExported)
5836     DelayedDllExportClasses.push_back(Class);
5837 }
5838
5839 /// Perform propagation of DLL attributes from a derived class to a
5840 /// templated base class for MS compatibility.
5841 void Sema::propagateDLLAttrToBaseClassTemplate(
5842     CXXRecordDecl *Class, Attr *ClassAttr,
5843     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5844   if (getDLLAttr(
5845           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5846     // If the base class template has a DLL attribute, don't try to change it.
5847     return;
5848   }
5849
5850   auto TSK = BaseTemplateSpec->getSpecializationKind();
5851   if (!getDLLAttr(BaseTemplateSpec) &&
5852       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5853        TSK == TSK_ImplicitInstantiation)) {
5854     // The template hasn't been instantiated yet (or it has, but only as an
5855     // explicit instantiation declaration or implicit instantiation, which means
5856     // we haven't codegenned any members yet), so propagate the attribute.
5857     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5858     NewAttr->setInherited(true);
5859     BaseTemplateSpec->addAttr(NewAttr);
5860
5861     // If this was an import, mark that we propagated it from a derived class to
5862     // a base class template specialization.
5863     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5864       ImportAttr->setPropagatedToBaseTemplate();
5865
5866     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5867     // needs to be run again to work see the new attribute. Otherwise this will
5868     // get run whenever the template is instantiated.
5869     if (TSK != TSK_Undeclared)
5870       checkClassLevelDLLAttribute(BaseTemplateSpec);
5871
5872     return;
5873   }
5874
5875   if (getDLLAttr(BaseTemplateSpec)) {
5876     // The template has already been specialized or instantiated with an
5877     // attribute, explicitly or through propagation. We should not try to change
5878     // it.
5879     return;
5880   }
5881
5882   // The template was previously instantiated or explicitly specialized without
5883   // a dll attribute, It's too late for us to add an attribute, so warn that
5884   // this is unsupported.
5885   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5886       << BaseTemplateSpec->isExplicitSpecialization();
5887   Diag(ClassAttr->getLocation(), diag::note_attribute);
5888   if (BaseTemplateSpec->isExplicitSpecialization()) {
5889     Diag(BaseTemplateSpec->getLocation(),
5890            diag::note_template_class_explicit_specialization_was_here)
5891         << BaseTemplateSpec;
5892   } else {
5893     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5894            diag::note_template_class_instantiation_was_here)
5895         << BaseTemplateSpec;
5896   }
5897 }
5898
5899 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5900                                         SourceLocation DefaultLoc) {
5901   switch (S.getSpecialMember(MD)) {
5902   case Sema::CXXDefaultConstructor:
5903     S.DefineImplicitDefaultConstructor(DefaultLoc,
5904                                        cast<CXXConstructorDecl>(MD));
5905     break;
5906   case Sema::CXXCopyConstructor:
5907     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5908     break;
5909   case Sema::CXXCopyAssignment:
5910     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5911     break;
5912   case Sema::CXXDestructor:
5913     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5914     break;
5915   case Sema::CXXMoveConstructor:
5916     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5917     break;
5918   case Sema::CXXMoveAssignment:
5919     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5920     break;
5921   case Sema::CXXInvalid:
5922     llvm_unreachable("Invalid special member.");
5923   }
5924 }
5925
5926 /// Determine whether a type is permitted to be passed or returned in
5927 /// registers, per C++ [class.temporary]p3.
5928 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5929                                TargetInfo::CallingConvKind CCK) {
5930   if (D->isDependentType() || D->isInvalidDecl())
5931     return false;
5932
5933   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5934   // The PS4 platform ABI follows the behavior of Clang 3.2.
5935   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5936     return !D->hasNonTrivialDestructorForCall() &&
5937            !D->hasNonTrivialCopyConstructorForCall();
5938
5939   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
5940     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5941     bool DtorIsTrivialForCall = false;
5942
5943     // If a class has at least one non-deleted, trivial copy constructor, it
5944     // is passed according to the C ABI. Otherwise, it is passed indirectly.
5945     //
5946     // Note: This permits classes with non-trivial copy or move ctors to be
5947     // passed in registers, so long as they *also* have a trivial copy ctor,
5948     // which is non-conforming.
5949     if (D->needsImplicitCopyConstructor()) {
5950       if (!D->defaultedCopyConstructorIsDeleted()) {
5951         if (D->hasTrivialCopyConstructor())
5952           CopyCtorIsTrivial = true;
5953         if (D->hasTrivialCopyConstructorForCall())
5954           CopyCtorIsTrivialForCall = true;
5955       }
5956     } else {
5957       for (const CXXConstructorDecl *CD : D->ctors()) {
5958         if (CD->isCopyConstructor() && !CD->isDeleted()) {
5959           if (CD->isTrivial())
5960             CopyCtorIsTrivial = true;
5961           if (CD->isTrivialForCall())
5962             CopyCtorIsTrivialForCall = true;
5963         }
5964       }
5965     }
5966
5967     if (D->needsImplicitDestructor()) {
5968       if (!D->defaultedDestructorIsDeleted() &&
5969           D->hasTrivialDestructorForCall())
5970         DtorIsTrivialForCall = true;
5971     } else if (const auto *DD = D->getDestructor()) {
5972       if (!DD->isDeleted() && DD->isTrivialForCall())
5973         DtorIsTrivialForCall = true;
5974     }
5975
5976     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5977     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5978       return true;
5979
5980     // If a class has a destructor, we'd really like to pass it indirectly
5981     // because it allows us to elide copies.  Unfortunately, MSVC makes that
5982     // impossible for small types, which it will pass in a single register or
5983     // stack slot. Most objects with dtors are large-ish, so handle that early.
5984     // We can't call out all large objects as being indirect because there are
5985     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5986     // how we pass large POD types.
5987
5988     // Note: This permits small classes with nontrivial destructors to be
5989     // passed in registers, which is non-conforming.
5990     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5991     uint64_t TypeSize = isAArch64 ? 128 : 64;
5992
5993     if (CopyCtorIsTrivial &&
5994         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
5995       return true;
5996     return false;
5997   }
5998
5999   // Per C++ [class.temporary]p3, the relevant condition is:
6000   //   each copy constructor, move constructor, and destructor of X is
6001   //   either trivial or deleted, and X has at least one non-deleted copy
6002   //   or move constructor
6003   bool HasNonDeletedCopyOrMove = false;
6004
6005   if (D->needsImplicitCopyConstructor() &&
6006       !D->defaultedCopyConstructorIsDeleted()) {
6007     if (!D->hasTrivialCopyConstructorForCall())
6008       return false;
6009     HasNonDeletedCopyOrMove = true;
6010   }
6011
6012   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6013       !D->defaultedMoveConstructorIsDeleted()) {
6014     if (!D->hasTrivialMoveConstructorForCall())
6015       return false;
6016     HasNonDeletedCopyOrMove = true;
6017   }
6018
6019   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6020       !D->hasTrivialDestructorForCall())
6021     return false;
6022
6023   for (const CXXMethodDecl *MD : D->methods()) {
6024     if (MD->isDeleted())
6025       continue;
6026
6027     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6028     if (CD && CD->isCopyOrMoveConstructor())
6029       HasNonDeletedCopyOrMove = true;
6030     else if (!isa<CXXDestructorDecl>(MD))
6031       continue;
6032
6033     if (!MD->isTrivialForCall())
6034       return false;
6035   }
6036
6037   return HasNonDeletedCopyOrMove;
6038 }
6039
6040 /// Perform semantic checks on a class definition that has been
6041 /// completing, introducing implicitly-declared members, checking for
6042 /// abstract types, etc.
6043 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
6044   if (!Record)
6045     return;
6046
6047   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6048     AbstractUsageInfo Info(*this, Record);
6049     CheckAbstractClassUsage(Info, Record);
6050   }
6051
6052   // If this is not an aggregate type and has no user-declared constructor,
6053   // complain about any non-static data members of reference or const scalar
6054   // type, since they will never get initializers.
6055   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6056       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6057       !Record->isLambda()) {
6058     bool Complained = false;
6059     for (const auto *F : Record->fields()) {
6060       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6061         continue;
6062
6063       if (F->getType()->isReferenceType() ||
6064           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6065         if (!Complained) {
6066           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6067             << Record->getTagKind() << Record;
6068           Complained = true;
6069         }
6070
6071         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6072           << F->getType()->isReferenceType()
6073           << F->getDeclName();
6074       }
6075     }
6076   }
6077
6078   if (Record->getIdentifier()) {
6079     // C++ [class.mem]p13:
6080     //   If T is the name of a class, then each of the following shall have a
6081     //   name different from T:
6082     //     - every member of every anonymous union that is a member of class T.
6083     //
6084     // C++ [class.mem]p14:
6085     //   In addition, if class T has a user-declared constructor (12.1), every
6086     //   non-static data member of class T shall have a name different from T.
6087     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6088     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6089          ++I) {
6090       NamedDecl *D = (*I)->getUnderlyingDecl();
6091       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6092            Record->hasUserDeclaredConstructor()) ||
6093           isa<IndirectFieldDecl>(D)) {
6094         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6095           << D->getDeclName();
6096         break;
6097       }
6098     }
6099   }
6100
6101   // Warn if the class has virtual methods but non-virtual public destructor.
6102   if (Record->isPolymorphic() && !Record->isDependentType()) {
6103     CXXDestructorDecl *dtor = Record->getDestructor();
6104     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6105         !Record->hasAttr<FinalAttr>())
6106       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6107            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6108   }
6109
6110   if (Record->isAbstract()) {
6111     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6112       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6113         << FA->isSpelledAsSealed();
6114       DiagnoseAbstractType(Record);
6115     }
6116   }
6117
6118   // See if trivial_abi has to be dropped.
6119   if (Record->hasAttr<TrivialABIAttr>())
6120     checkIllFormedTrivialABIStruct(*Record);
6121
6122   // Set HasTrivialSpecialMemberForCall if the record has attribute
6123   // "trivial_abi".
6124   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6125
6126   if (HasTrivialABI)
6127     Record->setHasTrivialSpecialMemberForCall();
6128
6129   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6130     // Check whether the explicitly-defaulted special members are valid.
6131     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6132       CheckExplicitlyDefaultedSpecialMember(M);
6133
6134     // For an explicitly defaulted or deleted special member, we defer
6135     // determining triviality until the class is complete. That time is now!
6136     CXXSpecialMember CSM = getSpecialMember(M);
6137     if (!M->isImplicit() && !M->isUserProvided()) {
6138       if (CSM != CXXInvalid) {
6139         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6140         // Inform the class that we've finished declaring this member.
6141         Record->finishedDefaultedOrDeletedMember(M);
6142         M->setTrivialForCall(
6143             HasTrivialABI ||
6144             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6145         Record->setTrivialForCallFlags(M);
6146       }
6147     }
6148
6149     // Set triviality for the purpose of calls if this is a user-provided
6150     // copy/move constructor or destructor.
6151     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6152          CSM == CXXDestructor) && M->isUserProvided()) {
6153       M->setTrivialForCall(HasTrivialABI);
6154       Record->setTrivialForCallFlags(M);
6155     }
6156
6157     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6158         M->hasAttr<DLLExportAttr>()) {
6159       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6160           M->isTrivial() &&
6161           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6162            CSM == CXXDestructor))
6163         M->dropAttr<DLLExportAttr>();
6164
6165       if (M->hasAttr<DLLExportAttr>()) {
6166         // Define after any fields with in-class initializers have been parsed.
6167         DelayedDllExportMemberFunctions.push_back(M);
6168       }
6169     }
6170   };
6171
6172   bool HasMethodWithOverrideControl = false,
6173        HasOverridingMethodWithoutOverrideControl = false;
6174   if (!Record->isDependentType()) {
6175     // Check the destructor before any other member function. We need to
6176     // determine whether it's trivial in order to determine whether the claas
6177     // type is a literal type, which is a prerequisite for determining whether
6178     // other special member functions are valid and whether they're implicitly
6179     // 'constexpr'.
6180     if (CXXDestructorDecl *Dtor = Record->getDestructor())
6181       CompleteMemberFunction(Dtor);
6182
6183     for (auto *M : Record->methods()) {
6184       // See if a method overloads virtual methods in a base
6185       // class without overriding any.
6186       if (!M->isStatic())
6187         DiagnoseHiddenVirtualMethods(M);
6188       if (M->hasAttr<OverrideAttr>())
6189         HasMethodWithOverrideControl = true;
6190       else if (M->size_overridden_methods() > 0)
6191         HasOverridingMethodWithoutOverrideControl = true;
6192
6193       if (!isa<CXXDestructorDecl>(M))
6194         CompleteMemberFunction(M);
6195     }
6196   }
6197
6198   if (HasMethodWithOverrideControl &&
6199       HasOverridingMethodWithoutOverrideControl) {
6200     // At least one method has the 'override' control declared.
6201     // Diagnose all other overridden methods which do not have 'override' specified on them.
6202     for (auto *M : Record->methods())
6203       DiagnoseAbsenceOfOverrideControl(M);
6204   }
6205
6206   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6207   // whether this class uses any C++ features that are implemented
6208   // completely differently in MSVC, and if so, emit a diagnostic.
6209   // That diagnostic defaults to an error, but we allow projects to
6210   // map it down to a warning (or ignore it).  It's a fairly common
6211   // practice among users of the ms_struct pragma to mass-annotate
6212   // headers, sweeping up a bunch of types that the project doesn't
6213   // really rely on MSVC-compatible layout for.  We must therefore
6214   // support "ms_struct except for C++ stuff" as a secondary ABI.
6215   if (Record->isMsStruct(Context) &&
6216       (Record->isPolymorphic() || Record->getNumBases())) {
6217     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6218   }
6219
6220   checkClassLevelDLLAttribute(Record);
6221   checkClassLevelCodeSegAttribute(Record);
6222
6223   bool ClangABICompat4 =
6224       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6225   TargetInfo::CallingConvKind CCK =
6226       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6227   bool CanPass = canPassInRegisters(*this, Record, CCK);
6228
6229   // Do not change ArgPassingRestrictions if it has already been set to
6230   // APK_CanNeverPassInRegs.
6231   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6232     Record->setArgPassingRestrictions(CanPass
6233                                           ? RecordDecl::APK_CanPassInRegs
6234                                           : RecordDecl::APK_CannotPassInRegs);
6235
6236   // If canPassInRegisters returns true despite the record having a non-trivial
6237   // destructor, the record is destructed in the callee. This happens only when
6238   // the record or one of its subobjects has a field annotated with trivial_abi
6239   // or a field qualified with ObjC __strong/__weak.
6240   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6241     Record->setParamDestroyedInCallee(true);
6242   else if (Record->hasNonTrivialDestructor())
6243     Record->setParamDestroyedInCallee(CanPass);
6244
6245   if (getLangOpts().ForceEmitVTables) {
6246     // If we want to emit all the vtables, we need to mark it as used.  This
6247     // is especially required for cases like vtable assumption loads.
6248     MarkVTableUsed(Record->getInnerLocStart(), Record);
6249   }
6250 }
6251
6252 /// Look up the special member function that would be called by a special
6253 /// member function for a subobject of class type.
6254 ///
6255 /// \param Class The class type of the subobject.
6256 /// \param CSM The kind of special member function.
6257 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6258 /// \param ConstRHS True if this is a copy operation with a const object
6259 ///        on its RHS, that is, if the argument to the outer special member
6260 ///        function is 'const' and this is not a field marked 'mutable'.
6261 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6262     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6263     unsigned FieldQuals, bool ConstRHS) {
6264   unsigned LHSQuals = 0;
6265   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6266     LHSQuals = FieldQuals;
6267
6268   unsigned RHSQuals = FieldQuals;
6269   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6270     RHSQuals = 0;
6271   else if (ConstRHS)
6272     RHSQuals |= Qualifiers::Const;
6273
6274   return S.LookupSpecialMember(Class, CSM,
6275                                RHSQuals & Qualifiers::Const,
6276                                RHSQuals & Qualifiers::Volatile,
6277                                false,
6278                                LHSQuals & Qualifiers::Const,
6279                                LHSQuals & Qualifiers::Volatile);
6280 }
6281
6282 class Sema::InheritedConstructorInfo {
6283   Sema &S;
6284   SourceLocation UseLoc;
6285
6286   /// A mapping from the base classes through which the constructor was
6287   /// inherited to the using shadow declaration in that base class (or a null
6288   /// pointer if the constructor was declared in that base class).
6289   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6290       InheritedFromBases;
6291
6292 public:
6293   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6294                            ConstructorUsingShadowDecl *Shadow)
6295       : S(S), UseLoc(UseLoc) {
6296     bool DiagnosedMultipleConstructedBases = false;
6297     CXXRecordDecl *ConstructedBase = nullptr;
6298     UsingDecl *ConstructedBaseUsing = nullptr;
6299
6300     // Find the set of such base class subobjects and check that there's a
6301     // unique constructed subobject.
6302     for (auto *D : Shadow->redecls()) {
6303       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6304       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6305       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6306
6307       InheritedFromBases.insert(
6308           std::make_pair(DNominatedBase->getCanonicalDecl(),
6309                          DShadow->getNominatedBaseClassShadowDecl()));
6310       if (DShadow->constructsVirtualBase())
6311         InheritedFromBases.insert(
6312             std::make_pair(DConstructedBase->getCanonicalDecl(),
6313                            DShadow->getConstructedBaseClassShadowDecl()));
6314       else
6315         assert(DNominatedBase == DConstructedBase);
6316
6317       // [class.inhctor.init]p2:
6318       //   If the constructor was inherited from multiple base class subobjects
6319       //   of type B, the program is ill-formed.
6320       if (!ConstructedBase) {
6321         ConstructedBase = DConstructedBase;
6322         ConstructedBaseUsing = D->getUsingDecl();
6323       } else if (ConstructedBase != DConstructedBase &&
6324                  !Shadow->isInvalidDecl()) {
6325         if (!DiagnosedMultipleConstructedBases) {
6326           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6327               << Shadow->getTargetDecl();
6328           S.Diag(ConstructedBaseUsing->getLocation(),
6329                diag::note_ambiguous_inherited_constructor_using)
6330               << ConstructedBase;
6331           DiagnosedMultipleConstructedBases = true;
6332         }
6333         S.Diag(D->getUsingDecl()->getLocation(),
6334                diag::note_ambiguous_inherited_constructor_using)
6335             << DConstructedBase;
6336       }
6337     }
6338
6339     if (DiagnosedMultipleConstructedBases)
6340       Shadow->setInvalidDecl();
6341   }
6342
6343   /// Find the constructor to use for inherited construction of a base class,
6344   /// and whether that base class constructor inherits the constructor from a
6345   /// virtual base class (in which case it won't actually invoke it).
6346   std::pair<CXXConstructorDecl *, bool>
6347   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6348     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6349     if (It == InheritedFromBases.end())
6350       return std::make_pair(nullptr, false);
6351
6352     // This is an intermediary class.
6353     if (It->second)
6354       return std::make_pair(
6355           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6356           It->second->constructsVirtualBase());
6357
6358     // This is the base class from which the constructor was inherited.
6359     return std::make_pair(Ctor, false);
6360   }
6361 };
6362
6363 /// Is the special member function which would be selected to perform the
6364 /// specified operation on the specified class type a constexpr constructor?
6365 static bool
6366 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6367                          Sema::CXXSpecialMember CSM, unsigned Quals,
6368                          bool ConstRHS,
6369                          CXXConstructorDecl *InheritedCtor = nullptr,
6370                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6371   // If we're inheriting a constructor, see if we need to call it for this base
6372   // class.
6373   if (InheritedCtor) {
6374     assert(CSM == Sema::CXXDefaultConstructor);
6375     auto BaseCtor =
6376         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6377     if (BaseCtor)
6378       return BaseCtor->isConstexpr();
6379   }
6380
6381   if (CSM == Sema::CXXDefaultConstructor)
6382     return ClassDecl->hasConstexprDefaultConstructor();
6383
6384   Sema::SpecialMemberOverloadResult SMOR =
6385       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6386   if (!SMOR.getMethod())
6387     // A constructor we wouldn't select can't be "involved in initializing"
6388     // anything.
6389     return true;
6390   return SMOR.getMethod()->isConstexpr();
6391 }
6392
6393 /// Determine whether the specified special member function would be constexpr
6394 /// if it were implicitly defined.
6395 static bool defaultedSpecialMemberIsConstexpr(
6396     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6397     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6398     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6399   if (!S.getLangOpts().CPlusPlus11)
6400     return false;
6401
6402   // C++11 [dcl.constexpr]p4:
6403   // In the definition of a constexpr constructor [...]
6404   bool Ctor = true;
6405   switch (CSM) {
6406   case Sema::CXXDefaultConstructor:
6407     if (Inherited)
6408       break;
6409     // Since default constructor lookup is essentially trivial (and cannot
6410     // involve, for instance, template instantiation), we compute whether a
6411     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6412     //
6413     // This is important for performance; we need to know whether the default
6414     // constructor is constexpr to determine whether the type is a literal type.
6415     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6416
6417   case Sema::CXXCopyConstructor:
6418   case Sema::CXXMoveConstructor:
6419     // For copy or move constructors, we need to perform overload resolution.
6420     break;
6421
6422   case Sema::CXXCopyAssignment:
6423   case Sema::CXXMoveAssignment:
6424     if (!S.getLangOpts().CPlusPlus14)
6425       return false;
6426     // In C++1y, we need to perform overload resolution.
6427     Ctor = false;
6428     break;
6429
6430   case Sema::CXXDestructor:
6431   case Sema::CXXInvalid:
6432     return false;
6433   }
6434
6435   //   -- if the class is a non-empty union, or for each non-empty anonymous
6436   //      union member of a non-union class, exactly one non-static data member
6437   //      shall be initialized; [DR1359]
6438   //
6439   // If we squint, this is guaranteed, since exactly one non-static data member
6440   // will be initialized (if the constructor isn't deleted), we just don't know
6441   // which one.
6442   if (Ctor && ClassDecl->isUnion())
6443     return CSM == Sema::CXXDefaultConstructor
6444                ? ClassDecl->hasInClassInitializer() ||
6445                      !ClassDecl->hasVariantMembers()
6446                : true;
6447
6448   //   -- the class shall not have any virtual base classes;
6449   if (Ctor && ClassDecl->getNumVBases())
6450     return false;
6451
6452   // C++1y [class.copy]p26:
6453   //   -- [the class] is a literal type, and
6454   if (!Ctor && !ClassDecl->isLiteral())
6455     return false;
6456
6457   //   -- every constructor involved in initializing [...] base class
6458   //      sub-objects shall be a constexpr constructor;
6459   //   -- the assignment operator selected to copy/move each direct base
6460   //      class is a constexpr function, and
6461   for (const auto &B : ClassDecl->bases()) {
6462     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6463     if (!BaseType) continue;
6464
6465     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6466     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6467                                   InheritedCtor, Inherited))
6468       return false;
6469   }
6470
6471   //   -- every constructor involved in initializing non-static data members
6472   //      [...] shall be a constexpr constructor;
6473   //   -- every non-static data member and base class sub-object shall be
6474   //      initialized
6475   //   -- for each non-static data member of X that is of class type (or array
6476   //      thereof), the assignment operator selected to copy/move that member is
6477   //      a constexpr function
6478   for (const auto *F : ClassDecl->fields()) {
6479     if (F->isInvalidDecl())
6480       continue;
6481     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6482       continue;
6483     QualType BaseType = S.Context.getBaseElementType(F->getType());
6484     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6485       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6486       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6487                                     BaseType.getCVRQualifiers(),
6488                                     ConstArg && !F->isMutable()))
6489         return false;
6490     } else if (CSM == Sema::CXXDefaultConstructor) {
6491       return false;
6492     }
6493   }
6494
6495   // All OK, it's constexpr!
6496   return true;
6497 }
6498
6499 static Sema::ImplicitExceptionSpecification
6500 ComputeDefaultedSpecialMemberExceptionSpec(
6501     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6502     Sema::InheritedConstructorInfo *ICI);
6503
6504 static Sema::ImplicitExceptionSpecification
6505 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6506   auto CSM = S.getSpecialMember(MD);
6507   if (CSM != Sema::CXXInvalid)
6508     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6509
6510   auto *CD = cast<CXXConstructorDecl>(MD);
6511   assert(CD->getInheritedConstructor() &&
6512          "only special members have implicit exception specs");
6513   Sema::InheritedConstructorInfo ICI(
6514       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6515   return ComputeDefaultedSpecialMemberExceptionSpec(
6516       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6517 }
6518
6519 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6520                                                             CXXMethodDecl *MD) {
6521   FunctionProtoType::ExtProtoInfo EPI;
6522
6523   // Build an exception specification pointing back at this member.
6524   EPI.ExceptionSpec.Type = EST_Unevaluated;
6525   EPI.ExceptionSpec.SourceDecl = MD;
6526
6527   // Set the calling convention to the default for C++ instance methods.
6528   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6529       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6530                                             /*IsCXXMethod=*/true));
6531   return EPI;
6532 }
6533
6534 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6535   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6536   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6537     return;
6538
6539   // Evaluate the exception specification.
6540   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6541   auto ESI = IES.getExceptionSpec();
6542
6543   // Update the type of the special member to use it.
6544   UpdateExceptionSpec(MD, ESI);
6545
6546   // A user-provided destructor can be defined outside the class. When that
6547   // happens, be sure to update the exception specification on both
6548   // declarations.
6549   const FunctionProtoType *CanonicalFPT =
6550     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6551   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6552     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6553 }
6554
6555 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6556   CXXRecordDecl *RD = MD->getParent();
6557   CXXSpecialMember CSM = getSpecialMember(MD);
6558
6559   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6560          "not an explicitly-defaulted special member");
6561
6562   // Whether this was the first-declared instance of the constructor.
6563   // This affects whether we implicitly add an exception spec and constexpr.
6564   bool First = MD == MD->getCanonicalDecl();
6565
6566   bool HadError = false;
6567
6568   // C++11 [dcl.fct.def.default]p1:
6569   //   A function that is explicitly defaulted shall
6570   //     -- be a special member function (checked elsewhere),
6571   //     -- have the same type (except for ref-qualifiers, and except that a
6572   //        copy operation can take a non-const reference) as an implicit
6573   //        declaration, and
6574   //     -- not have default arguments.
6575   // C++2a changes the second bullet to instead delete the function if it's
6576   // defaulted on its first declaration, unless it's "an assignment operator,
6577   // and its return type differs or its parameter type is not a reference".
6578   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6579   bool ShouldDeleteForTypeMismatch = false;
6580   unsigned ExpectedParams = 1;
6581   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6582     ExpectedParams = 0;
6583   if (MD->getNumParams() != ExpectedParams) {
6584     // This checks for default arguments: a copy or move constructor with a
6585     // default argument is classified as a default constructor, and assignment
6586     // operations and destructors can't have default arguments.
6587     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6588       << CSM << MD->getSourceRange();
6589     HadError = true;
6590   } else if (MD->isVariadic()) {
6591     if (DeleteOnTypeMismatch)
6592       ShouldDeleteForTypeMismatch = true;
6593     else {
6594       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6595         << CSM << MD->getSourceRange();
6596       HadError = true;
6597     }
6598   }
6599
6600   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6601
6602   bool CanHaveConstParam = false;
6603   if (CSM == CXXCopyConstructor)
6604     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6605   else if (CSM == CXXCopyAssignment)
6606     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6607
6608   QualType ReturnType = Context.VoidTy;
6609   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6610     // Check for return type matching.
6611     ReturnType = Type->getReturnType();
6612
6613     QualType DeclType = Context.getTypeDeclType(RD);
6614     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
6615     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
6616
6617     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6618       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6619         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6620       HadError = true;
6621     }
6622
6623     // A defaulted special member cannot have cv-qualifiers.
6624     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
6625       if (DeleteOnTypeMismatch)
6626         ShouldDeleteForTypeMismatch = true;
6627       else {
6628         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6629           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6630         HadError = true;
6631       }
6632     }
6633   }
6634
6635   // Check for parameter type matching.
6636   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6637   bool HasConstParam = false;
6638   if (ExpectedParams && ArgType->isReferenceType()) {
6639     // Argument must be reference to possibly-const T.
6640     QualType ReferentType = ArgType->getPointeeType();
6641     HasConstParam = ReferentType.isConstQualified();
6642
6643     if (ReferentType.isVolatileQualified()) {
6644       if (DeleteOnTypeMismatch)
6645         ShouldDeleteForTypeMismatch = true;
6646       else {
6647         Diag(MD->getLocation(),
6648              diag::err_defaulted_special_member_volatile_param) << CSM;
6649         HadError = true;
6650       }
6651     }
6652
6653     if (HasConstParam && !CanHaveConstParam) {
6654       if (DeleteOnTypeMismatch)
6655         ShouldDeleteForTypeMismatch = true;
6656       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6657         Diag(MD->getLocation(),
6658              diag::err_defaulted_special_member_copy_const_param)
6659           << (CSM == CXXCopyAssignment);
6660         // FIXME: Explain why this special member can't be const.
6661         HadError = true;
6662       } else {
6663         Diag(MD->getLocation(),
6664              diag::err_defaulted_special_member_move_const_param)
6665           << (CSM == CXXMoveAssignment);
6666         HadError = true;
6667       }
6668     }
6669   } else if (ExpectedParams) {
6670     // A copy assignment operator can take its argument by value, but a
6671     // defaulted one cannot.
6672     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6673     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6674     HadError = true;
6675   }
6676
6677   // C++11 [dcl.fct.def.default]p2:
6678   //   An explicitly-defaulted function may be declared constexpr only if it
6679   //   would have been implicitly declared as constexpr,
6680   // Do not apply this rule to members of class templates, since core issue 1358
6681   // makes such functions always instantiate to constexpr functions. For
6682   // functions which cannot be constexpr (for non-constructors in C++11 and for
6683   // destructors in C++1y), this is checked elsewhere.
6684   //
6685   // FIXME: This should not apply if the member is deleted.
6686   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6687                                                      HasConstParam);
6688   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6689                                  : isa<CXXConstructorDecl>(MD)) &&
6690       MD->isConstexpr() && !Constexpr &&
6691       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6692     Diag(MD->getBeginLoc(), MD->isConsteval()
6693                                 ? diag::err_incorrect_defaulted_consteval
6694                                 : diag::err_incorrect_defaulted_constexpr)
6695         << CSM;
6696     // FIXME: Explain why the special member can't be constexpr.
6697     HadError = true;
6698   }
6699
6700   if (First) {
6701     // C++2a [dcl.fct.def.default]p3:
6702     //   If a function is explicitly defaulted on its first declaration, it is
6703     //   implicitly considered to be constexpr if the implicit declaration
6704     //   would be.
6705     MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified);
6706
6707     if (!Type->hasExceptionSpec()) {
6708       // C++2a [except.spec]p3:
6709       //   If a declaration of a function does not have a noexcept-specifier
6710       //   [and] is defaulted on its first declaration, [...] the exception
6711       //   specification is as specified below
6712       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6713       EPI.ExceptionSpec.Type = EST_Unevaluated;
6714       EPI.ExceptionSpec.SourceDecl = MD;
6715       MD->setType(Context.getFunctionType(ReturnType,
6716                                           llvm::makeArrayRef(&ArgType,
6717                                                              ExpectedParams),
6718                                           EPI));
6719     }
6720   }
6721
6722   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6723     if (First) {
6724       SetDeclDeleted(MD, MD->getLocation());
6725       if (!inTemplateInstantiation() && !HadError) {
6726         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6727         if (ShouldDeleteForTypeMismatch) {
6728           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6729         } else {
6730           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6731         }
6732       }
6733       if (ShouldDeleteForTypeMismatch && !HadError) {
6734         Diag(MD->getLocation(),
6735              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6736       }
6737     } else {
6738       // C++11 [dcl.fct.def.default]p4:
6739       //   [For a] user-provided explicitly-defaulted function [...] if such a
6740       //   function is implicitly defined as deleted, the program is ill-formed.
6741       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6742       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
6743       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6744       HadError = true;
6745     }
6746   }
6747
6748   if (HadError)
6749     MD->setInvalidDecl();
6750 }
6751
6752 void Sema::CheckDelayedMemberExceptionSpecs() {
6753   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6754   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6755
6756   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6757   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6758
6759   // Perform any deferred checking of exception specifications for virtual
6760   // destructors.
6761   for (auto &Check : Overriding)
6762     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6763
6764   // Perform any deferred checking of exception specifications for befriended
6765   // special members.
6766   for (auto &Check : Equivalent)
6767     CheckEquivalentExceptionSpec(Check.second, Check.first);
6768 }
6769
6770 namespace {
6771 /// CRTP base class for visiting operations performed by a special member
6772 /// function (or inherited constructor).
6773 template<typename Derived>
6774 struct SpecialMemberVisitor {
6775   Sema &S;
6776   CXXMethodDecl *MD;
6777   Sema::CXXSpecialMember CSM;
6778   Sema::InheritedConstructorInfo *ICI;
6779
6780   // Properties of the special member, computed for convenience.
6781   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6782
6783   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6784                        Sema::InheritedConstructorInfo *ICI)
6785       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6786     switch (CSM) {
6787     case Sema::CXXDefaultConstructor:
6788     case Sema::CXXCopyConstructor:
6789     case Sema::CXXMoveConstructor:
6790       IsConstructor = true;
6791       break;
6792     case Sema::CXXCopyAssignment:
6793     case Sema::CXXMoveAssignment:
6794       IsAssignment = true;
6795       break;
6796     case Sema::CXXDestructor:
6797       break;
6798     case Sema::CXXInvalid:
6799       llvm_unreachable("invalid special member kind");
6800     }
6801
6802     if (MD->getNumParams()) {
6803       if (const ReferenceType *RT =
6804               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6805         ConstArg = RT->getPointeeType().isConstQualified();
6806     }
6807   }
6808
6809   Derived &getDerived() { return static_cast<Derived&>(*this); }
6810
6811   /// Is this a "move" special member?
6812   bool isMove() const {
6813     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6814   }
6815
6816   /// Look up the corresponding special member in the given class.
6817   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6818                                              unsigned Quals, bool IsMutable) {
6819     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6820                                        ConstArg && !IsMutable);
6821   }
6822
6823   /// Look up the constructor for the specified base class to see if it's
6824   /// overridden due to this being an inherited constructor.
6825   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6826     if (!ICI)
6827       return {};
6828     assert(CSM == Sema::CXXDefaultConstructor);
6829     auto *BaseCtor =
6830       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6831     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6832       return MD;
6833     return {};
6834   }
6835
6836   /// A base or member subobject.
6837   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6838
6839   /// Get the location to use for a subobject in diagnostics.
6840   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6841     // FIXME: For an indirect virtual base, the direct base leading to
6842     // the indirect virtual base would be a more useful choice.
6843     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6844       return B->getBaseTypeLoc();
6845     else
6846       return Subobj.get<FieldDecl*>()->getLocation();
6847   }
6848
6849   enum BasesToVisit {
6850     /// Visit all non-virtual (direct) bases.
6851     VisitNonVirtualBases,
6852     /// Visit all direct bases, virtual or not.
6853     VisitDirectBases,
6854     /// Visit all non-virtual bases, and all virtual bases if the class
6855     /// is not abstract.
6856     VisitPotentiallyConstructedBases,
6857     /// Visit all direct or virtual bases.
6858     VisitAllBases
6859   };
6860
6861   // Visit the bases and members of the class.
6862   bool visit(BasesToVisit Bases) {
6863     CXXRecordDecl *RD = MD->getParent();
6864
6865     if (Bases == VisitPotentiallyConstructedBases)
6866       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6867
6868     for (auto &B : RD->bases())
6869       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6870           getDerived().visitBase(&B))
6871         return true;
6872
6873     if (Bases == VisitAllBases)
6874       for (auto &B : RD->vbases())
6875         if (getDerived().visitBase(&B))
6876           return true;
6877
6878     for (auto *F : RD->fields())
6879       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6880           getDerived().visitField(F))
6881         return true;
6882
6883     return false;
6884   }
6885 };
6886 }
6887
6888 namespace {
6889 struct SpecialMemberDeletionInfo
6890     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6891   bool Diagnose;
6892
6893   SourceLocation Loc;
6894
6895   bool AllFieldsAreConst;
6896
6897   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6898                             Sema::CXXSpecialMember CSM,
6899                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6900       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6901         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6902
6903   bool inUnion() const { return MD->getParent()->isUnion(); }
6904
6905   Sema::CXXSpecialMember getEffectiveCSM() {
6906     return ICI ? Sema::CXXInvalid : CSM;
6907   }
6908
6909   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
6910
6911   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6912   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6913
6914   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6915   bool shouldDeleteForField(FieldDecl *FD);
6916   bool shouldDeleteForAllConstMembers();
6917
6918   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6919                                      unsigned Quals);
6920   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6921                                     Sema::SpecialMemberOverloadResult SMOR,
6922                                     bool IsDtorCallInCtor);
6923
6924   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6925 };
6926 }
6927
6928 /// Is the given special member inaccessible when used on the given
6929 /// sub-object.
6930 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6931                                              CXXMethodDecl *target) {
6932   /// If we're operating on a base class, the object type is the
6933   /// type of this special member.
6934   QualType objectTy;
6935   AccessSpecifier access = target->getAccess();
6936   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6937     objectTy = S.Context.getTypeDeclType(MD->getParent());
6938     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6939
6940   // If we're operating on a field, the object type is the type of the field.
6941   } else {
6942     objectTy = S.Context.getTypeDeclType(target->getParent());
6943   }
6944
6945   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6946 }
6947
6948 /// Check whether we should delete a special member due to the implicit
6949 /// definition containing a call to a special member of a subobject.
6950 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6951     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6952     bool IsDtorCallInCtor) {
6953   CXXMethodDecl *Decl = SMOR.getMethod();
6954   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6955
6956   int DiagKind = -1;
6957
6958   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6959     DiagKind = !Decl ? 0 : 1;
6960   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6961     DiagKind = 2;
6962   else if (!isAccessible(Subobj, Decl))
6963     DiagKind = 3;
6964   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6965            !Decl->isTrivial()) {
6966     // A member of a union must have a trivial corresponding special member.
6967     // As a weird special case, a destructor call from a union's constructor
6968     // must be accessible and non-deleted, but need not be trivial. Such a
6969     // destructor is never actually called, but is semantically checked as
6970     // if it were.
6971     DiagKind = 4;
6972   }
6973
6974   if (DiagKind == -1)
6975     return false;
6976
6977   if (Diagnose) {
6978     if (Field) {
6979       S.Diag(Field->getLocation(),
6980              diag::note_deleted_special_member_class_subobject)
6981         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6982         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
6983     } else {
6984       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6985       S.Diag(Base->getBeginLoc(),
6986              diag::note_deleted_special_member_class_subobject)
6987           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6988           << Base->getType() << DiagKind << IsDtorCallInCtor
6989           << /*IsObjCPtr*/false;
6990     }
6991
6992     if (DiagKind == 1)
6993       S.NoteDeletedFunction(Decl);
6994     // FIXME: Explain inaccessibility if DiagKind == 3.
6995   }
6996
6997   return true;
6998 }
6999
7000 /// Check whether we should delete a special member function due to having a
7001 /// direct or virtual base class or non-static data member of class type M.
7002 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
7003     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
7004   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
7005   bool IsMutable = Field && Field->isMutable();
7006
7007   // C++11 [class.ctor]p5:
7008   // -- any direct or virtual base class, or non-static data member with no
7009   //    brace-or-equal-initializer, has class type M (or array thereof) and
7010   //    either M has no default constructor or overload resolution as applied
7011   //    to M's default constructor results in an ambiguity or in a function
7012   //    that is deleted or inaccessible
7013   // C++11 [class.copy]p11, C++11 [class.copy]p23:
7014   // -- a direct or virtual base class B that cannot be copied/moved because
7015   //    overload resolution, as applied to B's corresponding special member,
7016   //    results in an ambiguity or a function that is deleted or inaccessible
7017   //    from the defaulted special member
7018   // C++11 [class.dtor]p5:
7019   // -- any direct or virtual base class [...] has a type with a destructor
7020   //    that is deleted or inaccessible
7021   if (!(CSM == Sema::CXXDefaultConstructor &&
7022         Field && Field->hasInClassInitializer()) &&
7023       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
7024                                    false))
7025     return true;
7026
7027   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
7028   // -- any direct or virtual base class or non-static data member has a
7029   //    type with a destructor that is deleted or inaccessible
7030   if (IsConstructor) {
7031     Sema::SpecialMemberOverloadResult SMOR =
7032         S.LookupSpecialMember(Class, Sema::CXXDestructor,
7033                               false, false, false, false, false);
7034     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
7035       return true;
7036   }
7037
7038   return false;
7039 }
7040
7041 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
7042     FieldDecl *FD, QualType FieldType) {
7043   // The defaulted special functions are defined as deleted if this is a variant
7044   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
7045   // type under ARC.
7046   if (!FieldType.hasNonTrivialObjCLifetime())
7047     return false;
7048
7049   // Don't make the defaulted default constructor defined as deleted if the
7050   // member has an in-class initializer.
7051   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
7052     return false;
7053
7054   if (Diagnose) {
7055     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
7056     S.Diag(FD->getLocation(),
7057            diag::note_deleted_special_member_class_subobject)
7058         << getEffectiveCSM() << ParentClass << /*IsField*/true
7059         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
7060   }
7061
7062   return true;
7063 }
7064
7065 /// Check whether we should delete a special member function due to the class
7066 /// having a particular direct or virtual base class.
7067 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
7068   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
7069   // If program is correct, BaseClass cannot be null, but if it is, the error
7070   // must be reported elsewhere.
7071   if (!BaseClass)
7072     return false;
7073   // If we have an inheriting constructor, check whether we're calling an
7074   // inherited constructor instead of a default constructor.
7075   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
7076   if (auto *BaseCtor = SMOR.getMethod()) {
7077     // Note that we do not check access along this path; other than that,
7078     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
7079     // FIXME: Check that the base has a usable destructor! Sink this into
7080     // shouldDeleteForClassSubobject.
7081     if (BaseCtor->isDeleted() && Diagnose) {
7082       S.Diag(Base->getBeginLoc(),
7083              diag::note_deleted_special_member_class_subobject)
7084           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7085           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
7086           << /*IsObjCPtr*/false;
7087       S.NoteDeletedFunction(BaseCtor);
7088     }
7089     return BaseCtor->isDeleted();
7090   }
7091   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7092 }
7093
7094 /// Check whether we should delete a special member function due to the class
7095 /// having a particular non-static data member.
7096 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7097   QualType FieldType = S.Context.getBaseElementType(FD->getType());
7098   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7099
7100   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
7101     return true;
7102
7103   if (CSM == Sema::CXXDefaultConstructor) {
7104     // For a default constructor, all references must be initialized in-class
7105     // and, if a union, it must have a non-const member.
7106     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7107       if (Diagnose)
7108         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7109           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7110       return true;
7111     }
7112     // C++11 [class.ctor]p5: any non-variant non-static data member of
7113     // const-qualified type (or array thereof) with no
7114     // brace-or-equal-initializer does not have a user-provided default
7115     // constructor.
7116     if (!inUnion() && FieldType.isConstQualified() &&
7117         !FD->hasInClassInitializer() &&
7118         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7119       if (Diagnose)
7120         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7121           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7122       return true;
7123     }
7124
7125     if (inUnion() && !FieldType.isConstQualified())
7126       AllFieldsAreConst = false;
7127   } else if (CSM == Sema::CXXCopyConstructor) {
7128     // For a copy constructor, data members must not be of rvalue reference
7129     // type.
7130     if (FieldType->isRValueReferenceType()) {
7131       if (Diagnose)
7132         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7133           << MD->getParent() << FD << FieldType;
7134       return true;
7135     }
7136   } else if (IsAssignment) {
7137     // For an assignment operator, data members must not be of reference type.
7138     if (FieldType->isReferenceType()) {
7139       if (Diagnose)
7140         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7141           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7142       return true;
7143     }
7144     if (!FieldRecord && FieldType.isConstQualified()) {
7145       // C++11 [class.copy]p23:
7146       // -- a non-static data member of const non-class type (or array thereof)
7147       if (Diagnose)
7148         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7149           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7150       return true;
7151     }
7152   }
7153
7154   if (FieldRecord) {
7155     // Some additional restrictions exist on the variant members.
7156     if (!inUnion() && FieldRecord->isUnion() &&
7157         FieldRecord->isAnonymousStructOrUnion()) {
7158       bool AllVariantFieldsAreConst = true;
7159
7160       // FIXME: Handle anonymous unions declared within anonymous unions.
7161       for (auto *UI : FieldRecord->fields()) {
7162         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7163
7164         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
7165           return true;
7166
7167         if (!UnionFieldType.isConstQualified())
7168           AllVariantFieldsAreConst = false;
7169
7170         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7171         if (UnionFieldRecord &&
7172             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7173                                           UnionFieldType.getCVRQualifiers()))
7174           return true;
7175       }
7176
7177       // At least one member in each anonymous union must be non-const
7178       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7179           !FieldRecord->field_empty()) {
7180         if (Diagnose)
7181           S.Diag(FieldRecord->getLocation(),
7182                  diag::note_deleted_default_ctor_all_const)
7183             << !!ICI << MD->getParent() << /*anonymous union*/1;
7184         return true;
7185       }
7186
7187       // Don't check the implicit member of the anonymous union type.
7188       // This is technically non-conformant, but sanity demands it.
7189       return false;
7190     }
7191
7192     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7193                                       FieldType.getCVRQualifiers()))
7194       return true;
7195   }
7196
7197   return false;
7198 }
7199
7200 /// C++11 [class.ctor] p5:
7201 ///   A defaulted default constructor for a class X is defined as deleted if
7202 /// X is a union and all of its variant members are of const-qualified type.
7203 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7204   // This is a silly definition, because it gives an empty union a deleted
7205   // default constructor. Don't do that.
7206   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7207     bool AnyFields = false;
7208     for (auto *F : MD->getParent()->fields())
7209       if ((AnyFields = !F->isUnnamedBitfield()))
7210         break;
7211     if (!AnyFields)
7212       return false;
7213     if (Diagnose)
7214       S.Diag(MD->getParent()->getLocation(),
7215              diag::note_deleted_default_ctor_all_const)
7216         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7217     return true;
7218   }
7219   return false;
7220 }
7221
7222 /// Determine whether a defaulted special member function should be defined as
7223 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7224 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7225 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7226                                      InheritedConstructorInfo *ICI,
7227                                      bool Diagnose) {
7228   if (MD->isInvalidDecl())
7229     return false;
7230   CXXRecordDecl *RD = MD->getParent();
7231   assert(!RD->isDependentType() && "do deletion after instantiation");
7232   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7233     return false;
7234
7235   // C++11 [expr.lambda.prim]p19:
7236   //   The closure type associated with a lambda-expression has a
7237   //   deleted (8.4.3) default constructor and a deleted copy
7238   //   assignment operator.
7239   // C++2a adds back these operators if the lambda has no lambda-capture.
7240   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7241       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7242     if (Diagnose)
7243       Diag(RD->getLocation(), diag::note_lambda_decl);
7244     return true;
7245   }
7246
7247   // For an anonymous struct or union, the copy and assignment special members
7248   // will never be used, so skip the check. For an anonymous union declared at
7249   // namespace scope, the constructor and destructor are used.
7250   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7251       RD->isAnonymousStructOrUnion())
7252     return false;
7253
7254   // C++11 [class.copy]p7, p18:
7255   //   If the class definition declares a move constructor or move assignment
7256   //   operator, an implicitly declared copy constructor or copy assignment
7257   //   operator is defined as deleted.
7258   if (MD->isImplicit() &&
7259       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7260     CXXMethodDecl *UserDeclaredMove = nullptr;
7261
7262     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7263     // deletion of the corresponding copy operation, not both copy operations.
7264     // MSVC 2015 has adopted the standards conforming behavior.
7265     bool DeletesOnlyMatchingCopy =
7266         getLangOpts().MSVCCompat &&
7267         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7268
7269     if (RD->hasUserDeclaredMoveConstructor() &&
7270         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7271       if (!Diagnose) return true;
7272
7273       // Find any user-declared move constructor.
7274       for (auto *I : RD->ctors()) {
7275         if (I->isMoveConstructor()) {
7276           UserDeclaredMove = I;
7277           break;
7278         }
7279       }
7280       assert(UserDeclaredMove);
7281     } else if (RD->hasUserDeclaredMoveAssignment() &&
7282                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7283       if (!Diagnose) return true;
7284
7285       // Find any user-declared move assignment operator.
7286       for (auto *I : RD->methods()) {
7287         if (I->isMoveAssignmentOperator()) {
7288           UserDeclaredMove = I;
7289           break;
7290         }
7291       }
7292       assert(UserDeclaredMove);
7293     }
7294
7295     if (UserDeclaredMove) {
7296       Diag(UserDeclaredMove->getLocation(),
7297            diag::note_deleted_copy_user_declared_move)
7298         << (CSM == CXXCopyAssignment) << RD
7299         << UserDeclaredMove->isMoveAssignmentOperator();
7300       return true;
7301     }
7302   }
7303
7304   // Do access control from the special member function
7305   ContextRAII MethodContext(*this, MD);
7306
7307   // C++11 [class.dtor]p5:
7308   // -- for a virtual destructor, lookup of the non-array deallocation function
7309   //    results in an ambiguity or in a function that is deleted or inaccessible
7310   if (CSM == CXXDestructor && MD->isVirtual()) {
7311     FunctionDecl *OperatorDelete = nullptr;
7312     DeclarationName Name =
7313       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7314     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7315                                  OperatorDelete, /*Diagnose*/false)) {
7316       if (Diagnose)
7317         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7318       return true;
7319     }
7320   }
7321
7322   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7323
7324   // Per DR1611, do not consider virtual bases of constructors of abstract
7325   // classes, since we are not going to construct them.
7326   // Per DR1658, do not consider virtual bases of destructors of abstract
7327   // classes either.
7328   // Per DR2180, for assignment operators we only assign (and thus only
7329   // consider) direct bases.
7330   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7331                                  : SMI.VisitPotentiallyConstructedBases))
7332     return true;
7333
7334   if (SMI.shouldDeleteForAllConstMembers())
7335     return true;
7336
7337   if (getLangOpts().CUDA) {
7338     // We should delete the special member in CUDA mode if target inference
7339     // failed.
7340     // For inherited constructors (non-null ICI), CSM may be passed so that MD
7341     // is treated as certain special member, which may not reflect what special
7342     // member MD really is. However inferCUDATargetForImplicitSpecialMember
7343     // expects CSM to match MD, therefore recalculate CSM.
7344     assert(ICI || CSM == getSpecialMember(MD));
7345     auto RealCSM = CSM;
7346     if (ICI)
7347       RealCSM = getSpecialMember(MD);
7348
7349     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7350                                                    SMI.ConstArg, Diagnose);
7351   }
7352
7353   return false;
7354 }
7355
7356 /// Perform lookup for a special member of the specified kind, and determine
7357 /// whether it is trivial. If the triviality can be determined without the
7358 /// lookup, skip it. This is intended for use when determining whether a
7359 /// special member of a containing object is trivial, and thus does not ever
7360 /// perform overload resolution for default constructors.
7361 ///
7362 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7363 /// member that was most likely to be intended to be trivial, if any.
7364 ///
7365 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7366 /// determine whether the special member is trivial.
7367 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7368                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7369                                      bool ConstRHS,
7370                                      Sema::TrivialABIHandling TAH,
7371                                      CXXMethodDecl **Selected) {
7372   if (Selected)
7373     *Selected = nullptr;
7374
7375   switch (CSM) {
7376   case Sema::CXXInvalid:
7377     llvm_unreachable("not a special member");
7378
7379   case Sema::CXXDefaultConstructor:
7380     // C++11 [class.ctor]p5:
7381     //   A default constructor is trivial if:
7382     //    - all the [direct subobjects] have trivial default constructors
7383     //
7384     // Note, no overload resolution is performed in this case.
7385     if (RD->hasTrivialDefaultConstructor())
7386       return true;
7387
7388     if (Selected) {
7389       // If there's a default constructor which could have been trivial, dig it
7390       // out. Otherwise, if there's any user-provided default constructor, point
7391       // to that as an example of why there's not a trivial one.
7392       CXXConstructorDecl *DefCtor = nullptr;
7393       if (RD->needsImplicitDefaultConstructor())
7394         S.DeclareImplicitDefaultConstructor(RD);
7395       for (auto *CI : RD->ctors()) {
7396         if (!CI->isDefaultConstructor())
7397           continue;
7398         DefCtor = CI;
7399         if (!DefCtor->isUserProvided())
7400           break;
7401       }
7402
7403       *Selected = DefCtor;
7404     }
7405
7406     return false;
7407
7408   case Sema::CXXDestructor:
7409     // C++11 [class.dtor]p5:
7410     //   A destructor is trivial if:
7411     //    - all the direct [subobjects] have trivial destructors
7412     if (RD->hasTrivialDestructor() ||
7413         (TAH == Sema::TAH_ConsiderTrivialABI &&
7414          RD->hasTrivialDestructorForCall()))
7415       return true;
7416
7417     if (Selected) {
7418       if (RD->needsImplicitDestructor())
7419         S.DeclareImplicitDestructor(RD);
7420       *Selected = RD->getDestructor();
7421     }
7422
7423     return false;
7424
7425   case Sema::CXXCopyConstructor:
7426     // C++11 [class.copy]p12:
7427     //   A copy constructor is trivial if:
7428     //    - the constructor selected to copy each direct [subobject] is trivial
7429     if (RD->hasTrivialCopyConstructor() ||
7430         (TAH == Sema::TAH_ConsiderTrivialABI &&
7431          RD->hasTrivialCopyConstructorForCall())) {
7432       if (Quals == Qualifiers::Const)
7433         // We must either select the trivial copy constructor or reach an
7434         // ambiguity; no need to actually perform overload resolution.
7435         return true;
7436     } else if (!Selected) {
7437       return false;
7438     }
7439     // In C++98, we are not supposed to perform overload resolution here, but we
7440     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7441     // cases like B as having a non-trivial copy constructor:
7442     //   struct A { template<typename T> A(T&); };
7443     //   struct B { mutable A a; };
7444     goto NeedOverloadResolution;
7445
7446   case Sema::CXXCopyAssignment:
7447     // C++11 [class.copy]p25:
7448     //   A copy assignment operator is trivial if:
7449     //    - the assignment operator selected to copy each direct [subobject] is
7450     //      trivial
7451     if (RD->hasTrivialCopyAssignment()) {
7452       if (Quals == Qualifiers::Const)
7453         return true;
7454     } else if (!Selected) {
7455       return false;
7456     }
7457     // In C++98, we are not supposed to perform overload resolution here, but we
7458     // treat that as a language defect.
7459     goto NeedOverloadResolution;
7460
7461   case Sema::CXXMoveConstructor:
7462   case Sema::CXXMoveAssignment:
7463   NeedOverloadResolution:
7464     Sema::SpecialMemberOverloadResult SMOR =
7465         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7466
7467     // The standard doesn't describe how to behave if the lookup is ambiguous.
7468     // We treat it as not making the member non-trivial, just like the standard
7469     // mandates for the default constructor. This should rarely matter, because
7470     // the member will also be deleted.
7471     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7472       return true;
7473
7474     if (!SMOR.getMethod()) {
7475       assert(SMOR.getKind() ==
7476              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7477       return false;
7478     }
7479
7480     // We deliberately don't check if we found a deleted special member. We're
7481     // not supposed to!
7482     if (Selected)
7483       *Selected = SMOR.getMethod();
7484
7485     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7486         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7487       return SMOR.getMethod()->isTrivialForCall();
7488     return SMOR.getMethod()->isTrivial();
7489   }
7490
7491   llvm_unreachable("unknown special method kind");
7492 }
7493
7494 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7495   for (auto *CI : RD->ctors())
7496     if (!CI->isImplicit())
7497       return CI;
7498
7499   // Look for constructor templates.
7500   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7501   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7502     if (CXXConstructorDecl *CD =
7503           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7504       return CD;
7505   }
7506
7507   return nullptr;
7508 }
7509
7510 /// The kind of subobject we are checking for triviality. The values of this
7511 /// enumeration are used in diagnostics.
7512 enum TrivialSubobjectKind {
7513   /// The subobject is a base class.
7514   TSK_BaseClass,
7515   /// The subobject is a non-static data member.
7516   TSK_Field,
7517   /// The object is actually the complete object.
7518   TSK_CompleteObject
7519 };
7520
7521 /// Check whether the special member selected for a given type would be trivial.
7522 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7523                                       QualType SubType, bool ConstRHS,
7524                                       Sema::CXXSpecialMember CSM,
7525                                       TrivialSubobjectKind Kind,
7526                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7527   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7528   if (!SubRD)
7529     return true;
7530
7531   CXXMethodDecl *Selected;
7532   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7533                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7534     return true;
7535
7536   if (Diagnose) {
7537     if (ConstRHS)
7538       SubType.addConst();
7539
7540     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7541       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7542         << Kind << SubType.getUnqualifiedType();
7543       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7544         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7545     } else if (!Selected)
7546       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7547         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7548     else if (Selected->isUserProvided()) {
7549       if (Kind == TSK_CompleteObject)
7550         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7551           << Kind << SubType.getUnqualifiedType() << CSM;
7552       else {
7553         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7554           << Kind << SubType.getUnqualifiedType() << CSM;
7555         S.Diag(Selected->getLocation(), diag::note_declared_at);
7556       }
7557     } else {
7558       if (Kind != TSK_CompleteObject)
7559         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7560           << Kind << SubType.getUnqualifiedType() << CSM;
7561
7562       // Explain why the defaulted or deleted special member isn't trivial.
7563       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7564                                Diagnose);
7565     }
7566   }
7567
7568   return false;
7569 }
7570
7571 /// Check whether the members of a class type allow a special member to be
7572 /// trivial.
7573 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7574                                      Sema::CXXSpecialMember CSM,
7575                                      bool ConstArg,
7576                                      Sema::TrivialABIHandling TAH,
7577                                      bool Diagnose) {
7578   for (const auto *FI : RD->fields()) {
7579     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7580       continue;
7581
7582     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7583
7584     // Pretend anonymous struct or union members are members of this class.
7585     if (FI->isAnonymousStructOrUnion()) {
7586       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7587                                     CSM, ConstArg, TAH, Diagnose))
7588         return false;
7589       continue;
7590     }
7591
7592     // C++11 [class.ctor]p5:
7593     //   A default constructor is trivial if [...]
7594     //    -- no non-static data member of its class has a
7595     //       brace-or-equal-initializer
7596     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7597       if (Diagnose)
7598         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7599       return false;
7600     }
7601
7602     // Objective C ARC 4.3.5:
7603     //   [...] nontrivally ownership-qualified types are [...] not trivially
7604     //   default constructible, copy constructible, move constructible, copy
7605     //   assignable, move assignable, or destructible [...]
7606     if (FieldType.hasNonTrivialObjCLifetime()) {
7607       if (Diagnose)
7608         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7609           << RD << FieldType.getObjCLifetime();
7610       return false;
7611     }
7612
7613     bool ConstRHS = ConstArg && !FI->isMutable();
7614     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7615                                    CSM, TSK_Field, TAH, Diagnose))
7616       return false;
7617   }
7618
7619   return true;
7620 }
7621
7622 /// Diagnose why the specified class does not have a trivial special member of
7623 /// the given kind.
7624 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7625   QualType Ty = Context.getRecordType(RD);
7626
7627   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7628   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7629                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7630                             /*Diagnose*/true);
7631 }
7632
7633 /// Determine whether a defaulted or deleted special member function is trivial,
7634 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7635 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7636 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7637                                   TrivialABIHandling TAH, bool Diagnose) {
7638   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7639
7640   CXXRecordDecl *RD = MD->getParent();
7641
7642   bool ConstArg = false;
7643
7644   // C++11 [class.copy]p12, p25: [DR1593]
7645   //   A [special member] is trivial if [...] its parameter-type-list is
7646   //   equivalent to the parameter-type-list of an implicit declaration [...]
7647   switch (CSM) {
7648   case CXXDefaultConstructor:
7649   case CXXDestructor:
7650     // Trivial default constructors and destructors cannot have parameters.
7651     break;
7652
7653   case CXXCopyConstructor:
7654   case CXXCopyAssignment: {
7655     // Trivial copy operations always have const, non-volatile parameter types.
7656     ConstArg = true;
7657     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7658     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7659     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7660       if (Diagnose)
7661         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7662           << Param0->getSourceRange() << Param0->getType()
7663           << Context.getLValueReferenceType(
7664                Context.getRecordType(RD).withConst());
7665       return false;
7666     }
7667     break;
7668   }
7669
7670   case CXXMoveConstructor:
7671   case CXXMoveAssignment: {
7672     // Trivial move operations always have non-cv-qualified parameters.
7673     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7674     const RValueReferenceType *RT =
7675       Param0->getType()->getAs<RValueReferenceType>();
7676     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7677       if (Diagnose)
7678         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7679           << Param0->getSourceRange() << Param0->getType()
7680           << Context.getRValueReferenceType(Context.getRecordType(RD));
7681       return false;
7682     }
7683     break;
7684   }
7685
7686   case CXXInvalid:
7687     llvm_unreachable("not a special member");
7688   }
7689
7690   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7691     if (Diagnose)
7692       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7693            diag::note_nontrivial_default_arg)
7694         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7695     return false;
7696   }
7697   if (MD->isVariadic()) {
7698     if (Diagnose)
7699       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7700     return false;
7701   }
7702
7703   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7704   //   A copy/move [constructor or assignment operator] is trivial if
7705   //    -- the [member] selected to copy/move each direct base class subobject
7706   //       is trivial
7707   //
7708   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7709   //   A [default constructor or destructor] is trivial if
7710   //    -- all the direct base classes have trivial [default constructors or
7711   //       destructors]
7712   for (const auto &BI : RD->bases())
7713     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7714                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7715       return false;
7716
7717   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7718   //   A copy/move [constructor or assignment operator] for a class X is
7719   //   trivial if
7720   //    -- for each non-static data member of X that is of class type (or array
7721   //       thereof), the constructor selected to copy/move that member is
7722   //       trivial
7723   //
7724   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7725   //   A [default constructor or destructor] is trivial if
7726   //    -- for all of the non-static data members of its class that are of class
7727   //       type (or array thereof), each such class has a trivial [default
7728   //       constructor or destructor]
7729   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7730     return false;
7731
7732   // C++11 [class.dtor]p5:
7733   //   A destructor is trivial if [...]
7734   //    -- the destructor is not virtual
7735   if (CSM == CXXDestructor && MD->isVirtual()) {
7736     if (Diagnose)
7737       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7738     return false;
7739   }
7740
7741   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7742   //   A [special member] for class X is trivial if [...]
7743   //    -- class X has no virtual functions and no virtual base classes
7744   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7745     if (!Diagnose)
7746       return false;
7747
7748     if (RD->getNumVBases()) {
7749       // Check for virtual bases. We already know that the corresponding
7750       // member in all bases is trivial, so vbases must all be direct.
7751       CXXBaseSpecifier &BS = *RD->vbases_begin();
7752       assert(BS.isVirtual());
7753       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7754       return false;
7755     }
7756
7757     // Must have a virtual method.
7758     for (const auto *MI : RD->methods()) {
7759       if (MI->isVirtual()) {
7760         SourceLocation MLoc = MI->getBeginLoc();
7761         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7762         return false;
7763       }
7764     }
7765
7766     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7767   }
7768
7769   // Looks like it's trivial!
7770   return true;
7771 }
7772
7773 namespace {
7774 struct FindHiddenVirtualMethod {
7775   Sema *S;
7776   CXXMethodDecl *Method;
7777   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7778   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7779
7780 private:
7781   /// Check whether any most overridden method from MD in Methods
7782   static bool CheckMostOverridenMethods(
7783       const CXXMethodDecl *MD,
7784       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7785     if (MD->size_overridden_methods() == 0)
7786       return Methods.count(MD->getCanonicalDecl());
7787     for (const CXXMethodDecl *O : MD->overridden_methods())
7788       if (CheckMostOverridenMethods(O, Methods))
7789         return true;
7790     return false;
7791   }
7792
7793 public:
7794   /// Member lookup function that determines whether a given C++
7795   /// method overloads virtual methods in a base class without overriding any,
7796   /// to be used with CXXRecordDecl::lookupInBases().
7797   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7798     RecordDecl *BaseRecord =
7799         Specifier->getType()->getAs<RecordType>()->getDecl();
7800
7801     DeclarationName Name = Method->getDeclName();
7802     assert(Name.getNameKind() == DeclarationName::Identifier);
7803
7804     bool foundSameNameMethod = false;
7805     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7806     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7807          Path.Decls = Path.Decls.slice(1)) {
7808       NamedDecl *D = Path.Decls.front();
7809       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7810         MD = MD->getCanonicalDecl();
7811         foundSameNameMethod = true;
7812         // Interested only in hidden virtual methods.
7813         if (!MD->isVirtual())
7814           continue;
7815         // If the method we are checking overrides a method from its base
7816         // don't warn about the other overloaded methods. Clang deviates from
7817         // GCC by only diagnosing overloads of inherited virtual functions that
7818         // do not override any other virtual functions in the base. GCC's
7819         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7820         // function from a base class. These cases may be better served by a
7821         // warning (not specific to virtual functions) on call sites when the
7822         // call would select a different function from the base class, were it
7823         // visible.
7824         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7825         if (!S->IsOverload(Method, MD, false))
7826           return true;
7827         // Collect the overload only if its hidden.
7828         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7829           overloadedMethods.push_back(MD);
7830       }
7831     }
7832
7833     if (foundSameNameMethod)
7834       OverloadedMethods.append(overloadedMethods.begin(),
7835                                overloadedMethods.end());
7836     return foundSameNameMethod;
7837   }
7838 };
7839 } // end anonymous namespace
7840
7841 /// Add the most overriden methods from MD to Methods
7842 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7843                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7844   if (MD->size_overridden_methods() == 0)
7845     Methods.insert(MD->getCanonicalDecl());
7846   else
7847     for (const CXXMethodDecl *O : MD->overridden_methods())
7848       AddMostOverridenMethods(O, Methods);
7849 }
7850
7851 /// Check if a method overloads virtual methods in a base class without
7852 /// overriding any.
7853 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7854                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7855   if (!MD->getDeclName().isIdentifier())
7856     return;
7857
7858   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7859                      /*bool RecordPaths=*/false,
7860                      /*bool DetectVirtual=*/false);
7861   FindHiddenVirtualMethod FHVM;
7862   FHVM.Method = MD;
7863   FHVM.S = this;
7864
7865   // Keep the base methods that were overridden or introduced in the subclass
7866   // by 'using' in a set. A base method not in this set is hidden.
7867   CXXRecordDecl *DC = MD->getParent();
7868   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7869   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7870     NamedDecl *ND = *I;
7871     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7872       ND = shad->getTargetDecl();
7873     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7874       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7875   }
7876
7877   if (DC->lookupInBases(FHVM, Paths))
7878     OverloadedMethods = FHVM.OverloadedMethods;
7879 }
7880
7881 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7882                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7883   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7884     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7885     PartialDiagnostic PD = PDiag(
7886          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7887     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7888     Diag(overloadedMD->getLocation(), PD);
7889   }
7890 }
7891
7892 /// Diagnose methods which overload virtual methods in a base class
7893 /// without overriding any.
7894 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7895   if (MD->isInvalidDecl())
7896     return;
7897
7898   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7899     return;
7900
7901   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7902   FindHiddenVirtualMethods(MD, OverloadedMethods);
7903   if (!OverloadedMethods.empty()) {
7904     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7905       << MD << (OverloadedMethods.size() > 1);
7906
7907     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7908   }
7909 }
7910
7911 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7912   auto PrintDiagAndRemoveAttr = [&]() {
7913     // No diagnostics if this is a template instantiation.
7914     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7915       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7916            diag::ext_cannot_use_trivial_abi) << &RD;
7917     RD.dropAttr<TrivialABIAttr>();
7918   };
7919
7920   // Ill-formed if the struct has virtual functions.
7921   if (RD.isPolymorphic()) {
7922     PrintDiagAndRemoveAttr();
7923     return;
7924   }
7925
7926   for (const auto &B : RD.bases()) {
7927     // Ill-formed if the base class is non-trivial for the purpose of calls or a
7928     // virtual base.
7929     if ((!B.getType()->isDependentType() &&
7930          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7931         B.isVirtual()) {
7932       PrintDiagAndRemoveAttr();
7933       return;
7934     }
7935   }
7936
7937   for (const auto *FD : RD.fields()) {
7938     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7939     // non-trivial for the purpose of calls.
7940     QualType FT = FD->getType();
7941     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7942       PrintDiagAndRemoveAttr();
7943       return;
7944     }
7945
7946     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7947       if (!RT->isDependentType() &&
7948           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7949         PrintDiagAndRemoveAttr();
7950         return;
7951       }
7952   }
7953 }
7954
7955 void Sema::ActOnFinishCXXMemberSpecification(
7956     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
7957     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
7958   if (!TagDecl)
7959     return;
7960
7961   AdjustDeclIfTemplate(TagDecl);
7962
7963   for (const ParsedAttr &AL : AttrList) {
7964     if (AL.getKind() != ParsedAttr::AT_Visibility)
7965       continue;
7966     AL.setInvalid();
7967     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
7968         << AL.getName();
7969   }
7970
7971   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7972               // strict aliasing violation!
7973               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7974               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7975
7976   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7977 }
7978
7979 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7980 /// special functions, such as the default constructor, copy
7981 /// constructor, or destructor, to the given C++ class (C++
7982 /// [special]p1).  This routine can only be executed just before the
7983 /// definition of the class is complete.
7984 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7985   if (ClassDecl->needsImplicitDefaultConstructor()) {
7986     ++getASTContext().NumImplicitDefaultConstructors;
7987
7988     if (ClassDecl->hasInheritedConstructor())
7989       DeclareImplicitDefaultConstructor(ClassDecl);
7990   }
7991
7992   if (ClassDecl->needsImplicitCopyConstructor()) {
7993     ++getASTContext().NumImplicitCopyConstructors;
7994
7995     // If the properties or semantics of the copy constructor couldn't be
7996     // determined while the class was being declared, force a declaration
7997     // of it now.
7998     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7999         ClassDecl->hasInheritedConstructor())
8000       DeclareImplicitCopyConstructor(ClassDecl);
8001     // For the MS ABI we need to know whether the copy ctor is deleted. A
8002     // prerequisite for deleting the implicit copy ctor is that the class has a
8003     // move ctor or move assignment that is either user-declared or whose
8004     // semantics are inherited from a subobject. FIXME: We should provide a more
8005     // direct way for CodeGen to ask whether the constructor was deleted.
8006     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8007              (ClassDecl->hasUserDeclaredMoveConstructor() ||
8008               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8009               ClassDecl->hasUserDeclaredMoveAssignment() ||
8010               ClassDecl->needsOverloadResolutionForMoveAssignment()))
8011       DeclareImplicitCopyConstructor(ClassDecl);
8012   }
8013
8014   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
8015     ++getASTContext().NumImplicitMoveConstructors;
8016
8017     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8018         ClassDecl->hasInheritedConstructor())
8019       DeclareImplicitMoveConstructor(ClassDecl);
8020   }
8021
8022   if (ClassDecl->needsImplicitCopyAssignment()) {
8023     ++getASTContext().NumImplicitCopyAssignmentOperators;
8024
8025     // If we have a dynamic class, then the copy assignment operator may be
8026     // virtual, so we have to declare it immediately. This ensures that, e.g.,
8027     // it shows up in the right place in the vtable and that we diagnose
8028     // problems with the implicit exception specification.
8029     if (ClassDecl->isDynamicClass() ||
8030         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
8031         ClassDecl->hasInheritedAssignment())
8032       DeclareImplicitCopyAssignment(ClassDecl);
8033   }
8034
8035   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
8036     ++getASTContext().NumImplicitMoveAssignmentOperators;
8037
8038     // Likewise for the move assignment operator.
8039     if (ClassDecl->isDynamicClass() ||
8040         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
8041         ClassDecl->hasInheritedAssignment())
8042       DeclareImplicitMoveAssignment(ClassDecl);
8043   }
8044
8045   if (ClassDecl->needsImplicitDestructor()) {
8046     ++getASTContext().NumImplicitDestructors;
8047
8048     // If we have a dynamic class, then the destructor may be virtual, so we
8049     // have to declare the destructor immediately. This ensures that, e.g., it
8050     // shows up in the right place in the vtable and that we diagnose problems
8051     // with the implicit exception specification.
8052     if (ClassDecl->isDynamicClass() ||
8053         ClassDecl->needsOverloadResolutionForDestructor())
8054       DeclareImplicitDestructor(ClassDecl);
8055   }
8056 }
8057
8058 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
8059   if (!D)
8060     return 0;
8061
8062   // The order of template parameters is not important here. All names
8063   // get added to the same scope.
8064   SmallVector<TemplateParameterList *, 4> ParameterLists;
8065
8066   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8067     D = TD->getTemplatedDecl();
8068
8069   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
8070     ParameterLists.push_back(PSD->getTemplateParameters());
8071
8072   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
8073     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
8074       ParameterLists.push_back(DD->getTemplateParameterList(i));
8075
8076     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8077       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
8078         ParameterLists.push_back(FTD->getTemplateParameters());
8079     }
8080   }
8081
8082   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8083     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
8084       ParameterLists.push_back(TD->getTemplateParameterList(i));
8085
8086     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
8087       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
8088         ParameterLists.push_back(CTD->getTemplateParameters());
8089     }
8090   }
8091
8092   unsigned Count = 0;
8093   for (TemplateParameterList *Params : ParameterLists) {
8094     if (Params->size() > 0)
8095       // Ignore explicit specializations; they don't contribute to the template
8096       // depth.
8097       ++Count;
8098     for (NamedDecl *Param : *Params) {
8099       if (Param->getDeclName()) {
8100         S->AddDecl(Param);
8101         IdResolver.AddDecl(Param);
8102       }
8103     }
8104   }
8105
8106   return Count;
8107 }
8108
8109 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8110   if (!RecordD) return;
8111   AdjustDeclIfTemplate(RecordD);
8112   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8113   PushDeclContext(S, Record);
8114 }
8115
8116 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8117   if (!RecordD) return;
8118   PopDeclContext();
8119 }
8120
8121 /// This is used to implement the constant expression evaluation part of the
8122 /// attribute enable_if extension. There is nothing in standard C++ which would
8123 /// require reentering parameters.
8124 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8125   if (!Param)
8126     return;
8127
8128   S->AddDecl(Param);
8129   if (Param->getDeclName())
8130     IdResolver.AddDecl(Param);
8131 }
8132
8133 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
8134 /// parsing a top-level (non-nested) C++ class, and we are now
8135 /// parsing those parts of the given Method declaration that could
8136 /// not be parsed earlier (C++ [class.mem]p2), such as default
8137 /// arguments. This action should enter the scope of the given
8138 /// Method declaration as if we had just parsed the qualified method
8139 /// name. However, it should not bring the parameters into scope;
8140 /// that will be performed by ActOnDelayedCXXMethodParameter.
8141 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8142 }
8143
8144 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8145 /// C++ method declaration. We're (re-)introducing the given
8146 /// function parameter into scope for use in parsing later parts of
8147 /// the method declaration. For example, we could see an
8148 /// ActOnParamDefaultArgument event for this parameter.
8149 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8150   if (!ParamD)
8151     return;
8152
8153   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8154
8155   // If this parameter has an unparsed default argument, clear it out
8156   // to make way for the parsed default argument.
8157   if (Param->hasUnparsedDefaultArg())
8158     Param->setDefaultArg(nullptr);
8159
8160   S->AddDecl(Param);
8161   if (Param->getDeclName())
8162     IdResolver.AddDecl(Param);
8163 }
8164
8165 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8166 /// processing the delayed method declaration for Method. The method
8167 /// declaration is now considered finished. There may be a separate
8168 /// ActOnStartOfFunctionDef action later (not necessarily
8169 /// immediately!) for this method, if it was also defined inside the
8170 /// class body.
8171 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8172   if (!MethodD)
8173     return;
8174
8175   AdjustDeclIfTemplate(MethodD);
8176
8177   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8178
8179   // Now that we have our default arguments, check the constructor
8180   // again. It could produce additional diagnostics or affect whether
8181   // the class has implicitly-declared destructors, among other
8182   // things.
8183   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8184     CheckConstructor(Constructor);
8185
8186   // Check the default arguments, which we may have added.
8187   if (!Method->isInvalidDecl())
8188     CheckCXXDefaultArguments(Method);
8189 }
8190
8191 // Emit the given diagnostic for each non-address-space qualifier.
8192 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
8193 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
8194   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8195   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
8196     bool DiagOccured = false;
8197     FTI.MethodQualifiers->forEachQualifier(
8198         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
8199                                    SourceLocation SL) {
8200           // This diagnostic should be emitted on any qualifier except an addr
8201           // space qualifier. However, forEachQualifier currently doesn't visit
8202           // addr space qualifiers, so there's no way to write this condition
8203           // right now; we just diagnose on everything.
8204           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
8205           DiagOccured = true;
8206         });
8207     if (DiagOccured)
8208       D.setInvalidType();
8209   }
8210 }
8211
8212 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8213 /// the well-formedness of the constructor declarator @p D with type @p
8214 /// R. If there are any errors in the declarator, this routine will
8215 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8216 /// will be updated to reflect a well-formed type for the constructor and
8217 /// returned.
8218 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8219                                           StorageClass &SC) {
8220   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8221
8222   // C++ [class.ctor]p3:
8223   //   A constructor shall not be virtual (10.3) or static (9.4). A
8224   //   constructor can be invoked for a const, volatile or const
8225   //   volatile object. A constructor shall not be declared const,
8226   //   volatile, or const volatile (9.3.2).
8227   if (isVirtual) {
8228     if (!D.isInvalidType())
8229       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8230         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8231         << SourceRange(D.getIdentifierLoc());
8232     D.setInvalidType();
8233   }
8234   if (SC == SC_Static) {
8235     if (!D.isInvalidType())
8236       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8237         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8238         << SourceRange(D.getIdentifierLoc());
8239     D.setInvalidType();
8240     SC = SC_None;
8241   }
8242
8243   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8244     diagnoseIgnoredQualifiers(
8245         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8246         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8247         D.getDeclSpec().getRestrictSpecLoc(),
8248         D.getDeclSpec().getAtomicSpecLoc());
8249     D.setInvalidType();
8250   }
8251
8252   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
8253
8254   // C++0x [class.ctor]p4:
8255   //   A constructor shall not be declared with a ref-qualifier.
8256   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8257   if (FTI.hasRefQualifier()) {
8258     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8259       << FTI.RefQualifierIsLValueRef
8260       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8261     D.setInvalidType();
8262   }
8263
8264   // Rebuild the function type "R" without any type qualifiers (in
8265   // case any of the errors above fired) and with "void" as the
8266   // return type, since constructors don't have return types.
8267   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8268   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8269     return R;
8270
8271   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8272   EPI.TypeQuals = Qualifiers();
8273   EPI.RefQualifier = RQ_None;
8274
8275   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8276 }
8277
8278 /// CheckConstructor - Checks a fully-formed constructor for
8279 /// well-formedness, issuing any diagnostics required. Returns true if
8280 /// the constructor declarator is invalid.
8281 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8282   CXXRecordDecl *ClassDecl
8283     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8284   if (!ClassDecl)
8285     return Constructor->setInvalidDecl();
8286
8287   // C++ [class.copy]p3:
8288   //   A declaration of a constructor for a class X is ill-formed if
8289   //   its first parameter is of type (optionally cv-qualified) X and
8290   //   either there are no other parameters or else all other
8291   //   parameters have default arguments.
8292   if (!Constructor->isInvalidDecl() &&
8293       ((Constructor->getNumParams() == 1) ||
8294        (Constructor->getNumParams() > 1 &&
8295         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8296       Constructor->getTemplateSpecializationKind()
8297                                               != TSK_ImplicitInstantiation) {
8298     QualType ParamType = Constructor->getParamDecl(0)->getType();
8299     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8300     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8301       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8302       const char *ConstRef
8303         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8304                                                         : " const &";
8305       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8306         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8307
8308       // FIXME: Rather that making the constructor invalid, we should endeavor
8309       // to fix the type.
8310       Constructor->setInvalidDecl();
8311     }
8312   }
8313 }
8314
8315 /// CheckDestructor - Checks a fully-formed destructor definition for
8316 /// well-formedness, issuing any diagnostics required.  Returns true
8317 /// on error.
8318 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8319   CXXRecordDecl *RD = Destructor->getParent();
8320
8321   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8322     SourceLocation Loc;
8323
8324     if (!Destructor->isImplicit())
8325       Loc = Destructor->getLocation();
8326     else
8327       Loc = RD->getLocation();
8328
8329     // If we have a virtual destructor, look up the deallocation function
8330     if (FunctionDecl *OperatorDelete =
8331             FindDeallocationFunctionForDestructor(Loc, RD)) {
8332       Expr *ThisArg = nullptr;
8333
8334       // If the notional 'delete this' expression requires a non-trivial
8335       // conversion from 'this' to the type of a destroying operator delete's
8336       // first parameter, perform that conversion now.
8337       if (OperatorDelete->isDestroyingOperatorDelete()) {
8338         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8339         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8340           // C++ [class.dtor]p13:
8341           //   ... as if for the expression 'delete this' appearing in a
8342           //   non-virtual destructor of the destructor's class.
8343           ContextRAII SwitchContext(*this, Destructor);
8344           ExprResult This =
8345               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8346           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8347           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8348           if (This.isInvalid()) {
8349             // FIXME: Register this as a context note so that it comes out
8350             // in the right order.
8351             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8352             return true;
8353           }
8354           ThisArg = This.get();
8355         }
8356       }
8357
8358       DiagnoseUseOfDecl(OperatorDelete, Loc);
8359       MarkFunctionReferenced(Loc, OperatorDelete);
8360       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8361     }
8362   }
8363
8364   return false;
8365 }
8366
8367 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8368 /// the well-formednes of the destructor declarator @p D with type @p
8369 /// R. If there are any errors in the declarator, this routine will
8370 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8371 /// will be updated to reflect a well-formed type for the destructor and
8372 /// returned.
8373 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8374                                          StorageClass& SC) {
8375   // C++ [class.dtor]p1:
8376   //   [...] A typedef-name that names a class is a class-name
8377   //   (7.1.3); however, a typedef-name that names a class shall not
8378   //   be used as the identifier in the declarator for a destructor
8379   //   declaration.
8380   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8381   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8382     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8383       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8384   else if (const TemplateSpecializationType *TST =
8385              DeclaratorType->getAs<TemplateSpecializationType>())
8386     if (TST->isTypeAlias())
8387       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8388         << DeclaratorType << 1;
8389
8390   // C++ [class.dtor]p2:
8391   //   A destructor is used to destroy objects of its class type. A
8392   //   destructor takes no parameters, and no return type can be
8393   //   specified for it (not even void). The address of a destructor
8394   //   shall not be taken. A destructor shall not be static. A
8395   //   destructor can be invoked for a const, volatile or const
8396   //   volatile object. A destructor shall not be declared const,
8397   //   volatile or const volatile (9.3.2).
8398   if (SC == SC_Static) {
8399     if (!D.isInvalidType())
8400       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8401         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8402         << SourceRange(D.getIdentifierLoc())
8403         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8404
8405     SC = SC_None;
8406   }
8407   if (!D.isInvalidType()) {
8408     // Destructors don't have return types, but the parser will
8409     // happily parse something like:
8410     //
8411     //   class X {
8412     //     float ~X();
8413     //   };
8414     //
8415     // The return type will be eliminated later.
8416     if (D.getDeclSpec().hasTypeSpecifier())
8417       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8418         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8419         << SourceRange(D.getIdentifierLoc());
8420     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8421       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8422                                 SourceLocation(),
8423                                 D.getDeclSpec().getConstSpecLoc(),
8424                                 D.getDeclSpec().getVolatileSpecLoc(),
8425                                 D.getDeclSpec().getRestrictSpecLoc(),
8426                                 D.getDeclSpec().getAtomicSpecLoc());
8427       D.setInvalidType();
8428     }
8429   }
8430
8431   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
8432
8433   // C++0x [class.dtor]p2:
8434   //   A destructor shall not be declared with a ref-qualifier.
8435   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8436   if (FTI.hasRefQualifier()) {
8437     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8438       << FTI.RefQualifierIsLValueRef
8439       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8440     D.setInvalidType();
8441   }
8442
8443   // Make sure we don't have any parameters.
8444   if (FTIHasNonVoidParameters(FTI)) {
8445     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8446
8447     // Delete the parameters.
8448     FTI.freeParams();
8449     D.setInvalidType();
8450   }
8451
8452   // Make sure the destructor isn't variadic.
8453   if (FTI.isVariadic) {
8454     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8455     D.setInvalidType();
8456   }
8457
8458   // Rebuild the function type "R" without any type qualifiers or
8459   // parameters (in case any of the errors above fired) and with
8460   // "void" as the return type, since destructors don't have return
8461   // types.
8462   if (!D.isInvalidType())
8463     return R;
8464
8465   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8466   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8467   EPI.Variadic = false;
8468   EPI.TypeQuals = Qualifiers();
8469   EPI.RefQualifier = RQ_None;
8470   return Context.getFunctionType(Context.VoidTy, None, EPI);
8471 }
8472
8473 static void extendLeft(SourceRange &R, SourceRange Before) {
8474   if (Before.isInvalid())
8475     return;
8476   R.setBegin(Before.getBegin());
8477   if (R.getEnd().isInvalid())
8478     R.setEnd(Before.getEnd());
8479 }
8480
8481 static void extendRight(SourceRange &R, SourceRange After) {
8482   if (After.isInvalid())
8483     return;
8484   if (R.getBegin().isInvalid())
8485     R.setBegin(After.getBegin());
8486   R.setEnd(After.getEnd());
8487 }
8488
8489 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8490 /// well-formednes of the conversion function declarator @p D with
8491 /// type @p R. If there are any errors in the declarator, this routine
8492 /// will emit diagnostics and return true. Otherwise, it will return
8493 /// false. Either way, the type @p R will be updated to reflect a
8494 /// well-formed type for the conversion operator.
8495 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8496                                      StorageClass& SC) {
8497   // C++ [class.conv.fct]p1:
8498   //   Neither parameter types nor return type can be specified. The
8499   //   type of a conversion function (8.3.5) is "function taking no
8500   //   parameter returning conversion-type-id."
8501   if (SC == SC_Static) {
8502     if (!D.isInvalidType())
8503       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8504         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8505         << D.getName().getSourceRange();
8506     D.setInvalidType();
8507     SC = SC_None;
8508   }
8509
8510   TypeSourceInfo *ConvTSI = nullptr;
8511   QualType ConvType =
8512       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8513
8514   const DeclSpec &DS = D.getDeclSpec();
8515   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8516     // Conversion functions don't have return types, but the parser will
8517     // happily parse something like:
8518     //
8519     //   class X {
8520     //     float operator bool();
8521     //   };
8522     //
8523     // The return type will be changed later anyway.
8524     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8525       << SourceRange(DS.getTypeSpecTypeLoc())
8526       << SourceRange(D.getIdentifierLoc());
8527     D.setInvalidType();
8528   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8529     // It's also plausible that the user writes type qualifiers in the wrong
8530     // place, such as:
8531     //   struct S { const operator int(); };
8532     // FIXME: we could provide a fixit to move the qualifiers onto the
8533     // conversion type.
8534     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8535         << SourceRange(D.getIdentifierLoc()) << 0;
8536     D.setInvalidType();
8537   }
8538
8539   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8540
8541   // Make sure we don't have any parameters.
8542   if (Proto->getNumParams() > 0) {
8543     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8544
8545     // Delete the parameters.
8546     D.getFunctionTypeInfo().freeParams();
8547     D.setInvalidType();
8548   } else if (Proto->isVariadic()) {
8549     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8550     D.setInvalidType();
8551   }
8552
8553   // Diagnose "&operator bool()" and other such nonsense.  This
8554   // is actually a gcc extension which we don't support.
8555   if (Proto->getReturnType() != ConvType) {
8556     bool NeedsTypedef = false;
8557     SourceRange Before, After;
8558
8559     // Walk the chunks and extract information on them for our diagnostic.
8560     bool PastFunctionChunk = false;
8561     for (auto &Chunk : D.type_objects()) {
8562       switch (Chunk.Kind) {
8563       case DeclaratorChunk::Function:
8564         if (!PastFunctionChunk) {
8565           if (Chunk.Fun.HasTrailingReturnType) {
8566             TypeSourceInfo *TRT = nullptr;
8567             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8568             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8569           }
8570           PastFunctionChunk = true;
8571           break;
8572         }
8573         LLVM_FALLTHROUGH;
8574       case DeclaratorChunk::Array:
8575         NeedsTypedef = true;
8576         extendRight(After, Chunk.getSourceRange());
8577         break;
8578
8579       case DeclaratorChunk::Pointer:
8580       case DeclaratorChunk::BlockPointer:
8581       case DeclaratorChunk::Reference:
8582       case DeclaratorChunk::MemberPointer:
8583       case DeclaratorChunk::Pipe:
8584         extendLeft(Before, Chunk.getSourceRange());
8585         break;
8586
8587       case DeclaratorChunk::Paren:
8588         extendLeft(Before, Chunk.Loc);
8589         extendRight(After, Chunk.EndLoc);
8590         break;
8591       }
8592     }
8593
8594     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8595                          After.isValid()  ? After.getBegin() :
8596                                             D.getIdentifierLoc();
8597     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8598     DB << Before << After;
8599
8600     if (!NeedsTypedef) {
8601       DB << /*don't need a typedef*/0;
8602
8603       // If we can provide a correct fix-it hint, do so.
8604       if (After.isInvalid() && ConvTSI) {
8605         SourceLocation InsertLoc =
8606             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8607         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8608            << FixItHint::CreateInsertionFromRange(
8609                   InsertLoc, CharSourceRange::getTokenRange(Before))
8610            << FixItHint::CreateRemoval(Before);
8611       }
8612     } else if (!Proto->getReturnType()->isDependentType()) {
8613       DB << /*typedef*/1 << Proto->getReturnType();
8614     } else if (getLangOpts().CPlusPlus11) {
8615       DB << /*alias template*/2 << Proto->getReturnType();
8616     } else {
8617       DB << /*might not be fixable*/3;
8618     }
8619
8620     // Recover by incorporating the other type chunks into the result type.
8621     // Note, this does *not* change the name of the function. This is compatible
8622     // with the GCC extension:
8623     //   struct S { &operator int(); } s;
8624     //   int &r = s.operator int(); // ok in GCC
8625     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8626     ConvType = Proto->getReturnType();
8627   }
8628
8629   // C++ [class.conv.fct]p4:
8630   //   The conversion-type-id shall not represent a function type nor
8631   //   an array type.
8632   if (ConvType->isArrayType()) {
8633     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8634     ConvType = Context.getPointerType(ConvType);
8635     D.setInvalidType();
8636   } else if (ConvType->isFunctionType()) {
8637     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8638     ConvType = Context.getPointerType(ConvType);
8639     D.setInvalidType();
8640   }
8641
8642   // Rebuild the function type "R" without any parameters (in case any
8643   // of the errors above fired) and with the conversion type as the
8644   // return type.
8645   if (D.isInvalidType())
8646     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8647
8648   // C++0x explicit conversion operators.
8649   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a)
8650     Diag(DS.getExplicitSpecLoc(),
8651          getLangOpts().CPlusPlus11
8652              ? diag::warn_cxx98_compat_explicit_conversion_functions
8653              : diag::ext_explicit_conversion_functions)
8654         << SourceRange(DS.getExplicitSpecRange());
8655 }
8656
8657 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8658 /// the declaration of the given C++ conversion function. This routine
8659 /// is responsible for recording the conversion function in the C++
8660 /// class, if possible.
8661 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8662   assert(Conversion && "Expected to receive a conversion function declaration");
8663
8664   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8665
8666   // Make sure we aren't redeclaring the conversion function.
8667   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8668
8669   // C++ [class.conv.fct]p1:
8670   //   [...] A conversion function is never used to convert a
8671   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8672   //   same object type (or a reference to it), to a (possibly
8673   //   cv-qualified) base class of that type (or a reference to it),
8674   //   or to (possibly cv-qualified) void.
8675   // FIXME: Suppress this warning if the conversion function ends up being a
8676   // virtual function that overrides a virtual function in a base class.
8677   QualType ClassType
8678     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8679   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8680     ConvType = ConvTypeRef->getPointeeType();
8681   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8682       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8683     /* Suppress diagnostics for instantiations. */;
8684   else if (ConvType->isRecordType()) {
8685     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8686     if (ConvType == ClassType)
8687       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8688         << ClassType;
8689     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8690       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8691         <<  ClassType << ConvType;
8692   } else if (ConvType->isVoidType()) {
8693     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8694       << ClassType << ConvType;
8695   }
8696
8697   if (FunctionTemplateDecl *ConversionTemplate
8698                                 = Conversion->getDescribedFunctionTemplate())
8699     return ConversionTemplate;
8700
8701   return Conversion;
8702 }
8703
8704 namespace {
8705 /// Utility class to accumulate and print a diagnostic listing the invalid
8706 /// specifier(s) on a declaration.
8707 struct BadSpecifierDiagnoser {
8708   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8709       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8710   ~BadSpecifierDiagnoser() {
8711     Diagnostic << Specifiers;
8712   }
8713
8714   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8715     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8716   }
8717   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8718     return check(SpecLoc,
8719                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8720   }
8721   void check(SourceLocation SpecLoc, const char *Spec) {
8722     if (SpecLoc.isInvalid()) return;
8723     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8724     if (!Specifiers.empty()) Specifiers += " ";
8725     Specifiers += Spec;
8726   }
8727
8728   Sema &S;
8729   Sema::SemaDiagnosticBuilder Diagnostic;
8730   std::string Specifiers;
8731 };
8732 }
8733
8734 /// Check the validity of a declarator that we parsed for a deduction-guide.
8735 /// These aren't actually declarators in the grammar, so we need to check that
8736 /// the user didn't specify any pieces that are not part of the deduction-guide
8737 /// grammar.
8738 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8739                                          StorageClass &SC) {
8740   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8741   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8742   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8743
8744   // C++ [temp.deduct.guide]p3:
8745   //   A deduction-gide shall be declared in the same scope as the
8746   //   corresponding class template.
8747   if (!CurContext->getRedeclContext()->Equals(
8748           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8749     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8750       << GuidedTemplateDecl;
8751     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8752   }
8753
8754   auto &DS = D.getMutableDeclSpec();
8755   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8756   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8757       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8758       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
8759     BadSpecifierDiagnoser Diagnoser(
8760         *this, D.getIdentifierLoc(),
8761         diag::err_deduction_guide_invalid_specifier);
8762
8763     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8764     DS.ClearStorageClassSpecs();
8765     SC = SC_None;
8766
8767     // 'explicit' is permitted.
8768     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8769     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8770     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8771     DS.ClearConstexprSpec();
8772
8773     Diagnoser.check(DS.getConstSpecLoc(), "const");
8774     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8775     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8776     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8777     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8778     DS.ClearTypeQualifiers();
8779
8780     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8781     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8782     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8783     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8784     DS.ClearTypeSpecType();
8785   }
8786
8787   if (D.isInvalidType())
8788     return;
8789
8790   // Check the declarator is simple enough.
8791   bool FoundFunction = false;
8792   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8793     if (Chunk.Kind == DeclaratorChunk::Paren)
8794       continue;
8795     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8796       Diag(D.getDeclSpec().getBeginLoc(),
8797            diag::err_deduction_guide_with_complex_decl)
8798           << D.getSourceRange();
8799       break;
8800     }
8801     if (!Chunk.Fun.hasTrailingReturnType()) {
8802       Diag(D.getName().getBeginLoc(),
8803            diag::err_deduction_guide_no_trailing_return_type);
8804       break;
8805     }
8806
8807     // Check that the return type is written as a specialization of
8808     // the template specified as the deduction-guide's name.
8809     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8810     TypeSourceInfo *TSI = nullptr;
8811     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8812     assert(TSI && "deduction guide has valid type but invalid return type?");
8813     bool AcceptableReturnType = false;
8814     bool MightInstantiateToSpecialization = false;
8815     if (auto RetTST =
8816             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8817       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8818       bool TemplateMatches =
8819           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8820       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8821         AcceptableReturnType = true;
8822       else {
8823         // This could still instantiate to the right type, unless we know it
8824         // names the wrong class template.
8825         auto *TD = SpecifiedName.getAsTemplateDecl();
8826         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8827                                              !TemplateMatches);
8828       }
8829     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8830       MightInstantiateToSpecialization = true;
8831     }
8832
8833     if (!AcceptableReturnType) {
8834       Diag(TSI->getTypeLoc().getBeginLoc(),
8835            diag::err_deduction_guide_bad_trailing_return_type)
8836           << GuidedTemplate << TSI->getType()
8837           << MightInstantiateToSpecialization
8838           << TSI->getTypeLoc().getSourceRange();
8839     }
8840
8841     // Keep going to check that we don't have any inner declarator pieces (we
8842     // could still have a function returning a pointer to a function).
8843     FoundFunction = true;
8844   }
8845
8846   if (D.isFunctionDefinition())
8847     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8848 }
8849
8850 //===----------------------------------------------------------------------===//
8851 // Namespace Handling
8852 //===----------------------------------------------------------------------===//
8853
8854 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8855 /// reopened.
8856 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8857                                             SourceLocation Loc,
8858                                             IdentifierInfo *II, bool *IsInline,
8859                                             NamespaceDecl *PrevNS) {
8860   assert(*IsInline != PrevNS->isInline());
8861
8862   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8863   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8864   // inline namespaces, with the intention of bringing names into namespace std.
8865   //
8866   // We support this just well enough to get that case working; this is not
8867   // sufficient to support reopening namespaces as inline in general.
8868   if (*IsInline && II && II->getName().startswith("__atomic") &&
8869       S.getSourceManager().isInSystemHeader(Loc)) {
8870     // Mark all prior declarations of the namespace as inline.
8871     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8872          NS = NS->getPreviousDecl())
8873       NS->setInline(*IsInline);
8874     // Patch up the lookup table for the containing namespace. This isn't really
8875     // correct, but it's good enough for this particular case.
8876     for (auto *I : PrevNS->decls())
8877       if (auto *ND = dyn_cast<NamedDecl>(I))
8878         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8879     return;
8880   }
8881
8882   if (PrevNS->isInline())
8883     // The user probably just forgot the 'inline', so suggest that it
8884     // be added back.
8885     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8886       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8887   else
8888     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8889
8890   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8891   *IsInline = PrevNS->isInline();
8892 }
8893
8894 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8895 /// definition.
8896 Decl *Sema::ActOnStartNamespaceDef(
8897     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
8898     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
8899     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
8900   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8901   // For anonymous namespace, take the location of the left brace.
8902   SourceLocation Loc = II ? IdentLoc : LBrace;
8903   bool IsInline = InlineLoc.isValid();
8904   bool IsInvalid = false;
8905   bool IsStd = false;
8906   bool AddToKnown = false;
8907   Scope *DeclRegionScope = NamespcScope->getParent();
8908
8909   NamespaceDecl *PrevNS = nullptr;
8910   if (II) {
8911     // C++ [namespace.def]p2:
8912     //   The identifier in an original-namespace-definition shall not
8913     //   have been previously defined in the declarative region in
8914     //   which the original-namespace-definition appears. The
8915     //   identifier in an original-namespace-definition is the name of
8916     //   the namespace. Subsequently in that declarative region, it is
8917     //   treated as an original-namespace-name.
8918     //
8919     // Since namespace names are unique in their scope, and we don't
8920     // look through using directives, just look for any ordinary names
8921     // as if by qualified name lookup.
8922     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8923                    ForExternalRedeclaration);
8924     LookupQualifiedName(R, CurContext->getRedeclContext());
8925     NamedDecl *PrevDecl =
8926         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8927     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8928
8929     if (PrevNS) {
8930       // This is an extended namespace definition.
8931       if (IsInline != PrevNS->isInline())
8932         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8933                                         &IsInline, PrevNS);
8934     } else if (PrevDecl) {
8935       // This is an invalid name redefinition.
8936       Diag(Loc, diag::err_redefinition_different_kind)
8937         << II;
8938       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8939       IsInvalid = true;
8940       // Continue on to push Namespc as current DeclContext and return it.
8941     } else if (II->isStr("std") &&
8942                CurContext->getRedeclContext()->isTranslationUnit()) {
8943       // This is the first "real" definition of the namespace "std", so update
8944       // our cache of the "std" namespace to point at this definition.
8945       PrevNS = getStdNamespace();
8946       IsStd = true;
8947       AddToKnown = !IsInline;
8948     } else {
8949       // We've seen this namespace for the first time.
8950       AddToKnown = !IsInline;
8951     }
8952   } else {
8953     // Anonymous namespaces.
8954
8955     // Determine whether the parent already has an anonymous namespace.
8956     DeclContext *Parent = CurContext->getRedeclContext();
8957     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8958       PrevNS = TU->getAnonymousNamespace();
8959     } else {
8960       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8961       PrevNS = ND->getAnonymousNamespace();
8962     }
8963
8964     if (PrevNS && IsInline != PrevNS->isInline())
8965       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8966                                       &IsInline, PrevNS);
8967   }
8968
8969   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8970                                                  StartLoc, Loc, II, PrevNS);
8971   if (IsInvalid)
8972     Namespc->setInvalidDecl();
8973
8974   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8975   AddPragmaAttributes(DeclRegionScope, Namespc);
8976
8977   // FIXME: Should we be merging attributes?
8978   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8979     PushNamespaceVisibilityAttr(Attr, Loc);
8980
8981   if (IsStd)
8982     StdNamespace = Namespc;
8983   if (AddToKnown)
8984     KnownNamespaces[Namespc] = false;
8985
8986   if (II) {
8987     PushOnScopeChains(Namespc, DeclRegionScope);
8988   } else {
8989     // Link the anonymous namespace into its parent.
8990     DeclContext *Parent = CurContext->getRedeclContext();
8991     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8992       TU->setAnonymousNamespace(Namespc);
8993     } else {
8994       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8995     }
8996
8997     CurContext->addDecl(Namespc);
8998
8999     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
9000     //   behaves as if it were replaced by
9001     //     namespace unique { /* empty body */ }
9002     //     using namespace unique;
9003     //     namespace unique { namespace-body }
9004     //   where all occurrences of 'unique' in a translation unit are
9005     //   replaced by the same identifier and this identifier differs
9006     //   from all other identifiers in the entire program.
9007
9008     // We just create the namespace with an empty name and then add an
9009     // implicit using declaration, just like the standard suggests.
9010     //
9011     // CodeGen enforces the "universally unique" aspect by giving all
9012     // declarations semantically contained within an anonymous
9013     // namespace internal linkage.
9014
9015     if (!PrevNS) {
9016       UD = UsingDirectiveDecl::Create(Context, Parent,
9017                                       /* 'using' */ LBrace,
9018                                       /* 'namespace' */ SourceLocation(),
9019                                       /* qualifier */ NestedNameSpecifierLoc(),
9020                                       /* identifier */ SourceLocation(),
9021                                       Namespc,
9022                                       /* Ancestor */ Parent);
9023       UD->setImplicit();
9024       Parent->addDecl(UD);
9025     }
9026   }
9027
9028   ActOnDocumentableDecl(Namespc);
9029
9030   // Although we could have an invalid decl (i.e. the namespace name is a
9031   // redefinition), push it as current DeclContext and try to continue parsing.
9032   // FIXME: We should be able to push Namespc here, so that the each DeclContext
9033   // for the namespace has the declarations that showed up in that particular
9034   // namespace definition.
9035   PushDeclContext(NamespcScope, Namespc);
9036   return Namespc;
9037 }
9038
9039 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
9040 /// is a namespace alias, returns the namespace it points to.
9041 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
9042   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
9043     return AD->getNamespace();
9044   return dyn_cast_or_null<NamespaceDecl>(D);
9045 }
9046
9047 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
9048 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
9049 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
9050   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
9051   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
9052   Namespc->setRBraceLoc(RBrace);
9053   PopDeclContext();
9054   if (Namespc->hasAttr<VisibilityAttr>())
9055     PopPragmaVisibility(true, RBrace);
9056   // If this namespace contains an export-declaration, export it now.
9057   if (DeferredExportedNamespaces.erase(Namespc))
9058     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
9059 }
9060
9061 CXXRecordDecl *Sema::getStdBadAlloc() const {
9062   return cast_or_null<CXXRecordDecl>(
9063                                   StdBadAlloc.get(Context.getExternalSource()));
9064 }
9065
9066 EnumDecl *Sema::getStdAlignValT() const {
9067   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9068 }
9069
9070 NamespaceDecl *Sema::getStdNamespace() const {
9071   return cast_or_null<NamespaceDecl>(
9072                                  StdNamespace.get(Context.getExternalSource()));
9073 }
9074
9075 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
9076   if (!StdExperimentalNamespaceCache) {
9077     if (auto Std = getStdNamespace()) {
9078       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9079                           SourceLocation(), LookupNamespaceName);
9080       if (!LookupQualifiedName(Result, Std) ||
9081           !(StdExperimentalNamespaceCache =
9082                 Result.getAsSingle<NamespaceDecl>()))
9083         Result.suppressDiagnostics();
9084     }
9085   }
9086   return StdExperimentalNamespaceCache;
9087 }
9088
9089 namespace {
9090
9091 enum UnsupportedSTLSelect {
9092   USS_InvalidMember,
9093   USS_MissingMember,
9094   USS_NonTrivial,
9095   USS_Other
9096 };
9097
9098 struct InvalidSTLDiagnoser {
9099   Sema &S;
9100   SourceLocation Loc;
9101   QualType TyForDiags;
9102
9103   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9104                       const VarDecl *VD = nullptr) {
9105     {
9106       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9107                << TyForDiags << ((int)Sel);
9108       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9109         assert(!Name.empty());
9110         D << Name;
9111       }
9112     }
9113     if (Sel == USS_InvalidMember) {
9114       S.Diag(VD->getLocation(), diag::note_var_declared_here)
9115           << VD << VD->getSourceRange();
9116     }
9117     return QualType();
9118   }
9119 };
9120 } // namespace
9121
9122 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9123                                            SourceLocation Loc) {
9124   assert(getLangOpts().CPlusPlus &&
9125          "Looking for comparison category type outside of C++.");
9126
9127   // Check if we've already successfully checked the comparison category type
9128   // before. If so, skip checking it again.
9129   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9130   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9131     return Info->getType();
9132
9133   // If lookup failed
9134   if (!Info) {
9135     std::string NameForDiags = "std::";
9136     NameForDiags += ComparisonCategories::getCategoryString(Kind);
9137     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9138         << NameForDiags;
9139     return QualType();
9140   }
9141
9142   assert(Info->Kind == Kind);
9143   assert(Info->Record);
9144
9145   // Update the Record decl in case we encountered a forward declaration on our
9146   // first pass. FIXME: This is a bit of a hack.
9147   if (Info->Record->hasDefinition())
9148     Info->Record = Info->Record->getDefinition();
9149
9150   // Use an elaborated type for diagnostics which has a name containing the
9151   // prepended 'std' namespace but not any inline namespace names.
9152   QualType TyForDiags = [&]() {
9153     auto *NNS =
9154         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9155     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9156   }();
9157
9158   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9159     return QualType();
9160
9161   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9162
9163   if (!Info->Record->isTriviallyCopyable())
9164     return UnsupportedSTLError(USS_NonTrivial);
9165
9166   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9167     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9168     // Tolerate empty base classes.
9169     if (Base->isEmpty())
9170       continue;
9171     // Reject STL implementations which have at least one non-empty base.
9172     return UnsupportedSTLError();
9173   }
9174
9175   // Check that the STL has implemented the types using a single integer field.
9176   // This expectation allows better codegen for builtin operators. We require:
9177   //   (1) The class has exactly one field.
9178   //   (2) The field is an integral or enumeration type.
9179   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9180   if (std::distance(FIt, FEnd) != 1 ||
9181       !FIt->getType()->isIntegralOrEnumerationType()) {
9182     return UnsupportedSTLError();
9183   }
9184
9185   // Build each of the require values and store them in Info.
9186   for (ComparisonCategoryResult CCR :
9187        ComparisonCategories::getPossibleResultsForType(Kind)) {
9188     StringRef MemName = ComparisonCategories::getResultString(CCR);
9189     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9190
9191     if (!ValInfo)
9192       return UnsupportedSTLError(USS_MissingMember, MemName);
9193
9194     VarDecl *VD = ValInfo->VD;
9195     assert(VD && "should not be null!");
9196
9197     // Attempt to diagnose reasons why the STL definition of this type
9198     // might be foobar, including it failing to be a constant expression.
9199     // TODO Handle more ways the lookup or result can be invalid.
9200     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9201         !VD->checkInitIsICE())
9202       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9203
9204     // Attempt to evaluate the var decl as a constant expression and extract
9205     // the value of its first field as a ICE. If this fails, the STL
9206     // implementation is not supported.
9207     if (!ValInfo->hasValidIntValue())
9208       return UnsupportedSTLError();
9209
9210     MarkVariableReferenced(Loc, VD);
9211   }
9212
9213   // We've successfully built the required types and expressions. Update
9214   // the cache and return the newly cached value.
9215   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9216   return Info->getType();
9217 }
9218
9219 /// Retrieve the special "std" namespace, which may require us to
9220 /// implicitly define the namespace.
9221 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9222   if (!StdNamespace) {
9223     // The "std" namespace has not yet been defined, so build one implicitly.
9224     StdNamespace = NamespaceDecl::Create(Context,
9225                                          Context.getTranslationUnitDecl(),
9226                                          /*Inline=*/false,
9227                                          SourceLocation(), SourceLocation(),
9228                                          &PP.getIdentifierTable().get("std"),
9229                                          /*PrevDecl=*/nullptr);
9230     getStdNamespace()->setImplicit(true);
9231   }
9232
9233   return getStdNamespace();
9234 }
9235
9236 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9237   assert(getLangOpts().CPlusPlus &&
9238          "Looking for std::initializer_list outside of C++.");
9239
9240   // We're looking for implicit instantiations of
9241   // template <typename E> class std::initializer_list.
9242
9243   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9244     return false;
9245
9246   ClassTemplateDecl *Template = nullptr;
9247   const TemplateArgument *Arguments = nullptr;
9248
9249   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9250
9251     ClassTemplateSpecializationDecl *Specialization =
9252         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9253     if (!Specialization)
9254       return false;
9255
9256     Template = Specialization->getSpecializedTemplate();
9257     Arguments = Specialization->getTemplateArgs().data();
9258   } else if (const TemplateSpecializationType *TST =
9259                  Ty->getAs<TemplateSpecializationType>()) {
9260     Template = dyn_cast_or_null<ClassTemplateDecl>(
9261         TST->getTemplateName().getAsTemplateDecl());
9262     Arguments = TST->getArgs();
9263   }
9264   if (!Template)
9265     return false;
9266
9267   if (!StdInitializerList) {
9268     // Haven't recognized std::initializer_list yet, maybe this is it.
9269     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9270     if (TemplateClass->getIdentifier() !=
9271             &PP.getIdentifierTable().get("initializer_list") ||
9272         !getStdNamespace()->InEnclosingNamespaceSetOf(
9273             TemplateClass->getDeclContext()))
9274       return false;
9275     // This is a template called std::initializer_list, but is it the right
9276     // template?
9277     TemplateParameterList *Params = Template->getTemplateParameters();
9278     if (Params->getMinRequiredArguments() != 1)
9279       return false;
9280     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9281       return false;
9282
9283     // It's the right template.
9284     StdInitializerList = Template;
9285   }
9286
9287   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9288     return false;
9289
9290   // This is an instance of std::initializer_list. Find the argument type.
9291   if (Element)
9292     *Element = Arguments[0].getAsType();
9293   return true;
9294 }
9295
9296 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9297   NamespaceDecl *Std = S.getStdNamespace();
9298   if (!Std) {
9299     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9300     return nullptr;
9301   }
9302
9303   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9304                       Loc, Sema::LookupOrdinaryName);
9305   if (!S.LookupQualifiedName(Result, Std)) {
9306     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9307     return nullptr;
9308   }
9309   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9310   if (!Template) {
9311     Result.suppressDiagnostics();
9312     // We found something weird. Complain about the first thing we found.
9313     NamedDecl *Found = *Result.begin();
9314     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9315     return nullptr;
9316   }
9317
9318   // We found some template called std::initializer_list. Now verify that it's
9319   // correct.
9320   TemplateParameterList *Params = Template->getTemplateParameters();
9321   if (Params->getMinRequiredArguments() != 1 ||
9322       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9323     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9324     return nullptr;
9325   }
9326
9327   return Template;
9328 }
9329
9330 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9331   if (!StdInitializerList) {
9332     StdInitializerList = LookupStdInitializerList(*this, Loc);
9333     if (!StdInitializerList)
9334       return QualType();
9335   }
9336
9337   TemplateArgumentListInfo Args(Loc, Loc);
9338   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9339                                        Context.getTrivialTypeSourceInfo(Element,
9340                                                                         Loc)));
9341   return Context.getCanonicalType(
9342       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9343 }
9344
9345 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9346   // C++ [dcl.init.list]p2:
9347   //   A constructor is an initializer-list constructor if its first parameter
9348   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9349   //   std::initializer_list<E> for some type E, and either there are no other
9350   //   parameters or else all other parameters have default arguments.
9351   if (Ctor->getNumParams() < 1 ||
9352       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9353     return false;
9354
9355   QualType ArgType = Ctor->getParamDecl(0)->getType();
9356   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9357     ArgType = RT->getPointeeType().getUnqualifiedType();
9358
9359   return isStdInitializerList(ArgType, nullptr);
9360 }
9361
9362 /// Determine whether a using statement is in a context where it will be
9363 /// apply in all contexts.
9364 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9365   switch (CurContext->getDeclKind()) {
9366     case Decl::TranslationUnit:
9367       return true;
9368     case Decl::LinkageSpec:
9369       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9370     default:
9371       return false;
9372   }
9373 }
9374
9375 namespace {
9376
9377 // Callback to only accept typo corrections that are namespaces.
9378 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
9379 public:
9380   bool ValidateCandidate(const TypoCorrection &candidate) override {
9381     if (NamedDecl *ND = candidate.getCorrectionDecl())
9382       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9383     return false;
9384   }
9385
9386   std::unique_ptr<CorrectionCandidateCallback> clone() override {
9387     return llvm::make_unique<NamespaceValidatorCCC>(*this);
9388   }
9389 };
9390
9391 }
9392
9393 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9394                                        CXXScopeSpec &SS,
9395                                        SourceLocation IdentLoc,
9396                                        IdentifierInfo *Ident) {
9397   R.clear();
9398   NamespaceValidatorCCC CCC{};
9399   if (TypoCorrection Corrected =
9400           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
9401                         Sema::CTK_ErrorRecovery)) {
9402     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9403       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9404       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9405                               Ident->getName().equals(CorrectedStr);
9406       S.diagnoseTypo(Corrected,
9407                      S.PDiag(diag::err_using_directive_member_suggest)
9408                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9409                      S.PDiag(diag::note_namespace_defined_here));
9410     } else {
9411       S.diagnoseTypo(Corrected,
9412                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9413                      S.PDiag(diag::note_namespace_defined_here));
9414     }
9415     R.addDecl(Corrected.getFoundDecl());
9416     return true;
9417   }
9418   return false;
9419 }
9420
9421 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9422                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9423                                 SourceLocation IdentLoc,
9424                                 IdentifierInfo *NamespcName,
9425                                 const ParsedAttributesView &AttrList) {
9426   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9427   assert(NamespcName && "Invalid NamespcName.");
9428   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9429
9430   // This can only happen along a recovery path.
9431   while (S->isTemplateParamScope())
9432     S = S->getParent();
9433   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9434
9435   UsingDirectiveDecl *UDir = nullptr;
9436   NestedNameSpecifier *Qualifier = nullptr;
9437   if (SS.isSet())
9438     Qualifier = SS.getScopeRep();
9439
9440   // Lookup namespace name.
9441   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9442   LookupParsedName(R, S, &SS);
9443   if (R.isAmbiguous())
9444     return nullptr;
9445
9446   if (R.empty()) {
9447     R.clear();
9448     // Allow "using namespace std;" or "using namespace ::std;" even if
9449     // "std" hasn't been defined yet, for GCC compatibility.
9450     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9451         NamespcName->isStr("std")) {
9452       Diag(IdentLoc, diag::ext_using_undefined_std);
9453       R.addDecl(getOrCreateStdNamespace());
9454       R.resolveKind();
9455     }
9456     // Otherwise, attempt typo correction.
9457     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9458   }
9459
9460   if (!R.empty()) {
9461     NamedDecl *Named = R.getRepresentativeDecl();
9462     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9463     assert(NS && "expected namespace decl");
9464
9465     // The use of a nested name specifier may trigger deprecation warnings.
9466     DiagnoseUseOfDecl(Named, IdentLoc);
9467
9468     // C++ [namespace.udir]p1:
9469     //   A using-directive specifies that the names in the nominated
9470     //   namespace can be used in the scope in which the
9471     //   using-directive appears after the using-directive. During
9472     //   unqualified name lookup (3.4.1), the names appear as if they
9473     //   were declared in the nearest enclosing namespace which
9474     //   contains both the using-directive and the nominated
9475     //   namespace. [Note: in this context, "contains" means "contains
9476     //   directly or indirectly". ]
9477
9478     // Find enclosing context containing both using-directive and
9479     // nominated namespace.
9480     DeclContext *CommonAncestor = NS;
9481     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9482       CommonAncestor = CommonAncestor->getParent();
9483
9484     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9485                                       SS.getWithLocInContext(Context),
9486                                       IdentLoc, Named, CommonAncestor);
9487
9488     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9489         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9490       Diag(IdentLoc, diag::warn_using_directive_in_header);
9491     }
9492
9493     PushUsingDirective(S, UDir);
9494   } else {
9495     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9496   }
9497
9498   if (UDir)
9499     ProcessDeclAttributeList(S, UDir, AttrList);
9500
9501   return UDir;
9502 }
9503
9504 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9505   // If the scope has an associated entity and the using directive is at
9506   // namespace or translation unit scope, add the UsingDirectiveDecl into
9507   // its lookup structure so qualified name lookup can find it.
9508   DeclContext *Ctx = S->getEntity();
9509   if (Ctx && !Ctx->isFunctionOrMethod())
9510     Ctx->addDecl(UDir);
9511   else
9512     // Otherwise, it is at block scope. The using-directives will affect lookup
9513     // only to the end of the scope.
9514     S->PushUsingDirective(UDir);
9515 }
9516
9517 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9518                                   SourceLocation UsingLoc,
9519                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
9520                                   UnqualifiedId &Name,
9521                                   SourceLocation EllipsisLoc,
9522                                   const ParsedAttributesView &AttrList) {
9523   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9524
9525   if (SS.isEmpty()) {
9526     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9527     return nullptr;
9528   }
9529
9530   switch (Name.getKind()) {
9531   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9532   case UnqualifiedIdKind::IK_Identifier:
9533   case UnqualifiedIdKind::IK_OperatorFunctionId:
9534   case UnqualifiedIdKind::IK_LiteralOperatorId:
9535   case UnqualifiedIdKind::IK_ConversionFunctionId:
9536     break;
9537
9538   case UnqualifiedIdKind::IK_ConstructorName:
9539   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9540     // C++11 inheriting constructors.
9541     Diag(Name.getBeginLoc(),
9542          getLangOpts().CPlusPlus11
9543              ? diag::warn_cxx98_compat_using_decl_constructor
9544              : diag::err_using_decl_constructor)
9545         << SS.getRange();
9546
9547     if (getLangOpts().CPlusPlus11) break;
9548
9549     return nullptr;
9550
9551   case UnqualifiedIdKind::IK_DestructorName:
9552     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9553     return nullptr;
9554
9555   case UnqualifiedIdKind::IK_TemplateId:
9556     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9557         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9558     return nullptr;
9559
9560   case UnqualifiedIdKind::IK_DeductionGuideName:
9561     llvm_unreachable("cannot parse qualified deduction guide name");
9562   }
9563
9564   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9565   DeclarationName TargetName = TargetNameInfo.getName();
9566   if (!TargetName)
9567     return nullptr;
9568
9569   // Warn about access declarations.
9570   if (UsingLoc.isInvalid()) {
9571     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9572                                  ? diag::err_access_decl
9573                                  : diag::warn_access_decl_deprecated)
9574         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9575   }
9576
9577   if (EllipsisLoc.isInvalid()) {
9578     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9579         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9580       return nullptr;
9581   } else {
9582     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9583         !TargetNameInfo.containsUnexpandedParameterPack()) {
9584       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9585         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9586       EllipsisLoc = SourceLocation();
9587     }
9588   }
9589
9590   NamedDecl *UD =
9591       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9592                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9593                             /*IsInstantiation*/false);
9594   if (UD)
9595     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9596
9597   return UD;
9598 }
9599
9600 /// Determine whether a using declaration considers the given
9601 /// declarations as "equivalent", e.g., if they are redeclarations of
9602 /// the same entity or are both typedefs of the same type.
9603 static bool
9604 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9605   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9606     return true;
9607
9608   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9609     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9610       return Context.hasSameType(TD1->getUnderlyingType(),
9611                                  TD2->getUnderlyingType());
9612
9613   return false;
9614 }
9615
9616
9617 /// Determines whether to create a using shadow decl for a particular
9618 /// decl, given the set of decls existing prior to this using lookup.
9619 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9620                                 const LookupResult &Previous,
9621                                 UsingShadowDecl *&PrevShadow) {
9622   // Diagnose finding a decl which is not from a base class of the
9623   // current class.  We do this now because there are cases where this
9624   // function will silently decide not to build a shadow decl, which
9625   // will pre-empt further diagnostics.
9626   //
9627   // We don't need to do this in C++11 because we do the check once on
9628   // the qualifier.
9629   //
9630   // FIXME: diagnose the following if we care enough:
9631   //   struct A { int foo; };
9632   //   struct B : A { using A::foo; };
9633   //   template <class T> struct C : A {};
9634   //   template <class T> struct D : C<T> { using B::foo; } // <---
9635   // This is invalid (during instantiation) in C++03 because B::foo
9636   // resolves to the using decl in B, which is not a base class of D<T>.
9637   // We can't diagnose it immediately because C<T> is an unknown
9638   // specialization.  The UsingShadowDecl in D<T> then points directly
9639   // to A::foo, which will look well-formed when we instantiate.
9640   // The right solution is to not collapse the shadow-decl chain.
9641   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9642     DeclContext *OrigDC = Orig->getDeclContext();
9643
9644     // Handle enums and anonymous structs.
9645     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9646     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9647     while (OrigRec->isAnonymousStructOrUnion())
9648       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9649
9650     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9651       if (OrigDC == CurContext) {
9652         Diag(Using->getLocation(),
9653              diag::err_using_decl_nested_name_specifier_is_current_class)
9654           << Using->getQualifierLoc().getSourceRange();
9655         Diag(Orig->getLocation(), diag::note_using_decl_target);
9656         Using->setInvalidDecl();
9657         return true;
9658       }
9659
9660       Diag(Using->getQualifierLoc().getBeginLoc(),
9661            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9662         << Using->getQualifier()
9663         << cast<CXXRecordDecl>(CurContext)
9664         << Using->getQualifierLoc().getSourceRange();
9665       Diag(Orig->getLocation(), diag::note_using_decl_target);
9666       Using->setInvalidDecl();
9667       return true;
9668     }
9669   }
9670
9671   if (Previous.empty()) return false;
9672
9673   NamedDecl *Target = Orig;
9674   if (isa<UsingShadowDecl>(Target))
9675     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9676
9677   // If the target happens to be one of the previous declarations, we
9678   // don't have a conflict.
9679   //
9680   // FIXME: but we might be increasing its access, in which case we
9681   // should redeclare it.
9682   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9683   bool FoundEquivalentDecl = false;
9684   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9685          I != E; ++I) {
9686     NamedDecl *D = (*I)->getUnderlyingDecl();
9687     // We can have UsingDecls in our Previous results because we use the same
9688     // LookupResult for checking whether the UsingDecl itself is a valid
9689     // redeclaration.
9690     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9691       continue;
9692
9693     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9694       // C++ [class.mem]p19:
9695       //   If T is the name of a class, then [every named member other than
9696       //   a non-static data member] shall have a name different from T
9697       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9698           !isa<IndirectFieldDecl>(Target) &&
9699           !isa<UnresolvedUsingValueDecl>(Target) &&
9700           DiagnoseClassNameShadow(
9701               CurContext,
9702               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9703         return true;
9704     }
9705
9706     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9707       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9708         PrevShadow = Shadow;
9709       FoundEquivalentDecl = true;
9710     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9711       // We don't conflict with an existing using shadow decl of an equivalent
9712       // declaration, but we're not a redeclaration of it.
9713       FoundEquivalentDecl = true;
9714     }
9715
9716     if (isVisible(D))
9717       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9718   }
9719
9720   if (FoundEquivalentDecl)
9721     return false;
9722
9723   if (FunctionDecl *FD = Target->getAsFunction()) {
9724     NamedDecl *OldDecl = nullptr;
9725     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9726                           /*IsForUsingDecl*/ true)) {
9727     case Ovl_Overload:
9728       return false;
9729
9730     case Ovl_NonFunction:
9731       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9732       break;
9733
9734     // We found a decl with the exact signature.
9735     case Ovl_Match:
9736       // If we're in a record, we want to hide the target, so we
9737       // return true (without a diagnostic) to tell the caller not to
9738       // build a shadow decl.
9739       if (CurContext->isRecord())
9740         return true;
9741
9742       // If we're not in a record, this is an error.
9743       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9744       break;
9745     }
9746
9747     Diag(Target->getLocation(), diag::note_using_decl_target);
9748     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9749     Using->setInvalidDecl();
9750     return true;
9751   }
9752
9753   // Target is not a function.
9754
9755   if (isa<TagDecl>(Target)) {
9756     // No conflict between a tag and a non-tag.
9757     if (!Tag) return false;
9758
9759     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9760     Diag(Target->getLocation(), diag::note_using_decl_target);
9761     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9762     Using->setInvalidDecl();
9763     return true;
9764   }
9765
9766   // No conflict between a tag and a non-tag.
9767   if (!NonTag) return false;
9768
9769   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9770   Diag(Target->getLocation(), diag::note_using_decl_target);
9771   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9772   Using->setInvalidDecl();
9773   return true;
9774 }
9775
9776 /// Determine whether a direct base class is a virtual base class.
9777 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9778   if (!Derived->getNumVBases())
9779     return false;
9780   for (auto &B : Derived->bases())
9781     if (B.getType()->getAsCXXRecordDecl() == Base)
9782       return B.isVirtual();
9783   llvm_unreachable("not a direct base class");
9784 }
9785
9786 /// Builds a shadow declaration corresponding to a 'using' declaration.
9787 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9788                                             UsingDecl *UD,
9789                                             NamedDecl *Orig,
9790                                             UsingShadowDecl *PrevDecl) {
9791   // If we resolved to another shadow declaration, just coalesce them.
9792   NamedDecl *Target = Orig;
9793   if (isa<UsingShadowDecl>(Target)) {
9794     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9795     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9796   }
9797
9798   NamedDecl *NonTemplateTarget = Target;
9799   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9800     NonTemplateTarget = TargetTD->getTemplatedDecl();
9801
9802   UsingShadowDecl *Shadow;
9803   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
9804     bool IsVirtualBase =
9805         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9806                             UD->getQualifier()->getAsRecordDecl());
9807     Shadow = ConstructorUsingShadowDecl::Create(
9808         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9809   } else {
9810     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9811                                      Target);
9812   }
9813   UD->addShadowDecl(Shadow);
9814
9815   Shadow->setAccess(UD->getAccess());
9816   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9817     Shadow->setInvalidDecl();
9818
9819   Shadow->setPreviousDecl(PrevDecl);
9820
9821   if (S)
9822     PushOnScopeChains(Shadow, S);
9823   else
9824     CurContext->addDecl(Shadow);
9825
9826
9827   return Shadow;
9828 }
9829
9830 /// Hides a using shadow declaration.  This is required by the current
9831 /// using-decl implementation when a resolvable using declaration in a
9832 /// class is followed by a declaration which would hide or override
9833 /// one or more of the using decl's targets; for example:
9834 ///
9835 ///   struct Base { void foo(int); };
9836 ///   struct Derived : Base {
9837 ///     using Base::foo;
9838 ///     void foo(int);
9839 ///   };
9840 ///
9841 /// The governing language is C++03 [namespace.udecl]p12:
9842 ///
9843 ///   When a using-declaration brings names from a base class into a
9844 ///   derived class scope, member functions in the derived class
9845 ///   override and/or hide member functions with the same name and
9846 ///   parameter types in a base class (rather than conflicting).
9847 ///
9848 /// There are two ways to implement this:
9849 ///   (1) optimistically create shadow decls when they're not hidden
9850 ///       by existing declarations, or
9851 ///   (2) don't create any shadow decls (or at least don't make them
9852 ///       visible) until we've fully parsed/instantiated the class.
9853 /// The problem with (1) is that we might have to retroactively remove
9854 /// a shadow decl, which requires several O(n) operations because the
9855 /// decl structures are (very reasonably) not designed for removal.
9856 /// (2) avoids this but is very fiddly and phase-dependent.
9857 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9858   if (Shadow->getDeclName().getNameKind() ==
9859         DeclarationName::CXXConversionFunctionName)
9860     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9861
9862   // Remove it from the DeclContext...
9863   Shadow->getDeclContext()->removeDecl(Shadow);
9864
9865   // ...and the scope, if applicable...
9866   if (S) {
9867     S->RemoveDecl(Shadow);
9868     IdResolver.RemoveDecl(Shadow);
9869   }
9870
9871   // ...and the using decl.
9872   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9873
9874   // TODO: complain somehow if Shadow was used.  It shouldn't
9875   // be possible for this to happen, because...?
9876 }
9877
9878 /// Find the base specifier for a base class with the given type.
9879 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9880                                                 QualType DesiredBase,
9881                                                 bool &AnyDependentBases) {
9882   // Check whether the named type is a direct base class.
9883   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9884   for (auto &Base : Derived->bases()) {
9885     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9886     if (CanonicalDesiredBase == BaseType)
9887       return &Base;
9888     if (BaseType->isDependentType())
9889       AnyDependentBases = true;
9890   }
9891   return nullptr;
9892 }
9893
9894 namespace {
9895 class UsingValidatorCCC final : public CorrectionCandidateCallback {
9896 public:
9897   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9898                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9899       : HasTypenameKeyword(HasTypenameKeyword),
9900         IsInstantiation(IsInstantiation), OldNNS(NNS),
9901         RequireMemberOf(RequireMemberOf) {}
9902
9903   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9904     NamedDecl *ND = Candidate.getCorrectionDecl();
9905
9906     // Keywords are not valid here.
9907     if (!ND || isa<NamespaceDecl>(ND))
9908       return false;
9909
9910     // Completely unqualified names are invalid for a 'using' declaration.
9911     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9912       return false;
9913
9914     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9915     // reject.
9916
9917     if (RequireMemberOf) {
9918       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9919       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9920         // No-one ever wants a using-declaration to name an injected-class-name
9921         // of a base class, unless they're declaring an inheriting constructor.
9922         ASTContext &Ctx = ND->getASTContext();
9923         if (!Ctx.getLangOpts().CPlusPlus11)
9924           return false;
9925         QualType FoundType = Ctx.getRecordType(FoundRecord);
9926
9927         // Check that the injected-class-name is named as a member of its own
9928         // type; we don't want to suggest 'using Derived::Base;', since that
9929         // means something else.
9930         NestedNameSpecifier *Specifier =
9931             Candidate.WillReplaceSpecifier()
9932                 ? Candidate.getCorrectionSpecifier()
9933                 : OldNNS;
9934         if (!Specifier->getAsType() ||
9935             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9936           return false;
9937
9938         // Check that this inheriting constructor declaration actually names a
9939         // direct base class of the current class.
9940         bool AnyDependentBases = false;
9941         if (!findDirectBaseWithType(RequireMemberOf,
9942                                     Ctx.getRecordType(FoundRecord),
9943                                     AnyDependentBases) &&
9944             !AnyDependentBases)
9945           return false;
9946       } else {
9947         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9948         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9949           return false;
9950
9951         // FIXME: Check that the base class member is accessible?
9952       }
9953     } else {
9954       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9955       if (FoundRecord && FoundRecord->isInjectedClassName())
9956         return false;
9957     }
9958
9959     if (isa<TypeDecl>(ND))
9960       return HasTypenameKeyword || !IsInstantiation;
9961
9962     return !HasTypenameKeyword;
9963   }
9964
9965   std::unique_ptr<CorrectionCandidateCallback> clone() override {
9966     return llvm::make_unique<UsingValidatorCCC>(*this);
9967   }
9968
9969 private:
9970   bool HasTypenameKeyword;
9971   bool IsInstantiation;
9972   NestedNameSpecifier *OldNNS;
9973   CXXRecordDecl *RequireMemberOf;
9974 };
9975 } // end anonymous namespace
9976
9977 /// Builds a using declaration.
9978 ///
9979 /// \param IsInstantiation - Whether this call arises from an
9980 ///   instantiation of an unresolved using declaration.  We treat
9981 ///   the lookup differently for these declarations.
9982 NamedDecl *Sema::BuildUsingDeclaration(
9983     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9984     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9985     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9986     const ParsedAttributesView &AttrList, bool IsInstantiation) {
9987   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9988   SourceLocation IdentLoc = NameInfo.getLoc();
9989   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9990
9991   // FIXME: We ignore attributes for now.
9992
9993   // For an inheriting constructor declaration, the name of the using
9994   // declaration is the name of a constructor in this class, not in the
9995   // base class.
9996   DeclarationNameInfo UsingName = NameInfo;
9997   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9998     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9999       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10000           Context.getCanonicalType(Context.getRecordType(RD))));
10001
10002   // Do the redeclaration lookup in the current scope.
10003   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
10004                         ForVisibleRedeclaration);
10005   Previous.setHideTags(false);
10006   if (S) {
10007     LookupName(Previous, S);
10008
10009     // It is really dumb that we have to do this.
10010     LookupResult::Filter F = Previous.makeFilter();
10011     while (F.hasNext()) {
10012       NamedDecl *D = F.next();
10013       if (!isDeclInScope(D, CurContext, S))
10014         F.erase();
10015       // If we found a local extern declaration that's not ordinarily visible,
10016       // and this declaration is being added to a non-block scope, ignore it.
10017       // We're only checking for scope conflicts here, not also for violations
10018       // of the linkage rules.
10019       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
10020                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
10021         F.erase();
10022     }
10023     F.done();
10024   } else {
10025     assert(IsInstantiation && "no scope in non-instantiation");
10026     if (CurContext->isRecord())
10027       LookupQualifiedName(Previous, CurContext);
10028     else {
10029       // No redeclaration check is needed here; in non-member contexts we
10030       // diagnosed all possible conflicts with other using-declarations when
10031       // building the template:
10032       //
10033       // For a dependent non-type using declaration, the only valid case is
10034       // if we instantiate to a single enumerator. We check for conflicts
10035       // between shadow declarations we introduce, and we check in the template
10036       // definition for conflicts between a non-type using declaration and any
10037       // other declaration, which together covers all cases.
10038       //
10039       // A dependent typename using declaration will never successfully
10040       // instantiate, since it will always name a class member, so we reject
10041       // that in the template definition.
10042     }
10043   }
10044
10045   // Check for invalid redeclarations.
10046   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
10047                                   SS, IdentLoc, Previous))
10048     return nullptr;
10049
10050   // Check for bad qualifiers.
10051   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
10052                               IdentLoc))
10053     return nullptr;
10054
10055   DeclContext *LookupContext = computeDeclContext(SS);
10056   NamedDecl *D;
10057   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10058   if (!LookupContext || EllipsisLoc.isValid()) {
10059     if (HasTypenameKeyword) {
10060       // FIXME: not all declaration name kinds are legal here
10061       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
10062                                               UsingLoc, TypenameLoc,
10063                                               QualifierLoc,
10064                                               IdentLoc, NameInfo.getName(),
10065                                               EllipsisLoc);
10066     } else {
10067       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
10068                                            QualifierLoc, NameInfo, EllipsisLoc);
10069     }
10070     D->setAccess(AS);
10071     CurContext->addDecl(D);
10072     return D;
10073   }
10074
10075   auto Build = [&](bool Invalid) {
10076     UsingDecl *UD =
10077         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10078                           UsingName, HasTypenameKeyword);
10079     UD->setAccess(AS);
10080     CurContext->addDecl(UD);
10081     UD->setInvalidDecl(Invalid);
10082     return UD;
10083   };
10084   auto BuildInvalid = [&]{ return Build(true); };
10085   auto BuildValid = [&]{ return Build(false); };
10086
10087   if (RequireCompleteDeclContext(SS, LookupContext))
10088     return BuildInvalid();
10089
10090   // Look up the target name.
10091   LookupResult R(*this, NameInfo, LookupOrdinaryName);
10092
10093   // Unlike most lookups, we don't always want to hide tag
10094   // declarations: tag names are visible through the using declaration
10095   // even if hidden by ordinary names, *except* in a dependent context
10096   // where it's important for the sanity of two-phase lookup.
10097   if (!IsInstantiation)
10098     R.setHideTags(false);
10099
10100   // For the purposes of this lookup, we have a base object type
10101   // equal to that of the current context.
10102   if (CurContext->isRecord()) {
10103     R.setBaseObjectType(
10104                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10105   }
10106
10107   LookupQualifiedName(R, LookupContext);
10108
10109   // Try to correct typos if possible. If constructor name lookup finds no
10110   // results, that means the named class has no explicit constructors, and we
10111   // suppressed declaring implicit ones (probably because it's dependent or
10112   // invalid).
10113   if (R.empty() &&
10114       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10115     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10116     // it will believe that glibc provides a ::gets in cases where it does not,
10117     // and will try to pull it into namespace std with a using-declaration.
10118     // Just ignore the using-declaration in that case.
10119     auto *II = NameInfo.getName().getAsIdentifierInfo();
10120     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10121         CurContext->isStdNamespace() &&
10122         isa<TranslationUnitDecl>(LookupContext) &&
10123         getSourceManager().isInSystemHeader(UsingLoc))
10124       return nullptr;
10125     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10126                           dyn_cast<CXXRecordDecl>(CurContext));
10127     if (TypoCorrection Corrected =
10128             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
10129                         CTK_ErrorRecovery)) {
10130       // We reject candidates where DroppedSpecifier == true, hence the
10131       // literal '0' below.
10132       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10133                                 << NameInfo.getName() << LookupContext << 0
10134                                 << SS.getRange());
10135
10136       // If we picked a correction with no attached Decl we can't do anything
10137       // useful with it, bail out.
10138       NamedDecl *ND = Corrected.getCorrectionDecl();
10139       if (!ND)
10140         return BuildInvalid();
10141
10142       // If we corrected to an inheriting constructor, handle it as one.
10143       auto *RD = dyn_cast<CXXRecordDecl>(ND);
10144       if (RD && RD->isInjectedClassName()) {
10145         // The parent of the injected class name is the class itself.
10146         RD = cast<CXXRecordDecl>(RD->getParent());
10147
10148         // Fix up the information we'll use to build the using declaration.
10149         if (Corrected.WillReplaceSpecifier()) {
10150           NestedNameSpecifierLocBuilder Builder;
10151           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10152                               QualifierLoc.getSourceRange());
10153           QualifierLoc = Builder.getWithLocInContext(Context);
10154         }
10155
10156         // In this case, the name we introduce is the name of a derived class
10157         // constructor.
10158         auto *CurClass = cast<CXXRecordDecl>(CurContext);
10159         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10160             Context.getCanonicalType(Context.getRecordType(CurClass))));
10161         UsingName.setNamedTypeInfo(nullptr);
10162         for (auto *Ctor : LookupConstructors(RD))
10163           R.addDecl(Ctor);
10164         R.resolveKind();
10165       } else {
10166         // FIXME: Pick up all the declarations if we found an overloaded
10167         // function.
10168         UsingName.setName(ND->getDeclName());
10169         R.addDecl(ND);
10170       }
10171     } else {
10172       Diag(IdentLoc, diag::err_no_member)
10173         << NameInfo.getName() << LookupContext << SS.getRange();
10174       return BuildInvalid();
10175     }
10176   }
10177
10178   if (R.isAmbiguous())
10179     return BuildInvalid();
10180
10181   if (HasTypenameKeyword) {
10182     // If we asked for a typename and got a non-type decl, error out.
10183     if (!R.getAsSingle<TypeDecl>()) {
10184       Diag(IdentLoc, diag::err_using_typename_non_type);
10185       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10186         Diag((*I)->getUnderlyingDecl()->getLocation(),
10187              diag::note_using_decl_target);
10188       return BuildInvalid();
10189     }
10190   } else {
10191     // If we asked for a non-typename and we got a type, error out,
10192     // but only if this is an instantiation of an unresolved using
10193     // decl.  Otherwise just silently find the type name.
10194     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10195       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10196       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10197       return BuildInvalid();
10198     }
10199   }
10200
10201   // C++14 [namespace.udecl]p6:
10202   // A using-declaration shall not name a namespace.
10203   if (R.getAsSingle<NamespaceDecl>()) {
10204     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10205       << SS.getRange();
10206     return BuildInvalid();
10207   }
10208
10209   // C++14 [namespace.udecl]p7:
10210   // A using-declaration shall not name a scoped enumerator.
10211   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10212     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10213       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10214         << SS.getRange();
10215       return BuildInvalid();
10216     }
10217   }
10218
10219   UsingDecl *UD = BuildValid();
10220
10221   // Some additional rules apply to inheriting constructors.
10222   if (UsingName.getName().getNameKind() ==
10223         DeclarationName::CXXConstructorName) {
10224     // Suppress access diagnostics; the access check is instead performed at the
10225     // point of use for an inheriting constructor.
10226     R.suppressDiagnostics();
10227     if (CheckInheritingConstructorUsingDecl(UD))
10228       return UD;
10229   }
10230
10231   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10232     UsingShadowDecl *PrevDecl = nullptr;
10233     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10234       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10235   }
10236
10237   return UD;
10238 }
10239
10240 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10241                                     ArrayRef<NamedDecl *> Expansions) {
10242   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10243          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10244          isa<UsingPackDecl>(InstantiatedFrom));
10245
10246   auto *UPD =
10247       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10248   UPD->setAccess(InstantiatedFrom->getAccess());
10249   CurContext->addDecl(UPD);
10250   return UPD;
10251 }
10252
10253 /// Additional checks for a using declaration referring to a constructor name.
10254 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10255   assert(!UD->hasTypename() && "expecting a constructor name");
10256
10257   const Type *SourceType = UD->getQualifier()->getAsType();
10258   assert(SourceType &&
10259          "Using decl naming constructor doesn't have type in scope spec.");
10260   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10261
10262   // Check whether the named type is a direct base class.
10263   bool AnyDependentBases = false;
10264   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10265                                       AnyDependentBases);
10266   if (!Base && !AnyDependentBases) {
10267     Diag(UD->getUsingLoc(),
10268          diag::err_using_decl_constructor_not_in_direct_base)
10269       << UD->getNameInfo().getSourceRange()
10270       << QualType(SourceType, 0) << TargetClass;
10271     UD->setInvalidDecl();
10272     return true;
10273   }
10274
10275   if (Base)
10276     Base->setInheritConstructors();
10277
10278   return false;
10279 }
10280
10281 /// Checks that the given using declaration is not an invalid
10282 /// redeclaration.  Note that this is checking only for the using decl
10283 /// itself, not for any ill-formedness among the UsingShadowDecls.
10284 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10285                                        bool HasTypenameKeyword,
10286                                        const CXXScopeSpec &SS,
10287                                        SourceLocation NameLoc,
10288                                        const LookupResult &Prev) {
10289   NestedNameSpecifier *Qual = SS.getScopeRep();
10290
10291   // C++03 [namespace.udecl]p8:
10292   // C++0x [namespace.udecl]p10:
10293   //   A using-declaration is a declaration and can therefore be used
10294   //   repeatedly where (and only where) multiple declarations are
10295   //   allowed.
10296   //
10297   // That's in non-member contexts.
10298   if (!CurContext->getRedeclContext()->isRecord()) {
10299     // A dependent qualifier outside a class can only ever resolve to an
10300     // enumeration type. Therefore it conflicts with any other non-type
10301     // declaration in the same scope.
10302     // FIXME: How should we check for dependent type-type conflicts at block
10303     // scope?
10304     if (Qual->isDependent() && !HasTypenameKeyword) {
10305       for (auto *D : Prev) {
10306         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10307           bool OldCouldBeEnumerator =
10308               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10309           Diag(NameLoc,
10310                OldCouldBeEnumerator ? diag::err_redefinition
10311                                     : diag::err_redefinition_different_kind)
10312               << Prev.getLookupName();
10313           Diag(D->getLocation(), diag::note_previous_definition);
10314           return true;
10315         }
10316       }
10317     }
10318     return false;
10319   }
10320
10321   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10322     NamedDecl *D = *I;
10323
10324     bool DTypename;
10325     NestedNameSpecifier *DQual;
10326     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10327       DTypename = UD->hasTypename();
10328       DQual = UD->getQualifier();
10329     } else if (UnresolvedUsingValueDecl *UD
10330                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10331       DTypename = false;
10332       DQual = UD->getQualifier();
10333     } else if (UnresolvedUsingTypenameDecl *UD
10334                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10335       DTypename = true;
10336       DQual = UD->getQualifier();
10337     } else continue;
10338
10339     // using decls differ if one says 'typename' and the other doesn't.
10340     // FIXME: non-dependent using decls?
10341     if (HasTypenameKeyword != DTypename) continue;
10342
10343     // using decls differ if they name different scopes (but note that
10344     // template instantiation can cause this check to trigger when it
10345     // didn't before instantiation).
10346     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10347         Context.getCanonicalNestedNameSpecifier(DQual))
10348       continue;
10349
10350     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10351     Diag(D->getLocation(), diag::note_using_decl) << 1;
10352     return true;
10353   }
10354
10355   return false;
10356 }
10357
10358
10359 /// Checks that the given nested-name qualifier used in a using decl
10360 /// in the current context is appropriately related to the current
10361 /// scope.  If an error is found, diagnoses it and returns true.
10362 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10363                                    bool HasTypename,
10364                                    const CXXScopeSpec &SS,
10365                                    const DeclarationNameInfo &NameInfo,
10366                                    SourceLocation NameLoc) {
10367   DeclContext *NamedContext = computeDeclContext(SS);
10368
10369   if (!CurContext->isRecord()) {
10370     // C++03 [namespace.udecl]p3:
10371     // C++0x [namespace.udecl]p8:
10372     //   A using-declaration for a class member shall be a member-declaration.
10373
10374     // If we weren't able to compute a valid scope, it might validly be a
10375     // dependent class scope or a dependent enumeration unscoped scope. If
10376     // we have a 'typename' keyword, the scope must resolve to a class type.
10377     if ((HasTypename && !NamedContext) ||
10378         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10379       auto *RD = NamedContext
10380                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10381                      : nullptr;
10382       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10383         RD = nullptr;
10384
10385       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10386         << SS.getRange();
10387
10388       // If we have a complete, non-dependent source type, try to suggest a
10389       // way to get the same effect.
10390       if (!RD)
10391         return true;
10392
10393       // Find what this using-declaration was referring to.
10394       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10395       R.setHideTags(false);
10396       R.suppressDiagnostics();
10397       LookupQualifiedName(R, RD);
10398
10399       if (R.getAsSingle<TypeDecl>()) {
10400         if (getLangOpts().CPlusPlus11) {
10401           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10402           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10403             << 0 // alias declaration
10404             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10405                                           NameInfo.getName().getAsString() +
10406                                               " = ");
10407         } else {
10408           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10409           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10410           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10411             << 1 // typedef declaration
10412             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10413             << FixItHint::CreateInsertion(
10414                    InsertLoc, " " + NameInfo.getName().getAsString());
10415         }
10416       } else if (R.getAsSingle<VarDecl>()) {
10417         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10418         // repeating the type of the static data member here.
10419         FixItHint FixIt;
10420         if (getLangOpts().CPlusPlus11) {
10421           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10422           FixIt = FixItHint::CreateReplacement(
10423               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10424         }
10425
10426         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10427           << 2 // reference declaration
10428           << FixIt;
10429       } else if (R.getAsSingle<EnumConstantDecl>()) {
10430         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10431         // repeating the type of the enumeration here, and we can't do so if
10432         // the type is anonymous.
10433         FixItHint FixIt;
10434         if (getLangOpts().CPlusPlus11) {
10435           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10436           FixIt = FixItHint::CreateReplacement(
10437               UsingLoc,
10438               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10439         }
10440
10441         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10442           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10443           << FixIt;
10444       }
10445       return true;
10446     }
10447
10448     // Otherwise, this might be valid.
10449     return false;
10450   }
10451
10452   // The current scope is a record.
10453
10454   // If the named context is dependent, we can't decide much.
10455   if (!NamedContext) {
10456     // FIXME: in C++0x, we can diagnose if we can prove that the
10457     // nested-name-specifier does not refer to a base class, which is
10458     // still possible in some cases.
10459
10460     // Otherwise we have to conservatively report that things might be
10461     // okay.
10462     return false;
10463   }
10464
10465   if (!NamedContext->isRecord()) {
10466     // Ideally this would point at the last name in the specifier,
10467     // but we don't have that level of source info.
10468     Diag(SS.getRange().getBegin(),
10469          diag::err_using_decl_nested_name_specifier_is_not_class)
10470       << SS.getScopeRep() << SS.getRange();
10471     return true;
10472   }
10473
10474   if (!NamedContext->isDependentContext() &&
10475       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10476     return true;
10477
10478   if (getLangOpts().CPlusPlus11) {
10479     // C++11 [namespace.udecl]p3:
10480     //   In a using-declaration used as a member-declaration, the
10481     //   nested-name-specifier shall name a base class of the class
10482     //   being defined.
10483
10484     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10485                                  cast<CXXRecordDecl>(NamedContext))) {
10486       if (CurContext == NamedContext) {
10487         Diag(NameLoc,
10488              diag::err_using_decl_nested_name_specifier_is_current_class)
10489           << SS.getRange();
10490         return true;
10491       }
10492
10493       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10494         Diag(SS.getRange().getBegin(),
10495              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10496           << SS.getScopeRep()
10497           << cast<CXXRecordDecl>(CurContext)
10498           << SS.getRange();
10499       }
10500       return true;
10501     }
10502
10503     return false;
10504   }
10505
10506   // C++03 [namespace.udecl]p4:
10507   //   A using-declaration used as a member-declaration shall refer
10508   //   to a member of a base class of the class being defined [etc.].
10509
10510   // Salient point: SS doesn't have to name a base class as long as
10511   // lookup only finds members from base classes.  Therefore we can
10512   // diagnose here only if we can prove that that can't happen,
10513   // i.e. if the class hierarchies provably don't intersect.
10514
10515   // TODO: it would be nice if "definitely valid" results were cached
10516   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10517   // need to be repeated.
10518
10519   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10520   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10521     Bases.insert(Base);
10522     return true;
10523   };
10524
10525   // Collect all bases. Return false if we find a dependent base.
10526   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10527     return false;
10528
10529   // Returns true if the base is dependent or is one of the accumulated base
10530   // classes.
10531   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10532     return !Bases.count(Base);
10533   };
10534
10535   // Return false if the class has a dependent base or if it or one
10536   // of its bases is present in the base set of the current context.
10537   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10538       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10539     return false;
10540
10541   Diag(SS.getRange().getBegin(),
10542        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10543     << SS.getScopeRep()
10544     << cast<CXXRecordDecl>(CurContext)
10545     << SS.getRange();
10546
10547   return true;
10548 }
10549
10550 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10551                                   MultiTemplateParamsArg TemplateParamLists,
10552                                   SourceLocation UsingLoc, UnqualifiedId &Name,
10553                                   const ParsedAttributesView &AttrList,
10554                                   TypeResult Type, Decl *DeclFromDeclSpec) {
10555   // Skip up to the relevant declaration scope.
10556   while (S->isTemplateParamScope())
10557     S = S->getParent();
10558   assert((S->getFlags() & Scope::DeclScope) &&
10559          "got alias-declaration outside of declaration scope");
10560
10561   if (Type.isInvalid())
10562     return nullptr;
10563
10564   bool Invalid = false;
10565   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10566   TypeSourceInfo *TInfo = nullptr;
10567   GetTypeFromParser(Type.get(), &TInfo);
10568
10569   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10570     return nullptr;
10571
10572   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10573                                       UPPC_DeclarationType)) {
10574     Invalid = true;
10575     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10576                                              TInfo->getTypeLoc().getBeginLoc());
10577   }
10578
10579   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10580                         TemplateParamLists.size()
10581                             ? forRedeclarationInCurContext()
10582                             : ForVisibleRedeclaration);
10583   LookupName(Previous, S);
10584
10585   // Warn about shadowing the name of a template parameter.
10586   if (Previous.isSingleResult() &&
10587       Previous.getFoundDecl()->isTemplateParameter()) {
10588     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10589     Previous.clear();
10590   }
10591
10592   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10593          "name in alias declaration must be an identifier");
10594   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10595                                                Name.StartLocation,
10596                                                Name.Identifier, TInfo);
10597
10598   NewTD->setAccess(AS);
10599
10600   if (Invalid)
10601     NewTD->setInvalidDecl();
10602
10603   ProcessDeclAttributeList(S, NewTD, AttrList);
10604   AddPragmaAttributes(S, NewTD);
10605
10606   CheckTypedefForVariablyModifiedType(S, NewTD);
10607   Invalid |= NewTD->isInvalidDecl();
10608
10609   bool Redeclaration = false;
10610
10611   NamedDecl *NewND;
10612   if (TemplateParamLists.size()) {
10613     TypeAliasTemplateDecl *OldDecl = nullptr;
10614     TemplateParameterList *OldTemplateParams = nullptr;
10615
10616     if (TemplateParamLists.size() != 1) {
10617       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10618         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10619          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10620     }
10621     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10622
10623     // Check that we can declare a template here.
10624     if (CheckTemplateDeclScope(S, TemplateParams))
10625       return nullptr;
10626
10627     // Only consider previous declarations in the same scope.
10628     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10629                          /*ExplicitInstantiationOrSpecialization*/false);
10630     if (!Previous.empty()) {
10631       Redeclaration = true;
10632
10633       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10634       if (!OldDecl && !Invalid) {
10635         Diag(UsingLoc, diag::err_redefinition_different_kind)
10636           << Name.Identifier;
10637
10638         NamedDecl *OldD = Previous.getRepresentativeDecl();
10639         if (OldD->getLocation().isValid())
10640           Diag(OldD->getLocation(), diag::note_previous_definition);
10641
10642         Invalid = true;
10643       }
10644
10645       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10646         if (TemplateParameterListsAreEqual(TemplateParams,
10647                                            OldDecl->getTemplateParameters(),
10648                                            /*Complain=*/true,
10649                                            TPL_TemplateMatch))
10650           OldTemplateParams =
10651               OldDecl->getMostRecentDecl()->getTemplateParameters();
10652         else
10653           Invalid = true;
10654
10655         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10656         if (!Invalid &&
10657             !Context.hasSameType(OldTD->getUnderlyingType(),
10658                                  NewTD->getUnderlyingType())) {
10659           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10660           // but we can't reasonably accept it.
10661           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10662             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10663           if (OldTD->getLocation().isValid())
10664             Diag(OldTD->getLocation(), diag::note_previous_definition);
10665           Invalid = true;
10666         }
10667       }
10668     }
10669
10670     // Merge any previous default template arguments into our parameters,
10671     // and check the parameter list.
10672     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10673                                    TPC_TypeAliasTemplate))
10674       return nullptr;
10675
10676     TypeAliasTemplateDecl *NewDecl =
10677       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10678                                     Name.Identifier, TemplateParams,
10679                                     NewTD);
10680     NewTD->setDescribedAliasTemplate(NewDecl);
10681
10682     NewDecl->setAccess(AS);
10683
10684     if (Invalid)
10685       NewDecl->setInvalidDecl();
10686     else if (OldDecl) {
10687       NewDecl->setPreviousDecl(OldDecl);
10688       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10689     }
10690
10691     NewND = NewDecl;
10692   } else {
10693     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10694       setTagNameForLinkagePurposes(TD, NewTD);
10695       handleTagNumbering(TD, S);
10696     }
10697     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10698     NewND = NewTD;
10699   }
10700
10701   PushOnScopeChains(NewND, S);
10702   ActOnDocumentableDecl(NewND);
10703   return NewND;
10704 }
10705
10706 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10707                                    SourceLocation AliasLoc,
10708                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10709                                    SourceLocation IdentLoc,
10710                                    IdentifierInfo *Ident) {
10711
10712   // Lookup the namespace name.
10713   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10714   LookupParsedName(R, S, &SS);
10715
10716   if (R.isAmbiguous())
10717     return nullptr;
10718
10719   if (R.empty()) {
10720     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10721       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10722       return nullptr;
10723     }
10724   }
10725   assert(!R.isAmbiguous() && !R.empty());
10726   NamedDecl *ND = R.getRepresentativeDecl();
10727
10728   // Check if we have a previous declaration with the same name.
10729   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10730                      ForVisibleRedeclaration);
10731   LookupName(PrevR, S);
10732
10733   // Check we're not shadowing a template parameter.
10734   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10735     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10736     PrevR.clear();
10737   }
10738
10739   // Filter out any other lookup result from an enclosing scope.
10740   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10741                        /*AllowInlineNamespace*/false);
10742
10743   // Find the previous declaration and check that we can redeclare it.
10744   NamespaceAliasDecl *Prev = nullptr;
10745   if (PrevR.isSingleResult()) {
10746     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10747     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10748       // We already have an alias with the same name that points to the same
10749       // namespace; check that it matches.
10750       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10751         Prev = AD;
10752       } else if (isVisible(PrevDecl)) {
10753         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10754           << Alias;
10755         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10756           << AD->getNamespace();
10757         return nullptr;
10758       }
10759     } else if (isVisible(PrevDecl)) {
10760       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10761                             ? diag::err_redefinition
10762                             : diag::err_redefinition_different_kind;
10763       Diag(AliasLoc, DiagID) << Alias;
10764       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10765       return nullptr;
10766     }
10767   }
10768
10769   // The use of a nested name specifier may trigger deprecation warnings.
10770   DiagnoseUseOfDecl(ND, IdentLoc);
10771
10772   NamespaceAliasDecl *AliasDecl =
10773     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10774                                Alias, SS.getWithLocInContext(Context),
10775                                IdentLoc, ND);
10776   if (Prev)
10777     AliasDecl->setPreviousDecl(Prev);
10778
10779   PushOnScopeChains(AliasDecl, S);
10780   return AliasDecl;
10781 }
10782
10783 namespace {
10784 struct SpecialMemberExceptionSpecInfo
10785     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10786   SourceLocation Loc;
10787   Sema::ImplicitExceptionSpecification ExceptSpec;
10788
10789   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10790                                  Sema::CXXSpecialMember CSM,
10791                                  Sema::InheritedConstructorInfo *ICI,
10792                                  SourceLocation Loc)
10793       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10794
10795   bool visitBase(CXXBaseSpecifier *Base);
10796   bool visitField(FieldDecl *FD);
10797
10798   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10799                            unsigned Quals);
10800
10801   void visitSubobjectCall(Subobject Subobj,
10802                           Sema::SpecialMemberOverloadResult SMOR);
10803 };
10804 }
10805
10806 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10807   auto *RT = Base->getType()->getAs<RecordType>();
10808   if (!RT)
10809     return false;
10810
10811   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10812   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10813   if (auto *BaseCtor = SMOR.getMethod()) {
10814     visitSubobjectCall(Base, BaseCtor);
10815     return false;
10816   }
10817
10818   visitClassSubobject(BaseClass, Base, 0);
10819   return false;
10820 }
10821
10822 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10823   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10824     Expr *E = FD->getInClassInitializer();
10825     if (!E)
10826       // FIXME: It's a little wasteful to build and throw away a
10827       // CXXDefaultInitExpr here.
10828       // FIXME: We should have a single context note pointing at Loc, and
10829       // this location should be MD->getLocation() instead, since that's
10830       // the location where we actually use the default init expression.
10831       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10832     if (E)
10833       ExceptSpec.CalledExpr(E);
10834   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10835                             ->getAs<RecordType>()) {
10836     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10837                         FD->getType().getCVRQualifiers());
10838   }
10839   return false;
10840 }
10841
10842 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10843                                                          Subobject Subobj,
10844                                                          unsigned Quals) {
10845   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10846   bool IsMutable = Field && Field->isMutable();
10847   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10848 }
10849
10850 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10851     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10852   // Note, if lookup fails, it doesn't matter what exception specification we
10853   // choose because the special member will be deleted.
10854   if (CXXMethodDecl *MD = SMOR.getMethod())
10855     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10856 }
10857
10858 namespace {
10859 /// RAII object to register a special member as being currently declared.
10860 struct ComputingExceptionSpec {
10861   Sema &S;
10862
10863   ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
10864       : S(S) {
10865     Sema::CodeSynthesisContext Ctx;
10866     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
10867     Ctx.PointOfInstantiation = Loc;
10868     Ctx.Entity = MD;
10869     S.pushCodeSynthesisContext(Ctx);
10870   }
10871   ~ComputingExceptionSpec() {
10872     S.popCodeSynthesisContext();
10873   }
10874 };
10875 }
10876
10877 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
10878   llvm::APSInt Result;
10879   ExprResult Converted = CheckConvertedConstantExpression(
10880       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
10881   ExplicitSpec.setExpr(Converted.get());
10882   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
10883     ExplicitSpec.setKind(Result.getBoolValue()
10884                              ? ExplicitSpecKind::ResolvedTrue
10885                              : ExplicitSpecKind::ResolvedFalse);
10886     return true;
10887   }
10888   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
10889   return false;
10890 }
10891
10892 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
10893   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
10894   if (!ExplicitExpr->isTypeDependent())
10895     tryResolveExplicitSpecifier(ES);
10896   return ES;
10897 }
10898
10899 static Sema::ImplicitExceptionSpecification
10900 ComputeDefaultedSpecialMemberExceptionSpec(
10901     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10902     Sema::InheritedConstructorInfo *ICI) {
10903   ComputingExceptionSpec CES(S, MD, Loc);
10904
10905   CXXRecordDecl *ClassDecl = MD->getParent();
10906
10907   // C++ [except.spec]p14:
10908   //   An implicitly declared special member function (Clause 12) shall have an
10909   //   exception-specification. [...]
10910   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
10911   if (ClassDecl->isInvalidDecl())
10912     return Info.ExceptSpec;
10913
10914   // FIXME: If this diagnostic fires, we're probably missing a check for
10915   // attempting to resolve an exception specification before it's known
10916   // at a higher level.
10917   if (S.RequireCompleteType(MD->getLocation(),
10918                             S.Context.getRecordType(ClassDecl),
10919                             diag::err_exception_spec_incomplete_type))
10920     return Info.ExceptSpec;
10921
10922   // C++1z [except.spec]p7:
10923   //   [Look for exceptions thrown by] a constructor selected [...] to
10924   //   initialize a potentially constructed subobject,
10925   // C++1z [except.spec]p8:
10926   //   The exception specification for an implicitly-declared destructor, or a
10927   //   destructor without a noexcept-specifier, is potentially-throwing if and
10928   //   only if any of the destructors for any of its potentially constructed
10929   //   subojects is potentially throwing.
10930   // FIXME: We respect the first rule but ignore the "potentially constructed"
10931   // in the second rule to resolve a core issue (no number yet) that would have
10932   // us reject:
10933   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10934   //   struct B : A {};
10935   //   struct C : B { void f(); };
10936   // ... due to giving B::~B() a non-throwing exception specification.
10937   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10938                                 : Info.VisitAllBases);
10939
10940   return Info.ExceptSpec;
10941 }
10942
10943 namespace {
10944 /// RAII object to register a special member as being currently declared.
10945 struct DeclaringSpecialMember {
10946   Sema &S;
10947   Sema::SpecialMemberDecl D;
10948   Sema::ContextRAII SavedContext;
10949   bool WasAlreadyBeingDeclared;
10950
10951   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10952       : S(S), D(RD, CSM), SavedContext(S, RD) {
10953     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10954     if (WasAlreadyBeingDeclared)
10955       // This almost never happens, but if it does, ensure that our cache
10956       // doesn't contain a stale result.
10957       S.SpecialMemberCache.clear();
10958     else {
10959       // Register a note to be produced if we encounter an error while
10960       // declaring the special member.
10961       Sema::CodeSynthesisContext Ctx;
10962       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10963       // FIXME: We don't have a location to use here. Using the class's
10964       // location maintains the fiction that we declare all special members
10965       // with the class, but (1) it's not clear that lying about that helps our
10966       // users understand what's going on, and (2) there may be outer contexts
10967       // on the stack (some of which are relevant) and printing them exposes
10968       // our lies.
10969       Ctx.PointOfInstantiation = RD->getLocation();
10970       Ctx.Entity = RD;
10971       Ctx.SpecialMember = CSM;
10972       S.pushCodeSynthesisContext(Ctx);
10973     }
10974   }
10975   ~DeclaringSpecialMember() {
10976     if (!WasAlreadyBeingDeclared) {
10977       S.SpecialMembersBeingDeclared.erase(D);
10978       S.popCodeSynthesisContext();
10979     }
10980   }
10981
10982   /// Are we already trying to declare this special member?
10983   bool isAlreadyBeingDeclared() const {
10984     return WasAlreadyBeingDeclared;
10985   }
10986 };
10987 }
10988
10989 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10990   // Look up any existing declarations, but don't trigger declaration of all
10991   // implicit special members with this name.
10992   DeclarationName Name = FD->getDeclName();
10993   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10994                  ForExternalRedeclaration);
10995   for (auto *D : FD->getParent()->lookup(Name))
10996     if (auto *Acceptable = R.getAcceptableDecl(D))
10997       R.addDecl(Acceptable);
10998   R.resolveKind();
10999   R.suppressDiagnostics();
11000
11001   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
11002 }
11003
11004 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
11005                                           QualType ResultTy,
11006                                           ArrayRef<QualType> Args) {
11007   // Build an exception specification pointing back at this constructor.
11008   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
11009
11010   if (getLangOpts().OpenCLCPlusPlus) {
11011     // OpenCL: Implicitly defaulted special member are of the generic address
11012     // space.
11013     EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
11014   }
11015
11016   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
11017   SpecialMem->setType(QT);
11018 }
11019
11020 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
11021                                                      CXXRecordDecl *ClassDecl) {
11022   // C++ [class.ctor]p5:
11023   //   A default constructor for a class X is a constructor of class X
11024   //   that can be called without an argument. If there is no
11025   //   user-declared constructor for class X, a default constructor is
11026   //   implicitly declared. An implicitly-declared default constructor
11027   //   is an inline public member of its class.
11028   assert(ClassDecl->needsImplicitDefaultConstructor() &&
11029          "Should not build implicit default constructor!");
11030
11031   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
11032   if (DSM.isAlreadyBeingDeclared())
11033     return nullptr;
11034
11035   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11036                                                      CXXDefaultConstructor,
11037                                                      false);
11038
11039   // Create the actual constructor declaration.
11040   CanQualType ClassType
11041     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11042   SourceLocation ClassLoc = ClassDecl->getLocation();
11043   DeclarationName Name
11044     = Context.DeclarationNames.getCXXConstructorName(ClassType);
11045   DeclarationNameInfo NameInfo(Name, ClassLoc);
11046   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
11047       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
11048       /*TInfo=*/nullptr, ExplicitSpecifier(),
11049       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11050       Constexpr ? CSK_constexpr : CSK_unspecified);
11051   DefaultCon->setAccess(AS_public);
11052   DefaultCon->setDefaulted();
11053
11054   if (getLangOpts().CUDA) {
11055     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
11056                                             DefaultCon,
11057                                             /* ConstRHS */ false,
11058                                             /* Diagnose */ false);
11059   }
11060
11061   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
11062
11063   // We don't need to use SpecialMemberIsTrivial here; triviality for default
11064   // constructors is easy to compute.
11065   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
11066
11067   // Note that we have declared this constructor.
11068   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
11069
11070   Scope *S = getScopeForContext(ClassDecl);
11071   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
11072
11073   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
11074     SetDeclDeleted(DefaultCon, ClassLoc);
11075
11076   if (S)
11077     PushOnScopeChains(DefaultCon, S, false);
11078   ClassDecl->addDecl(DefaultCon);
11079
11080   return DefaultCon;
11081 }
11082
11083 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
11084                                             CXXConstructorDecl *Constructor) {
11085   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
11086           !Constructor->doesThisDeclarationHaveABody() &&
11087           !Constructor->isDeleted()) &&
11088     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
11089   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11090     return;
11091
11092   CXXRecordDecl *ClassDecl = Constructor->getParent();
11093   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
11094
11095   SynthesizedFunctionScope Scope(*this, Constructor);
11096
11097   // The exception specification is needed because we are defining the
11098   // function.
11099   ResolveExceptionSpec(CurrentLocation,
11100                        Constructor->getType()->castAs<FunctionProtoType>());
11101   MarkVTableUsed(CurrentLocation, ClassDecl);
11102
11103   // Add a context note for diagnostics produced after this point.
11104   Scope.addContextNote(CurrentLocation);
11105
11106   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11107     Constructor->setInvalidDecl();
11108     return;
11109   }
11110
11111   SourceLocation Loc = Constructor->getEndLoc().isValid()
11112                            ? Constructor->getEndLoc()
11113                            : Constructor->getLocation();
11114   Constructor->setBody(new (Context) CompoundStmt(Loc));
11115   Constructor->markUsed(Context);
11116
11117   if (ASTMutationListener *L = getASTMutationListener()) {
11118     L->CompletedImplicitDefinition(Constructor);
11119   }
11120
11121   DiagnoseUninitializedFields(*this, Constructor);
11122 }
11123
11124 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
11125   // Perform any delayed checks on exception specifications.
11126   CheckDelayedMemberExceptionSpecs();
11127 }
11128
11129 /// Find or create the fake constructor we synthesize to model constructing an
11130 /// object of a derived class via a constructor of a base class.
11131 CXXConstructorDecl *
11132 Sema::findInheritingConstructor(SourceLocation Loc,
11133                                 CXXConstructorDecl *BaseCtor,
11134                                 ConstructorUsingShadowDecl *Shadow) {
11135   CXXRecordDecl *Derived = Shadow->getParent();
11136   SourceLocation UsingLoc = Shadow->getLocation();
11137
11138   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11139   // For now we use the name of the base class constructor as a member of the
11140   // derived class to indicate a (fake) inherited constructor name.
11141   DeclarationName Name = BaseCtor->getDeclName();
11142
11143   // Check to see if we already have a fake constructor for this inherited
11144   // constructor call.
11145   for (NamedDecl *Ctor : Derived->lookup(Name))
11146     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11147                                ->getInheritedConstructor()
11148                                .getConstructor(),
11149                            BaseCtor))
11150       return cast<CXXConstructorDecl>(Ctor);
11151
11152   DeclarationNameInfo NameInfo(Name, UsingLoc);
11153   TypeSourceInfo *TInfo =
11154       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11155   FunctionProtoTypeLoc ProtoLoc =
11156       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11157
11158   // Check the inherited constructor is valid and find the list of base classes
11159   // from which it was inherited.
11160   InheritedConstructorInfo ICI(*this, Loc, Shadow);
11161
11162   bool Constexpr =
11163       BaseCtor->isConstexpr() &&
11164       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11165                                         false, BaseCtor, &ICI);
11166
11167   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11168       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11169       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
11170       /*isImplicitlyDeclared=*/true,
11171       Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
11172       InheritedConstructor(Shadow, BaseCtor));
11173   if (Shadow->isInvalidDecl())
11174     DerivedCtor->setInvalidDecl();
11175
11176   // Build an unevaluated exception specification for this fake constructor.
11177   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11178   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11179   EPI.ExceptionSpec.Type = EST_Unevaluated;
11180   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11181   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11182                                                FPT->getParamTypes(), EPI));
11183
11184   // Build the parameter declarations.
11185   SmallVector<ParmVarDecl *, 16> ParamDecls;
11186   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11187     TypeSourceInfo *TInfo =
11188         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11189     ParmVarDecl *PD = ParmVarDecl::Create(
11190         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11191         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
11192     PD->setScopeInfo(0, I);
11193     PD->setImplicit();
11194     // Ensure attributes are propagated onto parameters (this matters for
11195     // format, pass_object_size, ...).
11196     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11197     ParamDecls.push_back(PD);
11198     ProtoLoc.setParam(I, PD);
11199   }
11200
11201   // Set up the new constructor.
11202   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11203   DerivedCtor->setAccess(BaseCtor->getAccess());
11204   DerivedCtor->setParams(ParamDecls);
11205   Derived->addDecl(DerivedCtor);
11206
11207   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11208     SetDeclDeleted(DerivedCtor, UsingLoc);
11209
11210   return DerivedCtor;
11211 }
11212
11213 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11214   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11215                                Ctor->getInheritedConstructor().getShadowDecl());
11216   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11217                             /*Diagnose*/true);
11218 }
11219
11220 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11221                                        CXXConstructorDecl *Constructor) {
11222   CXXRecordDecl *ClassDecl = Constructor->getParent();
11223   assert(Constructor->getInheritedConstructor() &&
11224          !Constructor->doesThisDeclarationHaveABody() &&
11225          !Constructor->isDeleted());
11226   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11227     return;
11228
11229   // Initializations are performed "as if by a defaulted default constructor",
11230   // so enter the appropriate scope.
11231   SynthesizedFunctionScope Scope(*this, Constructor);
11232
11233   // The exception specification is needed because we are defining the
11234   // function.
11235   ResolveExceptionSpec(CurrentLocation,
11236                        Constructor->getType()->castAs<FunctionProtoType>());
11237   MarkVTableUsed(CurrentLocation, ClassDecl);
11238
11239   // Add a context note for diagnostics produced after this point.
11240   Scope.addContextNote(CurrentLocation);
11241
11242   ConstructorUsingShadowDecl *Shadow =
11243       Constructor->getInheritedConstructor().getShadowDecl();
11244   CXXConstructorDecl *InheritedCtor =
11245       Constructor->getInheritedConstructor().getConstructor();
11246
11247   // [class.inhctor.init]p1:
11248   //   initialization proceeds as if a defaulted default constructor is used to
11249   //   initialize the D object and each base class subobject from which the
11250   //   constructor was inherited
11251
11252   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11253   CXXRecordDecl *RD = Shadow->getParent();
11254   SourceLocation InitLoc = Shadow->getLocation();
11255
11256   // Build explicit initializers for all base classes from which the
11257   // constructor was inherited.
11258   SmallVector<CXXCtorInitializer*, 8> Inits;
11259   for (bool VBase : {false, true}) {
11260     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11261       if (B.isVirtual() != VBase)
11262         continue;
11263
11264       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11265       if (!BaseRD)
11266         continue;
11267
11268       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11269       if (!BaseCtor.first)
11270         continue;
11271
11272       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11273       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11274           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11275
11276       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11277       Inits.push_back(new (Context) CXXCtorInitializer(
11278           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11279           SourceLocation()));
11280     }
11281   }
11282
11283   // We now proceed as if for a defaulted default constructor, with the relevant
11284   // initializers replaced.
11285
11286   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11287     Constructor->setInvalidDecl();
11288     return;
11289   }
11290
11291   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11292   Constructor->markUsed(Context);
11293
11294   if (ASTMutationListener *L = getASTMutationListener()) {
11295     L->CompletedImplicitDefinition(Constructor);
11296   }
11297
11298   DiagnoseUninitializedFields(*this, Constructor);
11299 }
11300
11301 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11302   // C++ [class.dtor]p2:
11303   //   If a class has no user-declared destructor, a destructor is
11304   //   declared implicitly. An implicitly-declared destructor is an
11305   //   inline public member of its class.
11306   assert(ClassDecl->needsImplicitDestructor());
11307
11308   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11309   if (DSM.isAlreadyBeingDeclared())
11310     return nullptr;
11311
11312   // Create the actual destructor declaration.
11313   CanQualType ClassType
11314     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11315   SourceLocation ClassLoc = ClassDecl->getLocation();
11316   DeclarationName Name
11317     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11318   DeclarationNameInfo NameInfo(Name, ClassLoc);
11319   CXXDestructorDecl *Destructor
11320       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11321                                   QualType(), nullptr, /*isInline=*/true,
11322                                   /*isImplicitlyDeclared=*/true);
11323   Destructor->setAccess(AS_public);
11324   Destructor->setDefaulted();
11325
11326   if (getLangOpts().CUDA) {
11327     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11328                                             Destructor,
11329                                             /* ConstRHS */ false,
11330                                             /* Diagnose */ false);
11331   }
11332
11333   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
11334
11335   // We don't need to use SpecialMemberIsTrivial here; triviality for
11336   // destructors is easy to compute.
11337   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11338   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11339                                 ClassDecl->hasTrivialDestructorForCall());
11340
11341   // Note that we have declared this destructor.
11342   ++getASTContext().NumImplicitDestructorsDeclared;
11343
11344   Scope *S = getScopeForContext(ClassDecl);
11345   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11346
11347   // We can't check whether an implicit destructor is deleted before we complete
11348   // the definition of the class, because its validity depends on the alignment
11349   // of the class. We'll check this from ActOnFields once the class is complete.
11350   if (ClassDecl->isCompleteDefinition() &&
11351       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11352     SetDeclDeleted(Destructor, ClassLoc);
11353
11354   // Introduce this destructor into its scope.
11355   if (S)
11356     PushOnScopeChains(Destructor, S, false);
11357   ClassDecl->addDecl(Destructor);
11358
11359   return Destructor;
11360 }
11361
11362 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11363                                     CXXDestructorDecl *Destructor) {
11364   assert((Destructor->isDefaulted() &&
11365           !Destructor->doesThisDeclarationHaveABody() &&
11366           !Destructor->isDeleted()) &&
11367          "DefineImplicitDestructor - call it for implicit default dtor");
11368   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11369     return;
11370
11371   CXXRecordDecl *ClassDecl = Destructor->getParent();
11372   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11373
11374   SynthesizedFunctionScope Scope(*this, Destructor);
11375
11376   // The exception specification is needed because we are defining the
11377   // function.
11378   ResolveExceptionSpec(CurrentLocation,
11379                        Destructor->getType()->castAs<FunctionProtoType>());
11380   MarkVTableUsed(CurrentLocation, ClassDecl);
11381
11382   // Add a context note for diagnostics produced after this point.
11383   Scope.addContextNote(CurrentLocation);
11384
11385   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11386                                          Destructor->getParent());
11387
11388   if (CheckDestructor(Destructor)) {
11389     Destructor->setInvalidDecl();
11390     return;
11391   }
11392
11393   SourceLocation Loc = Destructor->getEndLoc().isValid()
11394                            ? Destructor->getEndLoc()
11395                            : Destructor->getLocation();
11396   Destructor->setBody(new (Context) CompoundStmt(Loc));
11397   Destructor->markUsed(Context);
11398
11399   if (ASTMutationListener *L = getASTMutationListener()) {
11400     L->CompletedImplicitDefinition(Destructor);
11401   }
11402 }
11403
11404 /// Perform any semantic analysis which needs to be delayed until all
11405 /// pending class member declarations have been parsed.
11406 void Sema::ActOnFinishCXXMemberDecls() {
11407   // If the context is an invalid C++ class, just suppress these checks.
11408   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11409     if (Record->isInvalidDecl()) {
11410       DelayedOverridingExceptionSpecChecks.clear();
11411       DelayedEquivalentExceptionSpecChecks.clear();
11412       return;
11413     }
11414     checkForMultipleExportedDefaultConstructors(*this, Record);
11415   }
11416 }
11417
11418 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11419   referenceDLLExportedClassMethods();
11420
11421   if (!DelayedDllExportMemberFunctions.empty()) {
11422     SmallVector<CXXMethodDecl*, 4> WorkList;
11423     std::swap(DelayedDllExportMemberFunctions, WorkList);
11424     for (CXXMethodDecl *M : WorkList) {
11425       DefineImplicitSpecialMember(*this, M, M->getLocation());
11426
11427       // Pass the method to the consumer to get emitted. This is not necessary
11428       // for explicit instantiation definitions, as they will get emitted
11429       // anyway.
11430       if (M->getParent()->getTemplateSpecializationKind() !=
11431           TSK_ExplicitInstantiationDefinition)
11432         ActOnFinishInlineFunctionDef(M);
11433     }
11434   }
11435 }
11436
11437 void Sema::referenceDLLExportedClassMethods() {
11438   if (!DelayedDllExportClasses.empty()) {
11439     // Calling ReferenceDllExportedMembers might cause the current function to
11440     // be called again, so use a local copy of DelayedDllExportClasses.
11441     SmallVector<CXXRecordDecl *, 4> WorkList;
11442     std::swap(DelayedDllExportClasses, WorkList);
11443     for (CXXRecordDecl *Class : WorkList)
11444       ReferenceDllExportedMembers(*this, Class);
11445   }
11446 }
11447
11448 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11449   assert(getLangOpts().CPlusPlus11 &&
11450          "adjusting dtor exception specs was introduced in c++11");
11451
11452   if (Destructor->isDependentContext())
11453     return;
11454
11455   // C++11 [class.dtor]p3:
11456   //   A declaration of a destructor that does not have an exception-
11457   //   specification is implicitly considered to have the same exception-
11458   //   specification as an implicit declaration.
11459   const FunctionProtoType *DtorType = Destructor->getType()->
11460                                         getAs<FunctionProtoType>();
11461   if (DtorType->hasExceptionSpec())
11462     return;
11463
11464   // Replace the destructor's type, building off the existing one. Fortunately,
11465   // the only thing of interest in the destructor type is its extended info.
11466   // The return and arguments are fixed.
11467   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11468   EPI.ExceptionSpec.Type = EST_Unevaluated;
11469   EPI.ExceptionSpec.SourceDecl = Destructor;
11470   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11471
11472   // FIXME: If the destructor has a body that could throw, and the newly created
11473   // spec doesn't allow exceptions, we should emit a warning, because this
11474   // change in behavior can break conforming C++03 programs at runtime.
11475   // However, we don't have a body or an exception specification yet, so it
11476   // needs to be done somewhere else.
11477 }
11478
11479 namespace {
11480 /// An abstract base class for all helper classes used in building the
11481 //  copy/move operators. These classes serve as factory functions and help us
11482 //  avoid using the same Expr* in the AST twice.
11483 class ExprBuilder {
11484   ExprBuilder(const ExprBuilder&) = delete;
11485   ExprBuilder &operator=(const ExprBuilder&) = delete;
11486
11487 protected:
11488   static Expr *assertNotNull(Expr *E) {
11489     assert(E && "Expression construction must not fail.");
11490     return E;
11491   }
11492
11493 public:
11494   ExprBuilder() {}
11495   virtual ~ExprBuilder() {}
11496
11497   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11498 };
11499
11500 class RefBuilder: public ExprBuilder {
11501   VarDecl *Var;
11502   QualType VarType;
11503
11504 public:
11505   Expr *build(Sema &S, SourceLocation Loc) const override {
11506     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
11507   }
11508
11509   RefBuilder(VarDecl *Var, QualType VarType)
11510       : Var(Var), VarType(VarType) {}
11511 };
11512
11513 class ThisBuilder: public ExprBuilder {
11514 public:
11515   Expr *build(Sema &S, SourceLocation Loc) const override {
11516     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11517   }
11518 };
11519
11520 class CastBuilder: public ExprBuilder {
11521   const ExprBuilder &Builder;
11522   QualType Type;
11523   ExprValueKind Kind;
11524   const CXXCastPath &Path;
11525
11526 public:
11527   Expr *build(Sema &S, SourceLocation Loc) const override {
11528     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11529                                              CK_UncheckedDerivedToBase, Kind,
11530                                              &Path).get());
11531   }
11532
11533   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11534               const CXXCastPath &Path)
11535       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11536 };
11537
11538 class DerefBuilder: public ExprBuilder {
11539   const ExprBuilder &Builder;
11540
11541 public:
11542   Expr *build(Sema &S, SourceLocation Loc) const override {
11543     return assertNotNull(
11544         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11545   }
11546
11547   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11548 };
11549
11550 class MemberBuilder: public ExprBuilder {
11551   const ExprBuilder &Builder;
11552   QualType Type;
11553   CXXScopeSpec SS;
11554   bool IsArrow;
11555   LookupResult &MemberLookup;
11556
11557 public:
11558   Expr *build(Sema &S, SourceLocation Loc) const override {
11559     return assertNotNull(S.BuildMemberReferenceExpr(
11560         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11561         nullptr, MemberLookup, nullptr, nullptr).get());
11562   }
11563
11564   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11565                 LookupResult &MemberLookup)
11566       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11567         MemberLookup(MemberLookup) {}
11568 };
11569
11570 class MoveCastBuilder: public ExprBuilder {
11571   const ExprBuilder &Builder;
11572
11573 public:
11574   Expr *build(Sema &S, SourceLocation Loc) const override {
11575     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11576   }
11577
11578   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11579 };
11580
11581 class LvalueConvBuilder: public ExprBuilder {
11582   const ExprBuilder &Builder;
11583
11584 public:
11585   Expr *build(Sema &S, SourceLocation Loc) const override {
11586     return assertNotNull(
11587         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11588   }
11589
11590   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11591 };
11592
11593 class SubscriptBuilder: public ExprBuilder {
11594   const ExprBuilder &Base;
11595   const ExprBuilder &Index;
11596
11597 public:
11598   Expr *build(Sema &S, SourceLocation Loc) const override {
11599     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11600         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11601   }
11602
11603   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11604       : Base(Base), Index(Index) {}
11605 };
11606
11607 } // end anonymous namespace
11608
11609 /// When generating a defaulted copy or move assignment operator, if a field
11610 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11611 /// do so. This optimization only applies for arrays of scalars, and for arrays
11612 /// of class type where the selected copy/move-assignment operator is trivial.
11613 static StmtResult
11614 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11615                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11616   // Compute the size of the memory buffer to be copied.
11617   QualType SizeType = S.Context.getSizeType();
11618   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11619                    S.Context.getTypeSizeInChars(T).getQuantity());
11620
11621   // Take the address of the field references for "from" and "to". We
11622   // directly construct UnaryOperators here because semantic analysis
11623   // does not permit us to take the address of an xvalue.
11624   Expr *From = FromB.build(S, Loc);
11625   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11626                          S.Context.getPointerType(From->getType()),
11627                          VK_RValue, OK_Ordinary, Loc, false);
11628   Expr *To = ToB.build(S, Loc);
11629   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11630                        S.Context.getPointerType(To->getType()),
11631                        VK_RValue, OK_Ordinary, Loc, false);
11632
11633   const Type *E = T->getBaseElementTypeUnsafe();
11634   bool NeedsCollectableMemCpy =
11635     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11636
11637   // Create a reference to the __builtin_objc_memmove_collectable function
11638   StringRef MemCpyName = NeedsCollectableMemCpy ?
11639     "__builtin_objc_memmove_collectable" :
11640     "__builtin_memcpy";
11641   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11642                  Sema::LookupOrdinaryName);
11643   S.LookupName(R, S.TUScope, true);
11644
11645   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11646   if (!MemCpy)
11647     // Something went horribly wrong earlier, and we will have complained
11648     // about it.
11649     return StmtError();
11650
11651   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11652                                             VK_RValue, Loc, nullptr);
11653   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11654
11655   Expr *CallArgs[] = {
11656     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11657   };
11658   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11659                                     Loc, CallArgs, Loc);
11660
11661   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11662   return Call.getAs<Stmt>();
11663 }
11664
11665 /// Builds a statement that copies/moves the given entity from \p From to
11666 /// \c To.
11667 ///
11668 /// This routine is used to copy/move the members of a class with an
11669 /// implicitly-declared copy/move assignment operator. When the entities being
11670 /// copied are arrays, this routine builds for loops to copy them.
11671 ///
11672 /// \param S The Sema object used for type-checking.
11673 ///
11674 /// \param Loc The location where the implicit copy/move is being generated.
11675 ///
11676 /// \param T The type of the expressions being copied/moved. Both expressions
11677 /// must have this type.
11678 ///
11679 /// \param To The expression we are copying/moving to.
11680 ///
11681 /// \param From The expression we are copying/moving from.
11682 ///
11683 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11684 /// Otherwise, it's a non-static member subobject.
11685 ///
11686 /// \param Copying Whether we're copying or moving.
11687 ///
11688 /// \param Depth Internal parameter recording the depth of the recursion.
11689 ///
11690 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11691 /// if a memcpy should be used instead.
11692 static StmtResult
11693 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11694                                  const ExprBuilder &To, const ExprBuilder &From,
11695                                  bool CopyingBaseSubobject, bool Copying,
11696                                  unsigned Depth = 0) {
11697   // C++11 [class.copy]p28:
11698   //   Each subobject is assigned in the manner appropriate to its type:
11699   //
11700   //     - if the subobject is of class type, as if by a call to operator= with
11701   //       the subobject as the object expression and the corresponding
11702   //       subobject of x as a single function argument (as if by explicit
11703   //       qualification; that is, ignoring any possible virtual overriding
11704   //       functions in more derived classes);
11705   //
11706   // C++03 [class.copy]p13:
11707   //     - if the subobject is of class type, the copy assignment operator for
11708   //       the class is used (as if by explicit qualification; that is,
11709   //       ignoring any possible virtual overriding functions in more derived
11710   //       classes);
11711   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11712     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11713
11714     // Look for operator=.
11715     DeclarationName Name
11716       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11717     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11718     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11719
11720     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11721     // operator.
11722     if (!S.getLangOpts().CPlusPlus11) {
11723       LookupResult::Filter F = OpLookup.makeFilter();
11724       while (F.hasNext()) {
11725         NamedDecl *D = F.next();
11726         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11727           if (Method->isCopyAssignmentOperator() ||
11728               (!Copying && Method->isMoveAssignmentOperator()))
11729             continue;
11730
11731         F.erase();
11732       }
11733       F.done();
11734     }
11735
11736     // Suppress the protected check (C++ [class.protected]) for each of the
11737     // assignment operators we found. This strange dance is required when
11738     // we're assigning via a base classes's copy-assignment operator. To
11739     // ensure that we're getting the right base class subobject (without
11740     // ambiguities), we need to cast "this" to that subobject type; to
11741     // ensure that we don't go through the virtual call mechanism, we need
11742     // to qualify the operator= name with the base class (see below). However,
11743     // this means that if the base class has a protected copy assignment
11744     // operator, the protected member access check will fail. So, we
11745     // rewrite "protected" access to "public" access in this case, since we
11746     // know by construction that we're calling from a derived class.
11747     if (CopyingBaseSubobject) {
11748       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11749            L != LEnd; ++L) {
11750         if (L.getAccess() == AS_protected)
11751           L.setAccess(AS_public);
11752       }
11753     }
11754
11755     // Create the nested-name-specifier that will be used to qualify the
11756     // reference to operator=; this is required to suppress the virtual
11757     // call mechanism.
11758     CXXScopeSpec SS;
11759     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11760     SS.MakeTrivial(S.Context,
11761                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11762                                                CanonicalT),
11763                    Loc);
11764
11765     // Create the reference to operator=.
11766     ExprResult OpEqualRef
11767       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
11768                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11769                                    /*FirstQualifierInScope=*/nullptr,
11770                                    OpLookup,
11771                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11772                                    /*SuppressQualifierCheck=*/true);
11773     if (OpEqualRef.isInvalid())
11774       return StmtError();
11775
11776     // Build the call to the assignment operator.
11777
11778     Expr *FromInst = From.build(S, Loc);
11779     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11780                                                   OpEqualRef.getAs<Expr>(),
11781                                                   Loc, FromInst, Loc);
11782     if (Call.isInvalid())
11783       return StmtError();
11784
11785     // If we built a call to a trivial 'operator=' while copying an array,
11786     // bail out. We'll replace the whole shebang with a memcpy.
11787     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11788     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11789       return StmtResult((Stmt*)nullptr);
11790
11791     // Convert to an expression-statement, and clean up any produced
11792     // temporaries.
11793     return S.ActOnExprStmt(Call);
11794   }
11795
11796   //     - if the subobject is of scalar type, the built-in assignment
11797   //       operator is used.
11798   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11799   if (!ArrayTy) {
11800     ExprResult Assignment = S.CreateBuiltinBinOp(
11801         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11802     if (Assignment.isInvalid())
11803       return StmtError();
11804     return S.ActOnExprStmt(Assignment);
11805   }
11806
11807   //     - if the subobject is an array, each element is assigned, in the
11808   //       manner appropriate to the element type;
11809
11810   // Construct a loop over the array bounds, e.g.,
11811   //
11812   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11813   //
11814   // that will copy each of the array elements.
11815   QualType SizeType = S.Context.getSizeType();
11816
11817   // Create the iteration variable.
11818   IdentifierInfo *IterationVarName = nullptr;
11819   {
11820     SmallString<8> Str;
11821     llvm::raw_svector_ostream OS(Str);
11822     OS << "__i" << Depth;
11823     IterationVarName = &S.Context.Idents.get(OS.str());
11824   }
11825   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11826                                           IterationVarName, SizeType,
11827                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11828                                           SC_None);
11829
11830   // Initialize the iteration variable to zero.
11831   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11832   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11833
11834   // Creates a reference to the iteration variable.
11835   RefBuilder IterationVarRef(IterationVar, SizeType);
11836   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11837
11838   // Create the DeclStmt that holds the iteration variable.
11839   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11840
11841   // Subscript the "from" and "to" expressions with the iteration variable.
11842   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11843   MoveCastBuilder FromIndexMove(FromIndexCopy);
11844   const ExprBuilder *FromIndex;
11845   if (Copying)
11846     FromIndex = &FromIndexCopy;
11847   else
11848     FromIndex = &FromIndexMove;
11849
11850   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11851
11852   // Build the copy/move for an individual element of the array.
11853   StmtResult Copy =
11854     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11855                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11856                                      Copying, Depth + 1);
11857   // Bail out if copying fails or if we determined that we should use memcpy.
11858   if (Copy.isInvalid() || !Copy.get())
11859     return Copy;
11860
11861   // Create the comparison against the array bound.
11862   llvm::APInt Upper
11863     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11864   Expr *Comparison
11865     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11866                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11867                                      BO_NE, S.Context.BoolTy,
11868                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11869
11870   // Create the pre-increment of the iteration variable. We can determine
11871   // whether the increment will overflow based on the value of the array
11872   // bound.
11873   Expr *Increment = new (S.Context)
11874       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11875                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11876
11877   // Construct the loop that copies all elements of this array.
11878   return S.ActOnForStmt(
11879       Loc, Loc, InitStmt,
11880       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11881       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11882 }
11883
11884 static StmtResult
11885 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11886                       const ExprBuilder &To, const ExprBuilder &From,
11887                       bool CopyingBaseSubobject, bool Copying) {
11888   // Maybe we should use a memcpy?
11889   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11890       T.isTriviallyCopyableType(S.Context))
11891     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11892
11893   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11894                                                      CopyingBaseSubobject,
11895                                                      Copying, 0));
11896
11897   // If we ended up picking a trivial assignment operator for an array of a
11898   // non-trivially-copyable class type, just emit a memcpy.
11899   if (!Result.isInvalid() && !Result.get())
11900     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11901
11902   return Result;
11903 }
11904
11905 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11906   // Note: The following rules are largely analoguous to the copy
11907   // constructor rules. Note that virtual bases are not taken into account
11908   // for determining the argument type of the operator. Note also that
11909   // operators taking an object instead of a reference are allowed.
11910   assert(ClassDecl->needsImplicitCopyAssignment());
11911
11912   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11913   if (DSM.isAlreadyBeingDeclared())
11914     return nullptr;
11915
11916   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11917   if (Context.getLangOpts().OpenCLCPlusPlus)
11918     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
11919   QualType RetType = Context.getLValueReferenceType(ArgType);
11920   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11921   if (Const)
11922     ArgType = ArgType.withConst();
11923
11924   ArgType = Context.getLValueReferenceType(ArgType);
11925
11926   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11927                                                      CXXCopyAssignment,
11928                                                      Const);
11929
11930   //   An implicitly-declared copy assignment operator is an inline public
11931   //   member of its class.
11932   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11933   SourceLocation ClassLoc = ClassDecl->getLocation();
11934   DeclarationNameInfo NameInfo(Name, ClassLoc);
11935   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
11936       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11937       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11938       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
11939       SourceLocation());
11940   CopyAssignment->setAccess(AS_public);
11941   CopyAssignment->setDefaulted();
11942   CopyAssignment->setImplicit();
11943
11944   if (getLangOpts().CUDA) {
11945     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11946                                             CopyAssignment,
11947                                             /* ConstRHS */ Const,
11948                                             /* Diagnose */ false);
11949   }
11950
11951   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
11952
11953   // Add the parameter to the operator.
11954   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11955                                                ClassLoc, ClassLoc,
11956                                                /*Id=*/nullptr, ArgType,
11957                                                /*TInfo=*/nullptr, SC_None,
11958                                                nullptr);
11959   CopyAssignment->setParams(FromParam);
11960
11961   CopyAssignment->setTrivial(
11962     ClassDecl->needsOverloadResolutionForCopyAssignment()
11963       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11964       : ClassDecl->hasTrivialCopyAssignment());
11965
11966   // Note that we have added this copy-assignment operator.
11967   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
11968
11969   Scope *S = getScopeForContext(ClassDecl);
11970   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11971
11972   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11973     SetDeclDeleted(CopyAssignment, ClassLoc);
11974
11975   if (S)
11976     PushOnScopeChains(CopyAssignment, S, false);
11977   ClassDecl->addDecl(CopyAssignment);
11978
11979   return CopyAssignment;
11980 }
11981
11982 /// Diagnose an implicit copy operation for a class which is odr-used, but
11983 /// which is deprecated because the class has a user-declared copy constructor,
11984 /// copy assignment operator, or destructor.
11985 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11986   assert(CopyOp->isImplicit());
11987
11988   CXXRecordDecl *RD = CopyOp->getParent();
11989   CXXMethodDecl *UserDeclaredOperation = nullptr;
11990
11991   // In Microsoft mode, assignment operations don't affect constructors and
11992   // vice versa.
11993   if (RD->hasUserDeclaredDestructor()) {
11994     UserDeclaredOperation = RD->getDestructor();
11995   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11996              RD->hasUserDeclaredCopyConstructor() &&
11997              !S.getLangOpts().MSVCCompat) {
11998     // Find any user-declared copy constructor.
11999     for (auto *I : RD->ctors()) {
12000       if (I->isCopyConstructor()) {
12001         UserDeclaredOperation = I;
12002         break;
12003       }
12004     }
12005     assert(UserDeclaredOperation);
12006   } else if (isa<CXXConstructorDecl>(CopyOp) &&
12007              RD->hasUserDeclaredCopyAssignment() &&
12008              !S.getLangOpts().MSVCCompat) {
12009     // Find any user-declared move assignment operator.
12010     for (auto *I : RD->methods()) {
12011       if (I->isCopyAssignmentOperator()) {
12012         UserDeclaredOperation = I;
12013         break;
12014       }
12015     }
12016     assert(UserDeclaredOperation);
12017   }
12018
12019   if (UserDeclaredOperation) {
12020     S.Diag(UserDeclaredOperation->getLocation(),
12021          diag::warn_deprecated_copy_operation)
12022       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
12023       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
12024   }
12025 }
12026
12027 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
12028                                         CXXMethodDecl *CopyAssignOperator) {
12029   assert((CopyAssignOperator->isDefaulted() &&
12030           CopyAssignOperator->isOverloadedOperator() &&
12031           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
12032           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
12033           !CopyAssignOperator->isDeleted()) &&
12034          "DefineImplicitCopyAssignment called for wrong function");
12035   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
12036     return;
12037
12038   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
12039   if (ClassDecl->isInvalidDecl()) {
12040     CopyAssignOperator->setInvalidDecl();
12041     return;
12042   }
12043
12044   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
12045
12046   // The exception specification is needed because we are defining the
12047   // function.
12048   ResolveExceptionSpec(CurrentLocation,
12049                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
12050
12051   // Add a context note for diagnostics produced after this point.
12052   Scope.addContextNote(CurrentLocation);
12053
12054   // C++11 [class.copy]p18:
12055   //   The [definition of an implicitly declared copy assignment operator] is
12056   //   deprecated if the class has a user-declared copy constructor or a
12057   //   user-declared destructor.
12058   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
12059     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
12060
12061   // C++0x [class.copy]p30:
12062   //   The implicitly-defined or explicitly-defaulted copy assignment operator
12063   //   for a non-union class X performs memberwise copy assignment of its
12064   //   subobjects. The direct base classes of X are assigned first, in the
12065   //   order of their declaration in the base-specifier-list, and then the
12066   //   immediate non-static data members of X are assigned, in the order in
12067   //   which they were declared in the class definition.
12068
12069   // The statements that form the synthesized function body.
12070   SmallVector<Stmt*, 8> Statements;
12071
12072   // The parameter for the "other" object, which we are copying from.
12073   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
12074   Qualifiers OtherQuals = Other->getType().getQualifiers();
12075   QualType OtherRefType = Other->getType();
12076   if (const LValueReferenceType *OtherRef
12077                                 = OtherRefType->getAs<LValueReferenceType>()) {
12078     OtherRefType = OtherRef->getPointeeType();
12079     OtherQuals = OtherRefType.getQualifiers();
12080   }
12081
12082   // Our location for everything implicitly-generated.
12083   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
12084                            ? CopyAssignOperator->getEndLoc()
12085                            : CopyAssignOperator->getLocation();
12086
12087   // Builds a DeclRefExpr for the "other" object.
12088   RefBuilder OtherRef(Other, OtherRefType);
12089
12090   // Builds the "this" pointer.
12091   ThisBuilder This;
12092
12093   // Assign base classes.
12094   bool Invalid = false;
12095   for (auto &Base : ClassDecl->bases()) {
12096     // Form the assignment:
12097     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
12098     QualType BaseType = Base.getType().getUnqualifiedType();
12099     if (!BaseType->isRecordType()) {
12100       Invalid = true;
12101       continue;
12102     }
12103
12104     CXXCastPath BasePath;
12105     BasePath.push_back(&Base);
12106
12107     // Construct the "from" expression, which is an implicit cast to the
12108     // appropriately-qualified base type.
12109     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
12110                      VK_LValue, BasePath);
12111
12112     // Dereference "this".
12113     DerefBuilder DerefThis(This);
12114     CastBuilder To(DerefThis,
12115                    Context.getQualifiedType(
12116                        BaseType, CopyAssignOperator->getMethodQualifiers()),
12117                    VK_LValue, BasePath);
12118
12119     // Build the copy.
12120     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12121                                             To, From,
12122                                             /*CopyingBaseSubobject=*/true,
12123                                             /*Copying=*/true);
12124     if (Copy.isInvalid()) {
12125       CopyAssignOperator->setInvalidDecl();
12126       return;
12127     }
12128
12129     // Success! Record the copy.
12130     Statements.push_back(Copy.getAs<Expr>());
12131   }
12132
12133   // Assign non-static members.
12134   for (auto *Field : ClassDecl->fields()) {
12135     // FIXME: We should form some kind of AST representation for the implied
12136     // memcpy in a union copy operation.
12137     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12138       continue;
12139
12140     if (Field->isInvalidDecl()) {
12141       Invalid = true;
12142       continue;
12143     }
12144
12145     // Check for members of reference type; we can't copy those.
12146     if (Field->getType()->isReferenceType()) {
12147       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12148         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12149       Diag(Field->getLocation(), diag::note_declared_at);
12150       Invalid = true;
12151       continue;
12152     }
12153
12154     // Check for members of const-qualified, non-class type.
12155     QualType BaseType = Context.getBaseElementType(Field->getType());
12156     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12157       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12158         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12159       Diag(Field->getLocation(), diag::note_declared_at);
12160       Invalid = true;
12161       continue;
12162     }
12163
12164     // Suppress assigning zero-width bitfields.
12165     if (Field->isZeroLengthBitField(Context))
12166       continue;
12167
12168     QualType FieldType = Field->getType().getNonReferenceType();
12169     if (FieldType->isIncompleteArrayType()) {
12170       assert(ClassDecl->hasFlexibleArrayMember() &&
12171              "Incomplete array type is not valid");
12172       continue;
12173     }
12174
12175     // Build references to the field in the object we're copying from and to.
12176     CXXScopeSpec SS; // Intentionally empty
12177     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12178                               LookupMemberName);
12179     MemberLookup.addDecl(Field);
12180     MemberLookup.resolveKind();
12181
12182     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12183
12184     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12185
12186     // Build the copy of this field.
12187     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12188                                             To, From,
12189                                             /*CopyingBaseSubobject=*/false,
12190                                             /*Copying=*/true);
12191     if (Copy.isInvalid()) {
12192       CopyAssignOperator->setInvalidDecl();
12193       return;
12194     }
12195
12196     // Success! Record the copy.
12197     Statements.push_back(Copy.getAs<Stmt>());
12198   }
12199
12200   if (!Invalid) {
12201     // Add a "return *this;"
12202     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12203
12204     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12205     if (Return.isInvalid())
12206       Invalid = true;
12207     else
12208       Statements.push_back(Return.getAs<Stmt>());
12209   }
12210
12211   if (Invalid) {
12212     CopyAssignOperator->setInvalidDecl();
12213     return;
12214   }
12215
12216   StmtResult Body;
12217   {
12218     CompoundScopeRAII CompoundScope(*this);
12219     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12220                              /*isStmtExpr=*/false);
12221     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12222   }
12223   CopyAssignOperator->setBody(Body.getAs<Stmt>());
12224   CopyAssignOperator->markUsed(Context);
12225
12226   if (ASTMutationListener *L = getASTMutationListener()) {
12227     L->CompletedImplicitDefinition(CopyAssignOperator);
12228   }
12229 }
12230
12231 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12232   assert(ClassDecl->needsImplicitMoveAssignment());
12233
12234   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12235   if (DSM.isAlreadyBeingDeclared())
12236     return nullptr;
12237
12238   // Note: The following rules are largely analoguous to the move
12239   // constructor rules.
12240
12241   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12242   if (Context.getLangOpts().OpenCLCPlusPlus)
12243     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12244   QualType RetType = Context.getLValueReferenceType(ArgType);
12245   ArgType = Context.getRValueReferenceType(ArgType);
12246
12247   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12248                                                      CXXMoveAssignment,
12249                                                      false);
12250
12251   //   An implicitly-declared move assignment operator is an inline public
12252   //   member of its class.
12253   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12254   SourceLocation ClassLoc = ClassDecl->getLocation();
12255   DeclarationNameInfo NameInfo(Name, ClassLoc);
12256   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
12257       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12258       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12259       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
12260       SourceLocation());
12261   MoveAssignment->setAccess(AS_public);
12262   MoveAssignment->setDefaulted();
12263   MoveAssignment->setImplicit();
12264
12265   if (getLangOpts().CUDA) {
12266     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12267                                             MoveAssignment,
12268                                             /* ConstRHS */ false,
12269                                             /* Diagnose */ false);
12270   }
12271
12272   // Build an exception specification pointing back at this member.
12273   FunctionProtoType::ExtProtoInfo EPI =
12274       getImplicitMethodEPI(*this, MoveAssignment);
12275   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12276
12277   // Add the parameter to the operator.
12278   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12279                                                ClassLoc, ClassLoc,
12280                                                /*Id=*/nullptr, ArgType,
12281                                                /*TInfo=*/nullptr, SC_None,
12282                                                nullptr);
12283   MoveAssignment->setParams(FromParam);
12284
12285   MoveAssignment->setTrivial(
12286     ClassDecl->needsOverloadResolutionForMoveAssignment()
12287       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12288       : ClassDecl->hasTrivialMoveAssignment());
12289
12290   // Note that we have added this copy-assignment operator.
12291   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
12292
12293   Scope *S = getScopeForContext(ClassDecl);
12294   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12295
12296   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12297     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12298     SetDeclDeleted(MoveAssignment, ClassLoc);
12299   }
12300
12301   if (S)
12302     PushOnScopeChains(MoveAssignment, S, false);
12303   ClassDecl->addDecl(MoveAssignment);
12304
12305   return MoveAssignment;
12306 }
12307
12308 /// Check if we're implicitly defining a move assignment operator for a class
12309 /// with virtual bases. Such a move assignment might move-assign the virtual
12310 /// base multiple times.
12311 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12312                                                SourceLocation CurrentLocation) {
12313   assert(!Class->isDependentContext() && "should not define dependent move");
12314
12315   // Only a virtual base could get implicitly move-assigned multiple times.
12316   // Only a non-trivial move assignment can observe this. We only want to
12317   // diagnose if we implicitly define an assignment operator that assigns
12318   // two base classes, both of which move-assign the same virtual base.
12319   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12320       Class->getNumBases() < 2)
12321     return;
12322
12323   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12324   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12325   VBaseMap VBases;
12326
12327   for (auto &BI : Class->bases()) {
12328     Worklist.push_back(&BI);
12329     while (!Worklist.empty()) {
12330       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12331       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12332
12333       // If the base has no non-trivial move assignment operators,
12334       // we don't care about moves from it.
12335       if (!Base->hasNonTrivialMoveAssignment())
12336         continue;
12337
12338       // If there's nothing virtual here, skip it.
12339       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12340         continue;
12341
12342       // If we're not actually going to call a move assignment for this base,
12343       // or the selected move assignment is trivial, skip it.
12344       Sema::SpecialMemberOverloadResult SMOR =
12345         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12346                               /*ConstArg*/false, /*VolatileArg*/false,
12347                               /*RValueThis*/true, /*ConstThis*/false,
12348                               /*VolatileThis*/false);
12349       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12350           !SMOR.getMethod()->isMoveAssignmentOperator())
12351         continue;
12352
12353       if (BaseSpec->isVirtual()) {
12354         // We're going to move-assign this virtual base, and its move
12355         // assignment operator is not trivial. If this can happen for
12356         // multiple distinct direct bases of Class, diagnose it. (If it
12357         // only happens in one base, we'll diagnose it when synthesizing
12358         // that base class's move assignment operator.)
12359         CXXBaseSpecifier *&Existing =
12360             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12361                 .first->second;
12362         if (Existing && Existing != &BI) {
12363           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12364             << Class << Base;
12365           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12366               << (Base->getCanonicalDecl() ==
12367                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12368               << Base << Existing->getType() << Existing->getSourceRange();
12369           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12370               << (Base->getCanonicalDecl() ==
12371                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12372               << Base << BI.getType() << BaseSpec->getSourceRange();
12373
12374           // Only diagnose each vbase once.
12375           Existing = nullptr;
12376         }
12377       } else {
12378         // Only walk over bases that have defaulted move assignment operators.
12379         // We assume that any user-provided move assignment operator handles
12380         // the multiple-moves-of-vbase case itself somehow.
12381         if (!SMOR.getMethod()->isDefaulted())
12382           continue;
12383
12384         // We're going to move the base classes of Base. Add them to the list.
12385         for (auto &BI : Base->bases())
12386           Worklist.push_back(&BI);
12387       }
12388     }
12389   }
12390 }
12391
12392 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12393                                         CXXMethodDecl *MoveAssignOperator) {
12394   assert((MoveAssignOperator->isDefaulted() &&
12395           MoveAssignOperator->isOverloadedOperator() &&
12396           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12397           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12398           !MoveAssignOperator->isDeleted()) &&
12399          "DefineImplicitMoveAssignment called for wrong function");
12400   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12401     return;
12402
12403   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12404   if (ClassDecl->isInvalidDecl()) {
12405     MoveAssignOperator->setInvalidDecl();
12406     return;
12407   }
12408
12409   // C++0x [class.copy]p28:
12410   //   The implicitly-defined or move assignment operator for a non-union class
12411   //   X performs memberwise move assignment of its subobjects. The direct base
12412   //   classes of X are assigned first, in the order of their declaration in the
12413   //   base-specifier-list, and then the immediate non-static data members of X
12414   //   are assigned, in the order in which they were declared in the class
12415   //   definition.
12416
12417   // Issue a warning if our implicit move assignment operator will move
12418   // from a virtual base more than once.
12419   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12420
12421   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12422
12423   // The exception specification is needed because we are defining the
12424   // function.
12425   ResolveExceptionSpec(CurrentLocation,
12426                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12427
12428   // Add a context note for diagnostics produced after this point.
12429   Scope.addContextNote(CurrentLocation);
12430
12431   // The statements that form the synthesized function body.
12432   SmallVector<Stmt*, 8> Statements;
12433
12434   // The parameter for the "other" object, which we are move from.
12435   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12436   QualType OtherRefType = Other->getType()->
12437       getAs<RValueReferenceType>()->getPointeeType();
12438
12439   // Our location for everything implicitly-generated.
12440   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12441                            ? MoveAssignOperator->getEndLoc()
12442                            : MoveAssignOperator->getLocation();
12443
12444   // Builds a reference to the "other" object.
12445   RefBuilder OtherRef(Other, OtherRefType);
12446   // Cast to rvalue.
12447   MoveCastBuilder MoveOther(OtherRef);
12448
12449   // Builds the "this" pointer.
12450   ThisBuilder This;
12451
12452   // Assign base classes.
12453   bool Invalid = false;
12454   for (auto &Base : ClassDecl->bases()) {
12455     // C++11 [class.copy]p28:
12456     //   It is unspecified whether subobjects representing virtual base classes
12457     //   are assigned more than once by the implicitly-defined copy assignment
12458     //   operator.
12459     // FIXME: Do not assign to a vbase that will be assigned by some other base
12460     // class. For a move-assignment, this can result in the vbase being moved
12461     // multiple times.
12462
12463     // Form the assignment:
12464     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12465     QualType BaseType = Base.getType().getUnqualifiedType();
12466     if (!BaseType->isRecordType()) {
12467       Invalid = true;
12468       continue;
12469     }
12470
12471     CXXCastPath BasePath;
12472     BasePath.push_back(&Base);
12473
12474     // Construct the "from" expression, which is an implicit cast to the
12475     // appropriately-qualified base type.
12476     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12477
12478     // Dereference "this".
12479     DerefBuilder DerefThis(This);
12480
12481     // Implicitly cast "this" to the appropriately-qualified base type.
12482     CastBuilder To(DerefThis,
12483                    Context.getQualifiedType(
12484                        BaseType, MoveAssignOperator->getMethodQualifiers()),
12485                    VK_LValue, BasePath);
12486
12487     // Build the move.
12488     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12489                                             To, From,
12490                                             /*CopyingBaseSubobject=*/true,
12491                                             /*Copying=*/false);
12492     if (Move.isInvalid()) {
12493       MoveAssignOperator->setInvalidDecl();
12494       return;
12495     }
12496
12497     // Success! Record the move.
12498     Statements.push_back(Move.getAs<Expr>());
12499   }
12500
12501   // Assign non-static members.
12502   for (auto *Field : ClassDecl->fields()) {
12503     // FIXME: We should form some kind of AST representation for the implied
12504     // memcpy in a union copy operation.
12505     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12506       continue;
12507
12508     if (Field->isInvalidDecl()) {
12509       Invalid = true;
12510       continue;
12511     }
12512
12513     // Check for members of reference type; we can't move those.
12514     if (Field->getType()->isReferenceType()) {
12515       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12516         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12517       Diag(Field->getLocation(), diag::note_declared_at);
12518       Invalid = true;
12519       continue;
12520     }
12521
12522     // Check for members of const-qualified, non-class type.
12523     QualType BaseType = Context.getBaseElementType(Field->getType());
12524     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12525       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12526         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12527       Diag(Field->getLocation(), diag::note_declared_at);
12528       Invalid = true;
12529       continue;
12530     }
12531
12532     // Suppress assigning zero-width bitfields.
12533     if (Field->isZeroLengthBitField(Context))
12534       continue;
12535
12536     QualType FieldType = Field->getType().getNonReferenceType();
12537     if (FieldType->isIncompleteArrayType()) {
12538       assert(ClassDecl->hasFlexibleArrayMember() &&
12539              "Incomplete array type is not valid");
12540       continue;
12541     }
12542
12543     // Build references to the field in the object we're copying from and to.
12544     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12545                               LookupMemberName);
12546     MemberLookup.addDecl(Field);
12547     MemberLookup.resolveKind();
12548     MemberBuilder From(MoveOther, OtherRefType,
12549                        /*IsArrow=*/false, MemberLookup);
12550     MemberBuilder To(This, getCurrentThisType(),
12551                      /*IsArrow=*/true, MemberLookup);
12552
12553     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12554         "Member reference with rvalue base must be rvalue except for reference "
12555         "members, which aren't allowed for move assignment.");
12556
12557     // Build the move of this field.
12558     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12559                                             To, From,
12560                                             /*CopyingBaseSubobject=*/false,
12561                                             /*Copying=*/false);
12562     if (Move.isInvalid()) {
12563       MoveAssignOperator->setInvalidDecl();
12564       return;
12565     }
12566
12567     // Success! Record the copy.
12568     Statements.push_back(Move.getAs<Stmt>());
12569   }
12570
12571   if (!Invalid) {
12572     // Add a "return *this;"
12573     ExprResult ThisObj =
12574         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12575
12576     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12577     if (Return.isInvalid())
12578       Invalid = true;
12579     else
12580       Statements.push_back(Return.getAs<Stmt>());
12581   }
12582
12583   if (Invalid) {
12584     MoveAssignOperator->setInvalidDecl();
12585     return;
12586   }
12587
12588   StmtResult Body;
12589   {
12590     CompoundScopeRAII CompoundScope(*this);
12591     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12592                              /*isStmtExpr=*/false);
12593     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12594   }
12595   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12596   MoveAssignOperator->markUsed(Context);
12597
12598   if (ASTMutationListener *L = getASTMutationListener()) {
12599     L->CompletedImplicitDefinition(MoveAssignOperator);
12600   }
12601 }
12602
12603 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12604                                                     CXXRecordDecl *ClassDecl) {
12605   // C++ [class.copy]p4:
12606   //   If the class definition does not explicitly declare a copy
12607   //   constructor, one is declared implicitly.
12608   assert(ClassDecl->needsImplicitCopyConstructor());
12609
12610   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12611   if (DSM.isAlreadyBeingDeclared())
12612     return nullptr;
12613
12614   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12615   QualType ArgType = ClassType;
12616   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12617   if (Const)
12618     ArgType = ArgType.withConst();
12619
12620   if (Context.getLangOpts().OpenCLCPlusPlus)
12621     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12622
12623   ArgType = Context.getLValueReferenceType(ArgType);
12624
12625   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12626                                                      CXXCopyConstructor,
12627                                                      Const);
12628
12629   DeclarationName Name
12630     = Context.DeclarationNames.getCXXConstructorName(
12631                                            Context.getCanonicalType(ClassType));
12632   SourceLocation ClassLoc = ClassDecl->getLocation();
12633   DeclarationNameInfo NameInfo(Name, ClassLoc);
12634
12635   //   An implicitly-declared copy constructor is an inline public
12636   //   member of its class.
12637   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12638       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12639       ExplicitSpecifier(),
12640       /*isInline=*/true,
12641       /*isImplicitlyDeclared=*/true,
12642       Constexpr ? CSK_constexpr : CSK_unspecified);
12643   CopyConstructor->setAccess(AS_public);
12644   CopyConstructor->setDefaulted();
12645
12646   if (getLangOpts().CUDA) {
12647     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12648                                             CopyConstructor,
12649                                             /* ConstRHS */ Const,
12650                                             /* Diagnose */ false);
12651   }
12652
12653   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
12654
12655   // Add the parameter to the constructor.
12656   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12657                                                ClassLoc, ClassLoc,
12658                                                /*IdentifierInfo=*/nullptr,
12659                                                ArgType, /*TInfo=*/nullptr,
12660                                                SC_None, nullptr);
12661   CopyConstructor->setParams(FromParam);
12662
12663   CopyConstructor->setTrivial(
12664       ClassDecl->needsOverloadResolutionForCopyConstructor()
12665           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12666           : ClassDecl->hasTrivialCopyConstructor());
12667
12668   CopyConstructor->setTrivialForCall(
12669       ClassDecl->hasAttr<TrivialABIAttr>() ||
12670       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12671            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12672              TAH_ConsiderTrivialABI)
12673            : ClassDecl->hasTrivialCopyConstructorForCall()));
12674
12675   // Note that we have declared this constructor.
12676   ++getASTContext().NumImplicitCopyConstructorsDeclared;
12677
12678   Scope *S = getScopeForContext(ClassDecl);
12679   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12680
12681   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12682     ClassDecl->setImplicitCopyConstructorIsDeleted();
12683     SetDeclDeleted(CopyConstructor, ClassLoc);
12684   }
12685
12686   if (S)
12687     PushOnScopeChains(CopyConstructor, S, false);
12688   ClassDecl->addDecl(CopyConstructor);
12689
12690   return CopyConstructor;
12691 }
12692
12693 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12694                                          CXXConstructorDecl *CopyConstructor) {
12695   assert((CopyConstructor->isDefaulted() &&
12696           CopyConstructor->isCopyConstructor() &&
12697           !CopyConstructor->doesThisDeclarationHaveABody() &&
12698           !CopyConstructor->isDeleted()) &&
12699          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12700   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12701     return;
12702
12703   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12704   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12705
12706   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12707
12708   // The exception specification is needed because we are defining the
12709   // function.
12710   ResolveExceptionSpec(CurrentLocation,
12711                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12712   MarkVTableUsed(CurrentLocation, ClassDecl);
12713
12714   // Add a context note for diagnostics produced after this point.
12715   Scope.addContextNote(CurrentLocation);
12716
12717   // C++11 [class.copy]p7:
12718   //   The [definition of an implicitly declared copy constructor] is
12719   //   deprecated if the class has a user-declared copy assignment operator
12720   //   or a user-declared destructor.
12721   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12722     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12723
12724   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12725     CopyConstructor->setInvalidDecl();
12726   }  else {
12727     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12728                              ? CopyConstructor->getEndLoc()
12729                              : CopyConstructor->getLocation();
12730     Sema::CompoundScopeRAII CompoundScope(*this);
12731     CopyConstructor->setBody(
12732         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12733     CopyConstructor->markUsed(Context);
12734   }
12735
12736   if (ASTMutationListener *L = getASTMutationListener()) {
12737     L->CompletedImplicitDefinition(CopyConstructor);
12738   }
12739 }
12740
12741 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12742                                                     CXXRecordDecl *ClassDecl) {
12743   assert(ClassDecl->needsImplicitMoveConstructor());
12744
12745   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12746   if (DSM.isAlreadyBeingDeclared())
12747     return nullptr;
12748
12749   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12750
12751   QualType ArgType = ClassType;
12752   if (Context.getLangOpts().OpenCLCPlusPlus)
12753     ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
12754   ArgType = Context.getRValueReferenceType(ArgType);
12755
12756   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12757                                                      CXXMoveConstructor,
12758                                                      false);
12759
12760   DeclarationName Name
12761     = Context.DeclarationNames.getCXXConstructorName(
12762                                            Context.getCanonicalType(ClassType));
12763   SourceLocation ClassLoc = ClassDecl->getLocation();
12764   DeclarationNameInfo NameInfo(Name, ClassLoc);
12765
12766   // C++11 [class.copy]p11:
12767   //   An implicitly-declared copy/move constructor is an inline public
12768   //   member of its class.
12769   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12770       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12771       ExplicitSpecifier(),
12772       /*isInline=*/true,
12773       /*isImplicitlyDeclared=*/true,
12774       Constexpr ? CSK_constexpr : CSK_unspecified);
12775   MoveConstructor->setAccess(AS_public);
12776   MoveConstructor->setDefaulted();
12777
12778   if (getLangOpts().CUDA) {
12779     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12780                                             MoveConstructor,
12781                                             /* ConstRHS */ false,
12782                                             /* Diagnose */ false);
12783   }
12784
12785   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
12786
12787   // Add the parameter to the constructor.
12788   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12789                                                ClassLoc, ClassLoc,
12790                                                /*IdentifierInfo=*/nullptr,
12791                                                ArgType, /*TInfo=*/nullptr,
12792                                                SC_None, nullptr);
12793   MoveConstructor->setParams(FromParam);
12794
12795   MoveConstructor->setTrivial(
12796       ClassDecl->needsOverloadResolutionForMoveConstructor()
12797           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12798           : ClassDecl->hasTrivialMoveConstructor());
12799
12800   MoveConstructor->setTrivialForCall(
12801       ClassDecl->hasAttr<TrivialABIAttr>() ||
12802       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12803            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12804                                     TAH_ConsiderTrivialABI)
12805            : ClassDecl->hasTrivialMoveConstructorForCall()));
12806
12807   // Note that we have declared this constructor.
12808   ++getASTContext().NumImplicitMoveConstructorsDeclared;
12809
12810   Scope *S = getScopeForContext(ClassDecl);
12811   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12812
12813   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12814     ClassDecl->setImplicitMoveConstructorIsDeleted();
12815     SetDeclDeleted(MoveConstructor, ClassLoc);
12816   }
12817
12818   if (S)
12819     PushOnScopeChains(MoveConstructor, S, false);
12820   ClassDecl->addDecl(MoveConstructor);
12821
12822   return MoveConstructor;
12823 }
12824
12825 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12826                                          CXXConstructorDecl *MoveConstructor) {
12827   assert((MoveConstructor->isDefaulted() &&
12828           MoveConstructor->isMoveConstructor() &&
12829           !MoveConstructor->doesThisDeclarationHaveABody() &&
12830           !MoveConstructor->isDeleted()) &&
12831          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12832   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12833     return;
12834
12835   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12836   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12837
12838   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12839
12840   // The exception specification is needed because we are defining the
12841   // function.
12842   ResolveExceptionSpec(CurrentLocation,
12843                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12844   MarkVTableUsed(CurrentLocation, ClassDecl);
12845
12846   // Add a context note for diagnostics produced after this point.
12847   Scope.addContextNote(CurrentLocation);
12848
12849   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12850     MoveConstructor->setInvalidDecl();
12851   } else {
12852     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12853                              ? MoveConstructor->getEndLoc()
12854                              : MoveConstructor->getLocation();
12855     Sema::CompoundScopeRAII CompoundScope(*this);
12856     MoveConstructor->setBody(ActOnCompoundStmt(
12857         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12858     MoveConstructor->markUsed(Context);
12859   }
12860
12861   if (ASTMutationListener *L = getASTMutationListener()) {
12862     L->CompletedImplicitDefinition(MoveConstructor);
12863   }
12864 }
12865
12866 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12867   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12868 }
12869
12870 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12871                             SourceLocation CurrentLocation,
12872                             CXXConversionDecl *Conv) {
12873   SynthesizedFunctionScope Scope(*this, Conv);
12874   assert(!Conv->getReturnType()->isUndeducedType());
12875
12876   CXXRecordDecl *Lambda = Conv->getParent();
12877   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12878   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12879
12880   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12881     CallOp = InstantiateFunctionDeclaration(
12882         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12883     if (!CallOp)
12884       return;
12885
12886     Invoker = InstantiateFunctionDeclaration(
12887         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12888     if (!Invoker)
12889       return;
12890   }
12891
12892   if (CallOp->isInvalidDecl())
12893     return;
12894
12895   // Mark the call operator referenced (and add to pending instantiations
12896   // if necessary).
12897   // For both the conversion and static-invoker template specializations
12898   // we construct their body's in this function, so no need to add them
12899   // to the PendingInstantiations.
12900   MarkFunctionReferenced(CurrentLocation, CallOp);
12901
12902   // Fill in the __invoke function with a dummy implementation. IR generation
12903   // will fill in the actual details. Update its type in case it contained
12904   // an 'auto'.
12905   Invoker->markUsed(Context);
12906   Invoker->setReferenced();
12907   Invoker->setType(Conv->getReturnType()->getPointeeType());
12908   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12909
12910   // Construct the body of the conversion function { return __invoke; }.
12911   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12912                                        VK_LValue, Conv->getLocation());
12913   assert(FunctionRef && "Can't refer to __invoke function?");
12914   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12915   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12916                                      Conv->getLocation()));
12917   Conv->markUsed(Context);
12918   Conv->setReferenced();
12919
12920   if (ASTMutationListener *L = getASTMutationListener()) {
12921     L->CompletedImplicitDefinition(Conv);
12922     L->CompletedImplicitDefinition(Invoker);
12923   }
12924 }
12925
12926
12927
12928 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12929        SourceLocation CurrentLocation,
12930        CXXConversionDecl *Conv)
12931 {
12932   assert(!Conv->getParent()->isGenericLambda());
12933
12934   SynthesizedFunctionScope Scope(*this, Conv);
12935
12936   // Copy-initialize the lambda object as needed to capture it.
12937   Expr *This = ActOnCXXThis(CurrentLocation).get();
12938   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12939
12940   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12941                                                         Conv->getLocation(),
12942                                                         Conv, DerefThis);
12943
12944   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12945   // behavior.  Note that only the general conversion function does this
12946   // (since it's unusable otherwise); in the case where we inline the
12947   // block literal, it has block literal lifetime semantics.
12948   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12949     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12950                                           CK_CopyAndAutoreleaseBlockObject,
12951                                           BuildBlock.get(), nullptr, VK_RValue);
12952
12953   if (BuildBlock.isInvalid()) {
12954     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12955     Conv->setInvalidDecl();
12956     return;
12957   }
12958
12959   // Create the return statement that returns the block from the conversion
12960   // function.
12961   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12962   if (Return.isInvalid()) {
12963     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12964     Conv->setInvalidDecl();
12965     return;
12966   }
12967
12968   // Set the body of the conversion function.
12969   Stmt *ReturnS = Return.get();
12970   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12971                                      Conv->getLocation()));
12972   Conv->markUsed(Context);
12973
12974   // We're done; notify the mutation listener, if any.
12975   if (ASTMutationListener *L = getASTMutationListener()) {
12976     L->CompletedImplicitDefinition(Conv);
12977   }
12978 }
12979
12980 /// Determine whether the given list arguments contains exactly one
12981 /// "real" (non-default) argument.
12982 static bool hasOneRealArgument(MultiExprArg Args) {
12983   switch (Args.size()) {
12984   case 0:
12985     return false;
12986
12987   default:
12988     if (!Args[1]->isDefaultArgument())
12989       return false;
12990
12991     LLVM_FALLTHROUGH;
12992   case 1:
12993     return !Args[0]->isDefaultArgument();
12994   }
12995
12996   return false;
12997 }
12998
12999 ExprResult
13000 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13001                             NamedDecl *FoundDecl,
13002                             CXXConstructorDecl *Constructor,
13003                             MultiExprArg ExprArgs,
13004                             bool HadMultipleCandidates,
13005                             bool IsListInitialization,
13006                             bool IsStdInitListInitialization,
13007                             bool RequiresZeroInit,
13008                             unsigned ConstructKind,
13009                             SourceRange ParenRange) {
13010   bool Elidable = false;
13011
13012   // C++0x [class.copy]p34:
13013   //   When certain criteria are met, an implementation is allowed to
13014   //   omit the copy/move construction of a class object, even if the
13015   //   copy/move constructor and/or destructor for the object have
13016   //   side effects. [...]
13017   //     - when a temporary class object that has not been bound to a
13018   //       reference (12.2) would be copied/moved to a class object
13019   //       with the same cv-unqualified type, the copy/move operation
13020   //       can be omitted by constructing the temporary object
13021   //       directly into the target of the omitted copy/move
13022   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
13023       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
13024     Expr *SubExpr = ExprArgs[0];
13025     Elidable = SubExpr->isTemporaryObject(
13026         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
13027   }
13028
13029   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
13030                                FoundDecl, Constructor,
13031                                Elidable, ExprArgs, HadMultipleCandidates,
13032                                IsListInitialization,
13033                                IsStdInitListInitialization, RequiresZeroInit,
13034                                ConstructKind, ParenRange);
13035 }
13036
13037 ExprResult
13038 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13039                             NamedDecl *FoundDecl,
13040                             CXXConstructorDecl *Constructor,
13041                             bool Elidable,
13042                             MultiExprArg ExprArgs,
13043                             bool HadMultipleCandidates,
13044                             bool IsListInitialization,
13045                             bool IsStdInitListInitialization,
13046                             bool RequiresZeroInit,
13047                             unsigned ConstructKind,
13048                             SourceRange ParenRange) {
13049   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
13050     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
13051     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
13052       return ExprError();
13053   }
13054
13055   return BuildCXXConstructExpr(
13056       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
13057       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
13058       RequiresZeroInit, ConstructKind, ParenRange);
13059 }
13060
13061 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
13062 /// including handling of its default argument expressions.
13063 ExprResult
13064 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13065                             CXXConstructorDecl *Constructor,
13066                             bool Elidable,
13067                             MultiExprArg ExprArgs,
13068                             bool HadMultipleCandidates,
13069                             bool IsListInitialization,
13070                             bool IsStdInitListInitialization,
13071                             bool RequiresZeroInit,
13072                             unsigned ConstructKind,
13073                             SourceRange ParenRange) {
13074   assert(declaresSameEntity(
13075              Constructor->getParent(),
13076              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
13077          "given constructor for wrong type");
13078   MarkFunctionReferenced(ConstructLoc, Constructor);
13079   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
13080     return ExprError();
13081
13082   return CXXConstructExpr::Create(
13083       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
13084       ExprArgs, HadMultipleCandidates, IsListInitialization,
13085       IsStdInitListInitialization, RequiresZeroInit,
13086       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
13087       ParenRange);
13088 }
13089
13090 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
13091   assert(Field->hasInClassInitializer());
13092
13093   // If we already have the in-class initializer nothing needs to be done.
13094   if (Field->getInClassInitializer())
13095     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13096
13097   // If we might have already tried and failed to instantiate, don't try again.
13098   if (Field->isInvalidDecl())
13099     return ExprError();
13100
13101   // Maybe we haven't instantiated the in-class initializer. Go check the
13102   // pattern FieldDecl to see if it has one.
13103   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
13104
13105   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
13106     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
13107     DeclContext::lookup_result Lookup =
13108         ClassPattern->lookup(Field->getDeclName());
13109
13110     // Lookup can return at most two results: the pattern for the field, or the
13111     // injected class name of the parent record. No other member can have the
13112     // same name as the field.
13113     // In modules mode, lookup can return multiple results (coming from
13114     // different modules).
13115     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
13116            "more than two lookup results for field name");
13117     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
13118     if (!Pattern) {
13119       assert(isa<CXXRecordDecl>(Lookup[0]) &&
13120              "cannot have other non-field member with same name");
13121       for (auto L : Lookup)
13122         if (isa<FieldDecl>(L)) {
13123           Pattern = cast<FieldDecl>(L);
13124           break;
13125         }
13126       assert(Pattern && "We must have set the Pattern!");
13127     }
13128
13129     if (!Pattern->hasInClassInitializer() ||
13130         InstantiateInClassInitializer(Loc, Field, Pattern,
13131                                       getTemplateInstantiationArgs(Field))) {
13132       // Don't diagnose this again.
13133       Field->setInvalidDecl();
13134       return ExprError();
13135     }
13136     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13137   }
13138
13139   // DR1351:
13140   //   If the brace-or-equal-initializer of a non-static data member
13141   //   invokes a defaulted default constructor of its class or of an
13142   //   enclosing class in a potentially evaluated subexpression, the
13143   //   program is ill-formed.
13144   //
13145   // This resolution is unworkable: the exception specification of the
13146   // default constructor can be needed in an unevaluated context, in
13147   // particular, in the operand of a noexcept-expression, and we can be
13148   // unable to compute an exception specification for an enclosed class.
13149   //
13150   // Any attempt to resolve the exception specification of a defaulted default
13151   // constructor before the initializer is lexically complete will ultimately
13152   // come here at which point we can diagnose it.
13153   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13154   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13155       << OutermostClass << Field;
13156   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13157   // Recover by marking the field invalid, unless we're in a SFINAE context.
13158   if (!isSFINAEContext())
13159     Field->setInvalidDecl();
13160   return ExprError();
13161 }
13162
13163 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13164   if (VD->isInvalidDecl()) return;
13165
13166   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13167   if (ClassDecl->isInvalidDecl()) return;
13168   if (ClassDecl->hasIrrelevantDestructor()) return;
13169   if (ClassDecl->isDependentContext()) return;
13170
13171   if (VD->isNoDestroy(getASTContext()))
13172     return;
13173
13174   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13175
13176   // If this is an array, we'll require the destructor during initialization, so
13177   // we can skip over this. We still want to emit exit-time destructor warnings
13178   // though.
13179   if (!VD->getType()->isArrayType()) {
13180     MarkFunctionReferenced(VD->getLocation(), Destructor);
13181     CheckDestructorAccess(VD->getLocation(), Destructor,
13182                           PDiag(diag::err_access_dtor_var)
13183                               << VD->getDeclName() << VD->getType());
13184     DiagnoseUseOfDecl(Destructor, VD->getLocation());
13185   }
13186
13187   if (Destructor->isTrivial()) return;
13188   if (!VD->hasGlobalStorage()) return;
13189
13190   // Emit warning for non-trivial dtor in global scope (a real global,
13191   // class-static, function-static).
13192   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13193
13194   // TODO: this should be re-enabled for static locals by !CXAAtExit
13195   if (!VD->isStaticLocal())
13196     Diag(VD->getLocation(), diag::warn_global_destructor);
13197 }
13198
13199 /// Given a constructor and the set of arguments provided for the
13200 /// constructor, convert the arguments and add any required default arguments
13201 /// to form a proper call to this constructor.
13202 ///
13203 /// \returns true if an error occurred, false otherwise.
13204 bool
13205 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13206                               MultiExprArg ArgsPtr,
13207                               SourceLocation Loc,
13208                               SmallVectorImpl<Expr*> &ConvertedArgs,
13209                               bool AllowExplicit,
13210                               bool IsListInitialization) {
13211   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13212   unsigned NumArgs = ArgsPtr.size();
13213   Expr **Args = ArgsPtr.data();
13214
13215   const FunctionProtoType *Proto
13216     = Constructor->getType()->getAs<FunctionProtoType>();
13217   assert(Proto && "Constructor without a prototype?");
13218   unsigned NumParams = Proto->getNumParams();
13219
13220   // If too few arguments are available, we'll fill in the rest with defaults.
13221   if (NumArgs < NumParams)
13222     ConvertedArgs.reserve(NumParams);
13223   else
13224     ConvertedArgs.reserve(NumArgs);
13225
13226   VariadicCallType CallType =
13227     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13228   SmallVector<Expr *, 8> AllArgs;
13229   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13230                                         Proto, 0,
13231                                         llvm::makeArrayRef(Args, NumArgs),
13232                                         AllArgs,
13233                                         CallType, AllowExplicit,
13234                                         IsListInitialization);
13235   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13236
13237   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13238
13239   CheckConstructorCall(Constructor,
13240                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13241                        Proto, Loc);
13242
13243   return Invalid;
13244 }
13245
13246 static inline bool
13247 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13248                                        const FunctionDecl *FnDecl) {
13249   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13250   if (isa<NamespaceDecl>(DC)) {
13251     return SemaRef.Diag(FnDecl->getLocation(),
13252                         diag::err_operator_new_delete_declared_in_namespace)
13253       << FnDecl->getDeclName();
13254   }
13255
13256   if (isa<TranslationUnitDecl>(DC) &&
13257       FnDecl->getStorageClass() == SC_Static) {
13258     return SemaRef.Diag(FnDecl->getLocation(),
13259                         diag::err_operator_new_delete_declared_static)
13260       << FnDecl->getDeclName();
13261   }
13262
13263   return false;
13264 }
13265
13266 static QualType
13267 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13268   QualType QTy = PtrTy->getPointeeType();
13269   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13270   return SemaRef.Context.getPointerType(QTy);
13271 }
13272
13273 static inline bool
13274 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13275                             CanQualType ExpectedResultType,
13276                             CanQualType ExpectedFirstParamType,
13277                             unsigned DependentParamTypeDiag,
13278                             unsigned InvalidParamTypeDiag) {
13279   QualType ResultType =
13280       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13281
13282   // Check that the result type is not dependent.
13283   if (ResultType->isDependentType())
13284     return SemaRef.Diag(FnDecl->getLocation(),
13285                         diag::err_operator_new_delete_dependent_result_type)
13286     << FnDecl->getDeclName() << ExpectedResultType;
13287
13288   // The operator is valid on any address space for OpenCL.
13289   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13290     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13291       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13292     }
13293   }
13294
13295   // Check that the result type is what we expect.
13296   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13297     return SemaRef.Diag(FnDecl->getLocation(),
13298                         diag::err_operator_new_delete_invalid_result_type)
13299     << FnDecl->getDeclName() << ExpectedResultType;
13300
13301   // A function template must have at least 2 parameters.
13302   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13303     return SemaRef.Diag(FnDecl->getLocation(),
13304                       diag::err_operator_new_delete_template_too_few_parameters)
13305         << FnDecl->getDeclName();
13306
13307   // The function decl must have at least 1 parameter.
13308   if (FnDecl->getNumParams() == 0)
13309     return SemaRef.Diag(FnDecl->getLocation(),
13310                         diag::err_operator_new_delete_too_few_parameters)
13311       << FnDecl->getDeclName();
13312
13313   // Check the first parameter type is not dependent.
13314   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13315   if (FirstParamType->isDependentType())
13316     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13317       << FnDecl->getDeclName() << ExpectedFirstParamType;
13318
13319   // Check that the first parameter type is what we expect.
13320   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13321     // The operator is valid on any address space for OpenCL.
13322     if (auto *PtrTy =
13323             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13324       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13325     }
13326   }
13327   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13328       ExpectedFirstParamType)
13329     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13330     << FnDecl->getDeclName() << ExpectedFirstParamType;
13331
13332   return false;
13333 }
13334
13335 static bool
13336 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13337   // C++ [basic.stc.dynamic.allocation]p1:
13338   //   A program is ill-formed if an allocation function is declared in a
13339   //   namespace scope other than global scope or declared static in global
13340   //   scope.
13341   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13342     return true;
13343
13344   CanQualType SizeTy =
13345     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13346
13347   // C++ [basic.stc.dynamic.allocation]p1:
13348   //  The return type shall be void*. The first parameter shall have type
13349   //  std::size_t.
13350   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13351                                   SizeTy,
13352                                   diag::err_operator_new_dependent_param_type,
13353                                   diag::err_operator_new_param_type))
13354     return true;
13355
13356   // C++ [basic.stc.dynamic.allocation]p1:
13357   //  The first parameter shall not have an associated default argument.
13358   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13359     return SemaRef.Diag(FnDecl->getLocation(),
13360                         diag::err_operator_new_default_arg)
13361       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13362
13363   return false;
13364 }
13365
13366 static bool
13367 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13368   // C++ [basic.stc.dynamic.deallocation]p1:
13369   //   A program is ill-formed if deallocation functions are declared in a
13370   //   namespace scope other than global scope or declared static in global
13371   //   scope.
13372   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13373     return true;
13374
13375   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13376
13377   // C++ P0722:
13378   //   Within a class C, the first parameter of a destroying operator delete
13379   //   shall be of type C *. The first parameter of any other deallocation
13380   //   function shall be of type void *.
13381   CanQualType ExpectedFirstParamType =
13382       MD && MD->isDestroyingOperatorDelete()
13383           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13384                 SemaRef.Context.getRecordType(MD->getParent())))
13385           : SemaRef.Context.VoidPtrTy;
13386
13387   // C++ [basic.stc.dynamic.deallocation]p2:
13388   //   Each deallocation function shall return void
13389   if (CheckOperatorNewDeleteTypes(
13390           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13391           diag::err_operator_delete_dependent_param_type,
13392           diag::err_operator_delete_param_type))
13393     return true;
13394
13395   // C++ P0722:
13396   //   A destroying operator delete shall be a usual deallocation function.
13397   if (MD && !MD->getParent()->isDependentContext() &&
13398       MD->isDestroyingOperatorDelete() &&
13399       !SemaRef.isUsualDeallocationFunction(MD)) {
13400     SemaRef.Diag(MD->getLocation(),
13401                  diag::err_destroying_operator_delete_not_usual);
13402     return true;
13403   }
13404
13405   return false;
13406 }
13407
13408 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13409 /// of this overloaded operator is well-formed. If so, returns false;
13410 /// otherwise, emits appropriate diagnostics and returns true.
13411 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13412   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13413          "Expected an overloaded operator declaration");
13414
13415   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13416
13417   // C++ [over.oper]p5:
13418   //   The allocation and deallocation functions, operator new,
13419   //   operator new[], operator delete and operator delete[], are
13420   //   described completely in 3.7.3. The attributes and restrictions
13421   //   found in the rest of this subclause do not apply to them unless
13422   //   explicitly stated in 3.7.3.
13423   if (Op == OO_Delete || Op == OO_Array_Delete)
13424     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13425
13426   if (Op == OO_New || Op == OO_Array_New)
13427     return CheckOperatorNewDeclaration(*this, FnDecl);
13428
13429   // C++ [over.oper]p6:
13430   //   An operator function shall either be a non-static member
13431   //   function or be a non-member function and have at least one
13432   //   parameter whose type is a class, a reference to a class, an
13433   //   enumeration, or a reference to an enumeration.
13434   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13435     if (MethodDecl->isStatic())
13436       return Diag(FnDecl->getLocation(),
13437                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13438   } else {
13439     bool ClassOrEnumParam = false;
13440     for (auto Param : FnDecl->parameters()) {
13441       QualType ParamType = Param->getType().getNonReferenceType();
13442       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13443           ParamType->isEnumeralType()) {
13444         ClassOrEnumParam = true;
13445         break;
13446       }
13447     }
13448
13449     if (!ClassOrEnumParam)
13450       return Diag(FnDecl->getLocation(),
13451                   diag::err_operator_overload_needs_class_or_enum)
13452         << FnDecl->getDeclName();
13453   }
13454
13455   // C++ [over.oper]p8:
13456   //   An operator function cannot have default arguments (8.3.6),
13457   //   except where explicitly stated below.
13458   //
13459   // Only the function-call operator allows default arguments
13460   // (C++ [over.call]p1).
13461   if (Op != OO_Call) {
13462     for (auto Param : FnDecl->parameters()) {
13463       if (Param->hasDefaultArg())
13464         return Diag(Param->getLocation(),
13465                     diag::err_operator_overload_default_arg)
13466           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13467     }
13468   }
13469
13470   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13471     { false, false, false }
13472 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13473     , { Unary, Binary, MemberOnly }
13474 #include "clang/Basic/OperatorKinds.def"
13475   };
13476
13477   bool CanBeUnaryOperator = OperatorUses[Op][0];
13478   bool CanBeBinaryOperator = OperatorUses[Op][1];
13479   bool MustBeMemberOperator = OperatorUses[Op][2];
13480
13481   // C++ [over.oper]p8:
13482   //   [...] Operator functions cannot have more or fewer parameters
13483   //   than the number required for the corresponding operator, as
13484   //   described in the rest of this subclause.
13485   unsigned NumParams = FnDecl->getNumParams()
13486                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13487   if (Op != OO_Call &&
13488       ((NumParams == 1 && !CanBeUnaryOperator) ||
13489        (NumParams == 2 && !CanBeBinaryOperator) ||
13490        (NumParams < 1) || (NumParams > 2))) {
13491     // We have the wrong number of parameters.
13492     unsigned ErrorKind;
13493     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13494       ErrorKind = 2;  // 2 -> unary or binary.
13495     } else if (CanBeUnaryOperator) {
13496       ErrorKind = 0;  // 0 -> unary
13497     } else {
13498       assert(CanBeBinaryOperator &&
13499              "All non-call overloaded operators are unary or binary!");
13500       ErrorKind = 1;  // 1 -> binary
13501     }
13502
13503     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13504       << FnDecl->getDeclName() << NumParams << ErrorKind;
13505   }
13506
13507   // Overloaded operators other than operator() cannot be variadic.
13508   if (Op != OO_Call &&
13509       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13510     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13511       << FnDecl->getDeclName();
13512   }
13513
13514   // Some operators must be non-static member functions.
13515   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13516     return Diag(FnDecl->getLocation(),
13517                 diag::err_operator_overload_must_be_member)
13518       << FnDecl->getDeclName();
13519   }
13520
13521   // C++ [over.inc]p1:
13522   //   The user-defined function called operator++ implements the
13523   //   prefix and postfix ++ operator. If this function is a member
13524   //   function with no parameters, or a non-member function with one
13525   //   parameter of class or enumeration type, it defines the prefix
13526   //   increment operator ++ for objects of that type. If the function
13527   //   is a member function with one parameter (which shall be of type
13528   //   int) or a non-member function with two parameters (the second
13529   //   of which shall be of type int), it defines the postfix
13530   //   increment operator ++ for objects of that type.
13531   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13532     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13533     QualType ParamType = LastParam->getType();
13534
13535     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13536         !ParamType->isDependentType())
13537       return Diag(LastParam->getLocation(),
13538                   diag::err_operator_overload_post_incdec_must_be_int)
13539         << LastParam->getType() << (Op == OO_MinusMinus);
13540   }
13541
13542   return false;
13543 }
13544
13545 static bool
13546 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13547                                           FunctionTemplateDecl *TpDecl) {
13548   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13549
13550   // Must have one or two template parameters.
13551   if (TemplateParams->size() == 1) {
13552     NonTypeTemplateParmDecl *PmDecl =
13553         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13554
13555     // The template parameter must be a char parameter pack.
13556     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13557         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13558       return false;
13559
13560   } else if (TemplateParams->size() == 2) {
13561     TemplateTypeParmDecl *PmType =
13562         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13563     NonTypeTemplateParmDecl *PmArgs =
13564         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13565
13566     // The second template parameter must be a parameter pack with the
13567     // first template parameter as its type.
13568     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13569         PmArgs->isTemplateParameterPack()) {
13570       const TemplateTypeParmType *TArgs =
13571           PmArgs->getType()->getAs<TemplateTypeParmType>();
13572       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13573           TArgs->getIndex() == PmType->getIndex()) {
13574         if (!SemaRef.inTemplateInstantiation())
13575           SemaRef.Diag(TpDecl->getLocation(),
13576                        diag::ext_string_literal_operator_template);
13577         return false;
13578       }
13579     }
13580   }
13581
13582   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13583                diag::err_literal_operator_template)
13584       << TpDecl->getTemplateParameters()->getSourceRange();
13585   return true;
13586 }
13587
13588 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13589 /// of this literal operator function is well-formed. If so, returns
13590 /// false; otherwise, emits appropriate diagnostics and returns true.
13591 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13592   if (isa<CXXMethodDecl>(FnDecl)) {
13593     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13594       << FnDecl->getDeclName();
13595     return true;
13596   }
13597
13598   if (FnDecl->isExternC()) {
13599     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13600     if (const LinkageSpecDecl *LSD =
13601             FnDecl->getDeclContext()->getExternCContext())
13602       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13603     return true;
13604   }
13605
13606   // This might be the definition of a literal operator template.
13607   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13608
13609   // This might be a specialization of a literal operator template.
13610   if (!TpDecl)
13611     TpDecl = FnDecl->getPrimaryTemplate();
13612
13613   // template <char...> type operator "" name() and
13614   // template <class T, T...> type operator "" name() are the only valid
13615   // template signatures, and the only valid signatures with no parameters.
13616   if (TpDecl) {
13617     if (FnDecl->param_size() != 0) {
13618       Diag(FnDecl->getLocation(),
13619            diag::err_literal_operator_template_with_params);
13620       return true;
13621     }
13622
13623     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13624       return true;
13625
13626   } else if (FnDecl->param_size() == 1) {
13627     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13628
13629     QualType ParamType = Param->getType().getUnqualifiedType();
13630
13631     // Only unsigned long long int, long double, any character type, and const
13632     // char * are allowed as the only parameters.
13633     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13634         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13635         Context.hasSameType(ParamType, Context.CharTy) ||
13636         Context.hasSameType(ParamType, Context.WideCharTy) ||
13637         Context.hasSameType(ParamType, Context.Char8Ty) ||
13638         Context.hasSameType(ParamType, Context.Char16Ty) ||
13639         Context.hasSameType(ParamType, Context.Char32Ty)) {
13640     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13641       QualType InnerType = Ptr->getPointeeType();
13642
13643       // Pointer parameter must be a const char *.
13644       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13645                                 Context.CharTy) &&
13646             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13647         Diag(Param->getSourceRange().getBegin(),
13648              diag::err_literal_operator_param)
13649             << ParamType << "'const char *'" << Param->getSourceRange();
13650         return true;
13651       }
13652
13653     } else if (ParamType->isRealFloatingType()) {
13654       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13655           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13656       return true;
13657
13658     } else if (ParamType->isIntegerType()) {
13659       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13660           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13661       return true;
13662
13663     } else {
13664       Diag(Param->getSourceRange().getBegin(),
13665            diag::err_literal_operator_invalid_param)
13666           << ParamType << Param->getSourceRange();
13667       return true;
13668     }
13669
13670   } else if (FnDecl->param_size() == 2) {
13671     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13672
13673     // First, verify that the first parameter is correct.
13674
13675     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13676
13677     // Two parameter function must have a pointer to const as a
13678     // first parameter; let's strip those qualifiers.
13679     const PointerType *PT = FirstParamType->getAs<PointerType>();
13680
13681     if (!PT) {
13682       Diag((*Param)->getSourceRange().getBegin(),
13683            diag::err_literal_operator_param)
13684           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13685       return true;
13686     }
13687
13688     QualType PointeeType = PT->getPointeeType();
13689     // First parameter must be const
13690     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13691       Diag((*Param)->getSourceRange().getBegin(),
13692            diag::err_literal_operator_param)
13693           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13694       return true;
13695     }
13696
13697     QualType InnerType = PointeeType.getUnqualifiedType();
13698     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13699     // const char32_t* are allowed as the first parameter to a two-parameter
13700     // function
13701     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13702           Context.hasSameType(InnerType, Context.WideCharTy) ||
13703           Context.hasSameType(InnerType, Context.Char8Ty) ||
13704           Context.hasSameType(InnerType, Context.Char16Ty) ||
13705           Context.hasSameType(InnerType, Context.Char32Ty))) {
13706       Diag((*Param)->getSourceRange().getBegin(),
13707            diag::err_literal_operator_param)
13708           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13709       return true;
13710     }
13711
13712     // Move on to the second and final parameter.
13713     ++Param;
13714
13715     // The second parameter must be a std::size_t.
13716     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13717     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13718       Diag((*Param)->getSourceRange().getBegin(),
13719            diag::err_literal_operator_param)
13720           << SecondParamType << Context.getSizeType()
13721           << (*Param)->getSourceRange();
13722       return true;
13723     }
13724   } else {
13725     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13726     return true;
13727   }
13728
13729   // Parameters are good.
13730
13731   // A parameter-declaration-clause containing a default argument is not
13732   // equivalent to any of the permitted forms.
13733   for (auto Param : FnDecl->parameters()) {
13734     if (Param->hasDefaultArg()) {
13735       Diag(Param->getDefaultArgRange().getBegin(),
13736            diag::err_literal_operator_default_argument)
13737         << Param->getDefaultArgRange();
13738       break;
13739     }
13740   }
13741
13742   StringRef LiteralName
13743     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13744   if (LiteralName[0] != '_' &&
13745       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13746     // C++11 [usrlit.suffix]p1:
13747     //   Literal suffix identifiers that do not start with an underscore
13748     //   are reserved for future standardization.
13749     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13750       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13751   }
13752
13753   return false;
13754 }
13755
13756 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13757 /// linkage specification, including the language and (if present)
13758 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13759 /// language string literal. LBraceLoc, if valid, provides the location of
13760 /// the '{' brace. Otherwise, this linkage specification does not
13761 /// have any braces.
13762 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13763                                            Expr *LangStr,
13764                                            SourceLocation LBraceLoc) {
13765   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13766   if (!Lit->isAscii()) {
13767     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13768       << LangStr->getSourceRange();
13769     return nullptr;
13770   }
13771
13772   StringRef Lang = Lit->getString();
13773   LinkageSpecDecl::LanguageIDs Language;
13774   if (Lang == "C")
13775     Language = LinkageSpecDecl::lang_c;
13776   else if (Lang == "C++")
13777     Language = LinkageSpecDecl::lang_cxx;
13778   else {
13779     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13780       << LangStr->getSourceRange();
13781     return nullptr;
13782   }
13783
13784   // FIXME: Add all the various semantics of linkage specifications
13785
13786   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13787                                                LangStr->getExprLoc(), Language,
13788                                                LBraceLoc.isValid());
13789   CurContext->addDecl(D);
13790   PushDeclContext(S, D);
13791   return D;
13792 }
13793
13794 /// ActOnFinishLinkageSpecification - Complete the definition of
13795 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13796 /// valid, it's the position of the closing '}' brace in a linkage
13797 /// specification that uses braces.
13798 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13799                                             Decl *LinkageSpec,
13800                                             SourceLocation RBraceLoc) {
13801   if (RBraceLoc.isValid()) {
13802     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13803     LSDecl->setRBraceLoc(RBraceLoc);
13804   }
13805   PopDeclContext();
13806   return LinkageSpec;
13807 }
13808
13809 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13810                                   const ParsedAttributesView &AttrList,
13811                                   SourceLocation SemiLoc) {
13812   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13813   // Attribute declarations appertain to empty declaration so we handle
13814   // them here.
13815   ProcessDeclAttributeList(S, ED, AttrList);
13816
13817   CurContext->addDecl(ED);
13818   return ED;
13819 }
13820
13821 /// Perform semantic analysis for the variable declaration that
13822 /// occurs within a C++ catch clause, returning the newly-created
13823 /// variable.
13824 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13825                                          TypeSourceInfo *TInfo,
13826                                          SourceLocation StartLoc,
13827                                          SourceLocation Loc,
13828                                          IdentifierInfo *Name) {
13829   bool Invalid = false;
13830   QualType ExDeclType = TInfo->getType();
13831
13832   // Arrays and functions decay.
13833   if (ExDeclType->isArrayType())
13834     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13835   else if (ExDeclType->isFunctionType())
13836     ExDeclType = Context.getPointerType(ExDeclType);
13837
13838   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13839   // The exception-declaration shall not denote a pointer or reference to an
13840   // incomplete type, other than [cv] void*.
13841   // N2844 forbids rvalue references.
13842   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13843     Diag(Loc, diag::err_catch_rvalue_ref);
13844     Invalid = true;
13845   }
13846
13847   if (ExDeclType->isVariablyModifiedType()) {
13848     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13849     Invalid = true;
13850   }
13851
13852   QualType BaseType = ExDeclType;
13853   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13854   unsigned DK = diag::err_catch_incomplete;
13855   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13856     BaseType = Ptr->getPointeeType();
13857     Mode = 1;
13858     DK = diag::err_catch_incomplete_ptr;
13859   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13860     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13861     BaseType = Ref->getPointeeType();
13862     Mode = 2;
13863     DK = diag::err_catch_incomplete_ref;
13864   }
13865   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13866       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13867     Invalid = true;
13868
13869   if (!Invalid && !ExDeclType->isDependentType() &&
13870       RequireNonAbstractType(Loc, ExDeclType,
13871                              diag::err_abstract_type_in_decl,
13872                              AbstractVariableType))
13873     Invalid = true;
13874
13875   // Only the non-fragile NeXT runtime currently supports C++ catches
13876   // of ObjC types, and no runtime supports catching ObjC types by value.
13877   if (!Invalid && getLangOpts().ObjC) {
13878     QualType T = ExDeclType;
13879     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13880       T = RT->getPointeeType();
13881
13882     if (T->isObjCObjectType()) {
13883       Diag(Loc, diag::err_objc_object_catch);
13884       Invalid = true;
13885     } else if (T->isObjCObjectPointerType()) {
13886       // FIXME: should this be a test for macosx-fragile specifically?
13887       if (getLangOpts().ObjCRuntime.isFragile())
13888         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13889     }
13890   }
13891
13892   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13893                                     ExDeclType, TInfo, SC_None);
13894   ExDecl->setExceptionVariable(true);
13895
13896   // In ARC, infer 'retaining' for variables of retainable type.
13897   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13898     Invalid = true;
13899
13900   if (!Invalid && !ExDeclType->isDependentType()) {
13901     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13902       // Insulate this from anything else we might currently be parsing.
13903       EnterExpressionEvaluationContext scope(
13904           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13905
13906       // C++ [except.handle]p16:
13907       //   The object declared in an exception-declaration or, if the
13908       //   exception-declaration does not specify a name, a temporary (12.2) is
13909       //   copy-initialized (8.5) from the exception object. [...]
13910       //   The object is destroyed when the handler exits, after the destruction
13911       //   of any automatic objects initialized within the handler.
13912       //
13913       // We just pretend to initialize the object with itself, then make sure
13914       // it can be destroyed later.
13915       QualType initType = Context.getExceptionObjectType(ExDeclType);
13916
13917       InitializedEntity entity =
13918         InitializedEntity::InitializeVariable(ExDecl);
13919       InitializationKind initKind =
13920         InitializationKind::CreateCopy(Loc, SourceLocation());
13921
13922       Expr *opaqueValue =
13923         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13924       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13925       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13926       if (result.isInvalid())
13927         Invalid = true;
13928       else {
13929         // If the constructor used was non-trivial, set this as the
13930         // "initializer".
13931         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13932         if (!construct->getConstructor()->isTrivial()) {
13933           Expr *init = MaybeCreateExprWithCleanups(construct);
13934           ExDecl->setInit(init);
13935         }
13936
13937         // And make sure it's destructable.
13938         FinalizeVarWithDestructor(ExDecl, recordType);
13939       }
13940     }
13941   }
13942
13943   if (Invalid)
13944     ExDecl->setInvalidDecl();
13945
13946   return ExDecl;
13947 }
13948
13949 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13950 /// handler.
13951 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13952   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13953   bool Invalid = D.isInvalidType();
13954
13955   // Check for unexpanded parameter packs.
13956   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13957                                       UPPC_ExceptionType)) {
13958     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13959                                              D.getIdentifierLoc());
13960     Invalid = true;
13961   }
13962
13963   IdentifierInfo *II = D.getIdentifier();
13964   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13965                                              LookupOrdinaryName,
13966                                              ForVisibleRedeclaration)) {
13967     // The scope should be freshly made just for us. There is just no way
13968     // it contains any previous declaration, except for function parameters in
13969     // a function-try-block's catch statement.
13970     assert(!S->isDeclScope(PrevDecl));
13971     if (isDeclInScope(PrevDecl, CurContext, S)) {
13972       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13973         << D.getIdentifier();
13974       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13975       Invalid = true;
13976     } else if (PrevDecl->isTemplateParameter())
13977       // Maybe we will complain about the shadowed template parameter.
13978       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13979   }
13980
13981   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13982     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13983       << D.getCXXScopeSpec().getRange();
13984     Invalid = true;
13985   }
13986
13987   VarDecl *ExDecl = BuildExceptionDeclaration(
13988       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
13989   if (Invalid)
13990     ExDecl->setInvalidDecl();
13991
13992   // Add the exception declaration into this scope.
13993   if (II)
13994     PushOnScopeChains(ExDecl, S);
13995   else
13996     CurContext->addDecl(ExDecl);
13997
13998   ProcessDeclAttributes(S, ExDecl, D);
13999   return ExDecl;
14000 }
14001
14002 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
14003                                          Expr *AssertExpr,
14004                                          Expr *AssertMessageExpr,
14005                                          SourceLocation RParenLoc) {
14006   StringLiteral *AssertMessage =
14007       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
14008
14009   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
14010     return nullptr;
14011
14012   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
14013                                       AssertMessage, RParenLoc, false);
14014 }
14015
14016 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
14017                                          Expr *AssertExpr,
14018                                          StringLiteral *AssertMessage,
14019                                          SourceLocation RParenLoc,
14020                                          bool Failed) {
14021   assert(AssertExpr != nullptr && "Expected non-null condition");
14022   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
14023       !Failed) {
14024     // In a static_assert-declaration, the constant-expression shall be a
14025     // constant expression that can be contextually converted to bool.
14026     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
14027     if (Converted.isInvalid())
14028       Failed = true;
14029
14030     llvm::APSInt Cond;
14031     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
14032           diag::err_static_assert_expression_is_not_constant,
14033           /*AllowFold=*/false).isInvalid())
14034       Failed = true;
14035
14036     if (!Failed && !Cond) {
14037       SmallString<256> MsgBuffer;
14038       llvm::raw_svector_ostream Msg(MsgBuffer);
14039       if (AssertMessage)
14040         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
14041
14042       Expr *InnerCond = nullptr;
14043       std::string InnerCondDescription;
14044       std::tie(InnerCond, InnerCondDescription) =
14045         findFailedBooleanCondition(Converted.get());
14046       if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
14047                     && !isa<IntegerLiteral>(InnerCond)) {
14048         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
14049           << InnerCondDescription << !AssertMessage
14050           << Msg.str() << InnerCond->getSourceRange();
14051       } else {
14052         Diag(StaticAssertLoc, diag::err_static_assert_failed)
14053           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
14054       }
14055       Failed = true;
14056     }
14057   }
14058
14059   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
14060                                                   /*DiscardedValue*/false,
14061                                                   /*IsConstexpr*/true);
14062   if (FullAssertExpr.isInvalid())
14063     Failed = true;
14064   else
14065     AssertExpr = FullAssertExpr.get();
14066
14067   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
14068                                         AssertExpr, AssertMessage, RParenLoc,
14069                                         Failed);
14070
14071   CurContext->addDecl(Decl);
14072   return Decl;
14073 }
14074
14075 /// Perform semantic analysis of the given friend type declaration.
14076 ///
14077 /// \returns A friend declaration that.
14078 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
14079                                       SourceLocation FriendLoc,
14080                                       TypeSourceInfo *TSInfo) {
14081   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
14082
14083   QualType T = TSInfo->getType();
14084   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
14085
14086   // C++03 [class.friend]p2:
14087   //   An elaborated-type-specifier shall be used in a friend declaration
14088   //   for a class.*
14089   //
14090   //   * The class-key of the elaborated-type-specifier is required.
14091   if (!CodeSynthesisContexts.empty()) {
14092     // Do not complain about the form of friend template types during any kind
14093     // of code synthesis. For template instantiation, we will have complained
14094     // when the template was defined.
14095   } else {
14096     if (!T->isElaboratedTypeSpecifier()) {
14097       // If we evaluated the type to a record type, suggest putting
14098       // a tag in front.
14099       if (const RecordType *RT = T->getAs<RecordType>()) {
14100         RecordDecl *RD = RT->getDecl();
14101
14102         SmallString<16> InsertionText(" ");
14103         InsertionText += RD->getKindName();
14104
14105         Diag(TypeRange.getBegin(),
14106              getLangOpts().CPlusPlus11 ?
14107                diag::warn_cxx98_compat_unelaborated_friend_type :
14108                diag::ext_unelaborated_friend_type)
14109           << (unsigned) RD->getTagKind()
14110           << T
14111           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
14112                                         InsertionText);
14113       } else {
14114         Diag(FriendLoc,
14115              getLangOpts().CPlusPlus11 ?
14116                diag::warn_cxx98_compat_nonclass_type_friend :
14117                diag::ext_nonclass_type_friend)
14118           << T
14119           << TypeRange;
14120       }
14121     } else if (T->getAs<EnumType>()) {
14122       Diag(FriendLoc,
14123            getLangOpts().CPlusPlus11 ?
14124              diag::warn_cxx98_compat_enum_friend :
14125              diag::ext_enum_friend)
14126         << T
14127         << TypeRange;
14128     }
14129
14130     // C++11 [class.friend]p3:
14131     //   A friend declaration that does not declare a function shall have one
14132     //   of the following forms:
14133     //     friend elaborated-type-specifier ;
14134     //     friend simple-type-specifier ;
14135     //     friend typename-specifier ;
14136     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14137       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14138   }
14139
14140   //   If the type specifier in a friend declaration designates a (possibly
14141   //   cv-qualified) class type, that class is declared as a friend; otherwise,
14142   //   the friend declaration is ignored.
14143   return FriendDecl::Create(Context, CurContext,
14144                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14145                             FriendLoc);
14146 }
14147
14148 /// Handle a friend tag declaration where the scope specifier was
14149 /// templated.
14150 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
14151                                     unsigned TagSpec, SourceLocation TagLoc,
14152                                     CXXScopeSpec &SS, IdentifierInfo *Name,
14153                                     SourceLocation NameLoc,
14154                                     const ParsedAttributesView &Attr,
14155                                     MultiTemplateParamsArg TempParamLists) {
14156   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14157
14158   bool IsMemberSpecialization = false;
14159   bool Invalid = false;
14160
14161   if (TemplateParameterList *TemplateParams =
14162           MatchTemplateParametersToScopeSpecifier(
14163               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14164               IsMemberSpecialization, Invalid)) {
14165     if (TemplateParams->size() > 0) {
14166       // This is a declaration of a class template.
14167       if (Invalid)
14168         return nullptr;
14169
14170       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14171                                 NameLoc, Attr, TemplateParams, AS_public,
14172                                 /*ModulePrivateLoc=*/SourceLocation(),
14173                                 FriendLoc, TempParamLists.size() - 1,
14174                                 TempParamLists.data()).get();
14175     } else {
14176       // The "template<>" header is extraneous.
14177       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14178         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14179       IsMemberSpecialization = true;
14180     }
14181   }
14182
14183   if (Invalid) return nullptr;
14184
14185   bool isAllExplicitSpecializations = true;
14186   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14187     if (TempParamLists[I]->size()) {
14188       isAllExplicitSpecializations = false;
14189       break;
14190     }
14191   }
14192
14193   // FIXME: don't ignore attributes.
14194
14195   // If it's explicit specializations all the way down, just forget
14196   // about the template header and build an appropriate non-templated
14197   // friend.  TODO: for source fidelity, remember the headers.
14198   if (isAllExplicitSpecializations) {
14199     if (SS.isEmpty()) {
14200       bool Owned = false;
14201       bool IsDependent = false;
14202       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14203                       Attr, AS_public,
14204                       /*ModulePrivateLoc=*/SourceLocation(),
14205                       MultiTemplateParamsArg(), Owned, IsDependent,
14206                       /*ScopedEnumKWLoc=*/SourceLocation(),
14207                       /*ScopedEnumUsesClassTag=*/false,
14208                       /*UnderlyingType=*/TypeResult(),
14209                       /*IsTypeSpecifier=*/false,
14210                       /*IsTemplateParamOrArg=*/false);
14211     }
14212
14213     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14214     ElaboratedTypeKeyword Keyword
14215       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14216     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14217                                    *Name, NameLoc);
14218     if (T.isNull())
14219       return nullptr;
14220
14221     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14222     if (isa<DependentNameType>(T)) {
14223       DependentNameTypeLoc TL =
14224           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14225       TL.setElaboratedKeywordLoc(TagLoc);
14226       TL.setQualifierLoc(QualifierLoc);
14227       TL.setNameLoc(NameLoc);
14228     } else {
14229       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14230       TL.setElaboratedKeywordLoc(TagLoc);
14231       TL.setQualifierLoc(QualifierLoc);
14232       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14233     }
14234
14235     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14236                                             TSI, FriendLoc, TempParamLists);
14237     Friend->setAccess(AS_public);
14238     CurContext->addDecl(Friend);
14239     return Friend;
14240   }
14241
14242   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14243
14244
14245
14246   // Handle the case of a templated-scope friend class.  e.g.
14247   //   template <class T> class A<T>::B;
14248   // FIXME: we don't support these right now.
14249   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14250     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14251   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14252   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14253   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14254   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14255   TL.setElaboratedKeywordLoc(TagLoc);
14256   TL.setQualifierLoc(SS.getWithLocInContext(Context));
14257   TL.setNameLoc(NameLoc);
14258
14259   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14260                                           TSI, FriendLoc, TempParamLists);
14261   Friend->setAccess(AS_public);
14262   Friend->setUnsupportedFriend(true);
14263   CurContext->addDecl(Friend);
14264   return Friend;
14265 }
14266
14267 /// Handle a friend type declaration.  This works in tandem with
14268 /// ActOnTag.
14269 ///
14270 /// Notes on friend class templates:
14271 ///
14272 /// We generally treat friend class declarations as if they were
14273 /// declaring a class.  So, for example, the elaborated type specifier
14274 /// in a friend declaration is required to obey the restrictions of a
14275 /// class-head (i.e. no typedefs in the scope chain), template
14276 /// parameters are required to match up with simple template-ids, &c.
14277 /// However, unlike when declaring a template specialization, it's
14278 /// okay to refer to a template specialization without an empty
14279 /// template parameter declaration, e.g.
14280 ///   friend class A<T>::B<unsigned>;
14281 /// We permit this as a special case; if there are any template
14282 /// parameters present at all, require proper matching, i.e.
14283 ///   template <> template \<class T> friend class A<int>::B;
14284 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14285                                 MultiTemplateParamsArg TempParams) {
14286   SourceLocation Loc = DS.getBeginLoc();
14287
14288   assert(DS.isFriendSpecified());
14289   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14290
14291   // C++ [class.friend]p3:
14292   // A friend declaration that does not declare a function shall have one of
14293   // the following forms:
14294   //     friend elaborated-type-specifier ;
14295   //     friend simple-type-specifier ;
14296   //     friend typename-specifier ;
14297   //
14298   // Any declaration with a type qualifier does not have that form. (It's
14299   // legal to specify a qualified type as a friend, you just can't write the
14300   // keywords.)
14301   if (DS.getTypeQualifiers()) {
14302     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14303       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14304     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14305       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14306     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14307       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14308     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14309       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14310     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14311       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14312   }
14313
14314   // Try to convert the decl specifier to a type.  This works for
14315   // friend templates because ActOnTag never produces a ClassTemplateDecl
14316   // for a TUK_Friend.
14317   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14318   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14319   QualType T = TSI->getType();
14320   if (TheDeclarator.isInvalidType())
14321     return nullptr;
14322
14323   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14324     return nullptr;
14325
14326   // This is definitely an error in C++98.  It's probably meant to
14327   // be forbidden in C++0x, too, but the specification is just
14328   // poorly written.
14329   //
14330   // The problem is with declarations like the following:
14331   //   template <T> friend A<T>::foo;
14332   // where deciding whether a class C is a friend or not now hinges
14333   // on whether there exists an instantiation of A that causes
14334   // 'foo' to equal C.  There are restrictions on class-heads
14335   // (which we declare (by fiat) elaborated friend declarations to
14336   // be) that makes this tractable.
14337   //
14338   // FIXME: handle "template <> friend class A<T>;", which
14339   // is possibly well-formed?  Who even knows?
14340   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14341     Diag(Loc, diag::err_tagless_friend_type_template)
14342       << DS.getSourceRange();
14343     return nullptr;
14344   }
14345
14346   // C++98 [class.friend]p1: A friend of a class is a function
14347   //   or class that is not a member of the class . . .
14348   // This is fixed in DR77, which just barely didn't make the C++03
14349   // deadline.  It's also a very silly restriction that seriously
14350   // affects inner classes and which nobody else seems to implement;
14351   // thus we never diagnose it, not even in -pedantic.
14352   //
14353   // But note that we could warn about it: it's always useless to
14354   // friend one of your own members (it's not, however, worthless to
14355   // friend a member of an arbitrary specialization of your template).
14356
14357   Decl *D;
14358   if (!TempParams.empty())
14359     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14360                                    TempParams,
14361                                    TSI,
14362                                    DS.getFriendSpecLoc());
14363   else
14364     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14365
14366   if (!D)
14367     return nullptr;
14368
14369   D->setAccess(AS_public);
14370   CurContext->addDecl(D);
14371
14372   return D;
14373 }
14374
14375 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14376                                         MultiTemplateParamsArg TemplateParams) {
14377   const DeclSpec &DS = D.getDeclSpec();
14378
14379   assert(DS.isFriendSpecified());
14380   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14381
14382   SourceLocation Loc = D.getIdentifierLoc();
14383   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14384
14385   // C++ [class.friend]p1
14386   //   A friend of a class is a function or class....
14387   // Note that this sees through typedefs, which is intended.
14388   // It *doesn't* see through dependent types, which is correct
14389   // according to [temp.arg.type]p3:
14390   //   If a declaration acquires a function type through a
14391   //   type dependent on a template-parameter and this causes
14392   //   a declaration that does not use the syntactic form of a
14393   //   function declarator to have a function type, the program
14394   //   is ill-formed.
14395   if (!TInfo->getType()->isFunctionType()) {
14396     Diag(Loc, diag::err_unexpected_friend);
14397
14398     // It might be worthwhile to try to recover by creating an
14399     // appropriate declaration.
14400     return nullptr;
14401   }
14402
14403   // C++ [namespace.memdef]p3
14404   //  - If a friend declaration in a non-local class first declares a
14405   //    class or function, the friend class or function is a member
14406   //    of the innermost enclosing namespace.
14407   //  - The name of the friend is not found by simple name lookup
14408   //    until a matching declaration is provided in that namespace
14409   //    scope (either before or after the class declaration granting
14410   //    friendship).
14411   //  - If a friend function is called, its name may be found by the
14412   //    name lookup that considers functions from namespaces and
14413   //    classes associated with the types of the function arguments.
14414   //  - When looking for a prior declaration of a class or a function
14415   //    declared as a friend, scopes outside the innermost enclosing
14416   //    namespace scope are not considered.
14417
14418   CXXScopeSpec &SS = D.getCXXScopeSpec();
14419   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14420   assert(NameInfo.getName());
14421
14422   // Check for unexpanded parameter packs.
14423   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14424       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14425       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14426     return nullptr;
14427
14428   // The context we found the declaration in, or in which we should
14429   // create the declaration.
14430   DeclContext *DC;
14431   Scope *DCScope = S;
14432   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14433                         ForExternalRedeclaration);
14434
14435   // There are five cases here.
14436   //   - There's no scope specifier and we're in a local class. Only look
14437   //     for functions declared in the immediately-enclosing block scope.
14438   // We recover from invalid scope qualifiers as if they just weren't there.
14439   FunctionDecl *FunctionContainingLocalClass = nullptr;
14440   if ((SS.isInvalid() || !SS.isSet()) &&
14441       (FunctionContainingLocalClass =
14442            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14443     // C++11 [class.friend]p11:
14444     //   If a friend declaration appears in a local class and the name
14445     //   specified is an unqualified name, a prior declaration is
14446     //   looked up without considering scopes that are outside the
14447     //   innermost enclosing non-class scope. For a friend function
14448     //   declaration, if there is no prior declaration, the program is
14449     //   ill-formed.
14450
14451     // Find the innermost enclosing non-class scope. This is the block
14452     // scope containing the local class definition (or for a nested class,
14453     // the outer local class).
14454     DCScope = S->getFnParent();
14455
14456     // Look up the function name in the scope.
14457     Previous.clear(LookupLocalFriendName);
14458     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14459
14460     if (!Previous.empty()) {
14461       // All possible previous declarations must have the same context:
14462       // either they were declared at block scope or they are members of
14463       // one of the enclosing local classes.
14464       DC = Previous.getRepresentativeDecl()->getDeclContext();
14465     } else {
14466       // This is ill-formed, but provide the context that we would have
14467       // declared the function in, if we were permitted to, for error recovery.
14468       DC = FunctionContainingLocalClass;
14469     }
14470     adjustContextForLocalExternDecl(DC);
14471
14472     // C++ [class.friend]p6:
14473     //   A function can be defined in a friend declaration of a class if and
14474     //   only if the class is a non-local class (9.8), the function name is
14475     //   unqualified, and the function has namespace scope.
14476     if (D.isFunctionDefinition()) {
14477       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14478     }
14479
14480   //   - There's no scope specifier, in which case we just go to the
14481   //     appropriate scope and look for a function or function template
14482   //     there as appropriate.
14483   } else if (SS.isInvalid() || !SS.isSet()) {
14484     // C++11 [namespace.memdef]p3:
14485     //   If the name in a friend declaration is neither qualified nor
14486     //   a template-id and the declaration is a function or an
14487     //   elaborated-type-specifier, the lookup to determine whether
14488     //   the entity has been previously declared shall not consider
14489     //   any scopes outside the innermost enclosing namespace.
14490     bool isTemplateId =
14491         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14492
14493     // Find the appropriate context according to the above.
14494     DC = CurContext;
14495
14496     // Skip class contexts.  If someone can cite chapter and verse
14497     // for this behavior, that would be nice --- it's what GCC and
14498     // EDG do, and it seems like a reasonable intent, but the spec
14499     // really only says that checks for unqualified existing
14500     // declarations should stop at the nearest enclosing namespace,
14501     // not that they should only consider the nearest enclosing
14502     // namespace.
14503     while (DC->isRecord())
14504       DC = DC->getParent();
14505
14506     DeclContext *LookupDC = DC;
14507     while (LookupDC->isTransparentContext())
14508       LookupDC = LookupDC->getParent();
14509
14510     while (true) {
14511       LookupQualifiedName(Previous, LookupDC);
14512
14513       if (!Previous.empty()) {
14514         DC = LookupDC;
14515         break;
14516       }
14517
14518       if (isTemplateId) {
14519         if (isa<TranslationUnitDecl>(LookupDC)) break;
14520       } else {
14521         if (LookupDC->isFileContext()) break;
14522       }
14523       LookupDC = LookupDC->getParent();
14524     }
14525
14526     DCScope = getScopeForDeclContext(S, DC);
14527
14528   //   - There's a non-dependent scope specifier, in which case we
14529   //     compute it and do a previous lookup there for a function
14530   //     or function template.
14531   } else if (!SS.getScopeRep()->isDependent()) {
14532     DC = computeDeclContext(SS);
14533     if (!DC) return nullptr;
14534
14535     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14536
14537     LookupQualifiedName(Previous, DC);
14538
14539     // C++ [class.friend]p1: A friend of a class is a function or
14540     //   class that is not a member of the class . . .
14541     if (DC->Equals(CurContext))
14542       Diag(DS.getFriendSpecLoc(),
14543            getLangOpts().CPlusPlus11 ?
14544              diag::warn_cxx98_compat_friend_is_member :
14545              diag::err_friend_is_member);
14546
14547     if (D.isFunctionDefinition()) {
14548       // C++ [class.friend]p6:
14549       //   A function can be defined in a friend declaration of a class if and
14550       //   only if the class is a non-local class (9.8), the function name is
14551       //   unqualified, and the function has namespace scope.
14552       //
14553       // FIXME: We should only do this if the scope specifier names the
14554       // innermost enclosing namespace; otherwise the fixit changes the
14555       // meaning of the code.
14556       SemaDiagnosticBuilder DB
14557         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14558
14559       DB << SS.getScopeRep();
14560       if (DC->isFileContext())
14561         DB << FixItHint::CreateRemoval(SS.getRange());
14562       SS.clear();
14563     }
14564
14565   //   - There's a scope specifier that does not match any template
14566   //     parameter lists, in which case we use some arbitrary context,
14567   //     create a method or method template, and wait for instantiation.
14568   //   - There's a scope specifier that does match some template
14569   //     parameter lists, which we don't handle right now.
14570   } else {
14571     if (D.isFunctionDefinition()) {
14572       // C++ [class.friend]p6:
14573       //   A function can be defined in a friend declaration of a class if and
14574       //   only if the class is a non-local class (9.8), the function name is
14575       //   unqualified, and the function has namespace scope.
14576       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14577         << SS.getScopeRep();
14578     }
14579
14580     DC = CurContext;
14581     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14582   }
14583
14584   if (!DC->isRecord()) {
14585     int DiagArg = -1;
14586     switch (D.getName().getKind()) {
14587     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14588     case UnqualifiedIdKind::IK_ConstructorName:
14589       DiagArg = 0;
14590       break;
14591     case UnqualifiedIdKind::IK_DestructorName:
14592       DiagArg = 1;
14593       break;
14594     case UnqualifiedIdKind::IK_ConversionFunctionId:
14595       DiagArg = 2;
14596       break;
14597     case UnqualifiedIdKind::IK_DeductionGuideName:
14598       DiagArg = 3;
14599       break;
14600     case UnqualifiedIdKind::IK_Identifier:
14601     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14602     case UnqualifiedIdKind::IK_LiteralOperatorId:
14603     case UnqualifiedIdKind::IK_OperatorFunctionId:
14604     case UnqualifiedIdKind::IK_TemplateId:
14605       break;
14606     }
14607     // This implies that it has to be an operator or function.
14608     if (DiagArg >= 0) {
14609       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14610       return nullptr;
14611     }
14612   }
14613
14614   // FIXME: This is an egregious hack to cope with cases where the scope stack
14615   // does not contain the declaration context, i.e., in an out-of-line
14616   // definition of a class.
14617   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14618   if (!DCScope) {
14619     FakeDCScope.setEntity(DC);
14620     DCScope = &FakeDCScope;
14621   }
14622
14623   bool AddToScope = true;
14624   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14625                                           TemplateParams, AddToScope);
14626   if (!ND) return nullptr;
14627
14628   assert(ND->getLexicalDeclContext() == CurContext);
14629
14630   // If we performed typo correction, we might have added a scope specifier
14631   // and changed the decl context.
14632   DC = ND->getDeclContext();
14633
14634   // Add the function declaration to the appropriate lookup tables,
14635   // adjusting the redeclarations list as necessary.  We don't
14636   // want to do this yet if the friending class is dependent.
14637   //
14638   // Also update the scope-based lookup if the target context's
14639   // lookup context is in lexical scope.
14640   if (!CurContext->isDependentContext()) {
14641     DC = DC->getRedeclContext();
14642     DC->makeDeclVisibleInContext(ND);
14643     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14644       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14645   }
14646
14647   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14648                                        D.getIdentifierLoc(), ND,
14649                                        DS.getFriendSpecLoc());
14650   FrD->setAccess(AS_public);
14651   CurContext->addDecl(FrD);
14652
14653   if (ND->isInvalidDecl()) {
14654     FrD->setInvalidDecl();
14655   } else {
14656     if (DC->isRecord()) CheckFriendAccess(ND);
14657
14658     FunctionDecl *FD;
14659     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14660       FD = FTD->getTemplatedDecl();
14661     else
14662       FD = cast<FunctionDecl>(ND);
14663
14664     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14665     // default argument expression, that declaration shall be a definition
14666     // and shall be the only declaration of the function or function
14667     // template in the translation unit.
14668     if (functionDeclHasDefaultArgument(FD)) {
14669       // We can't look at FD->getPreviousDecl() because it may not have been set
14670       // if we're in a dependent context. If the function is known to be a
14671       // redeclaration, we will have narrowed Previous down to the right decl.
14672       if (D.isRedeclaration()) {
14673         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14674         Diag(Previous.getRepresentativeDecl()->getLocation(),
14675              diag::note_previous_declaration);
14676       } else if (!D.isFunctionDefinition())
14677         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14678     }
14679
14680     // Mark templated-scope function declarations as unsupported.
14681     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14682       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14683         << SS.getScopeRep() << SS.getRange()
14684         << cast<CXXRecordDecl>(CurContext);
14685       FrD->setUnsupportedFriend(true);
14686     }
14687   }
14688
14689   return ND;
14690 }
14691
14692 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14693   AdjustDeclIfTemplate(Dcl);
14694
14695   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14696   if (!Fn) {
14697     Diag(DelLoc, diag::err_deleted_non_function);
14698     return;
14699   }
14700
14701   // Deleted function does not have a body.
14702   Fn->setWillHaveBody(false);
14703
14704   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14705     // Don't consider the implicit declaration we generate for explicit
14706     // specializations. FIXME: Do not generate these implicit declarations.
14707     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14708          Prev->getPreviousDecl()) &&
14709         !Prev->isDefined()) {
14710       Diag(DelLoc, diag::err_deleted_decl_not_first);
14711       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14712            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14713                               : diag::note_previous_declaration);
14714     }
14715     // If the declaration wasn't the first, we delete the function anyway for
14716     // recovery.
14717     Fn = Fn->getCanonicalDecl();
14718   }
14719
14720   // dllimport/dllexport cannot be deleted.
14721   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14722     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14723     Fn->setInvalidDecl();
14724   }
14725
14726   if (Fn->isDeleted())
14727     return;
14728
14729   // See if we're deleting a function which is already known to override a
14730   // non-deleted virtual function.
14731   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14732     bool IssuedDiagnostic = false;
14733     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14734       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14735         if (!IssuedDiagnostic) {
14736           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14737           IssuedDiagnostic = true;
14738         }
14739         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14740       }
14741     }
14742     // If this function was implicitly deleted because it was defaulted,
14743     // explain why it was deleted.
14744     if (IssuedDiagnostic && MD->isDefaulted())
14745       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14746                                 /*Diagnose*/true);
14747   }
14748
14749   // C++11 [basic.start.main]p3:
14750   //   A program that defines main as deleted [...] is ill-formed.
14751   if (Fn->isMain())
14752     Diag(DelLoc, diag::err_deleted_main);
14753
14754   // C++11 [dcl.fct.def.delete]p4:
14755   //  A deleted function is implicitly inline.
14756   Fn->setImplicitlyInline();
14757   Fn->setDeletedAsWritten();
14758 }
14759
14760 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14761   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14762
14763   if (MD) {
14764     if (MD->getParent()->isDependentType()) {
14765       MD->setDefaulted();
14766       MD->setExplicitlyDefaulted();
14767       return;
14768     }
14769
14770     CXXSpecialMember Member = getSpecialMember(MD);
14771     if (Member == CXXInvalid) {
14772       if (!MD->isInvalidDecl())
14773         Diag(DefaultLoc, diag::err_default_special_members);
14774       return;
14775     }
14776
14777     MD->setDefaulted();
14778     MD->setExplicitlyDefaulted();
14779
14780     // Unset that we will have a body for this function. We might not,
14781     // if it turns out to be trivial, and we don't need this marking now
14782     // that we've marked it as defaulted.
14783     MD->setWillHaveBody(false);
14784
14785     // If this definition appears within the record, do the checking when
14786     // the record is complete.
14787     const FunctionDecl *Primary = MD;
14788     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14789       // Ask the template instantiation pattern that actually had the
14790       // '= default' on it.
14791       Primary = Pattern;
14792
14793     // If the method was defaulted on its first declaration, we will have
14794     // already performed the checking in CheckCompletedCXXClass. Such a
14795     // declaration doesn't trigger an implicit definition.
14796     if (Primary->getCanonicalDecl()->isDefaulted())
14797       return;
14798
14799     CheckExplicitlyDefaultedSpecialMember(MD);
14800
14801     if (!MD->isInvalidDecl())
14802       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14803   } else {
14804     Diag(DefaultLoc, diag::err_default_special_members);
14805   }
14806 }
14807
14808 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14809   for (Stmt *SubStmt : S->children()) {
14810     if (!SubStmt)
14811       continue;
14812     if (isa<ReturnStmt>(SubStmt))
14813       Self.Diag(SubStmt->getBeginLoc(),
14814                 diag::err_return_in_constructor_handler);
14815     if (!isa<Expr>(SubStmt))
14816       SearchForReturnInStmt(Self, SubStmt);
14817   }
14818 }
14819
14820 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14821   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14822     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14823     SearchForReturnInStmt(*this, Handler);
14824   }
14825 }
14826
14827 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14828                                              const CXXMethodDecl *Old) {
14829   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14830   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14831
14832   if (OldFT->hasExtParameterInfos()) {
14833     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14834       // A parameter of the overriding method should be annotated with noescape
14835       // if the corresponding parameter of the overridden method is annotated.
14836       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14837           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14838         Diag(New->getParamDecl(I)->getLocation(),
14839              diag::warn_overriding_method_missing_noescape);
14840         Diag(Old->getParamDecl(I)->getLocation(),
14841              diag::note_overridden_marked_noescape);
14842       }
14843   }
14844
14845   // Virtual overrides must have the same code_seg.
14846   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14847   const auto *NewCSA = New->getAttr<CodeSegAttr>();
14848   if ((NewCSA || OldCSA) &&
14849       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14850     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14851     Diag(Old->getLocation(), diag::note_previous_declaration);
14852     return true;
14853   }
14854
14855   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14856
14857   // If the calling conventions match, everything is fine
14858   if (NewCC == OldCC)
14859     return false;
14860
14861   // If the calling conventions mismatch because the new function is static,
14862   // suppress the calling convention mismatch error; the error about static
14863   // function override (err_static_overrides_virtual from
14864   // Sema::CheckFunctionDeclaration) is more clear.
14865   if (New->getStorageClass() == SC_Static)
14866     return false;
14867
14868   Diag(New->getLocation(),
14869        diag::err_conflicting_overriding_cc_attributes)
14870     << New->getDeclName() << New->getType() << Old->getType();
14871   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14872   return true;
14873 }
14874
14875 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14876                                              const CXXMethodDecl *Old) {
14877   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14878   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14879
14880   if (Context.hasSameType(NewTy, OldTy) ||
14881       NewTy->isDependentType() || OldTy->isDependentType())
14882     return false;
14883
14884   // Check if the return types are covariant
14885   QualType NewClassTy, OldClassTy;
14886
14887   /// Both types must be pointers or references to classes.
14888   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14889     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14890       NewClassTy = NewPT->getPointeeType();
14891       OldClassTy = OldPT->getPointeeType();
14892     }
14893   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14894     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14895       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14896         NewClassTy = NewRT->getPointeeType();
14897         OldClassTy = OldRT->getPointeeType();
14898       }
14899     }
14900   }
14901
14902   // The return types aren't either both pointers or references to a class type.
14903   if (NewClassTy.isNull()) {
14904     Diag(New->getLocation(),
14905          diag::err_different_return_type_for_overriding_virtual_function)
14906         << New->getDeclName() << NewTy << OldTy
14907         << New->getReturnTypeSourceRange();
14908     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14909         << Old->getReturnTypeSourceRange();
14910
14911     return true;
14912   }
14913
14914   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14915     // C++14 [class.virtual]p8:
14916     //   If the class type in the covariant return type of D::f differs from
14917     //   that of B::f, the class type in the return type of D::f shall be
14918     //   complete at the point of declaration of D::f or shall be the class
14919     //   type D.
14920     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14921       if (!RT->isBeingDefined() &&
14922           RequireCompleteType(New->getLocation(), NewClassTy,
14923                               diag::err_covariant_return_incomplete,
14924                               New->getDeclName()))
14925         return true;
14926     }
14927
14928     // Check if the new class derives from the old class.
14929     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14930       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14931           << New->getDeclName() << NewTy << OldTy
14932           << New->getReturnTypeSourceRange();
14933       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14934           << Old->getReturnTypeSourceRange();
14935       return true;
14936     }
14937
14938     // Check if we the conversion from derived to base is valid.
14939     if (CheckDerivedToBaseConversion(
14940             NewClassTy, OldClassTy,
14941             diag::err_covariant_return_inaccessible_base,
14942             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14943             New->getLocation(), New->getReturnTypeSourceRange(),
14944             New->getDeclName(), nullptr)) {
14945       // FIXME: this note won't trigger for delayed access control
14946       // diagnostics, and it's impossible to get an undelayed error
14947       // here from access control during the original parse because
14948       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14949       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14950           << Old->getReturnTypeSourceRange();
14951       return true;
14952     }
14953   }
14954
14955   // The qualifiers of the return types must be the same.
14956   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14957     Diag(New->getLocation(),
14958          diag::err_covariant_return_type_different_qualifications)
14959         << New->getDeclName() << NewTy << OldTy
14960         << New->getReturnTypeSourceRange();
14961     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14962         << Old->getReturnTypeSourceRange();
14963     return true;
14964   }
14965
14966
14967   // The new class type must have the same or less qualifiers as the old type.
14968   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14969     Diag(New->getLocation(),
14970          diag::err_covariant_return_type_class_type_more_qualified)
14971         << New->getDeclName() << NewTy << OldTy
14972         << New->getReturnTypeSourceRange();
14973     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14974         << Old->getReturnTypeSourceRange();
14975     return true;
14976   }
14977
14978   return false;
14979 }
14980
14981 /// Mark the given method pure.
14982 ///
14983 /// \param Method the method to be marked pure.
14984 ///
14985 /// \param InitRange the source range that covers the "0" initializer.
14986 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14987   SourceLocation EndLoc = InitRange.getEnd();
14988   if (EndLoc.isValid())
14989     Method->setRangeEnd(EndLoc);
14990
14991   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14992     Method->setPure();
14993     return false;
14994   }
14995
14996   if (!Method->isInvalidDecl())
14997     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14998       << Method->getDeclName() << InitRange;
14999   return true;
15000 }
15001
15002 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
15003   if (D->getFriendObjectKind())
15004     Diag(D->getLocation(), diag::err_pure_friend);
15005   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
15006     CheckPureMethod(M, ZeroLoc);
15007   else
15008     Diag(D->getLocation(), diag::err_illegal_initializer);
15009 }
15010
15011 /// Determine whether the given declaration is a global variable or
15012 /// static data member.
15013 static bool isNonlocalVariable(const Decl *D) {
15014   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
15015     return Var->hasGlobalStorage();
15016
15017   return false;
15018 }
15019
15020 /// Invoked when we are about to parse an initializer for the declaration
15021 /// 'Dcl'.
15022 ///
15023 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
15024 /// static data member of class X, names should be looked up in the scope of
15025 /// class X. If the declaration had a scope specifier, a scope will have
15026 /// been created and passed in for this purpose. Otherwise, S will be null.
15027 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
15028   // If there is no declaration, there was an error parsing it.
15029   if (!D || D->isInvalidDecl())
15030     return;
15031
15032   // We will always have a nested name specifier here, but this declaration
15033   // might not be out of line if the specifier names the current namespace:
15034   //   extern int n;
15035   //   int ::n = 0;
15036   if (S && D->isOutOfLine())
15037     EnterDeclaratorContext(S, D->getDeclContext());
15038
15039   // If we are parsing the initializer for a static data member, push a
15040   // new expression evaluation context that is associated with this static
15041   // data member.
15042   if (isNonlocalVariable(D))
15043     PushExpressionEvaluationContext(
15044         ExpressionEvaluationContext::PotentiallyEvaluated, D);
15045 }
15046
15047 /// Invoked after we are finished parsing an initializer for the declaration D.
15048 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
15049   // If there is no declaration, there was an error parsing it.
15050   if (!D || D->isInvalidDecl())
15051     return;
15052
15053   if (isNonlocalVariable(D))
15054     PopExpressionEvaluationContext();
15055
15056   if (S && D->isOutOfLine())
15057     ExitDeclaratorContext(S);
15058 }
15059
15060 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
15061 /// C++ if/switch/while/for statement.
15062 /// e.g: "if (int x = f()) {...}"
15063 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
15064   // C++ 6.4p2:
15065   // The declarator shall not specify a function or an array.
15066   // The type-specifier-seq shall not contain typedef and shall not declare a
15067   // new class or enumeration.
15068   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
15069          "Parser allowed 'typedef' as storage class of condition decl.");
15070
15071   Decl *Dcl = ActOnDeclarator(S, D);
15072   if (!Dcl)
15073     return true;
15074
15075   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
15076     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
15077       << D.getSourceRange();
15078     return true;
15079   }
15080
15081   return Dcl;
15082 }
15083
15084 void Sema::LoadExternalVTableUses() {
15085   if (!ExternalSource)
15086     return;
15087
15088   SmallVector<ExternalVTableUse, 4> VTables;
15089   ExternalSource->ReadUsedVTables(VTables);
15090   SmallVector<VTableUse, 4> NewUses;
15091   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
15092     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
15093       = VTablesUsed.find(VTables[I].Record);
15094     // Even if a definition wasn't required before, it may be required now.
15095     if (Pos != VTablesUsed.end()) {
15096       if (!Pos->second && VTables[I].DefinitionRequired)
15097         Pos->second = true;
15098       continue;
15099     }
15100
15101     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
15102     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
15103   }
15104
15105   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
15106 }
15107
15108 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
15109                           bool DefinitionRequired) {
15110   // Ignore any vtable uses in unevaluated operands or for classes that do
15111   // not have a vtable.
15112   if (!Class->isDynamicClass() || Class->isDependentContext() ||
15113       CurContext->isDependentContext() || isUnevaluatedContext())
15114     return;
15115   // Do not mark as used if compiling for the device outside of the target
15116   // region.
15117   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15118       !isInOpenMPDeclareTargetContext() &&
15119       !isInOpenMPTargetExecutionDirective()) {
15120     if (!DefinitionRequired)
15121       MarkVirtualMembersReferenced(Loc, Class);
15122     return;
15123   }
15124
15125   // Try to insert this class into the map.
15126   LoadExternalVTableUses();
15127   Class = Class->getCanonicalDecl();
15128   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15129     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15130   if (!Pos.second) {
15131     // If we already had an entry, check to see if we are promoting this vtable
15132     // to require a definition. If so, we need to reappend to the VTableUses
15133     // list, since we may have already processed the first entry.
15134     if (DefinitionRequired && !Pos.first->second) {
15135       Pos.first->second = true;
15136     } else {
15137       // Otherwise, we can early exit.
15138       return;
15139     }
15140   } else {
15141     // The Microsoft ABI requires that we perform the destructor body
15142     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15143     // the deleting destructor is emitted with the vtable, not with the
15144     // destructor definition as in the Itanium ABI.
15145     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15146       CXXDestructorDecl *DD = Class->getDestructor();
15147       if (DD && DD->isVirtual() && !DD->isDeleted()) {
15148         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15149           // If this is an out-of-line declaration, marking it referenced will
15150           // not do anything. Manually call CheckDestructor to look up operator
15151           // delete().
15152           ContextRAII SavedContext(*this, DD);
15153           CheckDestructor(DD);
15154         } else {
15155           MarkFunctionReferenced(Loc, Class->getDestructor());
15156         }
15157       }
15158     }
15159   }
15160
15161   // Local classes need to have their virtual members marked
15162   // immediately. For all other classes, we mark their virtual members
15163   // at the end of the translation unit.
15164   if (Class->isLocalClass())
15165     MarkVirtualMembersReferenced(Loc, Class);
15166   else
15167     VTableUses.push_back(std::make_pair(Class, Loc));
15168 }
15169
15170 bool Sema::DefineUsedVTables() {
15171   LoadExternalVTableUses();
15172   if (VTableUses.empty())
15173     return false;
15174
15175   // Note: The VTableUses vector could grow as a result of marking
15176   // the members of a class as "used", so we check the size each
15177   // time through the loop and prefer indices (which are stable) to
15178   // iterators (which are not).
15179   bool DefinedAnything = false;
15180   for (unsigned I = 0; I != VTableUses.size(); ++I) {
15181     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15182     if (!Class)
15183       continue;
15184     TemplateSpecializationKind ClassTSK =
15185         Class->getTemplateSpecializationKind();
15186
15187     SourceLocation Loc = VTableUses[I].second;
15188
15189     bool DefineVTable = true;
15190
15191     // If this class has a key function, but that key function is
15192     // defined in another translation unit, we don't need to emit the
15193     // vtable even though we're using it.
15194     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15195     if (KeyFunction && !KeyFunction->hasBody()) {
15196       // The key function is in another translation unit.
15197       DefineVTable = false;
15198       TemplateSpecializationKind TSK =
15199           KeyFunction->getTemplateSpecializationKind();
15200       assert(TSK != TSK_ExplicitInstantiationDefinition &&
15201              TSK != TSK_ImplicitInstantiation &&
15202              "Instantiations don't have key functions");
15203       (void)TSK;
15204     } else if (!KeyFunction) {
15205       // If we have a class with no key function that is the subject
15206       // of an explicit instantiation declaration, suppress the
15207       // vtable; it will live with the explicit instantiation
15208       // definition.
15209       bool IsExplicitInstantiationDeclaration =
15210           ClassTSK == TSK_ExplicitInstantiationDeclaration;
15211       for (auto R : Class->redecls()) {
15212         TemplateSpecializationKind TSK
15213           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15214         if (TSK == TSK_ExplicitInstantiationDeclaration)
15215           IsExplicitInstantiationDeclaration = true;
15216         else if (TSK == TSK_ExplicitInstantiationDefinition) {
15217           IsExplicitInstantiationDeclaration = false;
15218           break;
15219         }
15220       }
15221
15222       if (IsExplicitInstantiationDeclaration)
15223         DefineVTable = false;
15224     }
15225
15226     // The exception specifications for all virtual members may be needed even
15227     // if we are not providing an authoritative form of the vtable in this TU.
15228     // We may choose to emit it available_externally anyway.
15229     if (!DefineVTable) {
15230       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15231       continue;
15232     }
15233
15234     // Mark all of the virtual members of this class as referenced, so
15235     // that we can build a vtable. Then, tell the AST consumer that a
15236     // vtable for this class is required.
15237     DefinedAnything = true;
15238     MarkVirtualMembersReferenced(Loc, Class);
15239     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15240     if (VTablesUsed[Canonical])
15241       Consumer.HandleVTable(Class);
15242
15243     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15244     // no key function or the key function is inlined. Don't warn in C++ ABIs
15245     // that lack key functions, since the user won't be able to make one.
15246     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15247         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15248       const FunctionDecl *KeyFunctionDef = nullptr;
15249       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15250                            KeyFunctionDef->isInlined())) {
15251         Diag(Class->getLocation(),
15252              ClassTSK == TSK_ExplicitInstantiationDefinition
15253                  ? diag::warn_weak_template_vtable
15254                  : diag::warn_weak_vtable)
15255             << Class;
15256       }
15257     }
15258   }
15259   VTableUses.clear();
15260
15261   return DefinedAnything;
15262 }
15263
15264 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15265                                                  const CXXRecordDecl *RD) {
15266   for (const auto *I : RD->methods())
15267     if (I->isVirtual() && !I->isPure())
15268       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15269 }
15270
15271 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15272                                         const CXXRecordDecl *RD,
15273                                         bool ConstexprOnly) {
15274   // Mark all functions which will appear in RD's vtable as used.
15275   CXXFinalOverriderMap FinalOverriders;
15276   RD->getFinalOverriders(FinalOverriders);
15277   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15278                                             E = FinalOverriders.end();
15279        I != E; ++I) {
15280     for (OverridingMethods::const_iterator OI = I->second.begin(),
15281                                            OE = I->second.end();
15282          OI != OE; ++OI) {
15283       assert(OI->second.size() > 0 && "no final overrider");
15284       CXXMethodDecl *Overrider = OI->second.front().Method;
15285
15286       // C++ [basic.def.odr]p2:
15287       //   [...] A virtual member function is used if it is not pure. [...]
15288       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
15289         MarkFunctionReferenced(Loc, Overrider);
15290     }
15291   }
15292
15293   // Only classes that have virtual bases need a VTT.
15294   if (RD->getNumVBases() == 0)
15295     return;
15296
15297   for (const auto &I : RD->bases()) {
15298     const CXXRecordDecl *Base =
15299         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15300     if (Base->getNumVBases() == 0)
15301       continue;
15302     MarkVirtualMembersReferenced(Loc, Base);
15303   }
15304 }
15305
15306 /// SetIvarInitializers - This routine builds initialization ASTs for the
15307 /// Objective-C implementation whose ivars need be initialized.
15308 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15309   if (!getLangOpts().CPlusPlus)
15310     return;
15311   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15312     SmallVector<ObjCIvarDecl*, 8> ivars;
15313     CollectIvarsToConstructOrDestruct(OID, ivars);
15314     if (ivars.empty())
15315       return;
15316     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15317     for (unsigned i = 0; i < ivars.size(); i++) {
15318       FieldDecl *Field = ivars[i];
15319       if (Field->isInvalidDecl())
15320         continue;
15321
15322       CXXCtorInitializer *Member;
15323       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15324       InitializationKind InitKind =
15325         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15326
15327       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15328       ExprResult MemberInit =
15329         InitSeq.Perform(*this, InitEntity, InitKind, None);
15330       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15331       // Note, MemberInit could actually come back empty if no initialization
15332       // is required (e.g., because it would call a trivial default constructor)
15333       if (!MemberInit.get() || MemberInit.isInvalid())
15334         continue;
15335
15336       Member =
15337         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15338                                          SourceLocation(),
15339                                          MemberInit.getAs<Expr>(),
15340                                          SourceLocation());
15341       AllToInit.push_back(Member);
15342
15343       // Be sure that the destructor is accessible and is marked as referenced.
15344       if (const RecordType *RecordTy =
15345               Context.getBaseElementType(Field->getType())
15346                   ->getAs<RecordType>()) {
15347         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15348         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15349           MarkFunctionReferenced(Field->getLocation(), Destructor);
15350           CheckDestructorAccess(Field->getLocation(), Destructor,
15351                             PDiag(diag::err_access_dtor_ivar)
15352                               << Context.getBaseElementType(Field->getType()));
15353         }
15354       }
15355     }
15356     ObjCImplementation->setIvarInitializers(Context,
15357                                             AllToInit.data(), AllToInit.size());
15358   }
15359 }
15360
15361 static
15362 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15363                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15364                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15365                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15366                            Sema &S) {
15367   if (Ctor->isInvalidDecl())
15368     return;
15369
15370   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15371
15372   // Target may not be determinable yet, for instance if this is a dependent
15373   // call in an uninstantiated template.
15374   if (Target) {
15375     const FunctionDecl *FNTarget = nullptr;
15376     (void)Target->hasBody(FNTarget);
15377     Target = const_cast<CXXConstructorDecl*>(
15378       cast_or_null<CXXConstructorDecl>(FNTarget));
15379   }
15380
15381   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15382                      // Avoid dereferencing a null pointer here.
15383                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15384
15385   if (!Current.insert(Canonical).second)
15386     return;
15387
15388   // We know that beyond here, we aren't chaining into a cycle.
15389   if (!Target || !Target->isDelegatingConstructor() ||
15390       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15391     Valid.insert(Current.begin(), Current.end());
15392     Current.clear();
15393   // We've hit a cycle.
15394   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15395              Current.count(TCanonical)) {
15396     // If we haven't diagnosed this cycle yet, do so now.
15397     if (!Invalid.count(TCanonical)) {
15398       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15399              diag::warn_delegating_ctor_cycle)
15400         << Ctor;
15401
15402       // Don't add a note for a function delegating directly to itself.
15403       if (TCanonical != Canonical)
15404         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15405
15406       CXXConstructorDecl *C = Target;
15407       while (C->getCanonicalDecl() != Canonical) {
15408         const FunctionDecl *FNTarget = nullptr;
15409         (void)C->getTargetConstructor()->hasBody(FNTarget);
15410         assert(FNTarget && "Ctor cycle through bodiless function");
15411
15412         C = const_cast<CXXConstructorDecl*>(
15413           cast<CXXConstructorDecl>(FNTarget));
15414         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15415       }
15416     }
15417
15418     Invalid.insert(Current.begin(), Current.end());
15419     Current.clear();
15420   } else {
15421     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15422   }
15423 }
15424
15425
15426 void Sema::CheckDelegatingCtorCycles() {
15427   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15428
15429   for (DelegatingCtorDeclsType::iterator
15430          I = DelegatingCtorDecls.begin(ExternalSource),
15431          E = DelegatingCtorDecls.end();
15432        I != E; ++I)
15433     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15434
15435   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15436     (*CI)->setInvalidDecl();
15437 }
15438
15439 namespace {
15440   /// AST visitor that finds references to the 'this' expression.
15441   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15442     Sema &S;
15443
15444   public:
15445     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15446
15447     bool VisitCXXThisExpr(CXXThisExpr *E) {
15448       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15449         << E->isImplicit();
15450       return false;
15451     }
15452   };
15453 }
15454
15455 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15456   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15457   if (!TSInfo)
15458     return false;
15459
15460   TypeLoc TL = TSInfo->getTypeLoc();
15461   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15462   if (!ProtoTL)
15463     return false;
15464
15465   // C++11 [expr.prim.general]p3:
15466   //   [The expression this] shall not appear before the optional
15467   //   cv-qualifier-seq and it shall not appear within the declaration of a
15468   //   static member function (although its type and value category are defined
15469   //   within a static member function as they are within a non-static member
15470   //   function). [ Note: this is because declaration matching does not occur
15471   //  until the complete declarator is known. - end note ]
15472   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15473   FindCXXThisExpr Finder(*this);
15474
15475   // If the return type came after the cv-qualifier-seq, check it now.
15476   if (Proto->hasTrailingReturn() &&
15477       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15478     return true;
15479
15480   // Check the exception specification.
15481   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15482     return true;
15483
15484   return checkThisInStaticMemberFunctionAttributes(Method);
15485 }
15486
15487 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15488   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15489   if (!TSInfo)
15490     return false;
15491
15492   TypeLoc TL = TSInfo->getTypeLoc();
15493   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15494   if (!ProtoTL)
15495     return false;
15496
15497   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15498   FindCXXThisExpr Finder(*this);
15499
15500   switch (Proto->getExceptionSpecType()) {
15501   case EST_Unparsed:
15502   case EST_Uninstantiated:
15503   case EST_Unevaluated:
15504   case EST_BasicNoexcept:
15505   case EST_NoThrow:
15506   case EST_DynamicNone:
15507   case EST_MSAny:
15508   case EST_None:
15509     break;
15510
15511   case EST_DependentNoexcept:
15512   case EST_NoexceptFalse:
15513   case EST_NoexceptTrue:
15514     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15515       return true;
15516     LLVM_FALLTHROUGH;
15517
15518   case EST_Dynamic:
15519     for (const auto &E : Proto->exceptions()) {
15520       if (!Finder.TraverseType(E))
15521         return true;
15522     }
15523     break;
15524   }
15525
15526   return false;
15527 }
15528
15529 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15530   FindCXXThisExpr Finder(*this);
15531
15532   // Check attributes.
15533   for (const auto *A : Method->attrs()) {
15534     // FIXME: This should be emitted by tblgen.
15535     Expr *Arg = nullptr;
15536     ArrayRef<Expr *> Args;
15537     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15538       Arg = G->getArg();
15539     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15540       Arg = G->getArg();
15541     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15542       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15543     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15544       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15545     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15546       Arg = ETLF->getSuccessValue();
15547       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15548     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15549       Arg = STLF->getSuccessValue();
15550       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15551     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15552       Arg = LR->getArg();
15553     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15554       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15555     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15556       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15557     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15558       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15559     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15560       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15561     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15562       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15563
15564     if (Arg && !Finder.TraverseStmt(Arg))
15565       return true;
15566
15567     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15568       if (!Finder.TraverseStmt(Args[I]))
15569         return true;
15570     }
15571   }
15572
15573   return false;
15574 }
15575
15576 void Sema::checkExceptionSpecification(
15577     bool IsTopLevel, ExceptionSpecificationType EST,
15578     ArrayRef<ParsedType> DynamicExceptions,
15579     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15580     SmallVectorImpl<QualType> &Exceptions,
15581     FunctionProtoType::ExceptionSpecInfo &ESI) {
15582   Exceptions.clear();
15583   ESI.Type = EST;
15584   if (EST == EST_Dynamic) {
15585     Exceptions.reserve(DynamicExceptions.size());
15586     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15587       // FIXME: Preserve type source info.
15588       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15589
15590       if (IsTopLevel) {
15591         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15592         collectUnexpandedParameterPacks(ET, Unexpanded);
15593         if (!Unexpanded.empty()) {
15594           DiagnoseUnexpandedParameterPacks(
15595               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15596               Unexpanded);
15597           continue;
15598         }
15599       }
15600
15601       // Check that the type is valid for an exception spec, and
15602       // drop it if not.
15603       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15604         Exceptions.push_back(ET);
15605     }
15606     ESI.Exceptions = Exceptions;
15607     return;
15608   }
15609
15610   if (isComputedNoexcept(EST)) {
15611     assert((NoexceptExpr->isTypeDependent() ||
15612             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15613             Context.BoolTy) &&
15614            "Parser should have made sure that the expression is boolean");
15615     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15616       ESI.Type = EST_BasicNoexcept;
15617       return;
15618     }
15619
15620     ESI.NoexceptExpr = NoexceptExpr;
15621     return;
15622   }
15623 }
15624
15625 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15626              ExceptionSpecificationType EST,
15627              SourceRange SpecificationRange,
15628              ArrayRef<ParsedType> DynamicExceptions,
15629              ArrayRef<SourceRange> DynamicExceptionRanges,
15630              Expr *NoexceptExpr) {
15631   if (!MethodD)
15632     return;
15633
15634   // Dig out the method we're referring to.
15635   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15636     MethodD = FunTmpl->getTemplatedDecl();
15637
15638   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15639   if (!Method)
15640     return;
15641
15642   // Check the exception specification.
15643   llvm::SmallVector<QualType, 4> Exceptions;
15644   FunctionProtoType::ExceptionSpecInfo ESI;
15645   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15646                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15647                               ESI);
15648
15649   // Update the exception specification on the function type.
15650   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15651
15652   if (Method->isStatic())
15653     checkThisInStaticMemberFunctionExceptionSpec(Method);
15654
15655   if (Method->isVirtual()) {
15656     // Check overrides, which we previously had to delay.
15657     for (const CXXMethodDecl *O : Method->overridden_methods())
15658       CheckOverridingFunctionExceptionSpec(Method, O);
15659   }
15660 }
15661
15662 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15663 ///
15664 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15665                                        SourceLocation DeclStart, Declarator &D,
15666                                        Expr *BitWidth,
15667                                        InClassInitStyle InitStyle,
15668                                        AccessSpecifier AS,
15669                                        const ParsedAttr &MSPropertyAttr) {
15670   IdentifierInfo *II = D.getIdentifier();
15671   if (!II) {
15672     Diag(DeclStart, diag::err_anonymous_property);
15673     return nullptr;
15674   }
15675   SourceLocation Loc = D.getIdentifierLoc();
15676
15677   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15678   QualType T = TInfo->getType();
15679   if (getLangOpts().CPlusPlus) {
15680     CheckExtraCXXDefaultArguments(D);
15681
15682     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15683                                         UPPC_DataMemberType)) {
15684       D.setInvalidType();
15685       T = Context.IntTy;
15686       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15687     }
15688   }
15689
15690   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15691
15692   if (D.getDeclSpec().isInlineSpecified())
15693     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15694         << getLangOpts().CPlusPlus17;
15695   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15696     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15697          diag::err_invalid_thread)
15698       << DeclSpec::getSpecifierName(TSCS);
15699
15700   // Check to see if this name was declared as a member previously
15701   NamedDecl *PrevDecl = nullptr;
15702   LookupResult Previous(*this, II, Loc, LookupMemberName,
15703                         ForVisibleRedeclaration);
15704   LookupName(Previous, S);
15705   switch (Previous.getResultKind()) {
15706   case LookupResult::Found:
15707   case LookupResult::FoundUnresolvedValue:
15708     PrevDecl = Previous.getAsSingle<NamedDecl>();
15709     break;
15710
15711   case LookupResult::FoundOverloaded:
15712     PrevDecl = Previous.getRepresentativeDecl();
15713     break;
15714
15715   case LookupResult::NotFound:
15716   case LookupResult::NotFoundInCurrentInstantiation:
15717   case LookupResult::Ambiguous:
15718     break;
15719   }
15720
15721   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15722     // Maybe we will complain about the shadowed template parameter.
15723     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15724     // Just pretend that we didn't see the previous declaration.
15725     PrevDecl = nullptr;
15726   }
15727
15728   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15729     PrevDecl = nullptr;
15730
15731   SourceLocation TSSL = D.getBeginLoc();
15732   MSPropertyDecl *NewPD =
15733       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15734                              MSPropertyAttr.getPropertyDataGetter(),
15735                              MSPropertyAttr.getPropertyDataSetter());
15736   ProcessDeclAttributes(TUScope, NewPD, D);
15737   NewPD->setAccess(AS);
15738
15739   if (NewPD->isInvalidDecl())
15740     Record->setInvalidDecl();
15741
15742   if (D.getDeclSpec().isModulePrivateSpecified())
15743     NewPD->setModulePrivate();
15744
15745   if (NewPD->isInvalidDecl() && PrevDecl) {
15746     // Don't introduce NewFD into scope; there's already something
15747     // with the same name in the same scope.
15748   } else if (II) {
15749     PushOnScopeChains(NewPD, S);
15750   } else
15751     Record->addDecl(NewPD);
15752
15753   return NewPD;
15754 }