• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/AttributeCommonInfo.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "clang/Sema/Template.h"
41 #include "llvm/ADT/ScopeExit.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include <map>
46 #include <set>
47 
48 using namespace clang;
49 
50 //===----------------------------------------------------------------------===//
51 // CheckDefaultArgumentVisitor
52 //===----------------------------------------------------------------------===//
53 
54 namespace {
55 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
56 /// the default argument of a parameter to determine whether it
57 /// contains any ill-formed subexpressions. For example, this will
58 /// diagnose the use of local variables or parameters within the
59 /// default argument expression.
60 class CheckDefaultArgumentVisitor
61     : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
62   Sema &S;
63   const Expr *DefaultArg;
64 
65 public:
CheckDefaultArgumentVisitor(Sema & S,const Expr * DefaultArg)66   CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
67       : S(S), DefaultArg(DefaultArg) {}
68 
69   bool VisitExpr(const Expr *Node);
70   bool VisitDeclRefExpr(const DeclRefExpr *DRE);
71   bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
72   bool VisitLambdaExpr(const LambdaExpr *Lambda);
73   bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
74 };
75 
76 /// VisitExpr - Visit all of the children of this expression.
VisitExpr(const Expr * Node)77 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
78   bool IsInvalid = false;
79   for (const Stmt *SubStmt : Node->children())
80     IsInvalid |= Visit(SubStmt);
81   return IsInvalid;
82 }
83 
84 /// VisitDeclRefExpr - Visit a reference to a declaration, to
85 /// determine whether this declaration can be used in the default
86 /// argument expression.
VisitDeclRefExpr(const DeclRefExpr * DRE)87 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
88   const NamedDecl *Decl = DRE->getDecl();
89   if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
90     // C++ [dcl.fct.default]p9:
91     //   [...] parameters of a function shall not be used in default
92     //   argument expressions, even if they are not evaluated. [...]
93     //
94     // C++17 [dcl.fct.default]p9 (by CWG 2082):
95     //   [...] A parameter shall not appear as a potentially-evaluated
96     //   expression in a default argument. [...]
97     //
98     if (DRE->isNonOdrUse() != NOUR_Unevaluated)
99       return S.Diag(DRE->getBeginLoc(),
100                     diag::err_param_default_argument_references_param)
101              << Param->getDeclName() << DefaultArg->getSourceRange();
102   } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
103     // C++ [dcl.fct.default]p7:
104     //   Local variables shall not be used in default argument
105     //   expressions.
106     //
107     // C++17 [dcl.fct.default]p7 (by CWG 2082):
108     //   A local variable shall not appear as a potentially-evaluated
109     //   expression in a default argument.
110     //
111     // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
112     //   Note: A local variable cannot be odr-used (6.3) in a default argument.
113     //
114     if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
115       return S.Diag(DRE->getBeginLoc(),
116                     diag::err_param_default_argument_references_local)
117              << VDecl->getDeclName() << DefaultArg->getSourceRange();
118   }
119 
120   return false;
121 }
122 
123 /// VisitCXXThisExpr - Visit a C++ "this" expression.
VisitCXXThisExpr(const CXXThisExpr * ThisE)124 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
125   // C++ [dcl.fct.default]p8:
126   //   The keyword this shall not be used in a default argument of a
127   //   member function.
128   return S.Diag(ThisE->getBeginLoc(),
129                 diag::err_param_default_argument_references_this)
130          << ThisE->getSourceRange();
131 }
132 
VisitPseudoObjectExpr(const PseudoObjectExpr * POE)133 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
134     const PseudoObjectExpr *POE) {
135   bool Invalid = false;
136   for (const Expr *E : POE->semantics()) {
137     // Look through bindings.
138     if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
139       E = OVE->getSourceExpr();
140       assert(E && "pseudo-object binding without source expression?");
141     }
142 
143     Invalid |= Visit(E);
144   }
145   return Invalid;
146 }
147 
VisitLambdaExpr(const LambdaExpr * Lambda)148 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
149   // C++11 [expr.lambda.prim]p13:
150   //   A lambda-expression appearing in a default argument shall not
151   //   implicitly or explicitly capture any entity.
152   if (Lambda->capture_begin() == Lambda->capture_end())
153     return false;
154 
155   return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
156 }
157 } // namespace
158 
159 void
CalledDecl(SourceLocation CallLoc,const CXXMethodDecl * Method)160 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
161                                                  const CXXMethodDecl *Method) {
162   // If we have an MSAny spec already, don't bother.
163   if (!Method || ComputedEST == EST_MSAny)
164     return;
165 
166   const FunctionProtoType *Proto
167     = Method->getType()->getAs<FunctionProtoType>();
168   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
169   if (!Proto)
170     return;
171 
172   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
173 
174   // If we have a throw-all spec at this point, ignore the function.
175   if (ComputedEST == EST_None)
176     return;
177 
178   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
179     EST = EST_BasicNoexcept;
180 
181   switch (EST) {
182   case EST_Unparsed:
183   case EST_Uninstantiated:
184   case EST_Unevaluated:
185     llvm_unreachable("should not see unresolved exception specs here");
186 
187   // If this function can throw any exceptions, make a note of that.
188   case EST_MSAny:
189   case EST_None:
190     // FIXME: Whichever we see last of MSAny and None determines our result.
191     // We should make a consistent, order-independent choice here.
192     ClearExceptions();
193     ComputedEST = EST;
194     return;
195   case EST_NoexceptFalse:
196     ClearExceptions();
197     ComputedEST = EST_None;
198     return;
199   // FIXME: If the call to this decl is using any of its default arguments, we
200   // need to search them for potentially-throwing calls.
201   // If this function has a basic noexcept, it doesn't affect the outcome.
202   case EST_BasicNoexcept:
203   case EST_NoexceptTrue:
204   case EST_NoThrow:
205     return;
206   // If we're still at noexcept(true) and there's a throw() callee,
207   // change to that specification.
208   case EST_DynamicNone:
209     if (ComputedEST == EST_BasicNoexcept)
210       ComputedEST = EST_DynamicNone;
211     return;
212   case EST_DependentNoexcept:
213     llvm_unreachable(
214         "should not generate implicit declarations for dependent cases");
215   case EST_Dynamic:
216     break;
217   }
218   assert(EST == EST_Dynamic && "EST case not considered earlier.");
219   assert(ComputedEST != EST_None &&
220          "Shouldn't collect exceptions when throw-all is guaranteed.");
221   ComputedEST = EST_Dynamic;
222   // Record the exceptions in this function's exception specification.
223   for (const auto &E : Proto->exceptions())
224     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
225       Exceptions.push_back(E);
226 }
227 
CalledStmt(Stmt * S)228 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
229   if (!S || ComputedEST == EST_MSAny)
230     return;
231 
232   // FIXME:
233   //
234   // C++0x [except.spec]p14:
235   //   [An] implicit exception-specification specifies the type-id T if and
236   // only if T is allowed by the exception-specification of a function directly
237   // invoked by f's implicit definition; f shall allow all exceptions if any
238   // function it directly invokes allows all exceptions, and f shall allow no
239   // exceptions if every function it directly invokes allows no exceptions.
240   //
241   // Note in particular that if an implicit exception-specification is generated
242   // for a function containing a throw-expression, that specification can still
243   // be noexcept(true).
244   //
245   // Note also that 'directly invoked' is not defined in the standard, and there
246   // is no indication that we should only consider potentially-evaluated calls.
247   //
248   // Ultimately we should implement the intent of the standard: the exception
249   // specification should be the set of exceptions which can be thrown by the
250   // implicit definition. For now, we assume that any non-nothrow expression can
251   // throw any exception.
252 
253   if (Self->canThrow(S))
254     ComputedEST = EST_None;
255 }
256 
ConvertParamDefaultArgument(const ParmVarDecl * Param,Expr * Arg,SourceLocation EqualLoc)257 ExprResult Sema::ConvertParamDefaultArgument(const ParmVarDecl *Param,
258                                              Expr *Arg,
259                                              SourceLocation EqualLoc) {
260   if (RequireCompleteType(Param->getLocation(), Param->getType(),
261                           diag::err_typecheck_decl_incomplete_type))
262     return true;
263 
264   // C++ [dcl.fct.default]p5
265   //   A default argument expression is implicitly converted (clause
266   //   4) to the parameter type. The default argument expression has
267   //   the same semantic constraints as the initializer expression in
268   //   a declaration of a variable of the parameter type, using the
269   //   copy-initialization semantics (8.5).
270   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
271                                                                     Param);
272   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
273                                                            EqualLoc);
274   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
275   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
276   if (Result.isInvalid())
277     return true;
278   Arg = Result.getAs<Expr>();
279 
280   CheckCompletedExpr(Arg, EqualLoc);
281   Arg = MaybeCreateExprWithCleanups(Arg);
282 
283   return Arg;
284 }
285 
SetParamDefaultArgument(ParmVarDecl * Param,Expr * Arg,SourceLocation EqualLoc)286 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
287                                    SourceLocation EqualLoc) {
288   // Add the default argument to the parameter
289   Param->setDefaultArg(Arg);
290 
291   // We have already instantiated this parameter; provide each of the
292   // instantiations with the uninstantiated default argument.
293   UnparsedDefaultArgInstantiationsMap::iterator InstPos
294     = UnparsedDefaultArgInstantiations.find(Param);
295   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
296     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
297       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
298 
299     // We're done tracking this parameter's instantiations.
300     UnparsedDefaultArgInstantiations.erase(InstPos);
301   }
302 }
303 
304 /// ActOnParamDefaultArgument - Check whether the default argument
305 /// provided for a function parameter is well-formed. If so, attach it
306 /// to the parameter declaration.
307 void
ActOnParamDefaultArgument(Decl * param,SourceLocation EqualLoc,Expr * DefaultArg)308 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
309                                 Expr *DefaultArg) {
310   if (!param || !DefaultArg)
311     return;
312 
313   ParmVarDecl *Param = cast<ParmVarDecl>(param);
314   UnparsedDefaultArgLocs.erase(Param);
315 
316   auto Fail = [&] {
317     Param->setInvalidDecl();
318     Param->setDefaultArg(new (Context) OpaqueValueExpr(
319         EqualLoc, Param->getType().getNonReferenceType(), VK_RValue));
320   };
321 
322   // Default arguments are only permitted in C++
323   if (!getLangOpts().CPlusPlus) {
324     Diag(EqualLoc, diag::err_param_default_argument)
325       << DefaultArg->getSourceRange();
326     return Fail();
327   }
328 
329   // Check for unexpanded parameter packs.
330   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
331     return Fail();
332   }
333 
334   // C++11 [dcl.fct.default]p3
335   //   A default argument expression [...] shall not be specified for a
336   //   parameter pack.
337   if (Param->isParameterPack()) {
338     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
339         << DefaultArg->getSourceRange();
340     // Recover by discarding the default argument.
341     Param->setDefaultArg(nullptr);
342     return;
343   }
344 
345   ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
346   if (Result.isInvalid())
347     return Fail();
348 
349   DefaultArg = Result.getAs<Expr>();
350 
351   // Check that the default argument is well-formed
352   CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
353   if (DefaultArgChecker.Visit(DefaultArg))
354     return Fail();
355 
356   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
357 }
358 
359 /// ActOnParamUnparsedDefaultArgument - We've seen a default
360 /// argument for a function parameter, but we can't parse it yet
361 /// because we're inside a class definition. Note that this default
362 /// argument will be parsed later.
ActOnParamUnparsedDefaultArgument(Decl * param,SourceLocation EqualLoc,SourceLocation ArgLoc)363 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
364                                              SourceLocation EqualLoc,
365                                              SourceLocation ArgLoc) {
366   if (!param)
367     return;
368 
369   ParmVarDecl *Param = cast<ParmVarDecl>(param);
370   Param->setUnparsedDefaultArg();
371   UnparsedDefaultArgLocs[Param] = ArgLoc;
372 }
373 
374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
375 /// the default argument for the parameter param failed.
ActOnParamDefaultArgumentError(Decl * param,SourceLocation EqualLoc)376 void Sema::ActOnParamDefaultArgumentError(Decl *param,
377                                           SourceLocation EqualLoc) {
378   if (!param)
379     return;
380 
381   ParmVarDecl *Param = cast<ParmVarDecl>(param);
382   Param->setInvalidDecl();
383   UnparsedDefaultArgLocs.erase(Param);
384   Param->setDefaultArg(new(Context)
385                        OpaqueValueExpr(EqualLoc,
386                                        Param->getType().getNonReferenceType(),
387                                        VK_RValue));
388 }
389 
390 /// CheckExtraCXXDefaultArguments - Check for any extra default
391 /// arguments in the declarator, which is not a function declaration
392 /// or definition and therefore is not permitted to have default
393 /// arguments. This routine should be invoked for every declarator
394 /// that is not a function declaration or definition.
CheckExtraCXXDefaultArguments(Declarator & D)395 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
396   // C++ [dcl.fct.default]p3
397   //   A default argument expression shall be specified only in the
398   //   parameter-declaration-clause of a function declaration or in a
399   //   template-parameter (14.1). It shall not be specified for a
400   //   parameter pack. If it is specified in a
401   //   parameter-declaration-clause, it shall not occur within a
402   //   declarator or abstract-declarator of a parameter-declaration.
403   bool MightBeFunction = D.isFunctionDeclarationContext();
404   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
405     DeclaratorChunk &chunk = D.getTypeObject(i);
406     if (chunk.Kind == DeclaratorChunk::Function) {
407       if (MightBeFunction) {
408         // This is a function declaration. It can have default arguments, but
409         // keep looking in case its return type is a function type with default
410         // arguments.
411         MightBeFunction = false;
412         continue;
413       }
414       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
415            ++argIdx) {
416         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
417         if (Param->hasUnparsedDefaultArg()) {
418           std::unique_ptr<CachedTokens> Toks =
419               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
420           SourceRange SR;
421           if (Toks->size() > 1)
422             SR = SourceRange((*Toks)[1].getLocation(),
423                              Toks->back().getLocation());
424           else
425             SR = UnparsedDefaultArgLocs[Param];
426           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
427             << SR;
428         } else if (Param->getDefaultArg()) {
429           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
430             << Param->getDefaultArg()->getSourceRange();
431           Param->setDefaultArg(nullptr);
432         }
433       }
434     } else if (chunk.Kind != DeclaratorChunk::Paren) {
435       MightBeFunction = false;
436     }
437   }
438 }
439 
functionDeclHasDefaultArgument(const FunctionDecl * FD)440 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
441   return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) {
442     return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
443   });
444 }
445 
446 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
447 /// function, once we already know that they have the same
448 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
449 /// error, false otherwise.
MergeCXXFunctionDecl(FunctionDecl * New,FunctionDecl * Old,Scope * S)450 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
451                                 Scope *S) {
452   bool Invalid = false;
453 
454   // The declaration context corresponding to the scope is the semantic
455   // parent, unless this is a local function declaration, in which case
456   // it is that surrounding function.
457   DeclContext *ScopeDC = New->isLocalExternDecl()
458                              ? New->getLexicalDeclContext()
459                              : New->getDeclContext();
460 
461   // Find the previous declaration for the purpose of default arguments.
462   FunctionDecl *PrevForDefaultArgs = Old;
463   for (/**/; PrevForDefaultArgs;
464        // Don't bother looking back past the latest decl if this is a local
465        // extern declaration; nothing else could work.
466        PrevForDefaultArgs = New->isLocalExternDecl()
467                                 ? nullptr
468                                 : PrevForDefaultArgs->getPreviousDecl()) {
469     // Ignore hidden declarations.
470     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
471       continue;
472 
473     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
474         !New->isCXXClassMember()) {
475       // Ignore default arguments of old decl if they are not in
476       // the same scope and this is not an out-of-line definition of
477       // a member function.
478       continue;
479     }
480 
481     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
482       // If only one of these is a local function declaration, then they are
483       // declared in different scopes, even though isDeclInScope may think
484       // they're in the same scope. (If both are local, the scope check is
485       // sufficient, and if neither is local, then they are in the same scope.)
486       continue;
487     }
488 
489     // We found the right previous declaration.
490     break;
491   }
492 
493   // C++ [dcl.fct.default]p4:
494   //   For non-template functions, default arguments can be added in
495   //   later declarations of a function in the same
496   //   scope. Declarations in different scopes have completely
497   //   distinct sets of default arguments. That is, declarations in
498   //   inner scopes do not acquire default arguments from
499   //   declarations in outer scopes, and vice versa. In a given
500   //   function declaration, all parameters subsequent to a
501   //   parameter with a default argument shall have default
502   //   arguments supplied in this or previous declarations. A
503   //   default argument shall not be redefined by a later
504   //   declaration (not even to the same value).
505   //
506   // C++ [dcl.fct.default]p6:
507   //   Except for member functions of class templates, the default arguments
508   //   in a member function definition that appears outside of the class
509   //   definition are added to the set of default arguments provided by the
510   //   member function declaration in the class definition.
511   for (unsigned p = 0, NumParams = PrevForDefaultArgs
512                                        ? PrevForDefaultArgs->getNumParams()
513                                        : 0;
514        p < NumParams; ++p) {
515     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
516     ParmVarDecl *NewParam = New->getParamDecl(p);
517 
518     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
519     bool NewParamHasDfl = NewParam->hasDefaultArg();
520 
521     if (OldParamHasDfl && NewParamHasDfl) {
522       unsigned DiagDefaultParamID =
523         diag::err_param_default_argument_redefinition;
524 
525       // MSVC accepts that default parameters be redefined for member functions
526       // of template class. The new default parameter's value is ignored.
527       Invalid = true;
528       if (getLangOpts().MicrosoftExt) {
529         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
530         if (MD && MD->getParent()->getDescribedClassTemplate()) {
531           // Merge the old default argument into the new parameter.
532           NewParam->setHasInheritedDefaultArg();
533           if (OldParam->hasUninstantiatedDefaultArg())
534             NewParam->setUninstantiatedDefaultArg(
535                                       OldParam->getUninstantiatedDefaultArg());
536           else
537             NewParam->setDefaultArg(OldParam->getInit());
538           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
539           Invalid = false;
540         }
541       }
542 
543       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
544       // hint here. Alternatively, we could walk the type-source information
545       // for NewParam to find the last source location in the type... but it
546       // isn't worth the effort right now. This is the kind of test case that
547       // is hard to get right:
548       //   int f(int);
549       //   void g(int (*fp)(int) = f);
550       //   void g(int (*fp)(int) = &f);
551       Diag(NewParam->getLocation(), DiagDefaultParamID)
552         << NewParam->getDefaultArgRange();
553 
554       // Look for the function declaration where the default argument was
555       // actually written, which may be a declaration prior to Old.
556       for (auto Older = PrevForDefaultArgs;
557            OldParam->hasInheritedDefaultArg(); /**/) {
558         Older = Older->getPreviousDecl();
559         OldParam = Older->getParamDecl(p);
560       }
561 
562       Diag(OldParam->getLocation(), diag::note_previous_definition)
563         << OldParam->getDefaultArgRange();
564     } else if (OldParamHasDfl) {
565       // Merge the old default argument into the new parameter unless the new
566       // function is a friend declaration in a template class. In the latter
567       // case the default arguments will be inherited when the friend
568       // declaration will be instantiated.
569       if (New->getFriendObjectKind() == Decl::FOK_None ||
570           !New->getLexicalDeclContext()->isDependentContext()) {
571         // It's important to use getInit() here;  getDefaultArg()
572         // strips off any top-level ExprWithCleanups.
573         NewParam->setHasInheritedDefaultArg();
574         if (OldParam->hasUnparsedDefaultArg())
575           NewParam->setUnparsedDefaultArg();
576         else if (OldParam->hasUninstantiatedDefaultArg())
577           NewParam->setUninstantiatedDefaultArg(
578                                        OldParam->getUninstantiatedDefaultArg());
579         else
580           NewParam->setDefaultArg(OldParam->getInit());
581       }
582     } else if (NewParamHasDfl) {
583       if (New->getDescribedFunctionTemplate()) {
584         // Paragraph 4, quoted above, only applies to non-template functions.
585         Diag(NewParam->getLocation(),
586              diag::err_param_default_argument_template_redecl)
587           << NewParam->getDefaultArgRange();
588         Diag(PrevForDefaultArgs->getLocation(),
589              diag::note_template_prev_declaration)
590             << false;
591       } else if (New->getTemplateSpecializationKind()
592                    != TSK_ImplicitInstantiation &&
593                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
594         // C++ [temp.expr.spec]p21:
595         //   Default function arguments shall not be specified in a declaration
596         //   or a definition for one of the following explicit specializations:
597         //     - the explicit specialization of a function template;
598         //     - the explicit specialization of a member function template;
599         //     - the explicit specialization of a member function of a class
600         //       template where the class template specialization to which the
601         //       member function specialization belongs is implicitly
602         //       instantiated.
603         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
604           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
605           << New->getDeclName()
606           << NewParam->getDefaultArgRange();
607       } else if (New->getDeclContext()->isDependentContext()) {
608         // C++ [dcl.fct.default]p6 (DR217):
609         //   Default arguments for a member function of a class template shall
610         //   be specified on the initial declaration of the member function
611         //   within the class template.
612         //
613         // Reading the tea leaves a bit in DR217 and its reference to DR205
614         // leads me to the conclusion that one cannot add default function
615         // arguments for an out-of-line definition of a member function of a
616         // dependent type.
617         int WhichKind = 2;
618         if (CXXRecordDecl *Record
619               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
620           if (Record->getDescribedClassTemplate())
621             WhichKind = 0;
622           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
623             WhichKind = 1;
624           else
625             WhichKind = 2;
626         }
627 
628         Diag(NewParam->getLocation(),
629              diag::err_param_default_argument_member_template_redecl)
630           << WhichKind
631           << NewParam->getDefaultArgRange();
632       }
633     }
634   }
635 
636   // DR1344: If a default argument is added outside a class definition and that
637   // default argument makes the function a special member function, the program
638   // is ill-formed. This can only happen for constructors.
639   if (isa<CXXConstructorDecl>(New) &&
640       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
641     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
642                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
643     if (NewSM != OldSM) {
644       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
645       assert(NewParam->hasDefaultArg());
646       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
647         << NewParam->getDefaultArgRange() << NewSM;
648       Diag(Old->getLocation(), diag::note_previous_declaration);
649     }
650   }
651 
652   const FunctionDecl *Def;
653   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
654   // template has a constexpr specifier then all its declarations shall
655   // contain the constexpr specifier.
656   if (New->getConstexprKind() != Old->getConstexprKind()) {
657     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
658         << New << static_cast<int>(New->getConstexprKind())
659         << static_cast<int>(Old->getConstexprKind());
660     Diag(Old->getLocation(), diag::note_previous_declaration);
661     Invalid = true;
662   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
663              Old->isDefined(Def) &&
664              // If a friend function is inlined but does not have 'inline'
665              // specifier, it is a definition. Do not report attribute conflict
666              // in this case, redefinition will be diagnosed later.
667              (New->isInlineSpecified() ||
668               New->getFriendObjectKind() == Decl::FOK_None)) {
669     // C++11 [dcl.fcn.spec]p4:
670     //   If the definition of a function appears in a translation unit before its
671     //   first declaration as inline, the program is ill-formed.
672     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
673     Diag(Def->getLocation(), diag::note_previous_definition);
674     Invalid = true;
675   }
676 
677   // C++17 [temp.deduct.guide]p3:
678   //   Two deduction guide declarations in the same translation unit
679   //   for the same class template shall not have equivalent
680   //   parameter-declaration-clauses.
681   if (isa<CXXDeductionGuideDecl>(New) &&
682       !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
683     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
684     Diag(Old->getLocation(), diag::note_previous_declaration);
685   }
686 
687   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
688   // argument expression, that declaration shall be a definition and shall be
689   // the only declaration of the function or function template in the
690   // translation unit.
691   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
692       functionDeclHasDefaultArgument(Old)) {
693     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
694     Diag(Old->getLocation(), diag::note_previous_declaration);
695     Invalid = true;
696   }
697 
698   // C++11 [temp.friend]p4 (DR329):
699   //   When a function is defined in a friend function declaration in a class
700   //   template, the function is instantiated when the function is odr-used.
701   //   The same restrictions on multiple declarations and definitions that
702   //   apply to non-template function declarations and definitions also apply
703   //   to these implicit definitions.
704   const FunctionDecl *OldDefinition = nullptr;
705   if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
706       Old->isDefined(OldDefinition, true))
707     CheckForFunctionRedefinition(New, OldDefinition);
708 
709   return Invalid;
710 }
711 
712 NamedDecl *
ActOnDecompositionDeclarator(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParamLists)713 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
714                                    MultiTemplateParamsArg TemplateParamLists) {
715   assert(D.isDecompositionDeclarator());
716   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
717 
718   // The syntax only allows a decomposition declarator as a simple-declaration,
719   // a for-range-declaration, or a condition in Clang, but we parse it in more
720   // cases than that.
721   if (!D.mayHaveDecompositionDeclarator()) {
722     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
723       << Decomp.getSourceRange();
724     return nullptr;
725   }
726 
727   if (!TemplateParamLists.empty()) {
728     // FIXME: There's no rule against this, but there are also no rules that
729     // would actually make it usable, so we reject it for now.
730     Diag(TemplateParamLists.front()->getTemplateLoc(),
731          diag::err_decomp_decl_template);
732     return nullptr;
733   }
734 
735   Diag(Decomp.getLSquareLoc(),
736        !getLangOpts().CPlusPlus17
737            ? diag::ext_decomp_decl
738            : D.getContext() == DeclaratorContext::Condition
739                  ? diag::ext_decomp_decl_cond
740                  : diag::warn_cxx14_compat_decomp_decl)
741       << Decomp.getSourceRange();
742 
743   // The semantic context is always just the current context.
744   DeclContext *const DC = CurContext;
745 
746   // C++17 [dcl.dcl]/8:
747   //   The decl-specifier-seq shall contain only the type-specifier auto
748   //   and cv-qualifiers.
749   // C++2a [dcl.dcl]/8:
750   //   If decl-specifier-seq contains any decl-specifier other than static,
751   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
752   auto &DS = D.getDeclSpec();
753   {
754     SmallVector<StringRef, 8> BadSpecifiers;
755     SmallVector<SourceLocation, 8> BadSpecifierLocs;
756     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
757     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
758     if (auto SCS = DS.getStorageClassSpec()) {
759       if (SCS == DeclSpec::SCS_static) {
760         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
761         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
762       } else {
763         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
764         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
765       }
766     }
767     if (auto TSCS = DS.getThreadStorageClassSpec()) {
768       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
769       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
770     }
771     if (DS.hasConstexprSpecifier()) {
772       BadSpecifiers.push_back(
773           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
774       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
775     }
776     if (DS.isInlineSpecified()) {
777       BadSpecifiers.push_back("inline");
778       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
779     }
780     if (!BadSpecifiers.empty()) {
781       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
782       Err << (int)BadSpecifiers.size()
783           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
784       // Don't add FixItHints to remove the specifiers; we do still respect
785       // them when building the underlying variable.
786       for (auto Loc : BadSpecifierLocs)
787         Err << SourceRange(Loc, Loc);
788     } else if (!CPlusPlus20Specifiers.empty()) {
789       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
790                          getLangOpts().CPlusPlus20
791                              ? diag::warn_cxx17_compat_decomp_decl_spec
792                              : diag::ext_decomp_decl_spec);
793       Warn << (int)CPlusPlus20Specifiers.size()
794            << llvm::join(CPlusPlus20Specifiers.begin(),
795                          CPlusPlus20Specifiers.end(), " ");
796       for (auto Loc : CPlusPlus20SpecifierLocs)
797         Warn << SourceRange(Loc, Loc);
798     }
799     // We can't recover from it being declared as a typedef.
800     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
801       return nullptr;
802   }
803 
804   // C++2a [dcl.struct.bind]p1:
805   //   A cv that includes volatile is deprecated
806   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
807       getLangOpts().CPlusPlus20)
808     Diag(DS.getVolatileSpecLoc(),
809          diag::warn_deprecated_volatile_structured_binding);
810 
811   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
812   QualType R = TInfo->getType();
813 
814   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
815                                       UPPC_DeclarationType))
816     D.setInvalidType();
817 
818   // The syntax only allows a single ref-qualifier prior to the decomposition
819   // declarator. No other declarator chunks are permitted. Also check the type
820   // specifier here.
821   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
822       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
823       (D.getNumTypeObjects() == 1 &&
824        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
825     Diag(Decomp.getLSquareLoc(),
826          (D.hasGroupingParens() ||
827           (D.getNumTypeObjects() &&
828            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
829              ? diag::err_decomp_decl_parens
830              : diag::err_decomp_decl_type)
831         << R;
832 
833     // In most cases, there's no actual problem with an explicitly-specified
834     // type, but a function type won't work here, and ActOnVariableDeclarator
835     // shouldn't be called for such a type.
836     if (R->isFunctionType())
837       D.setInvalidType();
838   }
839 
840   // Build the BindingDecls.
841   SmallVector<BindingDecl*, 8> Bindings;
842 
843   // Build the BindingDecls.
844   for (auto &B : D.getDecompositionDeclarator().bindings()) {
845     // Check for name conflicts.
846     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
847     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
848                           ForVisibleRedeclaration);
849     LookupName(Previous, S,
850                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
851 
852     // It's not permitted to shadow a template parameter name.
853     if (Previous.isSingleResult() &&
854         Previous.getFoundDecl()->isTemplateParameter()) {
855       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
856                                       Previous.getFoundDecl());
857       Previous.clear();
858     }
859 
860     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
861                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
862     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
863                          /*AllowInlineNamespace*/false);
864     if (!Previous.empty()) {
865       auto *Old = Previous.getRepresentativeDecl();
866       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
867       Diag(Old->getLocation(), diag::note_previous_definition);
868     }
869 
870     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
871     PushOnScopeChains(BD, S, true);
872     Bindings.push_back(BD);
873     ParsingInitForAutoVars.insert(BD);
874   }
875 
876   // There are no prior lookup results for the variable itself, because it
877   // is unnamed.
878   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
879                                Decomp.getLSquareLoc());
880   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
881                         ForVisibleRedeclaration);
882 
883   // Build the variable that holds the non-decomposed object.
884   bool AddToScope = true;
885   NamedDecl *New =
886       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
887                               MultiTemplateParamsArg(), AddToScope, Bindings);
888   if (AddToScope) {
889     S->AddDecl(New);
890     CurContext->addHiddenDecl(New);
891   }
892 
893   if (isInOpenMPDeclareTargetContext())
894     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
895 
896   return New;
897 }
898 
checkSimpleDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const llvm::APSInt & NumElems,QualType ElemType,llvm::function_ref<ExprResult (SourceLocation,Expr *,unsigned)> GetInit)899 static bool checkSimpleDecomposition(
900     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
901     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
902     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
903   if ((int64_t)Bindings.size() != NumElems) {
904     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
905         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
906         << (NumElems < Bindings.size());
907     return true;
908   }
909 
910   unsigned I = 0;
911   for (auto *B : Bindings) {
912     SourceLocation Loc = B->getLocation();
913     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
914     if (E.isInvalid())
915       return true;
916     E = GetInit(Loc, E.get(), I++);
917     if (E.isInvalid())
918       return true;
919     B->setBinding(ElemType, E.get());
920   }
921 
922   return false;
923 }
924 
checkArrayLikeDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const llvm::APSInt & NumElems,QualType ElemType)925 static bool checkArrayLikeDecomposition(Sema &S,
926                                         ArrayRef<BindingDecl *> Bindings,
927                                         ValueDecl *Src, QualType DecompType,
928                                         const llvm::APSInt &NumElems,
929                                         QualType ElemType) {
930   return checkSimpleDecomposition(
931       S, Bindings, Src, DecompType, NumElems, ElemType,
932       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
933         ExprResult E = S.ActOnIntegerConstant(Loc, I);
934         if (E.isInvalid())
935           return ExprError();
936         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
937       });
938 }
939 
checkArrayDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const ConstantArrayType * CAT)940 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
941                                     ValueDecl *Src, QualType DecompType,
942                                     const ConstantArrayType *CAT) {
943   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
944                                      llvm::APSInt(CAT->getSize()),
945                                      CAT->getElementType());
946 }
947 
checkVectorDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const VectorType * VT)948 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
949                                      ValueDecl *Src, QualType DecompType,
950                                      const VectorType *VT) {
951   return checkArrayLikeDecomposition(
952       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
953       S.Context.getQualifiedType(VT->getElementType(),
954                                  DecompType.getQualifiers()));
955 }
956 
checkComplexDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const ComplexType * CT)957 static bool checkComplexDecomposition(Sema &S,
958                                       ArrayRef<BindingDecl *> Bindings,
959                                       ValueDecl *Src, QualType DecompType,
960                                       const ComplexType *CT) {
961   return checkSimpleDecomposition(
962       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
963       S.Context.getQualifiedType(CT->getElementType(),
964                                  DecompType.getQualifiers()),
965       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
966         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
967       });
968 }
969 
printTemplateArgs(const PrintingPolicy & PrintingPolicy,TemplateArgumentListInfo & Args)970 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
971                                      TemplateArgumentListInfo &Args) {
972   SmallString<128> SS;
973   llvm::raw_svector_ostream OS(SS);
974   bool First = true;
975   for (auto &Arg : Args.arguments()) {
976     if (!First)
977       OS << ", ";
978     Arg.getArgument().print(PrintingPolicy, OS);
979     First = false;
980   }
981   return std::string(OS.str());
982 }
983 
lookupStdTypeTraitMember(Sema & S,LookupResult & TraitMemberLookup,SourceLocation Loc,StringRef Trait,TemplateArgumentListInfo & Args,unsigned DiagID)984 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
985                                      SourceLocation Loc, StringRef Trait,
986                                      TemplateArgumentListInfo &Args,
987                                      unsigned DiagID) {
988   auto DiagnoseMissing = [&] {
989     if (DiagID)
990       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
991                                                Args);
992     return true;
993   };
994 
995   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
996   NamespaceDecl *Std = S.getStdNamespace();
997   if (!Std)
998     return DiagnoseMissing();
999 
1000   // Look up the trait itself, within namespace std. We can diagnose various
1001   // problems with this lookup even if we've been asked to not diagnose a
1002   // missing specialization, because this can only fail if the user has been
1003   // declaring their own names in namespace std or we don't support the
1004   // standard library implementation in use.
1005   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1006                       Loc, Sema::LookupOrdinaryName);
1007   if (!S.LookupQualifiedName(Result, Std))
1008     return DiagnoseMissing();
1009   if (Result.isAmbiguous())
1010     return true;
1011 
1012   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1013   if (!TraitTD) {
1014     Result.suppressDiagnostics();
1015     NamedDecl *Found = *Result.begin();
1016     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1017     S.Diag(Found->getLocation(), diag::note_declared_at);
1018     return true;
1019   }
1020 
1021   // Build the template-id.
1022   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1023   if (TraitTy.isNull())
1024     return true;
1025   if (!S.isCompleteType(Loc, TraitTy)) {
1026     if (DiagID)
1027       S.RequireCompleteType(
1028           Loc, TraitTy, DiagID,
1029           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
1030     return true;
1031   }
1032 
1033   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1034   assert(RD && "specialization of class template is not a class?");
1035 
1036   // Look up the member of the trait type.
1037   S.LookupQualifiedName(TraitMemberLookup, RD);
1038   return TraitMemberLookup.isAmbiguous();
1039 }
1040 
1041 static TemplateArgumentLoc
getTrivialIntegralTemplateArgument(Sema & S,SourceLocation Loc,QualType T,uint64_t I)1042 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1043                                    uint64_t I) {
1044   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1045   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1046 }
1047 
1048 static TemplateArgumentLoc
getTrivialTypeTemplateArgument(Sema & S,SourceLocation Loc,QualType T)1049 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1050   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1051 }
1052 
1053 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1054 
isTupleLike(Sema & S,SourceLocation Loc,QualType T,llvm::APSInt & Size)1055 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1056                                llvm::APSInt &Size) {
1057   EnterExpressionEvaluationContext ContextRAII(
1058       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1059 
1060   DeclarationName Value = S.PP.getIdentifierInfo("value");
1061   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1062 
1063   // Form template argument list for tuple_size<T>.
1064   TemplateArgumentListInfo Args(Loc, Loc);
1065   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1066 
1067   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1068   // it's not tuple-like.
1069   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1070       R.empty())
1071     return IsTupleLike::NotTupleLike;
1072 
1073   // If we get this far, we've committed to the tuple interpretation, but
1074   // we can still fail if there actually isn't a usable ::value.
1075 
1076   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1077     LookupResult &R;
1078     TemplateArgumentListInfo &Args;
1079     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1080         : R(R), Args(Args) {}
1081     Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1082                                                SourceLocation Loc) override {
1083       return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1084           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1085     }
1086   } Diagnoser(R, Args);
1087 
1088   ExprResult E =
1089       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1090   if (E.isInvalid())
1091     return IsTupleLike::Error;
1092 
1093   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1094   if (E.isInvalid())
1095     return IsTupleLike::Error;
1096 
1097   return IsTupleLike::TupleLike;
1098 }
1099 
1100 /// \return std::tuple_element<I, T>::type.
getTupleLikeElementType(Sema & S,SourceLocation Loc,unsigned I,QualType T)1101 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1102                                         unsigned I, QualType T) {
1103   // Form template argument list for tuple_element<I, T>.
1104   TemplateArgumentListInfo Args(Loc, Loc);
1105   Args.addArgument(
1106       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1107   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1108 
1109   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1110   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1111   if (lookupStdTypeTraitMember(
1112           S, R, Loc, "tuple_element", Args,
1113           diag::err_decomp_decl_std_tuple_element_not_specialized))
1114     return QualType();
1115 
1116   auto *TD = R.getAsSingle<TypeDecl>();
1117   if (!TD) {
1118     R.suppressDiagnostics();
1119     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1120       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1121     if (!R.empty())
1122       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1123     return QualType();
1124   }
1125 
1126   return S.Context.getTypeDeclType(TD);
1127 }
1128 
1129 namespace {
1130 struct InitializingBinding {
1131   Sema &S;
InitializingBinding__anonedc74bd70811::InitializingBinding1132   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1133     Sema::CodeSynthesisContext Ctx;
1134     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1135     Ctx.PointOfInstantiation = BD->getLocation();
1136     Ctx.Entity = BD;
1137     S.pushCodeSynthesisContext(Ctx);
1138   }
~InitializingBinding__anonedc74bd70811::InitializingBinding1139   ~InitializingBinding() {
1140     S.popCodeSynthesisContext();
1141   }
1142 };
1143 }
1144 
checkTupleLikeDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,VarDecl * Src,QualType DecompType,const llvm::APSInt & TupleSize)1145 static bool checkTupleLikeDecomposition(Sema &S,
1146                                         ArrayRef<BindingDecl *> Bindings,
1147                                         VarDecl *Src, QualType DecompType,
1148                                         const llvm::APSInt &TupleSize) {
1149   if ((int64_t)Bindings.size() != TupleSize) {
1150     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1151         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1152         << (TupleSize < Bindings.size());
1153     return true;
1154   }
1155 
1156   if (Bindings.empty())
1157     return false;
1158 
1159   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1160 
1161   // [dcl.decomp]p3:
1162   //   The unqualified-id get is looked up in the scope of E by class member
1163   //   access lookup ...
1164   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1165   bool UseMemberGet = false;
1166   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1167     if (auto *RD = DecompType->getAsCXXRecordDecl())
1168       S.LookupQualifiedName(MemberGet, RD);
1169     if (MemberGet.isAmbiguous())
1170       return true;
1171     //   ... and if that finds at least one declaration that is a function
1172     //   template whose first template parameter is a non-type parameter ...
1173     for (NamedDecl *D : MemberGet) {
1174       if (FunctionTemplateDecl *FTD =
1175               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1176         TemplateParameterList *TPL = FTD->getTemplateParameters();
1177         if (TPL->size() != 0 &&
1178             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1179           //   ... the initializer is e.get<i>().
1180           UseMemberGet = true;
1181           break;
1182         }
1183       }
1184     }
1185   }
1186 
1187   unsigned I = 0;
1188   for (auto *B : Bindings) {
1189     InitializingBinding InitContext(S, B);
1190     SourceLocation Loc = B->getLocation();
1191 
1192     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1193     if (E.isInvalid())
1194       return true;
1195 
1196     //   e is an lvalue if the type of the entity is an lvalue reference and
1197     //   an xvalue otherwise
1198     if (!Src->getType()->isLValueReferenceType())
1199       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1200                                    E.get(), nullptr, VK_XValue,
1201                                    FPOptionsOverride());
1202 
1203     TemplateArgumentListInfo Args(Loc, Loc);
1204     Args.addArgument(
1205         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1206 
1207     if (UseMemberGet) {
1208       //   if [lookup of member get] finds at least one declaration, the
1209       //   initializer is e.get<i-1>().
1210       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1211                                      CXXScopeSpec(), SourceLocation(), nullptr,
1212                                      MemberGet, &Args, nullptr);
1213       if (E.isInvalid())
1214         return true;
1215 
1216       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1217     } else {
1218       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1219       //   in the associated namespaces.
1220       Expr *Get = UnresolvedLookupExpr::Create(
1221           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1222           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1223           UnresolvedSetIterator(), UnresolvedSetIterator());
1224 
1225       Expr *Arg = E.get();
1226       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1227     }
1228     if (E.isInvalid())
1229       return true;
1230     Expr *Init = E.get();
1231 
1232     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1233     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1234     if (T.isNull())
1235       return true;
1236 
1237     //   each vi is a variable of type "reference to T" initialized with the
1238     //   initializer, where the reference is an lvalue reference if the
1239     //   initializer is an lvalue and an rvalue reference otherwise
1240     QualType RefType =
1241         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1242     if (RefType.isNull())
1243       return true;
1244     auto *RefVD = VarDecl::Create(
1245         S.Context, Src->getDeclContext(), Loc, Loc,
1246         B->getDeclName().getAsIdentifierInfo(), RefType,
1247         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1248     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1249     RefVD->setTSCSpec(Src->getTSCSpec());
1250     RefVD->setImplicit();
1251     if (Src->isInlineSpecified())
1252       RefVD->setInlineSpecified();
1253     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1254 
1255     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1256     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1257     InitializationSequence Seq(S, Entity, Kind, Init);
1258     E = Seq.Perform(S, Entity, Kind, Init);
1259     if (E.isInvalid())
1260       return true;
1261     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1262     if (E.isInvalid())
1263       return true;
1264     RefVD->setInit(E.get());
1265     S.CheckCompleteVariableDeclaration(RefVD);
1266 
1267     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1268                                    DeclarationNameInfo(B->getDeclName(), Loc),
1269                                    RefVD);
1270     if (E.isInvalid())
1271       return true;
1272 
1273     B->setBinding(T, E.get());
1274     I++;
1275   }
1276 
1277   return false;
1278 }
1279 
1280 /// Find the base class to decompose in a built-in decomposition of a class type.
1281 /// This base class search is, unfortunately, not quite like any other that we
1282 /// perform anywhere else in C++.
findDecomposableBaseClass(Sema & S,SourceLocation Loc,const CXXRecordDecl * RD,CXXCastPath & BasePath)1283 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1284                                                 const CXXRecordDecl *RD,
1285                                                 CXXCastPath &BasePath) {
1286   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1287                           CXXBasePath &Path) {
1288     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1289   };
1290 
1291   const CXXRecordDecl *ClassWithFields = nullptr;
1292   AccessSpecifier AS = AS_public;
1293   if (RD->hasDirectFields())
1294     // [dcl.decomp]p4:
1295     //   Otherwise, all of E's non-static data members shall be public direct
1296     //   members of E ...
1297     ClassWithFields = RD;
1298   else {
1299     //   ... or of ...
1300     CXXBasePaths Paths;
1301     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1302     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1303       // If no classes have fields, just decompose RD itself. (This will work
1304       // if and only if zero bindings were provided.)
1305       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1306     }
1307 
1308     CXXBasePath *BestPath = nullptr;
1309     for (auto &P : Paths) {
1310       if (!BestPath)
1311         BestPath = &P;
1312       else if (!S.Context.hasSameType(P.back().Base->getType(),
1313                                       BestPath->back().Base->getType())) {
1314         //   ... the same ...
1315         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1316           << false << RD << BestPath->back().Base->getType()
1317           << P.back().Base->getType();
1318         return DeclAccessPair();
1319       } else if (P.Access < BestPath->Access) {
1320         BestPath = &P;
1321       }
1322     }
1323 
1324     //   ... unambiguous ...
1325     QualType BaseType = BestPath->back().Base->getType();
1326     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1327       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1328         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1329       return DeclAccessPair();
1330     }
1331 
1332     //   ... [accessible, implied by other rules] base class of E.
1333     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1334                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1335     AS = BestPath->Access;
1336 
1337     ClassWithFields = BaseType->getAsCXXRecordDecl();
1338     S.BuildBasePathArray(Paths, BasePath);
1339   }
1340 
1341   // The above search did not check whether the selected class itself has base
1342   // classes with fields, so check that now.
1343   CXXBasePaths Paths;
1344   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1345     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1346       << (ClassWithFields == RD) << RD << ClassWithFields
1347       << Paths.front().back().Base->getType();
1348     return DeclAccessPair();
1349   }
1350 
1351   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1352 }
1353 
checkMemberDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const CXXRecordDecl * OrigRD)1354 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1355                                      ValueDecl *Src, QualType DecompType,
1356                                      const CXXRecordDecl *OrigRD) {
1357   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1358                             diag::err_incomplete_type))
1359     return true;
1360 
1361   CXXCastPath BasePath;
1362   DeclAccessPair BasePair =
1363       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1364   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1365   if (!RD)
1366     return true;
1367   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1368                                                  DecompType.getQualifiers());
1369 
1370   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1371     unsigned NumFields =
1372         std::count_if(RD->field_begin(), RD->field_end(),
1373                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1374     assert(Bindings.size() != NumFields);
1375     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1376         << DecompType << (unsigned)Bindings.size() << NumFields
1377         << (NumFields < Bindings.size());
1378     return true;
1379   };
1380 
1381   //   all of E's non-static data members shall be [...] well-formed
1382   //   when named as e.name in the context of the structured binding,
1383   //   E shall not have an anonymous union member, ...
1384   unsigned I = 0;
1385   for (auto *FD : RD->fields()) {
1386     if (FD->isUnnamedBitfield())
1387       continue;
1388 
1389     // All the non-static data members are required to be nameable, so they
1390     // must all have names.
1391     if (!FD->getDeclName()) {
1392       if (RD->isLambda()) {
1393         S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1394         S.Diag(RD->getLocation(), diag::note_lambda_decl);
1395         return true;
1396       }
1397 
1398       if (FD->isAnonymousStructOrUnion()) {
1399         S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1400           << DecompType << FD->getType()->isUnionType();
1401         S.Diag(FD->getLocation(), diag::note_declared_at);
1402         return true;
1403       }
1404 
1405       // FIXME: Are there any other ways we could have an anonymous member?
1406     }
1407 
1408     // We have a real field to bind.
1409     if (I >= Bindings.size())
1410       return DiagnoseBadNumberOfBindings();
1411     auto *B = Bindings[I++];
1412     SourceLocation Loc = B->getLocation();
1413 
1414     // The field must be accessible in the context of the structured binding.
1415     // We already checked that the base class is accessible.
1416     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1417     // const_cast here.
1418     S.CheckStructuredBindingMemberAccess(
1419         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1420         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1421                                      BasePair.getAccess(), FD->getAccess())));
1422 
1423     // Initialize the binding to Src.FD.
1424     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1425     if (E.isInvalid())
1426       return true;
1427     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1428                             VK_LValue, &BasePath);
1429     if (E.isInvalid())
1430       return true;
1431     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1432                                   CXXScopeSpec(), FD,
1433                                   DeclAccessPair::make(FD, FD->getAccess()),
1434                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1435     if (E.isInvalid())
1436       return true;
1437 
1438     // If the type of the member is T, the referenced type is cv T, where cv is
1439     // the cv-qualification of the decomposition expression.
1440     //
1441     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1442     // 'const' to the type of the field.
1443     Qualifiers Q = DecompType.getQualifiers();
1444     if (FD->isMutable())
1445       Q.removeConst();
1446     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1447   }
1448 
1449   if (I != Bindings.size())
1450     return DiagnoseBadNumberOfBindings();
1451 
1452   return false;
1453 }
1454 
CheckCompleteDecompositionDeclaration(DecompositionDecl * DD)1455 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1456   QualType DecompType = DD->getType();
1457 
1458   // If the type of the decomposition is dependent, then so is the type of
1459   // each binding.
1460   if (DecompType->isDependentType()) {
1461     for (auto *B : DD->bindings())
1462       B->setType(Context.DependentTy);
1463     return;
1464   }
1465 
1466   DecompType = DecompType.getNonReferenceType();
1467   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1468 
1469   // C++1z [dcl.decomp]/2:
1470   //   If E is an array type [...]
1471   // As an extension, we also support decomposition of built-in complex and
1472   // vector types.
1473   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1474     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1475       DD->setInvalidDecl();
1476     return;
1477   }
1478   if (auto *VT = DecompType->getAs<VectorType>()) {
1479     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1480       DD->setInvalidDecl();
1481     return;
1482   }
1483   if (auto *CT = DecompType->getAs<ComplexType>()) {
1484     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1485       DD->setInvalidDecl();
1486     return;
1487   }
1488 
1489   // C++1z [dcl.decomp]/3:
1490   //   if the expression std::tuple_size<E>::value is a well-formed integral
1491   //   constant expression, [...]
1492   llvm::APSInt TupleSize(32);
1493   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1494   case IsTupleLike::Error:
1495     DD->setInvalidDecl();
1496     return;
1497 
1498   case IsTupleLike::TupleLike:
1499     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1500       DD->setInvalidDecl();
1501     return;
1502 
1503   case IsTupleLike::NotTupleLike:
1504     break;
1505   }
1506 
1507   // C++1z [dcl.dcl]/8:
1508   //   [E shall be of array or non-union class type]
1509   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1510   if (!RD || RD->isUnion()) {
1511     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1512         << DD << !RD << DecompType;
1513     DD->setInvalidDecl();
1514     return;
1515   }
1516 
1517   // C++1z [dcl.decomp]/4:
1518   //   all of E's non-static data members shall be [...] direct members of
1519   //   E or of the same unambiguous public base class of E, ...
1520   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1521     DD->setInvalidDecl();
1522 }
1523 
1524 /// Merge the exception specifications of two variable declarations.
1525 ///
1526 /// This is called when there's a redeclaration of a VarDecl. The function
1527 /// checks if the redeclaration might have an exception specification and
1528 /// validates compatibility and merges the specs if necessary.
MergeVarDeclExceptionSpecs(VarDecl * New,VarDecl * Old)1529 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1530   // Shortcut if exceptions are disabled.
1531   if (!getLangOpts().CXXExceptions)
1532     return;
1533 
1534   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1535          "Should only be called if types are otherwise the same.");
1536 
1537   QualType NewType = New->getType();
1538   QualType OldType = Old->getType();
1539 
1540   // We're only interested in pointers and references to functions, as well
1541   // as pointers to member functions.
1542   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1543     NewType = R->getPointeeType();
1544     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1545   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1546     NewType = P->getPointeeType();
1547     OldType = OldType->castAs<PointerType>()->getPointeeType();
1548   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1549     NewType = M->getPointeeType();
1550     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1551   }
1552 
1553   if (!NewType->isFunctionProtoType())
1554     return;
1555 
1556   // There's lots of special cases for functions. For function pointers, system
1557   // libraries are hopefully not as broken so that we don't need these
1558   // workarounds.
1559   if (CheckEquivalentExceptionSpec(
1560         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1561         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1562     New->setInvalidDecl();
1563   }
1564 }
1565 
1566 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1567 /// function declaration are well-formed according to C++
1568 /// [dcl.fct.default].
CheckCXXDefaultArguments(FunctionDecl * FD)1569 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1570   unsigned NumParams = FD->getNumParams();
1571   unsigned ParamIdx = 0;
1572 
1573   // This checking doesn't make sense for explicit specializations; their
1574   // default arguments are determined by the declaration we're specializing,
1575   // not by FD.
1576   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1577     return;
1578   if (auto *FTD = FD->getDescribedFunctionTemplate())
1579     if (FTD->isMemberSpecialization())
1580       return;
1581 
1582   // Find first parameter with a default argument
1583   for (; ParamIdx < NumParams; ++ParamIdx) {
1584     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1585     if (Param->hasDefaultArg())
1586       break;
1587   }
1588 
1589   // C++20 [dcl.fct.default]p4:
1590   //   In a given function declaration, each parameter subsequent to a parameter
1591   //   with a default argument shall have a default argument supplied in this or
1592   //   a previous declaration, unless the parameter was expanded from a
1593   //   parameter pack, or shall be a function parameter pack.
1594   for (; ParamIdx < NumParams; ++ParamIdx) {
1595     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1596     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1597         !(CurrentInstantiationScope &&
1598           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1599       if (Param->isInvalidDecl())
1600         /* We already complained about this parameter. */;
1601       else if (Param->getIdentifier())
1602         Diag(Param->getLocation(),
1603              diag::err_param_default_argument_missing_name)
1604           << Param->getIdentifier();
1605       else
1606         Diag(Param->getLocation(),
1607              diag::err_param_default_argument_missing);
1608     }
1609   }
1610 }
1611 
1612 /// Check that the given type is a literal type. Issue a diagnostic if not,
1613 /// if Kind is Diagnose.
1614 /// \return \c true if a problem has been found (and optionally diagnosed).
1615 template <typename... Ts>
CheckLiteralType(Sema & SemaRef,Sema::CheckConstexprKind Kind,SourceLocation Loc,QualType T,unsigned DiagID,Ts &&...DiagArgs)1616 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1617                              SourceLocation Loc, QualType T, unsigned DiagID,
1618                              Ts &&...DiagArgs) {
1619   if (T->isDependentType())
1620     return false;
1621 
1622   switch (Kind) {
1623   case Sema::CheckConstexprKind::Diagnose:
1624     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1625                                       std::forward<Ts>(DiagArgs)...);
1626 
1627   case Sema::CheckConstexprKind::CheckValid:
1628     return !T->isLiteralType(SemaRef.Context);
1629   }
1630 
1631   llvm_unreachable("unknown CheckConstexprKind");
1632 }
1633 
1634 /// Determine whether a destructor cannot be constexpr due to
CheckConstexprDestructorSubobjects(Sema & SemaRef,const CXXDestructorDecl * DD,Sema::CheckConstexprKind Kind)1635 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1636                                                const CXXDestructorDecl *DD,
1637                                                Sema::CheckConstexprKind Kind) {
1638   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1639     const CXXRecordDecl *RD =
1640         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1641     if (!RD || RD->hasConstexprDestructor())
1642       return true;
1643 
1644     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1645       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1646           << static_cast<int>(DD->getConstexprKind()) << !FD
1647           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1648       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1649           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1650     }
1651     return false;
1652   };
1653 
1654   const CXXRecordDecl *RD = DD->getParent();
1655   for (const CXXBaseSpecifier &B : RD->bases())
1656     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1657       return false;
1658   for (const FieldDecl *FD : RD->fields())
1659     if (!Check(FD->getLocation(), FD->getType(), FD))
1660       return false;
1661   return true;
1662 }
1663 
1664 /// Check whether a function's parameter types are all literal types. If so,
1665 /// return true. If not, produce a suitable diagnostic and return false.
CheckConstexprParameterTypes(Sema & SemaRef,const FunctionDecl * FD,Sema::CheckConstexprKind Kind)1666 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1667                                          const FunctionDecl *FD,
1668                                          Sema::CheckConstexprKind Kind) {
1669   unsigned ArgIndex = 0;
1670   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1671   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1672                                               e = FT->param_type_end();
1673        i != e; ++i, ++ArgIndex) {
1674     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1675     SourceLocation ParamLoc = PD->getLocation();
1676     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1677                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1678                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1679                          FD->isConsteval()))
1680       return false;
1681   }
1682   return true;
1683 }
1684 
1685 /// Check whether a function's return type is a literal type. If so, return
1686 /// true. If not, produce a suitable diagnostic and return false.
CheckConstexprReturnType(Sema & SemaRef,const FunctionDecl * FD,Sema::CheckConstexprKind Kind)1687 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1688                                      Sema::CheckConstexprKind Kind) {
1689   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1690                        diag::err_constexpr_non_literal_return,
1691                        FD->isConsteval()))
1692     return false;
1693   return true;
1694 }
1695 
1696 /// Get diagnostic %select index for tag kind for
1697 /// record diagnostic message.
1698 /// WARNING: Indexes apply to particular diagnostics only!
1699 ///
1700 /// \returns diagnostic %select index.
getRecordDiagFromTagKind(TagTypeKind Tag)1701 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1702   switch (Tag) {
1703   case TTK_Struct: return 0;
1704   case TTK_Interface: return 1;
1705   case TTK_Class:  return 2;
1706   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1707   }
1708 }
1709 
1710 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1711                                        Stmt *Body,
1712                                        Sema::CheckConstexprKind Kind);
1713 
1714 // Check whether a function declaration satisfies the requirements of a
1715 // constexpr function definition or a constexpr constructor definition. If so,
1716 // return true. If not, produce appropriate diagnostics (unless asked not to by
1717 // Kind) and return false.
1718 //
1719 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
CheckConstexprFunctionDefinition(const FunctionDecl * NewFD,CheckConstexprKind Kind)1720 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1721                                             CheckConstexprKind Kind) {
1722   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1723   if (MD && MD->isInstance()) {
1724     // C++11 [dcl.constexpr]p4:
1725     //  The definition of a constexpr constructor shall satisfy the following
1726     //  constraints:
1727     //  - the class shall not have any virtual base classes;
1728     //
1729     // FIXME: This only applies to constructors and destructors, not arbitrary
1730     // member functions.
1731     const CXXRecordDecl *RD = MD->getParent();
1732     if (RD->getNumVBases()) {
1733       if (Kind == CheckConstexprKind::CheckValid)
1734         return false;
1735 
1736       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1737         << isa<CXXConstructorDecl>(NewFD)
1738         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1739       for (const auto &I : RD->vbases())
1740         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1741             << I.getSourceRange();
1742       return false;
1743     }
1744   }
1745 
1746   if (!isa<CXXConstructorDecl>(NewFD)) {
1747     // C++11 [dcl.constexpr]p3:
1748     //  The definition of a constexpr function shall satisfy the following
1749     //  constraints:
1750     // - it shall not be virtual; (removed in C++20)
1751     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1752     if (Method && Method->isVirtual()) {
1753       if (getLangOpts().CPlusPlus20) {
1754         if (Kind == CheckConstexprKind::Diagnose)
1755           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1756       } else {
1757         if (Kind == CheckConstexprKind::CheckValid)
1758           return false;
1759 
1760         Method = Method->getCanonicalDecl();
1761         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1762 
1763         // If it's not obvious why this function is virtual, find an overridden
1764         // function which uses the 'virtual' keyword.
1765         const CXXMethodDecl *WrittenVirtual = Method;
1766         while (!WrittenVirtual->isVirtualAsWritten())
1767           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1768         if (WrittenVirtual != Method)
1769           Diag(WrittenVirtual->getLocation(),
1770                diag::note_overridden_virtual_function);
1771         return false;
1772       }
1773     }
1774 
1775     // - its return type shall be a literal type;
1776     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1777       return false;
1778   }
1779 
1780   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1781     // A destructor can be constexpr only if the defaulted destructor could be;
1782     // we don't need to check the members and bases if we already know they all
1783     // have constexpr destructors.
1784     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1785       if (Kind == CheckConstexprKind::CheckValid)
1786         return false;
1787       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1788         return false;
1789     }
1790   }
1791 
1792   // - each of its parameter types shall be a literal type;
1793   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1794     return false;
1795 
1796   Stmt *Body = NewFD->getBody();
1797   assert(Body &&
1798          "CheckConstexprFunctionDefinition called on function with no body");
1799   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1800 }
1801 
1802 /// Check the given declaration statement is legal within a constexpr function
1803 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1804 ///
1805 /// \return true if the body is OK (maybe only as an extension), false if we
1806 ///         have diagnosed a problem.
CheckConstexprDeclStmt(Sema & SemaRef,const FunctionDecl * Dcl,DeclStmt * DS,SourceLocation & Cxx1yLoc,Sema::CheckConstexprKind Kind)1807 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1808                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1809                                    Sema::CheckConstexprKind Kind) {
1810   // C++11 [dcl.constexpr]p3 and p4:
1811   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1812   //  contain only
1813   for (const auto *DclIt : DS->decls()) {
1814     switch (DclIt->getKind()) {
1815     case Decl::StaticAssert:
1816     case Decl::Using:
1817     case Decl::UsingShadow:
1818     case Decl::UsingDirective:
1819     case Decl::UnresolvedUsingTypename:
1820     case Decl::UnresolvedUsingValue:
1821       //   - static_assert-declarations
1822       //   - using-declarations,
1823       //   - using-directives,
1824       continue;
1825 
1826     case Decl::Typedef:
1827     case Decl::TypeAlias: {
1828       //   - typedef declarations and alias-declarations that do not define
1829       //     classes or enumerations,
1830       const auto *TN = cast<TypedefNameDecl>(DclIt);
1831       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1832         // Don't allow variably-modified types in constexpr functions.
1833         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1834           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1835           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1836             << TL.getSourceRange() << TL.getType()
1837             << isa<CXXConstructorDecl>(Dcl);
1838         }
1839         return false;
1840       }
1841       continue;
1842     }
1843 
1844     case Decl::Enum:
1845     case Decl::CXXRecord:
1846       // C++1y allows types to be defined, not just declared.
1847       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1848         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1849           SemaRef.Diag(DS->getBeginLoc(),
1850                        SemaRef.getLangOpts().CPlusPlus14
1851                            ? diag::warn_cxx11_compat_constexpr_type_definition
1852                            : diag::ext_constexpr_type_definition)
1853               << isa<CXXConstructorDecl>(Dcl);
1854         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1855           return false;
1856         }
1857       }
1858       continue;
1859 
1860     case Decl::EnumConstant:
1861     case Decl::IndirectField:
1862     case Decl::ParmVar:
1863       // These can only appear with other declarations which are banned in
1864       // C++11 and permitted in C++1y, so ignore them.
1865       continue;
1866 
1867     case Decl::Var:
1868     case Decl::Decomposition: {
1869       // C++1y [dcl.constexpr]p3 allows anything except:
1870       //   a definition of a variable of non-literal type or of static or
1871       //   thread storage duration or [before C++2a] for which no
1872       //   initialization is performed.
1873       const auto *VD = cast<VarDecl>(DclIt);
1874       if (VD->isThisDeclarationADefinition()) {
1875         if (VD->isStaticLocal()) {
1876           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1877             SemaRef.Diag(VD->getLocation(),
1878                          diag::err_constexpr_local_var_static)
1879               << isa<CXXConstructorDecl>(Dcl)
1880               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1881           }
1882           return false;
1883         }
1884         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1885                              diag::err_constexpr_local_var_non_literal_type,
1886                              isa<CXXConstructorDecl>(Dcl)))
1887           return false;
1888         if (!VD->getType()->isDependentType() &&
1889             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1890           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1891             SemaRef.Diag(
1892                 VD->getLocation(),
1893                 SemaRef.getLangOpts().CPlusPlus20
1894                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1895                     : diag::ext_constexpr_local_var_no_init)
1896                 << isa<CXXConstructorDecl>(Dcl);
1897           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1898             return false;
1899           }
1900           continue;
1901         }
1902       }
1903       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1904         SemaRef.Diag(VD->getLocation(),
1905                      SemaRef.getLangOpts().CPlusPlus14
1906                       ? diag::warn_cxx11_compat_constexpr_local_var
1907                       : diag::ext_constexpr_local_var)
1908           << isa<CXXConstructorDecl>(Dcl);
1909       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1910         return false;
1911       }
1912       continue;
1913     }
1914 
1915     case Decl::NamespaceAlias:
1916     case Decl::Function:
1917       // These are disallowed in C++11 and permitted in C++1y. Allow them
1918       // everywhere as an extension.
1919       if (!Cxx1yLoc.isValid())
1920         Cxx1yLoc = DS->getBeginLoc();
1921       continue;
1922 
1923     default:
1924       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1925         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1926             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1927       }
1928       return false;
1929     }
1930   }
1931 
1932   return true;
1933 }
1934 
1935 /// Check that the given field is initialized within a constexpr constructor.
1936 ///
1937 /// \param Dcl The constexpr constructor being checked.
1938 /// \param Field The field being checked. This may be a member of an anonymous
1939 ///        struct or union nested within the class being checked.
1940 /// \param Inits All declarations, including anonymous struct/union members and
1941 ///        indirect members, for which any initialization was provided.
1942 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1943 ///        multiple notes for different members to the same error.
1944 /// \param Kind Whether we're diagnosing a constructor as written or determining
1945 ///        whether the formal requirements are satisfied.
1946 /// \return \c false if we're checking for validity and the constructor does
1947 ///         not satisfy the requirements on a constexpr constructor.
CheckConstexprCtorInitializer(Sema & SemaRef,const FunctionDecl * Dcl,FieldDecl * Field,llvm::SmallSet<Decl *,16> & Inits,bool & Diagnosed,Sema::CheckConstexprKind Kind)1948 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1949                                           const FunctionDecl *Dcl,
1950                                           FieldDecl *Field,
1951                                           llvm::SmallSet<Decl*, 16> &Inits,
1952                                           bool &Diagnosed,
1953                                           Sema::CheckConstexprKind Kind) {
1954   // In C++20 onwards, there's nothing to check for validity.
1955   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1956       SemaRef.getLangOpts().CPlusPlus20)
1957     return true;
1958 
1959   if (Field->isInvalidDecl())
1960     return true;
1961 
1962   if (Field->isUnnamedBitfield())
1963     return true;
1964 
1965   // Anonymous unions with no variant members and empty anonymous structs do not
1966   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1967   // indirect fields don't need initializing.
1968   if (Field->isAnonymousStructOrUnion() &&
1969       (Field->getType()->isUnionType()
1970            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1971            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1972     return true;
1973 
1974   if (!Inits.count(Field)) {
1975     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1976       if (!Diagnosed) {
1977         SemaRef.Diag(Dcl->getLocation(),
1978                      SemaRef.getLangOpts().CPlusPlus20
1979                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1980                          : diag::ext_constexpr_ctor_missing_init);
1981         Diagnosed = true;
1982       }
1983       SemaRef.Diag(Field->getLocation(),
1984                    diag::note_constexpr_ctor_missing_init);
1985     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1986       return false;
1987     }
1988   } else if (Field->isAnonymousStructOrUnion()) {
1989     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1990     for (auto *I : RD->fields())
1991       // If an anonymous union contains an anonymous struct of which any member
1992       // is initialized, all members must be initialized.
1993       if (!RD->isUnion() || Inits.count(I))
1994         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1995                                            Kind))
1996           return false;
1997   }
1998   return true;
1999 }
2000 
2001 /// Check the provided statement is allowed in a constexpr function
2002 /// definition.
2003 static bool
CheckConstexprFunctionStmt(Sema & SemaRef,const FunctionDecl * Dcl,Stmt * S,SmallVectorImpl<SourceLocation> & ReturnStmts,SourceLocation & Cxx1yLoc,SourceLocation & Cxx2aLoc,Sema::CheckConstexprKind Kind)2004 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2005                            SmallVectorImpl<SourceLocation> &ReturnStmts,
2006                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2007                            Sema::CheckConstexprKind Kind) {
2008   // - its function-body shall be [...] a compound-statement that contains only
2009   switch (S->getStmtClass()) {
2010   case Stmt::NullStmtClass:
2011     //   - null statements,
2012     return true;
2013 
2014   case Stmt::DeclStmtClass:
2015     //   - static_assert-declarations
2016     //   - using-declarations,
2017     //   - using-directives,
2018     //   - typedef declarations and alias-declarations that do not define
2019     //     classes or enumerations,
2020     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2021       return false;
2022     return true;
2023 
2024   case Stmt::ReturnStmtClass:
2025     //   - and exactly one return statement;
2026     if (isa<CXXConstructorDecl>(Dcl)) {
2027       // C++1y allows return statements in constexpr constructors.
2028       if (!Cxx1yLoc.isValid())
2029         Cxx1yLoc = S->getBeginLoc();
2030       return true;
2031     }
2032 
2033     ReturnStmts.push_back(S->getBeginLoc());
2034     return true;
2035 
2036   case Stmt::CompoundStmtClass: {
2037     // C++1y allows compound-statements.
2038     if (!Cxx1yLoc.isValid())
2039       Cxx1yLoc = S->getBeginLoc();
2040 
2041     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2042     for (auto *BodyIt : CompStmt->body()) {
2043       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2044                                       Cxx1yLoc, Cxx2aLoc, Kind))
2045         return false;
2046     }
2047     return true;
2048   }
2049 
2050   case Stmt::AttributedStmtClass:
2051     if (!Cxx1yLoc.isValid())
2052       Cxx1yLoc = S->getBeginLoc();
2053     return true;
2054 
2055   case Stmt::IfStmtClass: {
2056     // C++1y allows if-statements.
2057     if (!Cxx1yLoc.isValid())
2058       Cxx1yLoc = S->getBeginLoc();
2059 
2060     IfStmt *If = cast<IfStmt>(S);
2061     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2062                                     Cxx1yLoc, Cxx2aLoc, Kind))
2063       return false;
2064     if (If->getElse() &&
2065         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2066                                     Cxx1yLoc, Cxx2aLoc, Kind))
2067       return false;
2068     return true;
2069   }
2070 
2071   case Stmt::WhileStmtClass:
2072   case Stmt::DoStmtClass:
2073   case Stmt::ForStmtClass:
2074   case Stmt::CXXForRangeStmtClass:
2075   case Stmt::ContinueStmtClass:
2076     // C++1y allows all of these. We don't allow them as extensions in C++11,
2077     // because they don't make sense without variable mutation.
2078     if (!SemaRef.getLangOpts().CPlusPlus14)
2079       break;
2080     if (!Cxx1yLoc.isValid())
2081       Cxx1yLoc = S->getBeginLoc();
2082     for (Stmt *SubStmt : S->children())
2083       if (SubStmt &&
2084           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2085                                       Cxx1yLoc, Cxx2aLoc, Kind))
2086         return false;
2087     return true;
2088 
2089   case Stmt::SwitchStmtClass:
2090   case Stmt::CaseStmtClass:
2091   case Stmt::DefaultStmtClass:
2092   case Stmt::BreakStmtClass:
2093     // C++1y allows switch-statements, and since they don't need variable
2094     // mutation, we can reasonably allow them in C++11 as an extension.
2095     if (!Cxx1yLoc.isValid())
2096       Cxx1yLoc = S->getBeginLoc();
2097     for (Stmt *SubStmt : S->children())
2098       if (SubStmt &&
2099           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2100                                       Cxx1yLoc, Cxx2aLoc, Kind))
2101         return false;
2102     return true;
2103 
2104   case Stmt::GCCAsmStmtClass:
2105   case Stmt::MSAsmStmtClass:
2106     // C++2a allows inline assembly statements.
2107   case Stmt::CXXTryStmtClass:
2108     if (Cxx2aLoc.isInvalid())
2109       Cxx2aLoc = S->getBeginLoc();
2110     for (Stmt *SubStmt : S->children()) {
2111       if (SubStmt &&
2112           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2113                                       Cxx1yLoc, Cxx2aLoc, Kind))
2114         return false;
2115     }
2116     return true;
2117 
2118   case Stmt::CXXCatchStmtClass:
2119     // Do not bother checking the language mode (already covered by the
2120     // try block check).
2121     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2122                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2123                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2124       return false;
2125     return true;
2126 
2127   default:
2128     if (!isa<Expr>(S))
2129       break;
2130 
2131     // C++1y allows expression-statements.
2132     if (!Cxx1yLoc.isValid())
2133       Cxx1yLoc = S->getBeginLoc();
2134     return true;
2135   }
2136 
2137   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2138     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2139         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2140   }
2141   return false;
2142 }
2143 
2144 /// Check the body for the given constexpr function declaration only contains
2145 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2146 ///
2147 /// \return true if the body is OK, false if we have found or diagnosed a
2148 /// problem.
CheckConstexprFunctionBody(Sema & SemaRef,const FunctionDecl * Dcl,Stmt * Body,Sema::CheckConstexprKind Kind)2149 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2150                                        Stmt *Body,
2151                                        Sema::CheckConstexprKind Kind) {
2152   SmallVector<SourceLocation, 4> ReturnStmts;
2153 
2154   if (isa<CXXTryStmt>(Body)) {
2155     // C++11 [dcl.constexpr]p3:
2156     //  The definition of a constexpr function shall satisfy the following
2157     //  constraints: [...]
2158     // - its function-body shall be = delete, = default, or a
2159     //   compound-statement
2160     //
2161     // C++11 [dcl.constexpr]p4:
2162     //  In the definition of a constexpr constructor, [...]
2163     // - its function-body shall not be a function-try-block;
2164     //
2165     // This restriction is lifted in C++2a, as long as inner statements also
2166     // apply the general constexpr rules.
2167     switch (Kind) {
2168     case Sema::CheckConstexprKind::CheckValid:
2169       if (!SemaRef.getLangOpts().CPlusPlus20)
2170         return false;
2171       break;
2172 
2173     case Sema::CheckConstexprKind::Diagnose:
2174       SemaRef.Diag(Body->getBeginLoc(),
2175            !SemaRef.getLangOpts().CPlusPlus20
2176                ? diag::ext_constexpr_function_try_block_cxx20
2177                : diag::warn_cxx17_compat_constexpr_function_try_block)
2178           << isa<CXXConstructorDecl>(Dcl);
2179       break;
2180     }
2181   }
2182 
2183   // - its function-body shall be [...] a compound-statement that contains only
2184   //   [... list of cases ...]
2185   //
2186   // Note that walking the children here is enough to properly check for
2187   // CompoundStmt and CXXTryStmt body.
2188   SourceLocation Cxx1yLoc, Cxx2aLoc;
2189   for (Stmt *SubStmt : Body->children()) {
2190     if (SubStmt &&
2191         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2192                                     Cxx1yLoc, Cxx2aLoc, Kind))
2193       return false;
2194   }
2195 
2196   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2197     // If this is only valid as an extension, report that we don't satisfy the
2198     // constraints of the current language.
2199     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2200         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2201       return false;
2202   } else if (Cxx2aLoc.isValid()) {
2203     SemaRef.Diag(Cxx2aLoc,
2204          SemaRef.getLangOpts().CPlusPlus20
2205            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2206            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2207       << isa<CXXConstructorDecl>(Dcl);
2208   } else if (Cxx1yLoc.isValid()) {
2209     SemaRef.Diag(Cxx1yLoc,
2210          SemaRef.getLangOpts().CPlusPlus14
2211            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2212            : diag::ext_constexpr_body_invalid_stmt)
2213       << isa<CXXConstructorDecl>(Dcl);
2214   }
2215 
2216   if (const CXXConstructorDecl *Constructor
2217         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2218     const CXXRecordDecl *RD = Constructor->getParent();
2219     // DR1359:
2220     // - every non-variant non-static data member and base class sub-object
2221     //   shall be initialized;
2222     // DR1460:
2223     // - if the class is a union having variant members, exactly one of them
2224     //   shall be initialized;
2225     if (RD->isUnion()) {
2226       if (Constructor->getNumCtorInitializers() == 0 &&
2227           RD->hasVariantMembers()) {
2228         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2229           SemaRef.Diag(
2230               Dcl->getLocation(),
2231               SemaRef.getLangOpts().CPlusPlus20
2232                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2233                   : diag::ext_constexpr_union_ctor_no_init);
2234         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2235           return false;
2236         }
2237       }
2238     } else if (!Constructor->isDependentContext() &&
2239                !Constructor->isDelegatingConstructor()) {
2240       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2241 
2242       // Skip detailed checking if we have enough initializers, and we would
2243       // allow at most one initializer per member.
2244       bool AnyAnonStructUnionMembers = false;
2245       unsigned Fields = 0;
2246       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2247            E = RD->field_end(); I != E; ++I, ++Fields) {
2248         if (I->isAnonymousStructOrUnion()) {
2249           AnyAnonStructUnionMembers = true;
2250           break;
2251         }
2252       }
2253       // DR1460:
2254       // - if the class is a union-like class, but is not a union, for each of
2255       //   its anonymous union members having variant members, exactly one of
2256       //   them shall be initialized;
2257       if (AnyAnonStructUnionMembers ||
2258           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2259         // Check initialization of non-static data members. Base classes are
2260         // always initialized so do not need to be checked. Dependent bases
2261         // might not have initializers in the member initializer list.
2262         llvm::SmallSet<Decl*, 16> Inits;
2263         for (const auto *I: Constructor->inits()) {
2264           if (FieldDecl *FD = I->getMember())
2265             Inits.insert(FD);
2266           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2267             Inits.insert(ID->chain_begin(), ID->chain_end());
2268         }
2269 
2270         bool Diagnosed = false;
2271         for (auto *I : RD->fields())
2272           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2273                                              Kind))
2274             return false;
2275       }
2276     }
2277   } else {
2278     if (ReturnStmts.empty()) {
2279       // C++1y doesn't require constexpr functions to contain a 'return'
2280       // statement. We still do, unless the return type might be void, because
2281       // otherwise if there's no return statement, the function cannot
2282       // be used in a core constant expression.
2283       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2284                 (Dcl->getReturnType()->isVoidType() ||
2285                  Dcl->getReturnType()->isDependentType());
2286       switch (Kind) {
2287       case Sema::CheckConstexprKind::Diagnose:
2288         SemaRef.Diag(Dcl->getLocation(),
2289                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2290                         : diag::err_constexpr_body_no_return)
2291             << Dcl->isConsteval();
2292         if (!OK)
2293           return false;
2294         break;
2295 
2296       case Sema::CheckConstexprKind::CheckValid:
2297         // The formal requirements don't include this rule in C++14, even
2298         // though the "must be able to produce a constant expression" rules
2299         // still imply it in some cases.
2300         if (!SemaRef.getLangOpts().CPlusPlus14)
2301           return false;
2302         break;
2303       }
2304     } else if (ReturnStmts.size() > 1) {
2305       switch (Kind) {
2306       case Sema::CheckConstexprKind::Diagnose:
2307         SemaRef.Diag(
2308             ReturnStmts.back(),
2309             SemaRef.getLangOpts().CPlusPlus14
2310                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2311                 : diag::ext_constexpr_body_multiple_return);
2312         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2313           SemaRef.Diag(ReturnStmts[I],
2314                        diag::note_constexpr_body_previous_return);
2315         break;
2316 
2317       case Sema::CheckConstexprKind::CheckValid:
2318         if (!SemaRef.getLangOpts().CPlusPlus14)
2319           return false;
2320         break;
2321       }
2322     }
2323   }
2324 
2325   // C++11 [dcl.constexpr]p5:
2326   //   if no function argument values exist such that the function invocation
2327   //   substitution would produce a constant expression, the program is
2328   //   ill-formed; no diagnostic required.
2329   // C++11 [dcl.constexpr]p3:
2330   //   - every constructor call and implicit conversion used in initializing the
2331   //     return value shall be one of those allowed in a constant expression.
2332   // C++11 [dcl.constexpr]p4:
2333   //   - every constructor involved in initializing non-static data members and
2334   //     base class sub-objects shall be a constexpr constructor.
2335   //
2336   // Note that this rule is distinct from the "requirements for a constexpr
2337   // function", so is not checked in CheckValid mode.
2338   SmallVector<PartialDiagnosticAt, 8> Diags;
2339   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2340       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2341     SemaRef.Diag(Dcl->getLocation(),
2342                  diag::ext_constexpr_function_never_constant_expr)
2343         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2344     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2345       SemaRef.Diag(Diags[I].first, Diags[I].second);
2346     // Don't return false here: we allow this for compatibility in
2347     // system headers.
2348   }
2349 
2350   return true;
2351 }
2352 
2353 /// Get the class that is directly named by the current context. This is the
2354 /// class for which an unqualified-id in this scope could name a constructor
2355 /// or destructor.
2356 ///
2357 /// If the scope specifier denotes a class, this will be that class.
2358 /// If the scope specifier is empty, this will be the class whose
2359 /// member-specification we are currently within. Otherwise, there
2360 /// is no such class.
getCurrentClass(Scope *,const CXXScopeSpec * SS)2361 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2362   assert(getLangOpts().CPlusPlus && "No class names in C!");
2363 
2364   if (SS && SS->isInvalid())
2365     return nullptr;
2366 
2367   if (SS && SS->isNotEmpty()) {
2368     DeclContext *DC = computeDeclContext(*SS, true);
2369     return dyn_cast_or_null<CXXRecordDecl>(DC);
2370   }
2371 
2372   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2373 }
2374 
2375 /// isCurrentClassName - Determine whether the identifier II is the
2376 /// name of the class type currently being defined. In the case of
2377 /// nested classes, this will only return true if II is the name of
2378 /// the innermost class.
isCurrentClassName(const IdentifierInfo & II,Scope * S,const CXXScopeSpec * SS)2379 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2380                               const CXXScopeSpec *SS) {
2381   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2382   return CurDecl && &II == CurDecl->getIdentifier();
2383 }
2384 
2385 /// Determine whether the identifier II is a typo for the name of
2386 /// the class type currently being defined. If so, update it to the identifier
2387 /// that should have been used.
isCurrentClassNameTypo(IdentifierInfo * & II,const CXXScopeSpec * SS)2388 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2389   assert(getLangOpts().CPlusPlus && "No class names in C!");
2390 
2391   if (!getLangOpts().SpellChecking)
2392     return false;
2393 
2394   CXXRecordDecl *CurDecl;
2395   if (SS && SS->isSet() && !SS->isInvalid()) {
2396     DeclContext *DC = computeDeclContext(*SS, true);
2397     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2398   } else
2399     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2400 
2401   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2402       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2403           < II->getLength()) {
2404     II = CurDecl->getIdentifier();
2405     return true;
2406   }
2407 
2408   return false;
2409 }
2410 
2411 /// Determine whether the given class is a base class of the given
2412 /// class, including looking at dependent bases.
findCircularInheritance(const CXXRecordDecl * Class,const CXXRecordDecl * Current)2413 static bool findCircularInheritance(const CXXRecordDecl *Class,
2414                                     const CXXRecordDecl *Current) {
2415   SmallVector<const CXXRecordDecl*, 8> Queue;
2416 
2417   Class = Class->getCanonicalDecl();
2418   while (true) {
2419     for (const auto &I : Current->bases()) {
2420       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2421       if (!Base)
2422         continue;
2423 
2424       Base = Base->getDefinition();
2425       if (!Base)
2426         continue;
2427 
2428       if (Base->getCanonicalDecl() == Class)
2429         return true;
2430 
2431       Queue.push_back(Base);
2432     }
2433 
2434     if (Queue.empty())
2435       return false;
2436 
2437     Current = Queue.pop_back_val();
2438   }
2439 
2440   return false;
2441 }
2442 
2443 /// Check the validity of a C++ base class specifier.
2444 ///
2445 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2446 /// and returns NULL otherwise.
2447 CXXBaseSpecifier *
CheckBaseSpecifier(CXXRecordDecl * Class,SourceRange SpecifierRange,bool Virtual,AccessSpecifier Access,TypeSourceInfo * TInfo,SourceLocation EllipsisLoc)2448 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2449                          SourceRange SpecifierRange,
2450                          bool Virtual, AccessSpecifier Access,
2451                          TypeSourceInfo *TInfo,
2452                          SourceLocation EllipsisLoc) {
2453   QualType BaseType = TInfo->getType();
2454   if (BaseType->containsErrors()) {
2455     // Already emitted a diagnostic when parsing the error type.
2456     return nullptr;
2457   }
2458   // C++ [class.union]p1:
2459   //   A union shall not have base classes.
2460   if (Class->isUnion()) {
2461     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2462       << SpecifierRange;
2463     return nullptr;
2464   }
2465 
2466   if (EllipsisLoc.isValid() &&
2467       !TInfo->getType()->containsUnexpandedParameterPack()) {
2468     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2469       << TInfo->getTypeLoc().getSourceRange();
2470     EllipsisLoc = SourceLocation();
2471   }
2472 
2473   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2474 
2475   if (BaseType->isDependentType()) {
2476     // Make sure that we don't have circular inheritance among our dependent
2477     // bases. For non-dependent bases, the check for completeness below handles
2478     // this.
2479     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2480       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2481           ((BaseDecl = BaseDecl->getDefinition()) &&
2482            findCircularInheritance(Class, BaseDecl))) {
2483         Diag(BaseLoc, diag::err_circular_inheritance)
2484           << BaseType << Context.getTypeDeclType(Class);
2485 
2486         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2487           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2488             << BaseType;
2489 
2490         return nullptr;
2491       }
2492     }
2493 
2494     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2495                                           Class->getTagKind() == TTK_Class,
2496                                           Access, TInfo, EllipsisLoc);
2497   }
2498 
2499   // Base specifiers must be record types.
2500   if (!BaseType->isRecordType()) {
2501     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2502     return nullptr;
2503   }
2504 
2505   // C++ [class.union]p1:
2506   //   A union shall not be used as a base class.
2507   if (BaseType->isUnionType()) {
2508     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2509     return nullptr;
2510   }
2511 
2512   // For the MS ABI, propagate DLL attributes to base class templates.
2513   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2514     if (Attr *ClassAttr = getDLLAttr(Class)) {
2515       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2516               BaseType->getAsCXXRecordDecl())) {
2517         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2518                                             BaseLoc);
2519       }
2520     }
2521   }
2522 
2523   // C++ [class.derived]p2:
2524   //   The class-name in a base-specifier shall not be an incompletely
2525   //   defined class.
2526   if (RequireCompleteType(BaseLoc, BaseType,
2527                           diag::err_incomplete_base_class, SpecifierRange)) {
2528     Class->setInvalidDecl();
2529     return nullptr;
2530   }
2531 
2532   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2533   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2534   assert(BaseDecl && "Record type has no declaration");
2535   BaseDecl = BaseDecl->getDefinition();
2536   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2537   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2538   assert(CXXBaseDecl && "Base type is not a C++ type");
2539 
2540   // Microsoft docs say:
2541   // "If a base-class has a code_seg attribute, derived classes must have the
2542   // same attribute."
2543   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2544   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2545   if ((DerivedCSA || BaseCSA) &&
2546       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2547     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2548     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2549       << CXXBaseDecl;
2550     return nullptr;
2551   }
2552 
2553   // A class which contains a flexible array member is not suitable for use as a
2554   // base class:
2555   //   - If the layout determines that a base comes before another base,
2556   //     the flexible array member would index into the subsequent base.
2557   //   - If the layout determines that base comes before the derived class,
2558   //     the flexible array member would index into the derived class.
2559   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2560     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2561       << CXXBaseDecl->getDeclName();
2562     return nullptr;
2563   }
2564 
2565   // C++ [class]p3:
2566   //   If a class is marked final and it appears as a base-type-specifier in
2567   //   base-clause, the program is ill-formed.
2568   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2569     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2570       << CXXBaseDecl->getDeclName()
2571       << FA->isSpelledAsSealed();
2572     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2573         << CXXBaseDecl->getDeclName() << FA->getRange();
2574     return nullptr;
2575   }
2576 
2577   if (BaseDecl->isInvalidDecl())
2578     Class->setInvalidDecl();
2579 
2580   // Create the base specifier.
2581   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2582                                         Class->getTagKind() == TTK_Class,
2583                                         Access, TInfo, EllipsisLoc);
2584 }
2585 
2586 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2587 /// one entry in the base class list of a class specifier, for
2588 /// example:
2589 ///    class foo : public bar, virtual private baz {
2590 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2591 BaseResult
ActOnBaseSpecifier(Decl * classdecl,SourceRange SpecifierRange,ParsedAttributes & Attributes,bool Virtual,AccessSpecifier Access,ParsedType basetype,SourceLocation BaseLoc,SourceLocation EllipsisLoc)2592 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2593                          ParsedAttributes &Attributes,
2594                          bool Virtual, AccessSpecifier Access,
2595                          ParsedType basetype, SourceLocation BaseLoc,
2596                          SourceLocation EllipsisLoc) {
2597   if (!classdecl)
2598     return true;
2599 
2600   AdjustDeclIfTemplate(classdecl);
2601   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2602   if (!Class)
2603     return true;
2604 
2605   // We haven't yet attached the base specifiers.
2606   Class->setIsParsingBaseSpecifiers();
2607 
2608   // We do not support any C++11 attributes on base-specifiers yet.
2609   // Diagnose any attributes we see.
2610   for (const ParsedAttr &AL : Attributes) {
2611     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2612       continue;
2613     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2614                           ? (unsigned)diag::warn_unknown_attribute_ignored
2615                           : (unsigned)diag::err_base_specifier_attribute)
2616         << AL << AL.getRange();
2617   }
2618 
2619   TypeSourceInfo *TInfo = nullptr;
2620   GetTypeFromParser(basetype, &TInfo);
2621 
2622   if (EllipsisLoc.isInvalid() &&
2623       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2624                                       UPPC_BaseType))
2625     return true;
2626 
2627   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2628                                                       Virtual, Access, TInfo,
2629                                                       EllipsisLoc))
2630     return BaseSpec;
2631   else
2632     Class->setInvalidDecl();
2633 
2634   return true;
2635 }
2636 
2637 /// Use small set to collect indirect bases.  As this is only used
2638 /// locally, there's no need to abstract the small size parameter.
2639 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2640 
2641 /// Recursively add the bases of Type.  Don't add Type itself.
2642 static void
NoteIndirectBases(ASTContext & Context,IndirectBaseSet & Set,const QualType & Type)2643 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2644                   const QualType &Type)
2645 {
2646   // Even though the incoming type is a base, it might not be
2647   // a class -- it could be a template parm, for instance.
2648   if (auto Rec = Type->getAs<RecordType>()) {
2649     auto Decl = Rec->getAsCXXRecordDecl();
2650 
2651     // Iterate over its bases.
2652     for (const auto &BaseSpec : Decl->bases()) {
2653       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2654         .getUnqualifiedType();
2655       if (Set.insert(Base).second)
2656         // If we've not already seen it, recurse.
2657         NoteIndirectBases(Context, Set, Base);
2658     }
2659   }
2660 }
2661 
2662 /// Performs the actual work of attaching the given base class
2663 /// specifiers to a C++ class.
AttachBaseSpecifiers(CXXRecordDecl * Class,MutableArrayRef<CXXBaseSpecifier * > Bases)2664 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2665                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2666  if (Bases.empty())
2667     return false;
2668 
2669   // Used to keep track of which base types we have already seen, so
2670   // that we can properly diagnose redundant direct base types. Note
2671   // that the key is always the unqualified canonical type of the base
2672   // class.
2673   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2674 
2675   // Used to track indirect bases so we can see if a direct base is
2676   // ambiguous.
2677   IndirectBaseSet IndirectBaseTypes;
2678 
2679   // Copy non-redundant base specifiers into permanent storage.
2680   unsigned NumGoodBases = 0;
2681   bool Invalid = false;
2682   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2683     QualType NewBaseType
2684       = Context.getCanonicalType(Bases[idx]->getType());
2685     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2686 
2687     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2688     if (KnownBase) {
2689       // C++ [class.mi]p3:
2690       //   A class shall not be specified as a direct base class of a
2691       //   derived class more than once.
2692       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2693           << KnownBase->getType() << Bases[idx]->getSourceRange();
2694 
2695       // Delete the duplicate base class specifier; we're going to
2696       // overwrite its pointer later.
2697       Context.Deallocate(Bases[idx]);
2698 
2699       Invalid = true;
2700     } else {
2701       // Okay, add this new base class.
2702       KnownBase = Bases[idx];
2703       Bases[NumGoodBases++] = Bases[idx];
2704 
2705       // Note this base's direct & indirect bases, if there could be ambiguity.
2706       if (Bases.size() > 1)
2707         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2708 
2709       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2710         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2711         if (Class->isInterface() &&
2712               (!RD->isInterfaceLike() ||
2713                KnownBase->getAccessSpecifier() != AS_public)) {
2714           // The Microsoft extension __interface does not permit bases that
2715           // are not themselves public interfaces.
2716           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2717               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2718               << RD->getSourceRange();
2719           Invalid = true;
2720         }
2721         if (RD->hasAttr<WeakAttr>())
2722           Class->addAttr(WeakAttr::CreateImplicit(Context));
2723       }
2724     }
2725   }
2726 
2727   // Attach the remaining base class specifiers to the derived class.
2728   Class->setBases(Bases.data(), NumGoodBases);
2729 
2730   // Check that the only base classes that are duplicate are virtual.
2731   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2732     // Check whether this direct base is inaccessible due to ambiguity.
2733     QualType BaseType = Bases[idx]->getType();
2734 
2735     // Skip all dependent types in templates being used as base specifiers.
2736     // Checks below assume that the base specifier is a CXXRecord.
2737     if (BaseType->isDependentType())
2738       continue;
2739 
2740     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2741       .getUnqualifiedType();
2742 
2743     if (IndirectBaseTypes.count(CanonicalBase)) {
2744       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2745                          /*DetectVirtual=*/true);
2746       bool found
2747         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2748       assert(found);
2749       (void)found;
2750 
2751       if (Paths.isAmbiguous(CanonicalBase))
2752         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2753             << BaseType << getAmbiguousPathsDisplayString(Paths)
2754             << Bases[idx]->getSourceRange();
2755       else
2756         assert(Bases[idx]->isVirtual());
2757     }
2758 
2759     // Delete the base class specifier, since its data has been copied
2760     // into the CXXRecordDecl.
2761     Context.Deallocate(Bases[idx]);
2762   }
2763 
2764   return Invalid;
2765 }
2766 
2767 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2768 /// class, after checking whether there are any duplicate base
2769 /// classes.
ActOnBaseSpecifiers(Decl * ClassDecl,MutableArrayRef<CXXBaseSpecifier * > Bases)2770 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2771                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2772   if (!ClassDecl || Bases.empty())
2773     return;
2774 
2775   AdjustDeclIfTemplate(ClassDecl);
2776   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2777 }
2778 
2779 /// Determine whether the type \p Derived is a C++ class that is
2780 /// derived from the type \p Base.
IsDerivedFrom(SourceLocation Loc,QualType Derived,QualType Base)2781 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2782   if (!getLangOpts().CPlusPlus)
2783     return false;
2784 
2785   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2786   if (!DerivedRD)
2787     return false;
2788 
2789   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2790   if (!BaseRD)
2791     return false;
2792 
2793   // If either the base or the derived type is invalid, don't try to
2794   // check whether one is derived from the other.
2795   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2796     return false;
2797 
2798   // FIXME: In a modules build, do we need the entire path to be visible for us
2799   // to be able to use the inheritance relationship?
2800   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2801     return false;
2802 
2803   return DerivedRD->isDerivedFrom(BaseRD);
2804 }
2805 
2806 /// Determine whether the type \p Derived is a C++ class that is
2807 /// derived from the type \p Base.
IsDerivedFrom(SourceLocation Loc,QualType Derived,QualType Base,CXXBasePaths & Paths)2808 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2809                          CXXBasePaths &Paths) {
2810   if (!getLangOpts().CPlusPlus)
2811     return false;
2812 
2813   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2814   if (!DerivedRD)
2815     return false;
2816 
2817   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2818   if (!BaseRD)
2819     return false;
2820 
2821   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2822     return false;
2823 
2824   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2825 }
2826 
BuildBasePathArray(const CXXBasePath & Path,CXXCastPath & BasePathArray)2827 static void BuildBasePathArray(const CXXBasePath &Path,
2828                                CXXCastPath &BasePathArray) {
2829   // We first go backward and check if we have a virtual base.
2830   // FIXME: It would be better if CXXBasePath had the base specifier for
2831   // the nearest virtual base.
2832   unsigned Start = 0;
2833   for (unsigned I = Path.size(); I != 0; --I) {
2834     if (Path[I - 1].Base->isVirtual()) {
2835       Start = I - 1;
2836       break;
2837     }
2838   }
2839 
2840   // Now add all bases.
2841   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2842     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2843 }
2844 
2845 
BuildBasePathArray(const CXXBasePaths & Paths,CXXCastPath & BasePathArray)2846 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2847                               CXXCastPath &BasePathArray) {
2848   assert(BasePathArray.empty() && "Base path array must be empty!");
2849   assert(Paths.isRecordingPaths() && "Must record paths!");
2850   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2851 }
2852 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2853 /// conversion (where Derived and Base are class types) is
2854 /// well-formed, meaning that the conversion is unambiguous (and
2855 /// that all of the base classes are accessible). Returns true
2856 /// and emits a diagnostic if the code is ill-formed, returns false
2857 /// otherwise. Loc is the location where this routine should point to
2858 /// if there is an error, and Range is the source range to highlight
2859 /// if there is an error.
2860 ///
2861 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2862 /// diagnostic for the respective type of error will be suppressed, but the
2863 /// check for ill-formed code will still be performed.
2864 bool
CheckDerivedToBaseConversion(QualType Derived,QualType Base,unsigned InaccessibleBaseID,unsigned AmbiguousBaseConvID,SourceLocation Loc,SourceRange Range,DeclarationName Name,CXXCastPath * BasePath,bool IgnoreAccess)2865 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2866                                    unsigned InaccessibleBaseID,
2867                                    unsigned AmbiguousBaseConvID,
2868                                    SourceLocation Loc, SourceRange Range,
2869                                    DeclarationName Name,
2870                                    CXXCastPath *BasePath,
2871                                    bool IgnoreAccess) {
2872   // First, determine whether the path from Derived to Base is
2873   // ambiguous. This is slightly more expensive than checking whether
2874   // the Derived to Base conversion exists, because here we need to
2875   // explore multiple paths to determine if there is an ambiguity.
2876   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2877                      /*DetectVirtual=*/false);
2878   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2879   if (!DerivationOkay)
2880     return true;
2881 
2882   const CXXBasePath *Path = nullptr;
2883   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2884     Path = &Paths.front();
2885 
2886   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2887   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2888   // user to access such bases.
2889   if (!Path && getLangOpts().MSVCCompat) {
2890     for (const CXXBasePath &PossiblePath : Paths) {
2891       if (PossiblePath.size() == 1) {
2892         Path = &PossiblePath;
2893         if (AmbiguousBaseConvID)
2894           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2895               << Base << Derived << Range;
2896         break;
2897       }
2898     }
2899   }
2900 
2901   if (Path) {
2902     if (!IgnoreAccess) {
2903       // Check that the base class can be accessed.
2904       switch (
2905           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2906       case AR_inaccessible:
2907         return true;
2908       case AR_accessible:
2909       case AR_dependent:
2910       case AR_delayed:
2911         break;
2912       }
2913     }
2914 
2915     // Build a base path if necessary.
2916     if (BasePath)
2917       ::BuildBasePathArray(*Path, *BasePath);
2918     return false;
2919   }
2920 
2921   if (AmbiguousBaseConvID) {
2922     // We know that the derived-to-base conversion is ambiguous, and
2923     // we're going to produce a diagnostic. Perform the derived-to-base
2924     // search just one more time to compute all of the possible paths so
2925     // that we can print them out. This is more expensive than any of
2926     // the previous derived-to-base checks we've done, but at this point
2927     // performance isn't as much of an issue.
2928     Paths.clear();
2929     Paths.setRecordingPaths(true);
2930     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2931     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2932     (void)StillOkay;
2933 
2934     // Build up a textual representation of the ambiguous paths, e.g.,
2935     // D -> B -> A, that will be used to illustrate the ambiguous
2936     // conversions in the diagnostic. We only print one of the paths
2937     // to each base class subobject.
2938     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2939 
2940     Diag(Loc, AmbiguousBaseConvID)
2941     << Derived << Base << PathDisplayStr << Range << Name;
2942   }
2943   return true;
2944 }
2945 
2946 bool
CheckDerivedToBaseConversion(QualType Derived,QualType Base,SourceLocation Loc,SourceRange Range,CXXCastPath * BasePath,bool IgnoreAccess)2947 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2948                                    SourceLocation Loc, SourceRange Range,
2949                                    CXXCastPath *BasePath,
2950                                    bool IgnoreAccess) {
2951   return CheckDerivedToBaseConversion(
2952       Derived, Base, diag::err_upcast_to_inaccessible_base,
2953       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2954       BasePath, IgnoreAccess);
2955 }
2956 
2957 
2958 /// Builds a string representing ambiguous paths from a
2959 /// specific derived class to different subobjects of the same base
2960 /// class.
2961 ///
2962 /// This function builds a string that can be used in error messages
2963 /// to show the different paths that one can take through the
2964 /// inheritance hierarchy to go from the derived class to different
2965 /// subobjects of a base class. The result looks something like this:
2966 /// @code
2967 /// struct D -> struct B -> struct A
2968 /// struct D -> struct C -> struct A
2969 /// @endcode
getAmbiguousPathsDisplayString(CXXBasePaths & Paths)2970 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2971   std::string PathDisplayStr;
2972   std::set<unsigned> DisplayedPaths;
2973   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2974        Path != Paths.end(); ++Path) {
2975     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2976       // We haven't displayed a path to this particular base
2977       // class subobject yet.
2978       PathDisplayStr += "\n    ";
2979       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2980       for (CXXBasePath::const_iterator Element = Path->begin();
2981            Element != Path->end(); ++Element)
2982         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2983     }
2984   }
2985 
2986   return PathDisplayStr;
2987 }
2988 
2989 //===----------------------------------------------------------------------===//
2990 // C++ class member Handling
2991 //===----------------------------------------------------------------------===//
2992 
2993 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
ActOnAccessSpecifier(AccessSpecifier Access,SourceLocation ASLoc,SourceLocation ColonLoc,const ParsedAttributesView & Attrs)2994 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2995                                 SourceLocation ColonLoc,
2996                                 const ParsedAttributesView &Attrs) {
2997   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2998   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2999                                                   ASLoc, ColonLoc);
3000   CurContext->addHiddenDecl(ASDecl);
3001   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3002 }
3003 
3004 /// CheckOverrideControl - Check C++11 override control semantics.
CheckOverrideControl(NamedDecl * D)3005 void Sema::CheckOverrideControl(NamedDecl *D) {
3006   if (D->isInvalidDecl())
3007     return;
3008 
3009   // We only care about "override" and "final" declarations.
3010   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3011     return;
3012 
3013   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3014 
3015   // We can't check dependent instance methods.
3016   if (MD && MD->isInstance() &&
3017       (MD->getParent()->hasAnyDependentBases() ||
3018        MD->getType()->isDependentType()))
3019     return;
3020 
3021   if (MD && !MD->isVirtual()) {
3022     // If we have a non-virtual method, check if if hides a virtual method.
3023     // (In that case, it's most likely the method has the wrong type.)
3024     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3025     FindHiddenVirtualMethods(MD, OverloadedMethods);
3026 
3027     if (!OverloadedMethods.empty()) {
3028       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3029         Diag(OA->getLocation(),
3030              diag::override_keyword_hides_virtual_member_function)
3031           << "override" << (OverloadedMethods.size() > 1);
3032       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3033         Diag(FA->getLocation(),
3034              diag::override_keyword_hides_virtual_member_function)
3035           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3036           << (OverloadedMethods.size() > 1);
3037       }
3038       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3039       MD->setInvalidDecl();
3040       return;
3041     }
3042     // Fall through into the general case diagnostic.
3043     // FIXME: We might want to attempt typo correction here.
3044   }
3045 
3046   if (!MD || !MD->isVirtual()) {
3047     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3048       Diag(OA->getLocation(),
3049            diag::override_keyword_only_allowed_on_virtual_member_functions)
3050         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3051       D->dropAttr<OverrideAttr>();
3052     }
3053     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3054       Diag(FA->getLocation(),
3055            diag::override_keyword_only_allowed_on_virtual_member_functions)
3056         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3057         << FixItHint::CreateRemoval(FA->getLocation());
3058       D->dropAttr<FinalAttr>();
3059     }
3060     return;
3061   }
3062 
3063   // C++11 [class.virtual]p5:
3064   //   If a function is marked with the virt-specifier override and
3065   //   does not override a member function of a base class, the program is
3066   //   ill-formed.
3067   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3068   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3069     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3070       << MD->getDeclName();
3071 }
3072 
DiagnoseAbsenceOfOverrideControl(NamedDecl * D,bool Inconsistent)3073 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3074   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3075     return;
3076   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3077   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3078     return;
3079 
3080   SourceLocation Loc = MD->getLocation();
3081   SourceLocation SpellingLoc = Loc;
3082   if (getSourceManager().isMacroArgExpansion(Loc))
3083     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3084   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3085   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3086       return;
3087 
3088   if (MD->size_overridden_methods() > 0) {
3089     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3090       unsigned DiagID =
3091           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3092               ? DiagInconsistent
3093               : DiagSuggest;
3094       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3095       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3096       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3097     };
3098     if (isa<CXXDestructorDecl>(MD))
3099       EmitDiag(
3100           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3101           diag::warn_suggest_destructor_marked_not_override_overriding);
3102     else
3103       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3104                diag::warn_suggest_function_marked_not_override_overriding);
3105   }
3106 }
3107 
3108 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3109 /// function overrides a virtual member function marked 'final', according to
3110 /// C++11 [class.virtual]p4.
CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl * New,const CXXMethodDecl * Old)3111 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3112                                                   const CXXMethodDecl *Old) {
3113   FinalAttr *FA = Old->getAttr<FinalAttr>();
3114   if (!FA)
3115     return false;
3116 
3117   Diag(New->getLocation(), diag::err_final_function_overridden)
3118     << New->getDeclName()
3119     << FA->isSpelledAsSealed();
3120   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3121   return true;
3122 }
3123 
InitializationHasSideEffects(const FieldDecl & FD)3124 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3125   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3126   // FIXME: Destruction of ObjC lifetime types has side-effects.
3127   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3128     return !RD->isCompleteDefinition() ||
3129            !RD->hasTrivialDefaultConstructor() ||
3130            !RD->hasTrivialDestructor();
3131   return false;
3132 }
3133 
getMSPropertyAttr(const ParsedAttributesView & list)3134 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3135   ParsedAttributesView::const_iterator Itr =
3136       llvm::find_if(list, [](const ParsedAttr &AL) {
3137         return AL.isDeclspecPropertyAttribute();
3138       });
3139   if (Itr != list.end())
3140     return &*Itr;
3141   return nullptr;
3142 }
3143 
3144 // Check if there is a field shadowing.
CheckShadowInheritedFields(const SourceLocation & Loc,DeclarationName FieldName,const CXXRecordDecl * RD,bool DeclIsField)3145 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3146                                       DeclarationName FieldName,
3147                                       const CXXRecordDecl *RD,
3148                                       bool DeclIsField) {
3149   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3150     return;
3151 
3152   // To record a shadowed field in a base
3153   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3154   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3155                            CXXBasePath &Path) {
3156     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3157     // Record an ambiguous path directly
3158     if (Bases.find(Base) != Bases.end())
3159       return true;
3160     for (const auto Field : Base->lookup(FieldName)) {
3161       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3162           Field->getAccess() != AS_private) {
3163         assert(Field->getAccess() != AS_none);
3164         assert(Bases.find(Base) == Bases.end());
3165         Bases[Base] = Field;
3166         return true;
3167       }
3168     }
3169     return false;
3170   };
3171 
3172   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3173                      /*DetectVirtual=*/true);
3174   if (!RD->lookupInBases(FieldShadowed, Paths))
3175     return;
3176 
3177   for (const auto &P : Paths) {
3178     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3179     auto It = Bases.find(Base);
3180     // Skip duplicated bases
3181     if (It == Bases.end())
3182       continue;
3183     auto BaseField = It->second;
3184     assert(BaseField->getAccess() != AS_private);
3185     if (AS_none !=
3186         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3187       Diag(Loc, diag::warn_shadow_field)
3188         << FieldName << RD << Base << DeclIsField;
3189       Diag(BaseField->getLocation(), diag::note_shadow_field);
3190       Bases.erase(It);
3191     }
3192   }
3193 }
3194 
3195 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3196 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3197 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3198 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3199 /// present (but parsing it has been deferred).
3200 NamedDecl *
ActOnCXXMemberDeclarator(Scope * S,AccessSpecifier AS,Declarator & D,MultiTemplateParamsArg TemplateParameterLists,Expr * BW,const VirtSpecifiers & VS,InClassInitStyle InitStyle)3201 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3202                                MultiTemplateParamsArg TemplateParameterLists,
3203                                Expr *BW, const VirtSpecifiers &VS,
3204                                InClassInitStyle InitStyle) {
3205   const DeclSpec &DS = D.getDeclSpec();
3206   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3207   DeclarationName Name = NameInfo.getName();
3208   SourceLocation Loc = NameInfo.getLoc();
3209 
3210   // For anonymous bitfields, the location should point to the type.
3211   if (Loc.isInvalid())
3212     Loc = D.getBeginLoc();
3213 
3214   Expr *BitWidth = static_cast<Expr*>(BW);
3215 
3216   assert(isa<CXXRecordDecl>(CurContext));
3217   assert(!DS.isFriendSpecified());
3218 
3219   bool isFunc = D.isDeclarationOfFunction();
3220   const ParsedAttr *MSPropertyAttr =
3221       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3222 
3223   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3224     // The Microsoft extension __interface only permits public member functions
3225     // and prohibits constructors, destructors, operators, non-public member
3226     // functions, static methods and data members.
3227     unsigned InvalidDecl;
3228     bool ShowDeclName = true;
3229     if (!isFunc &&
3230         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3231       InvalidDecl = 0;
3232     else if (!isFunc)
3233       InvalidDecl = 1;
3234     else if (AS != AS_public)
3235       InvalidDecl = 2;
3236     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3237       InvalidDecl = 3;
3238     else switch (Name.getNameKind()) {
3239       case DeclarationName::CXXConstructorName:
3240         InvalidDecl = 4;
3241         ShowDeclName = false;
3242         break;
3243 
3244       case DeclarationName::CXXDestructorName:
3245         InvalidDecl = 5;
3246         ShowDeclName = false;
3247         break;
3248 
3249       case DeclarationName::CXXOperatorName:
3250       case DeclarationName::CXXConversionFunctionName:
3251         InvalidDecl = 6;
3252         break;
3253 
3254       default:
3255         InvalidDecl = 0;
3256         break;
3257     }
3258 
3259     if (InvalidDecl) {
3260       if (ShowDeclName)
3261         Diag(Loc, diag::err_invalid_member_in_interface)
3262           << (InvalidDecl-1) << Name;
3263       else
3264         Diag(Loc, diag::err_invalid_member_in_interface)
3265           << (InvalidDecl-1) << "";
3266       return nullptr;
3267     }
3268   }
3269 
3270   // C++ 9.2p6: A member shall not be declared to have automatic storage
3271   // duration (auto, register) or with the extern storage-class-specifier.
3272   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3273   // data members and cannot be applied to names declared const or static,
3274   // and cannot be applied to reference members.
3275   switch (DS.getStorageClassSpec()) {
3276   case DeclSpec::SCS_unspecified:
3277   case DeclSpec::SCS_typedef:
3278   case DeclSpec::SCS_static:
3279     break;
3280   case DeclSpec::SCS_mutable:
3281     if (isFunc) {
3282       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3283 
3284       // FIXME: It would be nicer if the keyword was ignored only for this
3285       // declarator. Otherwise we could get follow-up errors.
3286       D.getMutableDeclSpec().ClearStorageClassSpecs();
3287     }
3288     break;
3289   default:
3290     Diag(DS.getStorageClassSpecLoc(),
3291          diag::err_storageclass_invalid_for_member);
3292     D.getMutableDeclSpec().ClearStorageClassSpecs();
3293     break;
3294   }
3295 
3296   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3297                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3298                       !isFunc);
3299 
3300   if (DS.hasConstexprSpecifier() && isInstField) {
3301     SemaDiagnosticBuilder B =
3302         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3303     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3304     if (InitStyle == ICIS_NoInit) {
3305       B << 0 << 0;
3306       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3307         B << FixItHint::CreateRemoval(ConstexprLoc);
3308       else {
3309         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3310         D.getMutableDeclSpec().ClearConstexprSpec();
3311         const char *PrevSpec;
3312         unsigned DiagID;
3313         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3314             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3315         (void)Failed;
3316         assert(!Failed && "Making a constexpr member const shouldn't fail");
3317       }
3318     } else {
3319       B << 1;
3320       const char *PrevSpec;
3321       unsigned DiagID;
3322       if (D.getMutableDeclSpec().SetStorageClassSpec(
3323           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3324           Context.getPrintingPolicy())) {
3325         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3326                "This is the only DeclSpec that should fail to be applied");
3327         B << 1;
3328       } else {
3329         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3330         isInstField = false;
3331       }
3332     }
3333   }
3334 
3335   NamedDecl *Member;
3336   if (isInstField) {
3337     CXXScopeSpec &SS = D.getCXXScopeSpec();
3338 
3339     // Data members must have identifiers for names.
3340     if (!Name.isIdentifier()) {
3341       Diag(Loc, diag::err_bad_variable_name)
3342         << Name;
3343       return nullptr;
3344     }
3345 
3346     IdentifierInfo *II = Name.getAsIdentifierInfo();
3347 
3348     // Member field could not be with "template" keyword.
3349     // So TemplateParameterLists should be empty in this case.
3350     if (TemplateParameterLists.size()) {
3351       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3352       if (TemplateParams->size()) {
3353         // There is no such thing as a member field template.
3354         Diag(D.getIdentifierLoc(), diag::err_template_member)
3355             << II
3356             << SourceRange(TemplateParams->getTemplateLoc(),
3357                 TemplateParams->getRAngleLoc());
3358       } else {
3359         // There is an extraneous 'template<>' for this member.
3360         Diag(TemplateParams->getTemplateLoc(),
3361             diag::err_template_member_noparams)
3362             << II
3363             << SourceRange(TemplateParams->getTemplateLoc(),
3364                 TemplateParams->getRAngleLoc());
3365       }
3366       return nullptr;
3367     }
3368 
3369     if (SS.isSet() && !SS.isInvalid()) {
3370       // The user provided a superfluous scope specifier inside a class
3371       // definition:
3372       //
3373       // class X {
3374       //   int X::member;
3375       // };
3376       if (DeclContext *DC = computeDeclContext(SS, false))
3377         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3378                                      D.getName().getKind() ==
3379                                          UnqualifiedIdKind::IK_TemplateId);
3380       else
3381         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3382           << Name << SS.getRange();
3383 
3384       SS.clear();
3385     }
3386 
3387     if (MSPropertyAttr) {
3388       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3389                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3390       if (!Member)
3391         return nullptr;
3392       isInstField = false;
3393     } else {
3394       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3395                                 BitWidth, InitStyle, AS);
3396       if (!Member)
3397         return nullptr;
3398     }
3399 
3400     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3401   } else {
3402     Member = HandleDeclarator(S, D, TemplateParameterLists);
3403     if (!Member)
3404       return nullptr;
3405 
3406     // Non-instance-fields can't have a bitfield.
3407     if (BitWidth) {
3408       if (Member->isInvalidDecl()) {
3409         // don't emit another diagnostic.
3410       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3411         // C++ 9.6p3: A bit-field shall not be a static member.
3412         // "static member 'A' cannot be a bit-field"
3413         Diag(Loc, diag::err_static_not_bitfield)
3414           << Name << BitWidth->getSourceRange();
3415       } else if (isa<TypedefDecl>(Member)) {
3416         // "typedef member 'x' cannot be a bit-field"
3417         Diag(Loc, diag::err_typedef_not_bitfield)
3418           << Name << BitWidth->getSourceRange();
3419       } else {
3420         // A function typedef ("typedef int f(); f a;").
3421         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3422         Diag(Loc, diag::err_not_integral_type_bitfield)
3423           << Name << cast<ValueDecl>(Member)->getType()
3424           << BitWidth->getSourceRange();
3425       }
3426 
3427       BitWidth = nullptr;
3428       Member->setInvalidDecl();
3429     }
3430 
3431     NamedDecl *NonTemplateMember = Member;
3432     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3433       NonTemplateMember = FunTmpl->getTemplatedDecl();
3434     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3435       NonTemplateMember = VarTmpl->getTemplatedDecl();
3436 
3437     Member->setAccess(AS);
3438 
3439     // If we have declared a member function template or static data member
3440     // template, set the access of the templated declaration as well.
3441     if (NonTemplateMember != Member)
3442       NonTemplateMember->setAccess(AS);
3443 
3444     // C++ [temp.deduct.guide]p3:
3445     //   A deduction guide [...] for a member class template [shall be
3446     //   declared] with the same access [as the template].
3447     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3448       auto *TD = DG->getDeducedTemplate();
3449       // Access specifiers are only meaningful if both the template and the
3450       // deduction guide are from the same scope.
3451       if (AS != TD->getAccess() &&
3452           TD->getDeclContext()->getRedeclContext()->Equals(
3453               DG->getDeclContext()->getRedeclContext())) {
3454         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3455         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3456             << TD->getAccess();
3457         const AccessSpecDecl *LastAccessSpec = nullptr;
3458         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3459           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3460             LastAccessSpec = AccessSpec;
3461         }
3462         assert(LastAccessSpec && "differing access with no access specifier");
3463         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3464             << AS;
3465       }
3466     }
3467   }
3468 
3469   if (VS.isOverrideSpecified())
3470     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3471                                          AttributeCommonInfo::AS_Keyword));
3472   if (VS.isFinalSpecified())
3473     Member->addAttr(FinalAttr::Create(
3474         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3475         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3476 
3477   if (VS.getLastLocation().isValid()) {
3478     // Update the end location of a method that has a virt-specifiers.
3479     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3480       MD->setRangeEnd(VS.getLastLocation());
3481   }
3482 
3483   CheckOverrideControl(Member);
3484 
3485   assert((Name || isInstField) && "No identifier for non-field ?");
3486 
3487   if (isInstField) {
3488     FieldDecl *FD = cast<FieldDecl>(Member);
3489     FieldCollector->Add(FD);
3490 
3491     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3492       // Remember all explicit private FieldDecls that have a name, no side
3493       // effects and are not part of a dependent type declaration.
3494       if (!FD->isImplicit() && FD->getDeclName() &&
3495           FD->getAccess() == AS_private &&
3496           !FD->hasAttr<UnusedAttr>() &&
3497           !FD->getParent()->isDependentContext() &&
3498           !InitializationHasSideEffects(*FD))
3499         UnusedPrivateFields.insert(FD);
3500     }
3501   }
3502 
3503   return Member;
3504 }
3505 
3506 namespace {
3507   class UninitializedFieldVisitor
3508       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3509     Sema &S;
3510     // List of Decls to generate a warning on.  Also remove Decls that become
3511     // initialized.
3512     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3513     // List of base classes of the record.  Classes are removed after their
3514     // initializers.
3515     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3516     // Vector of decls to be removed from the Decl set prior to visiting the
3517     // nodes.  These Decls may have been initialized in the prior initializer.
3518     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3519     // If non-null, add a note to the warning pointing back to the constructor.
3520     const CXXConstructorDecl *Constructor;
3521     // Variables to hold state when processing an initializer list.  When
3522     // InitList is true, special case initialization of FieldDecls matching
3523     // InitListFieldDecl.
3524     bool InitList;
3525     FieldDecl *InitListFieldDecl;
3526     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3527 
3528   public:
3529     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
UninitializedFieldVisitor(Sema & S,llvm::SmallPtrSetImpl<ValueDecl * > & Decls,llvm::SmallPtrSetImpl<QualType> & BaseClasses)3530     UninitializedFieldVisitor(Sema &S,
3531                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3532                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3533       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3534         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3535 
3536     // Returns true if the use of ME is not an uninitialized use.
IsInitListMemberExprInitialized(MemberExpr * ME,bool CheckReferenceOnly)3537     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3538                                          bool CheckReferenceOnly) {
3539       llvm::SmallVector<FieldDecl*, 4> Fields;
3540       bool ReferenceField = false;
3541       while (ME) {
3542         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3543         if (!FD)
3544           return false;
3545         Fields.push_back(FD);
3546         if (FD->getType()->isReferenceType())
3547           ReferenceField = true;
3548         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3549       }
3550 
3551       // Binding a reference to an uninitialized field is not an
3552       // uninitialized use.
3553       if (CheckReferenceOnly && !ReferenceField)
3554         return true;
3555 
3556       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3557       // Discard the first field since it is the field decl that is being
3558       // initialized.
3559       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3560         UsedFieldIndex.push_back((*I)->getFieldIndex());
3561       }
3562 
3563       for (auto UsedIter = UsedFieldIndex.begin(),
3564                 UsedEnd = UsedFieldIndex.end(),
3565                 OrigIter = InitFieldIndex.begin(),
3566                 OrigEnd = InitFieldIndex.end();
3567            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3568         if (*UsedIter < *OrigIter)
3569           return true;
3570         if (*UsedIter > *OrigIter)
3571           break;
3572       }
3573 
3574       return false;
3575     }
3576 
HandleMemberExpr(MemberExpr * ME,bool CheckReferenceOnly,bool AddressOf)3577     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3578                           bool AddressOf) {
3579       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3580         return;
3581 
3582       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3583       // or union.
3584       MemberExpr *FieldME = ME;
3585 
3586       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3587 
3588       Expr *Base = ME;
3589       while (MemberExpr *SubME =
3590                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3591 
3592         if (isa<VarDecl>(SubME->getMemberDecl()))
3593           return;
3594 
3595         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3596           if (!FD->isAnonymousStructOrUnion())
3597             FieldME = SubME;
3598 
3599         if (!FieldME->getType().isPODType(S.Context))
3600           AllPODFields = false;
3601 
3602         Base = SubME->getBase();
3603       }
3604 
3605       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3606         Visit(Base);
3607         return;
3608       }
3609 
3610       if (AddressOf && AllPODFields)
3611         return;
3612 
3613       ValueDecl* FoundVD = FieldME->getMemberDecl();
3614 
3615       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3616         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3617           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3618         }
3619 
3620         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3621           QualType T = BaseCast->getType();
3622           if (T->isPointerType() &&
3623               BaseClasses.count(T->getPointeeType())) {
3624             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3625                 << T->getPointeeType() << FoundVD;
3626           }
3627         }
3628       }
3629 
3630       if (!Decls.count(FoundVD))
3631         return;
3632 
3633       const bool IsReference = FoundVD->getType()->isReferenceType();
3634 
3635       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3636         // Special checking for initializer lists.
3637         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3638           return;
3639         }
3640       } else {
3641         // Prevent double warnings on use of unbounded references.
3642         if (CheckReferenceOnly && !IsReference)
3643           return;
3644       }
3645 
3646       unsigned diag = IsReference
3647           ? diag::warn_reference_field_is_uninit
3648           : diag::warn_field_is_uninit;
3649       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3650       if (Constructor)
3651         S.Diag(Constructor->getLocation(),
3652                diag::note_uninit_in_this_constructor)
3653           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3654 
3655     }
3656 
HandleValue(Expr * E,bool AddressOf)3657     void HandleValue(Expr *E, bool AddressOf) {
3658       E = E->IgnoreParens();
3659 
3660       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3661         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3662                          AddressOf /*AddressOf*/);
3663         return;
3664       }
3665 
3666       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3667         Visit(CO->getCond());
3668         HandleValue(CO->getTrueExpr(), AddressOf);
3669         HandleValue(CO->getFalseExpr(), AddressOf);
3670         return;
3671       }
3672 
3673       if (BinaryConditionalOperator *BCO =
3674               dyn_cast<BinaryConditionalOperator>(E)) {
3675         Visit(BCO->getCond());
3676         HandleValue(BCO->getFalseExpr(), AddressOf);
3677         return;
3678       }
3679 
3680       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3681         HandleValue(OVE->getSourceExpr(), AddressOf);
3682         return;
3683       }
3684 
3685       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3686         switch (BO->getOpcode()) {
3687         default:
3688           break;
3689         case(BO_PtrMemD):
3690         case(BO_PtrMemI):
3691           HandleValue(BO->getLHS(), AddressOf);
3692           Visit(BO->getRHS());
3693           return;
3694         case(BO_Comma):
3695           Visit(BO->getLHS());
3696           HandleValue(BO->getRHS(), AddressOf);
3697           return;
3698         }
3699       }
3700 
3701       Visit(E);
3702     }
3703 
CheckInitListExpr(InitListExpr * ILE)3704     void CheckInitListExpr(InitListExpr *ILE) {
3705       InitFieldIndex.push_back(0);
3706       for (auto Child : ILE->children()) {
3707         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3708           CheckInitListExpr(SubList);
3709         } else {
3710           Visit(Child);
3711         }
3712         ++InitFieldIndex.back();
3713       }
3714       InitFieldIndex.pop_back();
3715     }
3716 
CheckInitializer(Expr * E,const CXXConstructorDecl * FieldConstructor,FieldDecl * Field,const Type * BaseClass)3717     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3718                           FieldDecl *Field, const Type *BaseClass) {
3719       // Remove Decls that may have been initialized in the previous
3720       // initializer.
3721       for (ValueDecl* VD : DeclsToRemove)
3722         Decls.erase(VD);
3723       DeclsToRemove.clear();
3724 
3725       Constructor = FieldConstructor;
3726       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3727 
3728       if (ILE && Field) {
3729         InitList = true;
3730         InitListFieldDecl = Field;
3731         InitFieldIndex.clear();
3732         CheckInitListExpr(ILE);
3733       } else {
3734         InitList = false;
3735         Visit(E);
3736       }
3737 
3738       if (Field)
3739         Decls.erase(Field);
3740       if (BaseClass)
3741         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3742     }
3743 
VisitMemberExpr(MemberExpr * ME)3744     void VisitMemberExpr(MemberExpr *ME) {
3745       // All uses of unbounded reference fields will warn.
3746       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3747     }
3748 
VisitImplicitCastExpr(ImplicitCastExpr * E)3749     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3750       if (E->getCastKind() == CK_LValueToRValue) {
3751         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3752         return;
3753       }
3754 
3755       Inherited::VisitImplicitCastExpr(E);
3756     }
3757 
VisitCXXConstructExpr(CXXConstructExpr * E)3758     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3759       if (E->getConstructor()->isCopyConstructor()) {
3760         Expr *ArgExpr = E->getArg(0);
3761         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3762           if (ILE->getNumInits() == 1)
3763             ArgExpr = ILE->getInit(0);
3764         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3765           if (ICE->getCastKind() == CK_NoOp)
3766             ArgExpr = ICE->getSubExpr();
3767         HandleValue(ArgExpr, false /*AddressOf*/);
3768         return;
3769       }
3770       Inherited::VisitCXXConstructExpr(E);
3771     }
3772 
VisitCXXMemberCallExpr(CXXMemberCallExpr * E)3773     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3774       Expr *Callee = E->getCallee();
3775       if (isa<MemberExpr>(Callee)) {
3776         HandleValue(Callee, false /*AddressOf*/);
3777         for (auto Arg : E->arguments())
3778           Visit(Arg);
3779         return;
3780       }
3781 
3782       Inherited::VisitCXXMemberCallExpr(E);
3783     }
3784 
VisitCallExpr(CallExpr * E)3785     void VisitCallExpr(CallExpr *E) {
3786       // Treat std::move as a use.
3787       if (E->isCallToStdMove()) {
3788         HandleValue(E->getArg(0), /*AddressOf=*/false);
3789         return;
3790       }
3791 
3792       Inherited::VisitCallExpr(E);
3793     }
3794 
VisitCXXOperatorCallExpr(CXXOperatorCallExpr * E)3795     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3796       Expr *Callee = E->getCallee();
3797 
3798       if (isa<UnresolvedLookupExpr>(Callee))
3799         return Inherited::VisitCXXOperatorCallExpr(E);
3800 
3801       Visit(Callee);
3802       for (auto Arg : E->arguments())
3803         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3804     }
3805 
VisitBinaryOperator(BinaryOperator * E)3806     void VisitBinaryOperator(BinaryOperator *E) {
3807       // If a field assignment is detected, remove the field from the
3808       // uninitiailized field set.
3809       if (E->getOpcode() == BO_Assign)
3810         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3811           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3812             if (!FD->getType()->isReferenceType())
3813               DeclsToRemove.push_back(FD);
3814 
3815       if (E->isCompoundAssignmentOp()) {
3816         HandleValue(E->getLHS(), false /*AddressOf*/);
3817         Visit(E->getRHS());
3818         return;
3819       }
3820 
3821       Inherited::VisitBinaryOperator(E);
3822     }
3823 
VisitUnaryOperator(UnaryOperator * E)3824     void VisitUnaryOperator(UnaryOperator *E) {
3825       if (E->isIncrementDecrementOp()) {
3826         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3827         return;
3828       }
3829       if (E->getOpcode() == UO_AddrOf) {
3830         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3831           HandleValue(ME->getBase(), true /*AddressOf*/);
3832           return;
3833         }
3834       }
3835 
3836       Inherited::VisitUnaryOperator(E);
3837     }
3838   };
3839 
3840   // Diagnose value-uses of fields to initialize themselves, e.g.
3841   //   foo(foo)
3842   // where foo is not also a parameter to the constructor.
3843   // Also diagnose across field uninitialized use such as
3844   //   x(y), y(x)
3845   // TODO: implement -Wuninitialized and fold this into that framework.
DiagnoseUninitializedFields(Sema & SemaRef,const CXXConstructorDecl * Constructor)3846   static void DiagnoseUninitializedFields(
3847       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3848 
3849     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3850                                            Constructor->getLocation())) {
3851       return;
3852     }
3853 
3854     if (Constructor->isInvalidDecl())
3855       return;
3856 
3857     const CXXRecordDecl *RD = Constructor->getParent();
3858 
3859     if (RD->isDependentContext())
3860       return;
3861 
3862     // Holds fields that are uninitialized.
3863     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3864 
3865     // At the beginning, all fields are uninitialized.
3866     for (auto *I : RD->decls()) {
3867       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3868         UninitializedFields.insert(FD);
3869       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3870         UninitializedFields.insert(IFD->getAnonField());
3871       }
3872     }
3873 
3874     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3875     for (auto I : RD->bases())
3876       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3877 
3878     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3879       return;
3880 
3881     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3882                                                    UninitializedFields,
3883                                                    UninitializedBaseClasses);
3884 
3885     for (const auto *FieldInit : Constructor->inits()) {
3886       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3887         break;
3888 
3889       Expr *InitExpr = FieldInit->getInit();
3890       if (!InitExpr)
3891         continue;
3892 
3893       if (CXXDefaultInitExpr *Default =
3894               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3895         InitExpr = Default->getExpr();
3896         if (!InitExpr)
3897           continue;
3898         // In class initializers will point to the constructor.
3899         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3900                                               FieldInit->getAnyMember(),
3901                                               FieldInit->getBaseClass());
3902       } else {
3903         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3904                                               FieldInit->getAnyMember(),
3905                                               FieldInit->getBaseClass());
3906       }
3907     }
3908   }
3909 } // namespace
3910 
3911 /// Enter a new C++ default initializer scope. After calling this, the
3912 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3913 /// parsing or instantiating the initializer failed.
ActOnStartCXXInClassMemberInitializer()3914 void Sema::ActOnStartCXXInClassMemberInitializer() {
3915   // Create a synthetic function scope to represent the call to the constructor
3916   // that notionally surrounds a use of this initializer.
3917   PushFunctionScope();
3918 }
3919 
ActOnStartTrailingRequiresClause(Scope * S,Declarator & D)3920 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3921   if (!D.isFunctionDeclarator())
3922     return;
3923   auto &FTI = D.getFunctionTypeInfo();
3924   if (!FTI.Params)
3925     return;
3926   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3927                                                           FTI.NumParams)) {
3928     auto *ParamDecl = cast<NamedDecl>(Param.Param);
3929     if (ParamDecl->getDeclName())
3930       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3931   }
3932 }
3933 
ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)3934 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3935   return ActOnRequiresClause(ConstraintExpr);
3936 }
3937 
ActOnRequiresClause(ExprResult ConstraintExpr)3938 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
3939   if (ConstraintExpr.isInvalid())
3940     return ExprError();
3941 
3942   ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
3943   if (ConstraintExpr.isInvalid())
3944     return ExprError();
3945 
3946   if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
3947                                       UPPC_RequiresClause))
3948     return ExprError();
3949 
3950   return ConstraintExpr;
3951 }
3952 
3953 /// This is invoked after parsing an in-class initializer for a
3954 /// non-static C++ class member, and after instantiating an in-class initializer
3955 /// in a class template. Such actions are deferred until the class is complete.
ActOnFinishCXXInClassMemberInitializer(Decl * D,SourceLocation InitLoc,Expr * InitExpr)3956 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3957                                                   SourceLocation InitLoc,
3958                                                   Expr *InitExpr) {
3959   // Pop the notional constructor scope we created earlier.
3960   PopFunctionScopeInfo(nullptr, D);
3961 
3962   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3963   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3964          "must set init style when field is created");
3965 
3966   if (!InitExpr) {
3967     D->setInvalidDecl();
3968     if (FD)
3969       FD->removeInClassInitializer();
3970     return;
3971   }
3972 
3973   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3974     FD->setInvalidDecl();
3975     FD->removeInClassInitializer();
3976     return;
3977   }
3978 
3979   ExprResult Init = InitExpr;
3980   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3981     InitializedEntity Entity =
3982         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3983     InitializationKind Kind =
3984         FD->getInClassInitStyle() == ICIS_ListInit
3985             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3986                                                    InitExpr->getBeginLoc(),
3987                                                    InitExpr->getEndLoc())
3988             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3989     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3990     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3991     if (Init.isInvalid()) {
3992       FD->setInvalidDecl();
3993       return;
3994     }
3995   }
3996 
3997   // C++11 [class.base.init]p7:
3998   //   The initialization of each base and member constitutes a
3999   //   full-expression.
4000   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4001   if (Init.isInvalid()) {
4002     FD->setInvalidDecl();
4003     return;
4004   }
4005 
4006   InitExpr = Init.get();
4007 
4008   FD->setInClassInitializer(InitExpr);
4009 }
4010 
4011 /// Find the direct and/or virtual base specifiers that
4012 /// correspond to the given base type, for use in base initialization
4013 /// within a constructor.
FindBaseInitializer(Sema & SemaRef,CXXRecordDecl * ClassDecl,QualType BaseType,const CXXBaseSpecifier * & DirectBaseSpec,const CXXBaseSpecifier * & VirtualBaseSpec)4014 static bool FindBaseInitializer(Sema &SemaRef,
4015                                 CXXRecordDecl *ClassDecl,
4016                                 QualType BaseType,
4017                                 const CXXBaseSpecifier *&DirectBaseSpec,
4018                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
4019   // First, check for a direct base class.
4020   DirectBaseSpec = nullptr;
4021   for (const auto &Base : ClassDecl->bases()) {
4022     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4023       // We found a direct base of this type. That's what we're
4024       // initializing.
4025       DirectBaseSpec = &Base;
4026       break;
4027     }
4028   }
4029 
4030   // Check for a virtual base class.
4031   // FIXME: We might be able to short-circuit this if we know in advance that
4032   // there are no virtual bases.
4033   VirtualBaseSpec = nullptr;
4034   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4035     // We haven't found a base yet; search the class hierarchy for a
4036     // virtual base class.
4037     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4038                        /*DetectVirtual=*/false);
4039     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4040                               SemaRef.Context.getTypeDeclType(ClassDecl),
4041                               BaseType, Paths)) {
4042       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4043            Path != Paths.end(); ++Path) {
4044         if (Path->back().Base->isVirtual()) {
4045           VirtualBaseSpec = Path->back().Base;
4046           break;
4047         }
4048       }
4049     }
4050   }
4051 
4052   return DirectBaseSpec || VirtualBaseSpec;
4053 }
4054 
4055 /// Handle a C++ member initializer using braced-init-list syntax.
4056 MemInitResult
ActOnMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,Expr * InitList,SourceLocation EllipsisLoc)4057 Sema::ActOnMemInitializer(Decl *ConstructorD,
4058                           Scope *S,
4059                           CXXScopeSpec &SS,
4060                           IdentifierInfo *MemberOrBase,
4061                           ParsedType TemplateTypeTy,
4062                           const DeclSpec &DS,
4063                           SourceLocation IdLoc,
4064                           Expr *InitList,
4065                           SourceLocation EllipsisLoc) {
4066   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4067                              DS, IdLoc, InitList,
4068                              EllipsisLoc);
4069 }
4070 
4071 /// Handle a C++ member initializer using parentheses syntax.
4072 MemInitResult
ActOnMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,SourceLocation LParenLoc,ArrayRef<Expr * > Args,SourceLocation RParenLoc,SourceLocation EllipsisLoc)4073 Sema::ActOnMemInitializer(Decl *ConstructorD,
4074                           Scope *S,
4075                           CXXScopeSpec &SS,
4076                           IdentifierInfo *MemberOrBase,
4077                           ParsedType TemplateTypeTy,
4078                           const DeclSpec &DS,
4079                           SourceLocation IdLoc,
4080                           SourceLocation LParenLoc,
4081                           ArrayRef<Expr *> Args,
4082                           SourceLocation RParenLoc,
4083                           SourceLocation EllipsisLoc) {
4084   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4085   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4086                              DS, IdLoc, List, EllipsisLoc);
4087 }
4088 
4089 namespace {
4090 
4091 // Callback to only accept typo corrections that can be a valid C++ member
4092 // intializer: either a non-static field member or a base class.
4093 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4094 public:
MemInitializerValidatorCCC(CXXRecordDecl * ClassDecl)4095   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4096       : ClassDecl(ClassDecl) {}
4097 
ValidateCandidate(const TypoCorrection & candidate)4098   bool ValidateCandidate(const TypoCorrection &candidate) override {
4099     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4100       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4101         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4102       return isa<TypeDecl>(ND);
4103     }
4104     return false;
4105   }
4106 
clone()4107   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4108     return std::make_unique<MemInitializerValidatorCCC>(*this);
4109   }
4110 
4111 private:
4112   CXXRecordDecl *ClassDecl;
4113 };
4114 
4115 }
4116 
tryLookupCtorInitMemberDecl(CXXRecordDecl * ClassDecl,CXXScopeSpec & SS,ParsedType TemplateTypeTy,IdentifierInfo * MemberOrBase)4117 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4118                                              CXXScopeSpec &SS,
4119                                              ParsedType TemplateTypeTy,
4120                                              IdentifierInfo *MemberOrBase) {
4121   if (SS.getScopeRep() || TemplateTypeTy)
4122     return nullptr;
4123   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
4124   if (Result.empty())
4125     return nullptr;
4126   ValueDecl *Member;
4127   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
4128       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
4129     return Member;
4130   return nullptr;
4131 }
4132 
4133 /// Handle a C++ member initializer.
4134 MemInitResult
BuildMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,Expr * Init,SourceLocation EllipsisLoc)4135 Sema::BuildMemInitializer(Decl *ConstructorD,
4136                           Scope *S,
4137                           CXXScopeSpec &SS,
4138                           IdentifierInfo *MemberOrBase,
4139                           ParsedType TemplateTypeTy,
4140                           const DeclSpec &DS,
4141                           SourceLocation IdLoc,
4142                           Expr *Init,
4143                           SourceLocation EllipsisLoc) {
4144   ExprResult Res = CorrectDelayedTyposInExpr(Init);
4145   if (!Res.isUsable())
4146     return true;
4147   Init = Res.get();
4148 
4149   if (!ConstructorD)
4150     return true;
4151 
4152   AdjustDeclIfTemplate(ConstructorD);
4153 
4154   CXXConstructorDecl *Constructor
4155     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4156   if (!Constructor) {
4157     // The user wrote a constructor initializer on a function that is
4158     // not a C++ constructor. Ignore the error for now, because we may
4159     // have more member initializers coming; we'll diagnose it just
4160     // once in ActOnMemInitializers.
4161     return true;
4162   }
4163 
4164   CXXRecordDecl *ClassDecl = Constructor->getParent();
4165 
4166   // C++ [class.base.init]p2:
4167   //   Names in a mem-initializer-id are looked up in the scope of the
4168   //   constructor's class and, if not found in that scope, are looked
4169   //   up in the scope containing the constructor's definition.
4170   //   [Note: if the constructor's class contains a member with the
4171   //   same name as a direct or virtual base class of the class, a
4172   //   mem-initializer-id naming the member or base class and composed
4173   //   of a single identifier refers to the class member. A
4174   //   mem-initializer-id for the hidden base class may be specified
4175   //   using a qualified name. ]
4176 
4177   // Look for a member, first.
4178   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4179           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4180     if (EllipsisLoc.isValid())
4181       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4182           << MemberOrBase
4183           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4184 
4185     return BuildMemberInitializer(Member, Init, IdLoc);
4186   }
4187   // It didn't name a member, so see if it names a class.
4188   QualType BaseType;
4189   TypeSourceInfo *TInfo = nullptr;
4190 
4191   if (TemplateTypeTy) {
4192     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4193     if (BaseType.isNull())
4194       return true;
4195   } else if (DS.getTypeSpecType() == TST_decltype) {
4196     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4197   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4198     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4199     return true;
4200   } else {
4201     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4202     LookupParsedName(R, S, &SS);
4203 
4204     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4205     if (!TyD) {
4206       if (R.isAmbiguous()) return true;
4207 
4208       // We don't want access-control diagnostics here.
4209       R.suppressDiagnostics();
4210 
4211       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4212         bool NotUnknownSpecialization = false;
4213         DeclContext *DC = computeDeclContext(SS, false);
4214         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4215           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4216 
4217         if (!NotUnknownSpecialization) {
4218           // When the scope specifier can refer to a member of an unknown
4219           // specialization, we take it as a type name.
4220           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4221                                        SS.getWithLocInContext(Context),
4222                                        *MemberOrBase, IdLoc);
4223           if (BaseType.isNull())
4224             return true;
4225 
4226           TInfo = Context.CreateTypeSourceInfo(BaseType);
4227           DependentNameTypeLoc TL =
4228               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4229           if (!TL.isNull()) {
4230             TL.setNameLoc(IdLoc);
4231             TL.setElaboratedKeywordLoc(SourceLocation());
4232             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4233           }
4234 
4235           R.clear();
4236           R.setLookupName(MemberOrBase);
4237         }
4238       }
4239 
4240       // If no results were found, try to correct typos.
4241       TypoCorrection Corr;
4242       MemInitializerValidatorCCC CCC(ClassDecl);
4243       if (R.empty() && BaseType.isNull() &&
4244           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4245                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4246         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4247           // We have found a non-static data member with a similar
4248           // name to what was typed; complain and initialize that
4249           // member.
4250           diagnoseTypo(Corr,
4251                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4252                          << MemberOrBase << true);
4253           return BuildMemberInitializer(Member, Init, IdLoc);
4254         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4255           const CXXBaseSpecifier *DirectBaseSpec;
4256           const CXXBaseSpecifier *VirtualBaseSpec;
4257           if (FindBaseInitializer(*this, ClassDecl,
4258                                   Context.getTypeDeclType(Type),
4259                                   DirectBaseSpec, VirtualBaseSpec)) {
4260             // We have found a direct or virtual base class with a
4261             // similar name to what was typed; complain and initialize
4262             // that base class.
4263             diagnoseTypo(Corr,
4264                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4265                            << MemberOrBase << false,
4266                          PDiag() /*Suppress note, we provide our own.*/);
4267 
4268             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4269                                                               : VirtualBaseSpec;
4270             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4271                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4272 
4273             TyD = Type;
4274           }
4275         }
4276       }
4277 
4278       if (!TyD && BaseType.isNull()) {
4279         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4280           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4281         return true;
4282       }
4283     }
4284 
4285     if (BaseType.isNull()) {
4286       BaseType = Context.getTypeDeclType(TyD);
4287       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4288       if (SS.isSet()) {
4289         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4290                                              BaseType);
4291         TInfo = Context.CreateTypeSourceInfo(BaseType);
4292         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4293         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4294         TL.setElaboratedKeywordLoc(SourceLocation());
4295         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4296       }
4297     }
4298   }
4299 
4300   if (!TInfo)
4301     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4302 
4303   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4304 }
4305 
4306 MemInitResult
BuildMemberInitializer(ValueDecl * Member,Expr * Init,SourceLocation IdLoc)4307 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4308                              SourceLocation IdLoc) {
4309   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4310   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4311   assert((DirectMember || IndirectMember) &&
4312          "Member must be a FieldDecl or IndirectFieldDecl");
4313 
4314   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4315     return true;
4316 
4317   if (Member->isInvalidDecl())
4318     return true;
4319 
4320   MultiExprArg Args;
4321   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4322     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4323   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4324     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4325   } else {
4326     // Template instantiation doesn't reconstruct ParenListExprs for us.
4327     Args = Init;
4328   }
4329 
4330   SourceRange InitRange = Init->getSourceRange();
4331 
4332   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4333     // Can't check initialization for a member of dependent type or when
4334     // any of the arguments are type-dependent expressions.
4335     DiscardCleanupsInEvaluationContext();
4336   } else {
4337     bool InitList = false;
4338     if (isa<InitListExpr>(Init)) {
4339       InitList = true;
4340       Args = Init;
4341     }
4342 
4343     // Initialize the member.
4344     InitializedEntity MemberEntity =
4345       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4346                    : InitializedEntity::InitializeMember(IndirectMember,
4347                                                          nullptr);
4348     InitializationKind Kind =
4349         InitList ? InitializationKind::CreateDirectList(
4350                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4351                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4352                                                     InitRange.getEnd());
4353 
4354     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4355     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4356                                             nullptr);
4357     if (MemberInit.isInvalid())
4358       return true;
4359 
4360     // C++11 [class.base.init]p7:
4361     //   The initialization of each base and member constitutes a
4362     //   full-expression.
4363     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4364                                      /*DiscardedValue*/ false);
4365     if (MemberInit.isInvalid())
4366       return true;
4367 
4368     Init = MemberInit.get();
4369   }
4370 
4371   if (DirectMember) {
4372     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4373                                             InitRange.getBegin(), Init,
4374                                             InitRange.getEnd());
4375   } else {
4376     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4377                                             InitRange.getBegin(), Init,
4378                                             InitRange.getEnd());
4379   }
4380 }
4381 
4382 MemInitResult
BuildDelegatingInitializer(TypeSourceInfo * TInfo,Expr * Init,CXXRecordDecl * ClassDecl)4383 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4384                                  CXXRecordDecl *ClassDecl) {
4385   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4386   if (!LangOpts.CPlusPlus11)
4387     return Diag(NameLoc, diag::err_delegating_ctor)
4388       << TInfo->getTypeLoc().getLocalSourceRange();
4389   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4390 
4391   bool InitList = true;
4392   MultiExprArg Args = Init;
4393   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4394     InitList = false;
4395     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4396   }
4397 
4398   SourceRange InitRange = Init->getSourceRange();
4399   // Initialize the object.
4400   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4401                                      QualType(ClassDecl->getTypeForDecl(), 0));
4402   InitializationKind Kind =
4403       InitList ? InitializationKind::CreateDirectList(
4404                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4405                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4406                                                   InitRange.getEnd());
4407   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4408   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4409                                               Args, nullptr);
4410   if (DelegationInit.isInvalid())
4411     return true;
4412 
4413   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4414          "Delegating constructor with no target?");
4415 
4416   // C++11 [class.base.init]p7:
4417   //   The initialization of each base and member constitutes a
4418   //   full-expression.
4419   DelegationInit = ActOnFinishFullExpr(
4420       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4421   if (DelegationInit.isInvalid())
4422     return true;
4423 
4424   // If we are in a dependent context, template instantiation will
4425   // perform this type-checking again. Just save the arguments that we
4426   // received in a ParenListExpr.
4427   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4428   // of the information that we have about the base
4429   // initializer. However, deconstructing the ASTs is a dicey process,
4430   // and this approach is far more likely to get the corner cases right.
4431   if (CurContext->isDependentContext())
4432     DelegationInit = Init;
4433 
4434   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4435                                           DelegationInit.getAs<Expr>(),
4436                                           InitRange.getEnd());
4437 }
4438 
4439 MemInitResult
BuildBaseInitializer(QualType BaseType,TypeSourceInfo * BaseTInfo,Expr * Init,CXXRecordDecl * ClassDecl,SourceLocation EllipsisLoc)4440 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4441                            Expr *Init, CXXRecordDecl *ClassDecl,
4442                            SourceLocation EllipsisLoc) {
4443   SourceLocation BaseLoc
4444     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4445 
4446   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4447     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4448              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4449 
4450   // C++ [class.base.init]p2:
4451   //   [...] Unless the mem-initializer-id names a nonstatic data
4452   //   member of the constructor's class or a direct or virtual base
4453   //   of that class, the mem-initializer is ill-formed. A
4454   //   mem-initializer-list can initialize a base class using any
4455   //   name that denotes that base class type.
4456   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4457 
4458   SourceRange InitRange = Init->getSourceRange();
4459   if (EllipsisLoc.isValid()) {
4460     // This is a pack expansion.
4461     if (!BaseType->containsUnexpandedParameterPack())  {
4462       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4463         << SourceRange(BaseLoc, InitRange.getEnd());
4464 
4465       EllipsisLoc = SourceLocation();
4466     }
4467   } else {
4468     // Check for any unexpanded parameter packs.
4469     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4470       return true;
4471 
4472     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4473       return true;
4474   }
4475 
4476   // Check for direct and virtual base classes.
4477   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4478   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4479   if (!Dependent) {
4480     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4481                                        BaseType))
4482       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4483 
4484     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4485                         VirtualBaseSpec);
4486 
4487     // C++ [base.class.init]p2:
4488     // Unless the mem-initializer-id names a nonstatic data member of the
4489     // constructor's class or a direct or virtual base of that class, the
4490     // mem-initializer is ill-formed.
4491     if (!DirectBaseSpec && !VirtualBaseSpec) {
4492       // If the class has any dependent bases, then it's possible that
4493       // one of those types will resolve to the same type as
4494       // BaseType. Therefore, just treat this as a dependent base
4495       // class initialization.  FIXME: Should we try to check the
4496       // initialization anyway? It seems odd.
4497       if (ClassDecl->hasAnyDependentBases())
4498         Dependent = true;
4499       else
4500         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4501           << BaseType << Context.getTypeDeclType(ClassDecl)
4502           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4503     }
4504   }
4505 
4506   if (Dependent) {
4507     DiscardCleanupsInEvaluationContext();
4508 
4509     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4510                                             /*IsVirtual=*/false,
4511                                             InitRange.getBegin(), Init,
4512                                             InitRange.getEnd(), EllipsisLoc);
4513   }
4514 
4515   // C++ [base.class.init]p2:
4516   //   If a mem-initializer-id is ambiguous because it designates both
4517   //   a direct non-virtual base class and an inherited virtual base
4518   //   class, the mem-initializer is ill-formed.
4519   if (DirectBaseSpec && VirtualBaseSpec)
4520     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4521       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4522 
4523   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4524   if (!BaseSpec)
4525     BaseSpec = VirtualBaseSpec;
4526 
4527   // Initialize the base.
4528   bool InitList = true;
4529   MultiExprArg Args = Init;
4530   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4531     InitList = false;
4532     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4533   }
4534 
4535   InitializedEntity BaseEntity =
4536     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4537   InitializationKind Kind =
4538       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4539                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4540                                                   InitRange.getEnd());
4541   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4542   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4543   if (BaseInit.isInvalid())
4544     return true;
4545 
4546   // C++11 [class.base.init]p7:
4547   //   The initialization of each base and member constitutes a
4548   //   full-expression.
4549   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4550                                  /*DiscardedValue*/ false);
4551   if (BaseInit.isInvalid())
4552     return true;
4553 
4554   // If we are in a dependent context, template instantiation will
4555   // perform this type-checking again. Just save the arguments that we
4556   // received in a ParenListExpr.
4557   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4558   // of the information that we have about the base
4559   // initializer. However, deconstructing the ASTs is a dicey process,
4560   // and this approach is far more likely to get the corner cases right.
4561   if (CurContext->isDependentContext())
4562     BaseInit = Init;
4563 
4564   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4565                                           BaseSpec->isVirtual(),
4566                                           InitRange.getBegin(),
4567                                           BaseInit.getAs<Expr>(),
4568                                           InitRange.getEnd(), EllipsisLoc);
4569 }
4570 
4571 // Create a static_cast\<T&&>(expr).
CastForMoving(Sema & SemaRef,Expr * E,QualType T=QualType ())4572 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4573   if (T.isNull()) T = E->getType();
4574   QualType TargetType = SemaRef.BuildReferenceType(
4575       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4576   SourceLocation ExprLoc = E->getBeginLoc();
4577   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4578       TargetType, ExprLoc);
4579 
4580   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4581                                    SourceRange(ExprLoc, ExprLoc),
4582                                    E->getSourceRange()).get();
4583 }
4584 
4585 /// ImplicitInitializerKind - How an implicit base or member initializer should
4586 /// initialize its base or member.
4587 enum ImplicitInitializerKind {
4588   IIK_Default,
4589   IIK_Copy,
4590   IIK_Move,
4591   IIK_Inherit
4592 };
4593 
4594 static bool
BuildImplicitBaseInitializer(Sema & SemaRef,CXXConstructorDecl * Constructor,ImplicitInitializerKind ImplicitInitKind,CXXBaseSpecifier * BaseSpec,bool IsInheritedVirtualBase,CXXCtorInitializer * & CXXBaseInit)4595 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4596                              ImplicitInitializerKind ImplicitInitKind,
4597                              CXXBaseSpecifier *BaseSpec,
4598                              bool IsInheritedVirtualBase,
4599                              CXXCtorInitializer *&CXXBaseInit) {
4600   InitializedEntity InitEntity
4601     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4602                                         IsInheritedVirtualBase);
4603 
4604   ExprResult BaseInit;
4605 
4606   switch (ImplicitInitKind) {
4607   case IIK_Inherit:
4608   case IIK_Default: {
4609     InitializationKind InitKind
4610       = InitializationKind::CreateDefault(Constructor->getLocation());
4611     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4612     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4613     break;
4614   }
4615 
4616   case IIK_Move:
4617   case IIK_Copy: {
4618     bool Moving = ImplicitInitKind == IIK_Move;
4619     ParmVarDecl *Param = Constructor->getParamDecl(0);
4620     QualType ParamType = Param->getType().getNonReferenceType();
4621 
4622     Expr *CopyCtorArg =
4623       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4624                           SourceLocation(), Param, false,
4625                           Constructor->getLocation(), ParamType,
4626                           VK_LValue, nullptr);
4627 
4628     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4629 
4630     // Cast to the base class to avoid ambiguities.
4631     QualType ArgTy =
4632       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4633                                        ParamType.getQualifiers());
4634 
4635     if (Moving) {
4636       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4637     }
4638 
4639     CXXCastPath BasePath;
4640     BasePath.push_back(BaseSpec);
4641     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4642                                             CK_UncheckedDerivedToBase,
4643                                             Moving ? VK_XValue : VK_LValue,
4644                                             &BasePath).get();
4645 
4646     InitializationKind InitKind
4647       = InitializationKind::CreateDirect(Constructor->getLocation(),
4648                                          SourceLocation(), SourceLocation());
4649     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4650     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4651     break;
4652   }
4653   }
4654 
4655   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4656   if (BaseInit.isInvalid())
4657     return true;
4658 
4659   CXXBaseInit =
4660     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4661                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4662                                                         SourceLocation()),
4663                                              BaseSpec->isVirtual(),
4664                                              SourceLocation(),
4665                                              BaseInit.getAs<Expr>(),
4666                                              SourceLocation(),
4667                                              SourceLocation());
4668 
4669   return false;
4670 }
4671 
RefersToRValueRef(Expr * MemRef)4672 static bool RefersToRValueRef(Expr *MemRef) {
4673   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4674   return Referenced->getType()->isRValueReferenceType();
4675 }
4676 
4677 static bool
BuildImplicitMemberInitializer(Sema & SemaRef,CXXConstructorDecl * Constructor,ImplicitInitializerKind ImplicitInitKind,FieldDecl * Field,IndirectFieldDecl * Indirect,CXXCtorInitializer * & CXXMemberInit)4678 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4679                                ImplicitInitializerKind ImplicitInitKind,
4680                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4681                                CXXCtorInitializer *&CXXMemberInit) {
4682   if (Field->isInvalidDecl())
4683     return true;
4684 
4685   SourceLocation Loc = Constructor->getLocation();
4686 
4687   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4688     bool Moving = ImplicitInitKind == IIK_Move;
4689     ParmVarDecl *Param = Constructor->getParamDecl(0);
4690     QualType ParamType = Param->getType().getNonReferenceType();
4691 
4692     // Suppress copying zero-width bitfields.
4693     if (Field->isZeroLengthBitField(SemaRef.Context))
4694       return false;
4695 
4696     Expr *MemberExprBase =
4697       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4698                           SourceLocation(), Param, false,
4699                           Loc, ParamType, VK_LValue, nullptr);
4700 
4701     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4702 
4703     if (Moving) {
4704       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4705     }
4706 
4707     // Build a reference to this field within the parameter.
4708     CXXScopeSpec SS;
4709     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4710                               Sema::LookupMemberName);
4711     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4712                                   : cast<ValueDecl>(Field), AS_public);
4713     MemberLookup.resolveKind();
4714     ExprResult CtorArg
4715       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4716                                          ParamType, Loc,
4717                                          /*IsArrow=*/false,
4718                                          SS,
4719                                          /*TemplateKWLoc=*/SourceLocation(),
4720                                          /*FirstQualifierInScope=*/nullptr,
4721                                          MemberLookup,
4722                                          /*TemplateArgs=*/nullptr,
4723                                          /*S*/nullptr);
4724     if (CtorArg.isInvalid())
4725       return true;
4726 
4727     // C++11 [class.copy]p15:
4728     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4729     //     with static_cast<T&&>(x.m);
4730     if (RefersToRValueRef(CtorArg.get())) {
4731       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4732     }
4733 
4734     InitializedEntity Entity =
4735         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4736                                                        /*Implicit*/ true)
4737                  : InitializedEntity::InitializeMember(Field, nullptr,
4738                                                        /*Implicit*/ true);
4739 
4740     // Direct-initialize to use the copy constructor.
4741     InitializationKind InitKind =
4742       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4743 
4744     Expr *CtorArgE = CtorArg.getAs<Expr>();
4745     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4746     ExprResult MemberInit =
4747         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4748     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4749     if (MemberInit.isInvalid())
4750       return true;
4751 
4752     if (Indirect)
4753       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4754           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4755     else
4756       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4757           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4758     return false;
4759   }
4760 
4761   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4762          "Unhandled implicit init kind!");
4763 
4764   QualType FieldBaseElementType =
4765     SemaRef.Context.getBaseElementType(Field->getType());
4766 
4767   if (FieldBaseElementType->isRecordType()) {
4768     InitializedEntity InitEntity =
4769         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4770                                                        /*Implicit*/ true)
4771                  : InitializedEntity::InitializeMember(Field, nullptr,
4772                                                        /*Implicit*/ true);
4773     InitializationKind InitKind =
4774       InitializationKind::CreateDefault(Loc);
4775 
4776     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4777     ExprResult MemberInit =
4778       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4779 
4780     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4781     if (MemberInit.isInvalid())
4782       return true;
4783 
4784     if (Indirect)
4785       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4786                                                                Indirect, Loc,
4787                                                                Loc,
4788                                                                MemberInit.get(),
4789                                                                Loc);
4790     else
4791       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4792                                                                Field, Loc, Loc,
4793                                                                MemberInit.get(),
4794                                                                Loc);
4795     return false;
4796   }
4797 
4798   if (!Field->getParent()->isUnion()) {
4799     if (FieldBaseElementType->isReferenceType()) {
4800       SemaRef.Diag(Constructor->getLocation(),
4801                    diag::err_uninitialized_member_in_ctor)
4802       << (int)Constructor->isImplicit()
4803       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4804       << 0 << Field->getDeclName();
4805       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4806       return true;
4807     }
4808 
4809     if (FieldBaseElementType.isConstQualified()) {
4810       SemaRef.Diag(Constructor->getLocation(),
4811                    diag::err_uninitialized_member_in_ctor)
4812       << (int)Constructor->isImplicit()
4813       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4814       << 1 << Field->getDeclName();
4815       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4816       return true;
4817     }
4818   }
4819 
4820   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4821     // ARC and Weak:
4822     //   Default-initialize Objective-C pointers to NULL.
4823     CXXMemberInit
4824       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4825                                                  Loc, Loc,
4826                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4827                                                  Loc);
4828     return false;
4829   }
4830 
4831   // Nothing to initialize.
4832   CXXMemberInit = nullptr;
4833   return false;
4834 }
4835 
4836 namespace {
4837 struct BaseAndFieldInfo {
4838   Sema &S;
4839   CXXConstructorDecl *Ctor;
4840   bool AnyErrorsInInits;
4841   ImplicitInitializerKind IIK;
4842   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4843   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4844   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4845 
BaseAndFieldInfo__anonedc74bd71211::BaseAndFieldInfo4846   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4847     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4848     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4849     if (Ctor->getInheritedConstructor())
4850       IIK = IIK_Inherit;
4851     else if (Generated && Ctor->isCopyConstructor())
4852       IIK = IIK_Copy;
4853     else if (Generated && Ctor->isMoveConstructor())
4854       IIK = IIK_Move;
4855     else
4856       IIK = IIK_Default;
4857   }
4858 
isImplicitCopyOrMove__anonedc74bd71211::BaseAndFieldInfo4859   bool isImplicitCopyOrMove() const {
4860     switch (IIK) {
4861     case IIK_Copy:
4862     case IIK_Move:
4863       return true;
4864 
4865     case IIK_Default:
4866     case IIK_Inherit:
4867       return false;
4868     }
4869 
4870     llvm_unreachable("Invalid ImplicitInitializerKind!");
4871   }
4872 
addFieldInitializer__anonedc74bd71211::BaseAndFieldInfo4873   bool addFieldInitializer(CXXCtorInitializer *Init) {
4874     AllToInit.push_back(Init);
4875 
4876     // Check whether this initializer makes the field "used".
4877     if (Init->getInit()->HasSideEffects(S.Context))
4878       S.UnusedPrivateFields.remove(Init->getAnyMember());
4879 
4880     return false;
4881   }
4882 
isInactiveUnionMember__anonedc74bd71211::BaseAndFieldInfo4883   bool isInactiveUnionMember(FieldDecl *Field) {
4884     RecordDecl *Record = Field->getParent();
4885     if (!Record->isUnion())
4886       return false;
4887 
4888     if (FieldDecl *Active =
4889             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4890       return Active != Field->getCanonicalDecl();
4891 
4892     // In an implicit copy or move constructor, ignore any in-class initializer.
4893     if (isImplicitCopyOrMove())
4894       return true;
4895 
4896     // If there's no explicit initialization, the field is active only if it
4897     // has an in-class initializer...
4898     if (Field->hasInClassInitializer())
4899       return false;
4900     // ... or it's an anonymous struct or union whose class has an in-class
4901     // initializer.
4902     if (!Field->isAnonymousStructOrUnion())
4903       return true;
4904     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4905     return !FieldRD->hasInClassInitializer();
4906   }
4907 
4908   /// Determine whether the given field is, or is within, a union member
4909   /// that is inactive (because there was an initializer given for a different
4910   /// member of the union, or because the union was not initialized at all).
isWithinInactiveUnionMember__anonedc74bd71211::BaseAndFieldInfo4911   bool isWithinInactiveUnionMember(FieldDecl *Field,
4912                                    IndirectFieldDecl *Indirect) {
4913     if (!Indirect)
4914       return isInactiveUnionMember(Field);
4915 
4916     for (auto *C : Indirect->chain()) {
4917       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4918       if (Field && isInactiveUnionMember(Field))
4919         return true;
4920     }
4921     return false;
4922   }
4923 };
4924 }
4925 
4926 /// Determine whether the given type is an incomplete or zero-lenfgth
4927 /// array type.
isIncompleteOrZeroLengthArrayType(ASTContext & Context,QualType T)4928 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4929   if (T->isIncompleteArrayType())
4930     return true;
4931 
4932   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4933     if (!ArrayT->getSize())
4934       return true;
4935 
4936     T = ArrayT->getElementType();
4937   }
4938 
4939   return false;
4940 }
4941 
CollectFieldInitializer(Sema & SemaRef,BaseAndFieldInfo & Info,FieldDecl * Field,IndirectFieldDecl * Indirect=nullptr)4942 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4943                                     FieldDecl *Field,
4944                                     IndirectFieldDecl *Indirect = nullptr) {
4945   if (Field->isInvalidDecl())
4946     return false;
4947 
4948   // Overwhelmingly common case: we have a direct initializer for this field.
4949   if (CXXCtorInitializer *Init =
4950           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4951     return Info.addFieldInitializer(Init);
4952 
4953   // C++11 [class.base.init]p8:
4954   //   if the entity is a non-static data member that has a
4955   //   brace-or-equal-initializer and either
4956   //   -- the constructor's class is a union and no other variant member of that
4957   //      union is designated by a mem-initializer-id or
4958   //   -- the constructor's class is not a union, and, if the entity is a member
4959   //      of an anonymous union, no other member of that union is designated by
4960   //      a mem-initializer-id,
4961   //   the entity is initialized as specified in [dcl.init].
4962   //
4963   // We also apply the same rules to handle anonymous structs within anonymous
4964   // unions.
4965   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4966     return false;
4967 
4968   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4969     ExprResult DIE =
4970         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4971     if (DIE.isInvalid())
4972       return true;
4973 
4974     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4975     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4976 
4977     CXXCtorInitializer *Init;
4978     if (Indirect)
4979       Init = new (SemaRef.Context)
4980           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4981                              SourceLocation(), DIE.get(), SourceLocation());
4982     else
4983       Init = new (SemaRef.Context)
4984           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4985                              SourceLocation(), DIE.get(), SourceLocation());
4986     return Info.addFieldInitializer(Init);
4987   }
4988 
4989   // Don't initialize incomplete or zero-length arrays.
4990   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4991     return false;
4992 
4993   // Don't try to build an implicit initializer if there were semantic
4994   // errors in any of the initializers (and therefore we might be
4995   // missing some that the user actually wrote).
4996   if (Info.AnyErrorsInInits)
4997     return false;
4998 
4999   CXXCtorInitializer *Init = nullptr;
5000   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5001                                      Indirect, Init))
5002     return true;
5003 
5004   if (!Init)
5005     return false;
5006 
5007   return Info.addFieldInitializer(Init);
5008 }
5009 
5010 bool
SetDelegatingInitializer(CXXConstructorDecl * Constructor,CXXCtorInitializer * Initializer)5011 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5012                                CXXCtorInitializer *Initializer) {
5013   assert(Initializer->isDelegatingInitializer());
5014   Constructor->setNumCtorInitializers(1);
5015   CXXCtorInitializer **initializer =
5016     new (Context) CXXCtorInitializer*[1];
5017   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5018   Constructor->setCtorInitializers(initializer);
5019 
5020   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5021     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5022     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5023   }
5024 
5025   DelegatingCtorDecls.push_back(Constructor);
5026 
5027   DiagnoseUninitializedFields(*this, Constructor);
5028 
5029   return false;
5030 }
5031 
SetCtorInitializers(CXXConstructorDecl * Constructor,bool AnyErrors,ArrayRef<CXXCtorInitializer * > Initializers)5032 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5033                                ArrayRef<CXXCtorInitializer *> Initializers) {
5034   if (Constructor->isDependentContext()) {
5035     // Just store the initializers as written, they will be checked during
5036     // instantiation.
5037     if (!Initializers.empty()) {
5038       Constructor->setNumCtorInitializers(Initializers.size());
5039       CXXCtorInitializer **baseOrMemberInitializers =
5040         new (Context) CXXCtorInitializer*[Initializers.size()];
5041       memcpy(baseOrMemberInitializers, Initializers.data(),
5042              Initializers.size() * sizeof(CXXCtorInitializer*));
5043       Constructor->setCtorInitializers(baseOrMemberInitializers);
5044     }
5045 
5046     // Let template instantiation know whether we had errors.
5047     if (AnyErrors)
5048       Constructor->setInvalidDecl();
5049 
5050     return false;
5051   }
5052 
5053   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5054 
5055   // We need to build the initializer AST according to order of construction
5056   // and not what user specified in the Initializers list.
5057   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5058   if (!ClassDecl)
5059     return true;
5060 
5061   bool HadError = false;
5062 
5063   for (unsigned i = 0; i < Initializers.size(); i++) {
5064     CXXCtorInitializer *Member = Initializers[i];
5065 
5066     if (Member->isBaseInitializer())
5067       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5068     else {
5069       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5070 
5071       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5072         for (auto *C : F->chain()) {
5073           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5074           if (FD && FD->getParent()->isUnion())
5075             Info.ActiveUnionMember.insert(std::make_pair(
5076                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5077         }
5078       } else if (FieldDecl *FD = Member->getMember()) {
5079         if (FD->getParent()->isUnion())
5080           Info.ActiveUnionMember.insert(std::make_pair(
5081               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5082       }
5083     }
5084   }
5085 
5086   // Keep track of the direct virtual bases.
5087   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5088   for (auto &I : ClassDecl->bases()) {
5089     if (I.isVirtual())
5090       DirectVBases.insert(&I);
5091   }
5092 
5093   // Push virtual bases before others.
5094   for (auto &VBase : ClassDecl->vbases()) {
5095     if (CXXCtorInitializer *Value
5096         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5097       // [class.base.init]p7, per DR257:
5098       //   A mem-initializer where the mem-initializer-id names a virtual base
5099       //   class is ignored during execution of a constructor of any class that
5100       //   is not the most derived class.
5101       if (ClassDecl->isAbstract()) {
5102         // FIXME: Provide a fixit to remove the base specifier. This requires
5103         // tracking the location of the associated comma for a base specifier.
5104         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5105           << VBase.getType() << ClassDecl;
5106         DiagnoseAbstractType(ClassDecl);
5107       }
5108 
5109       Info.AllToInit.push_back(Value);
5110     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5111       // [class.base.init]p8, per DR257:
5112       //   If a given [...] base class is not named by a mem-initializer-id
5113       //   [...] and the entity is not a virtual base class of an abstract
5114       //   class, then [...] the entity is default-initialized.
5115       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5116       CXXCtorInitializer *CXXBaseInit;
5117       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5118                                        &VBase, IsInheritedVirtualBase,
5119                                        CXXBaseInit)) {
5120         HadError = true;
5121         continue;
5122       }
5123 
5124       Info.AllToInit.push_back(CXXBaseInit);
5125     }
5126   }
5127 
5128   // Non-virtual bases.
5129   for (auto &Base : ClassDecl->bases()) {
5130     // Virtuals are in the virtual base list and already constructed.
5131     if (Base.isVirtual())
5132       continue;
5133 
5134     if (CXXCtorInitializer *Value
5135           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5136       Info.AllToInit.push_back(Value);
5137     } else if (!AnyErrors) {
5138       CXXCtorInitializer *CXXBaseInit;
5139       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5140                                        &Base, /*IsInheritedVirtualBase=*/false,
5141                                        CXXBaseInit)) {
5142         HadError = true;
5143         continue;
5144       }
5145 
5146       Info.AllToInit.push_back(CXXBaseInit);
5147     }
5148   }
5149 
5150   // Fields.
5151   for (auto *Mem : ClassDecl->decls()) {
5152     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5153       // C++ [class.bit]p2:
5154       //   A declaration for a bit-field that omits the identifier declares an
5155       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5156       //   initialized.
5157       if (F->isUnnamedBitfield())
5158         continue;
5159 
5160       // If we're not generating the implicit copy/move constructor, then we'll
5161       // handle anonymous struct/union fields based on their individual
5162       // indirect fields.
5163       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5164         continue;
5165 
5166       if (CollectFieldInitializer(*this, Info, F))
5167         HadError = true;
5168       continue;
5169     }
5170 
5171     // Beyond this point, we only consider default initialization.
5172     if (Info.isImplicitCopyOrMove())
5173       continue;
5174 
5175     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5176       if (F->getType()->isIncompleteArrayType()) {
5177         assert(ClassDecl->hasFlexibleArrayMember() &&
5178                "Incomplete array type is not valid");
5179         continue;
5180       }
5181 
5182       // Initialize each field of an anonymous struct individually.
5183       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5184         HadError = true;
5185 
5186       continue;
5187     }
5188   }
5189 
5190   unsigned NumInitializers = Info.AllToInit.size();
5191   if (NumInitializers > 0) {
5192     Constructor->setNumCtorInitializers(NumInitializers);
5193     CXXCtorInitializer **baseOrMemberInitializers =
5194       new (Context) CXXCtorInitializer*[NumInitializers];
5195     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5196            NumInitializers * sizeof(CXXCtorInitializer*));
5197     Constructor->setCtorInitializers(baseOrMemberInitializers);
5198 
5199     // Constructors implicitly reference the base and member
5200     // destructors.
5201     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5202                                            Constructor->getParent());
5203   }
5204 
5205   return HadError;
5206 }
5207 
PopulateKeysForFields(FieldDecl * Field,SmallVectorImpl<const void * > & IdealInits)5208 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5209   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5210     const RecordDecl *RD = RT->getDecl();
5211     if (RD->isAnonymousStructOrUnion()) {
5212       for (auto *Field : RD->fields())
5213         PopulateKeysForFields(Field, IdealInits);
5214       return;
5215     }
5216   }
5217   IdealInits.push_back(Field->getCanonicalDecl());
5218 }
5219 
GetKeyForBase(ASTContext & Context,QualType BaseType)5220 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5221   return Context.getCanonicalType(BaseType).getTypePtr();
5222 }
5223 
GetKeyForMember(ASTContext & Context,CXXCtorInitializer * Member)5224 static const void *GetKeyForMember(ASTContext &Context,
5225                                    CXXCtorInitializer *Member) {
5226   if (!Member->isAnyMemberInitializer())
5227     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5228 
5229   return Member->getAnyMember()->getCanonicalDecl();
5230 }
5231 
DiagnoseBaseOrMemInitializerOrder(Sema & SemaRef,const CXXConstructorDecl * Constructor,ArrayRef<CXXCtorInitializer * > Inits)5232 static void DiagnoseBaseOrMemInitializerOrder(
5233     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5234     ArrayRef<CXXCtorInitializer *> Inits) {
5235   if (Constructor->getDeclContext()->isDependentContext())
5236     return;
5237 
5238   // Don't check initializers order unless the warning is enabled at the
5239   // location of at least one initializer.
5240   bool ShouldCheckOrder = false;
5241   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5242     CXXCtorInitializer *Init = Inits[InitIndex];
5243     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5244                                  Init->getSourceLocation())) {
5245       ShouldCheckOrder = true;
5246       break;
5247     }
5248   }
5249   if (!ShouldCheckOrder)
5250     return;
5251 
5252   // Build the list of bases and members in the order that they'll
5253   // actually be initialized.  The explicit initializers should be in
5254   // this same order but may be missing things.
5255   SmallVector<const void*, 32> IdealInitKeys;
5256 
5257   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5258 
5259   // 1. Virtual bases.
5260   for (const auto &VBase : ClassDecl->vbases())
5261     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5262 
5263   // 2. Non-virtual bases.
5264   for (const auto &Base : ClassDecl->bases()) {
5265     if (Base.isVirtual())
5266       continue;
5267     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5268   }
5269 
5270   // 3. Direct fields.
5271   for (auto *Field : ClassDecl->fields()) {
5272     if (Field->isUnnamedBitfield())
5273       continue;
5274 
5275     PopulateKeysForFields(Field, IdealInitKeys);
5276   }
5277 
5278   unsigned NumIdealInits = IdealInitKeys.size();
5279   unsigned IdealIndex = 0;
5280 
5281   CXXCtorInitializer *PrevInit = nullptr;
5282   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5283     CXXCtorInitializer *Init = Inits[InitIndex];
5284     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5285 
5286     // Scan forward to try to find this initializer in the idealized
5287     // initializers list.
5288     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5289       if (InitKey == IdealInitKeys[IdealIndex])
5290         break;
5291 
5292     // If we didn't find this initializer, it must be because we
5293     // scanned past it on a previous iteration.  That can only
5294     // happen if we're out of order;  emit a warning.
5295     if (IdealIndex == NumIdealInits && PrevInit) {
5296       Sema::SemaDiagnosticBuilder D =
5297         SemaRef.Diag(PrevInit->getSourceLocation(),
5298                      diag::warn_initializer_out_of_order);
5299 
5300       if (PrevInit->isAnyMemberInitializer())
5301         D << 0 << PrevInit->getAnyMember()->getDeclName();
5302       else
5303         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5304 
5305       if (Init->isAnyMemberInitializer())
5306         D << 0 << Init->getAnyMember()->getDeclName();
5307       else
5308         D << 1 << Init->getTypeSourceInfo()->getType();
5309 
5310       // Move back to the initializer's location in the ideal list.
5311       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5312         if (InitKey == IdealInitKeys[IdealIndex])
5313           break;
5314 
5315       assert(IdealIndex < NumIdealInits &&
5316              "initializer not found in initializer list");
5317     }
5318 
5319     PrevInit = Init;
5320   }
5321 }
5322 
5323 namespace {
CheckRedundantInit(Sema & S,CXXCtorInitializer * Init,CXXCtorInitializer * & PrevInit)5324 bool CheckRedundantInit(Sema &S,
5325                         CXXCtorInitializer *Init,
5326                         CXXCtorInitializer *&PrevInit) {
5327   if (!PrevInit) {
5328     PrevInit = Init;
5329     return false;
5330   }
5331 
5332   if (FieldDecl *Field = Init->getAnyMember())
5333     S.Diag(Init->getSourceLocation(),
5334            diag::err_multiple_mem_initialization)
5335       << Field->getDeclName()
5336       << Init->getSourceRange();
5337   else {
5338     const Type *BaseClass = Init->getBaseClass();
5339     assert(BaseClass && "neither field nor base");
5340     S.Diag(Init->getSourceLocation(),
5341            diag::err_multiple_base_initialization)
5342       << QualType(BaseClass, 0)
5343       << Init->getSourceRange();
5344   }
5345   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5346     << 0 << PrevInit->getSourceRange();
5347 
5348   return true;
5349 }
5350 
5351 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5352 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5353 
CheckRedundantUnionInit(Sema & S,CXXCtorInitializer * Init,RedundantUnionMap & Unions)5354 bool CheckRedundantUnionInit(Sema &S,
5355                              CXXCtorInitializer *Init,
5356                              RedundantUnionMap &Unions) {
5357   FieldDecl *Field = Init->getAnyMember();
5358   RecordDecl *Parent = Field->getParent();
5359   NamedDecl *Child = Field;
5360 
5361   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5362     if (Parent->isUnion()) {
5363       UnionEntry &En = Unions[Parent];
5364       if (En.first && En.first != Child) {
5365         S.Diag(Init->getSourceLocation(),
5366                diag::err_multiple_mem_union_initialization)
5367           << Field->getDeclName()
5368           << Init->getSourceRange();
5369         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5370           << 0 << En.second->getSourceRange();
5371         return true;
5372       }
5373       if (!En.first) {
5374         En.first = Child;
5375         En.second = Init;
5376       }
5377       if (!Parent->isAnonymousStructOrUnion())
5378         return false;
5379     }
5380 
5381     Child = Parent;
5382     Parent = cast<RecordDecl>(Parent->getDeclContext());
5383   }
5384 
5385   return false;
5386 }
5387 }
5388 
5389 /// ActOnMemInitializers - Handle the member initializers for a constructor.
ActOnMemInitializers(Decl * ConstructorDecl,SourceLocation ColonLoc,ArrayRef<CXXCtorInitializer * > MemInits,bool AnyErrors)5390 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5391                                 SourceLocation ColonLoc,
5392                                 ArrayRef<CXXCtorInitializer*> MemInits,
5393                                 bool AnyErrors) {
5394   if (!ConstructorDecl)
5395     return;
5396 
5397   AdjustDeclIfTemplate(ConstructorDecl);
5398 
5399   CXXConstructorDecl *Constructor
5400     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5401 
5402   if (!Constructor) {
5403     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5404     return;
5405   }
5406 
5407   // Mapping for the duplicate initializers check.
5408   // For member initializers, this is keyed with a FieldDecl*.
5409   // For base initializers, this is keyed with a Type*.
5410   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5411 
5412   // Mapping for the inconsistent anonymous-union initializers check.
5413   RedundantUnionMap MemberUnions;
5414 
5415   bool HadError = false;
5416   for (unsigned i = 0; i < MemInits.size(); i++) {
5417     CXXCtorInitializer *Init = MemInits[i];
5418 
5419     // Set the source order index.
5420     Init->setSourceOrder(i);
5421 
5422     if (Init->isAnyMemberInitializer()) {
5423       const void *Key = GetKeyForMember(Context, Init);
5424       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5425           CheckRedundantUnionInit(*this, Init, MemberUnions))
5426         HadError = true;
5427     } else if (Init->isBaseInitializer()) {
5428       const void *Key = GetKeyForMember(Context, Init);
5429       if (CheckRedundantInit(*this, Init, Members[Key]))
5430         HadError = true;
5431     } else {
5432       assert(Init->isDelegatingInitializer());
5433       // This must be the only initializer
5434       if (MemInits.size() != 1) {
5435         Diag(Init->getSourceLocation(),
5436              diag::err_delegating_initializer_alone)
5437           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5438         // We will treat this as being the only initializer.
5439       }
5440       SetDelegatingInitializer(Constructor, MemInits[i]);
5441       // Return immediately as the initializer is set.
5442       return;
5443     }
5444   }
5445 
5446   if (HadError)
5447     return;
5448 
5449   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5450 
5451   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5452 
5453   DiagnoseUninitializedFields(*this, Constructor);
5454 }
5455 
5456 void
MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,CXXRecordDecl * ClassDecl)5457 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5458                                              CXXRecordDecl *ClassDecl) {
5459   // Ignore dependent contexts. Also ignore unions, since their members never
5460   // have destructors implicitly called.
5461   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5462     return;
5463 
5464   // FIXME: all the access-control diagnostics are positioned on the
5465   // field/base declaration.  That's probably good; that said, the
5466   // user might reasonably want to know why the destructor is being
5467   // emitted, and we currently don't say.
5468 
5469   // Non-static data members.
5470   for (auto *Field : ClassDecl->fields()) {
5471     if (Field->isInvalidDecl())
5472       continue;
5473 
5474     // Don't destroy incomplete or zero-length arrays.
5475     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5476       continue;
5477 
5478     QualType FieldType = Context.getBaseElementType(Field->getType());
5479 
5480     const RecordType* RT = FieldType->getAs<RecordType>();
5481     if (!RT)
5482       continue;
5483 
5484     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5485     if (FieldClassDecl->isInvalidDecl())
5486       continue;
5487     if (FieldClassDecl->hasIrrelevantDestructor())
5488       continue;
5489     // The destructor for an implicit anonymous union member is never invoked.
5490     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5491       continue;
5492 
5493     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5494     assert(Dtor && "No dtor found for FieldClassDecl!");
5495     CheckDestructorAccess(Field->getLocation(), Dtor,
5496                           PDiag(diag::err_access_dtor_field)
5497                             << Field->getDeclName()
5498                             << FieldType);
5499 
5500     MarkFunctionReferenced(Location, Dtor);
5501     DiagnoseUseOfDecl(Dtor, Location);
5502   }
5503 
5504   // We only potentially invoke the destructors of potentially constructed
5505   // subobjects.
5506   bool VisitVirtualBases = !ClassDecl->isAbstract();
5507 
5508   // If the destructor exists and has already been marked used in the MS ABI,
5509   // then virtual base destructors have already been checked and marked used.
5510   // Skip checking them again to avoid duplicate diagnostics.
5511   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5512     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5513     if (Dtor && Dtor->isUsed())
5514       VisitVirtualBases = false;
5515   }
5516 
5517   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5518 
5519   // Bases.
5520   for (const auto &Base : ClassDecl->bases()) {
5521     // Bases are always records in a well-formed non-dependent class.
5522     const RecordType *RT = Base.getType()->getAs<RecordType>();
5523 
5524     // Remember direct virtual bases.
5525     if (Base.isVirtual()) {
5526       if (!VisitVirtualBases)
5527         continue;
5528       DirectVirtualBases.insert(RT);
5529     }
5530 
5531     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5532     // If our base class is invalid, we probably can't get its dtor anyway.
5533     if (BaseClassDecl->isInvalidDecl())
5534       continue;
5535     if (BaseClassDecl->hasIrrelevantDestructor())
5536       continue;
5537 
5538     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5539     assert(Dtor && "No dtor found for BaseClassDecl!");
5540 
5541     // FIXME: caret should be on the start of the class name
5542     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5543                           PDiag(diag::err_access_dtor_base)
5544                               << Base.getType() << Base.getSourceRange(),
5545                           Context.getTypeDeclType(ClassDecl));
5546 
5547     MarkFunctionReferenced(Location, Dtor);
5548     DiagnoseUseOfDecl(Dtor, Location);
5549   }
5550 
5551   if (VisitVirtualBases)
5552     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5553                                          &DirectVirtualBases);
5554 }
5555 
MarkVirtualBaseDestructorsReferenced(SourceLocation Location,CXXRecordDecl * ClassDecl,llvm::SmallPtrSetImpl<const RecordType * > * DirectVirtualBases)5556 void Sema::MarkVirtualBaseDestructorsReferenced(
5557     SourceLocation Location, CXXRecordDecl *ClassDecl,
5558     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5559   // Virtual bases.
5560   for (const auto &VBase : ClassDecl->vbases()) {
5561     // Bases are always records in a well-formed non-dependent class.
5562     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5563 
5564     // Ignore already visited direct virtual bases.
5565     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5566       continue;
5567 
5568     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5569     // If our base class is invalid, we probably can't get its dtor anyway.
5570     if (BaseClassDecl->isInvalidDecl())
5571       continue;
5572     if (BaseClassDecl->hasIrrelevantDestructor())
5573       continue;
5574 
5575     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5576     assert(Dtor && "No dtor found for BaseClassDecl!");
5577     if (CheckDestructorAccess(
5578             ClassDecl->getLocation(), Dtor,
5579             PDiag(diag::err_access_dtor_vbase)
5580                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5581             Context.getTypeDeclType(ClassDecl)) ==
5582         AR_accessible) {
5583       CheckDerivedToBaseConversion(
5584           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5585           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5586           SourceRange(), DeclarationName(), nullptr);
5587     }
5588 
5589     MarkFunctionReferenced(Location, Dtor);
5590     DiagnoseUseOfDecl(Dtor, Location);
5591   }
5592 }
5593 
ActOnDefaultCtorInitializers(Decl * CDtorDecl)5594 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5595   if (!CDtorDecl)
5596     return;
5597 
5598   if (CXXConstructorDecl *Constructor
5599       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5600     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5601     DiagnoseUninitializedFields(*this, Constructor);
5602   }
5603 }
5604 
isAbstractType(SourceLocation Loc,QualType T)5605 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5606   if (!getLangOpts().CPlusPlus)
5607     return false;
5608 
5609   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5610   if (!RD)
5611     return false;
5612 
5613   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5614   // class template specialization here, but doing so breaks a lot of code.
5615 
5616   // We can't answer whether something is abstract until it has a
5617   // definition. If it's currently being defined, we'll walk back
5618   // over all the declarations when we have a full definition.
5619   const CXXRecordDecl *Def = RD->getDefinition();
5620   if (!Def || Def->isBeingDefined())
5621     return false;
5622 
5623   return RD->isAbstract();
5624 }
5625 
RequireNonAbstractType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)5626 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5627                                   TypeDiagnoser &Diagnoser) {
5628   if (!isAbstractType(Loc, T))
5629     return false;
5630 
5631   T = Context.getBaseElementType(T);
5632   Diagnoser.diagnose(*this, Loc, T);
5633   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5634   return true;
5635 }
5636 
DiagnoseAbstractType(const CXXRecordDecl * RD)5637 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5638   // Check if we've already emitted the list of pure virtual functions
5639   // for this class.
5640   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5641     return;
5642 
5643   // If the diagnostic is suppressed, don't emit the notes. We're only
5644   // going to emit them once, so try to attach them to a diagnostic we're
5645   // actually going to show.
5646   if (Diags.isLastDiagnosticIgnored())
5647     return;
5648 
5649   CXXFinalOverriderMap FinalOverriders;
5650   RD->getFinalOverriders(FinalOverriders);
5651 
5652   // Keep a set of seen pure methods so we won't diagnose the same method
5653   // more than once.
5654   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5655 
5656   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5657                                    MEnd = FinalOverriders.end();
5658        M != MEnd;
5659        ++M) {
5660     for (OverridingMethods::iterator SO = M->second.begin(),
5661                                   SOEnd = M->second.end();
5662          SO != SOEnd; ++SO) {
5663       // C++ [class.abstract]p4:
5664       //   A class is abstract if it contains or inherits at least one
5665       //   pure virtual function for which the final overrider is pure
5666       //   virtual.
5667 
5668       //
5669       if (SO->second.size() != 1)
5670         continue;
5671 
5672       if (!SO->second.front().Method->isPure())
5673         continue;
5674 
5675       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5676         continue;
5677 
5678       Diag(SO->second.front().Method->getLocation(),
5679            diag::note_pure_virtual_function)
5680         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5681     }
5682   }
5683 
5684   if (!PureVirtualClassDiagSet)
5685     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5686   PureVirtualClassDiagSet->insert(RD);
5687 }
5688 
5689 namespace {
5690 struct AbstractUsageInfo {
5691   Sema &S;
5692   CXXRecordDecl *Record;
5693   CanQualType AbstractType;
5694   bool Invalid;
5695 
AbstractUsageInfo__anonedc74bd71411::AbstractUsageInfo5696   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5697     : S(S), Record(Record),
5698       AbstractType(S.Context.getCanonicalType(
5699                    S.Context.getTypeDeclType(Record))),
5700       Invalid(false) {}
5701 
DiagnoseAbstractType__anonedc74bd71411::AbstractUsageInfo5702   void DiagnoseAbstractType() {
5703     if (Invalid) return;
5704     S.DiagnoseAbstractType(Record);
5705     Invalid = true;
5706   }
5707 
5708   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5709 };
5710 
5711 struct CheckAbstractUsage {
5712   AbstractUsageInfo &Info;
5713   const NamedDecl *Ctx;
5714 
CheckAbstractUsage__anonedc74bd71411::CheckAbstractUsage5715   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5716     : Info(Info), Ctx(Ctx) {}
5717 
Visit__anonedc74bd71411::CheckAbstractUsage5718   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5719     switch (TL.getTypeLocClass()) {
5720 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5721 #define TYPELOC(CLASS, PARENT) \
5722     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5723 #include "clang/AST/TypeLocNodes.def"
5724     }
5725   }
5726 
Check__anonedc74bd71411::CheckAbstractUsage5727   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5728     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5729     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5730       if (!TL.getParam(I))
5731         continue;
5732 
5733       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5734       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5735     }
5736   }
5737 
Check__anonedc74bd71411::CheckAbstractUsage5738   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5739     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5740   }
5741 
Check__anonedc74bd71411::CheckAbstractUsage5742   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5743     // Visit the type parameters from a permissive context.
5744     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5745       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5746       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5747         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5748           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5749       // TODO: other template argument types?
5750     }
5751   }
5752 
5753   // Visit pointee types from a permissive context.
5754 #define CheckPolymorphic(Type) \
5755   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5756     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5757   }
5758   CheckPolymorphic(PointerTypeLoc)
CheckPolymorphic__anonedc74bd71411::CheckAbstractUsage5759   CheckPolymorphic(ReferenceTypeLoc)
5760   CheckPolymorphic(MemberPointerTypeLoc)
5761   CheckPolymorphic(BlockPointerTypeLoc)
5762   CheckPolymorphic(AtomicTypeLoc)
5763 
5764   /// Handle all the types we haven't given a more specific
5765   /// implementation for above.
5766   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5767     // Every other kind of type that we haven't called out already
5768     // that has an inner type is either (1) sugar or (2) contains that
5769     // inner type in some way as a subobject.
5770     if (TypeLoc Next = TL.getNextTypeLoc())
5771       return Visit(Next, Sel);
5772 
5773     // If there's no inner type and we're in a permissive context,
5774     // don't diagnose.
5775     if (Sel == Sema::AbstractNone) return;
5776 
5777     // Check whether the type matches the abstract type.
5778     QualType T = TL.getType();
5779     if (T->isArrayType()) {
5780       Sel = Sema::AbstractArrayType;
5781       T = Info.S.Context.getBaseElementType(T);
5782     }
5783     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5784     if (CT != Info.AbstractType) return;
5785 
5786     // It matched; do some magic.
5787     if (Sel == Sema::AbstractArrayType) {
5788       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5789         << T << TL.getSourceRange();
5790     } else {
5791       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5792         << Sel << T << TL.getSourceRange();
5793     }
5794     Info.DiagnoseAbstractType();
5795   }
5796 };
5797 
CheckType(const NamedDecl * D,TypeLoc TL,Sema::AbstractDiagSelID Sel)5798 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5799                                   Sema::AbstractDiagSelID Sel) {
5800   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5801 }
5802 
5803 }
5804 
5805 /// Check for invalid uses of an abstract type in a method declaration.
CheckAbstractClassUsage(AbstractUsageInfo & Info,CXXMethodDecl * MD)5806 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5807                                     CXXMethodDecl *MD) {
5808   // No need to do the check on definitions, which require that
5809   // the return/param types be complete.
5810   if (MD->doesThisDeclarationHaveABody())
5811     return;
5812 
5813   // For safety's sake, just ignore it if we don't have type source
5814   // information.  This should never happen for non-implicit methods,
5815   // but...
5816   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5817     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5818 }
5819 
5820 /// Check for invalid uses of an abstract type within a class definition.
CheckAbstractClassUsage(AbstractUsageInfo & Info,CXXRecordDecl * RD)5821 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5822                                     CXXRecordDecl *RD) {
5823   for (auto *D : RD->decls()) {
5824     if (D->isImplicit()) continue;
5825 
5826     // Methods and method templates.
5827     if (isa<CXXMethodDecl>(D)) {
5828       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5829     } else if (isa<FunctionTemplateDecl>(D)) {
5830       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5831       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5832 
5833     // Fields and static variables.
5834     } else if (isa<FieldDecl>(D)) {
5835       FieldDecl *FD = cast<FieldDecl>(D);
5836       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5837         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5838     } else if (isa<VarDecl>(D)) {
5839       VarDecl *VD = cast<VarDecl>(D);
5840       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5841         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5842 
5843     // Nested classes and class templates.
5844     } else if (isa<CXXRecordDecl>(D)) {
5845       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5846     } else if (isa<ClassTemplateDecl>(D)) {
5847       CheckAbstractClassUsage(Info,
5848                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5849     }
5850   }
5851 }
5852 
ReferenceDllExportedMembers(Sema & S,CXXRecordDecl * Class)5853 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5854   Attr *ClassAttr = getDLLAttr(Class);
5855   if (!ClassAttr)
5856     return;
5857 
5858   assert(ClassAttr->getKind() == attr::DLLExport);
5859 
5860   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5861 
5862   if (TSK == TSK_ExplicitInstantiationDeclaration)
5863     // Don't go any further if this is just an explicit instantiation
5864     // declaration.
5865     return;
5866 
5867   // Add a context note to explain how we got to any diagnostics produced below.
5868   struct MarkingClassDllexported {
5869     Sema &S;
5870     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5871                             SourceLocation AttrLoc)
5872         : S(S) {
5873       Sema::CodeSynthesisContext Ctx;
5874       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5875       Ctx.PointOfInstantiation = AttrLoc;
5876       Ctx.Entity = Class;
5877       S.pushCodeSynthesisContext(Ctx);
5878     }
5879     ~MarkingClassDllexported() {
5880       S.popCodeSynthesisContext();
5881     }
5882   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5883 
5884   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5885     S.MarkVTableUsed(Class->getLocation(), Class, true);
5886 
5887   for (Decl *Member : Class->decls()) {
5888     // Defined static variables that are members of an exported base
5889     // class must be marked export too.
5890     auto *VD = dyn_cast<VarDecl>(Member);
5891     if (VD && Member->getAttr<DLLExportAttr>() &&
5892         VD->getStorageClass() == SC_Static &&
5893         TSK == TSK_ImplicitInstantiation)
5894       S.MarkVariableReferenced(VD->getLocation(), VD);
5895 
5896     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5897     if (!MD)
5898       continue;
5899 
5900     if (Member->getAttr<DLLExportAttr>()) {
5901       if (MD->isUserProvided()) {
5902         // Instantiate non-default class member functions ...
5903 
5904         // .. except for certain kinds of template specializations.
5905         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5906           continue;
5907 
5908         S.MarkFunctionReferenced(Class->getLocation(), MD);
5909 
5910         // The function will be passed to the consumer when its definition is
5911         // encountered.
5912       } else if (MD->isExplicitlyDefaulted()) {
5913         // Synthesize and instantiate explicitly defaulted methods.
5914         S.MarkFunctionReferenced(Class->getLocation(), MD);
5915 
5916         if (TSK != TSK_ExplicitInstantiationDefinition) {
5917           // Except for explicit instantiation defs, we will not see the
5918           // definition again later, so pass it to the consumer now.
5919           S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5920         }
5921       } else if (!MD->isTrivial() ||
5922                  MD->isCopyAssignmentOperator() ||
5923                  MD->isMoveAssignmentOperator()) {
5924         // Synthesize and instantiate non-trivial implicit methods, and the copy
5925         // and move assignment operators. The latter are exported even if they
5926         // are trivial, because the address of an operator can be taken and
5927         // should compare equal across libraries.
5928         S.MarkFunctionReferenced(Class->getLocation(), MD);
5929 
5930         // There is no later point when we will see the definition of this
5931         // function, so pass it to the consumer now.
5932         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5933       }
5934     }
5935   }
5936 }
5937 
checkForMultipleExportedDefaultConstructors(Sema & S,CXXRecordDecl * Class)5938 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5939                                                         CXXRecordDecl *Class) {
5940   // Only the MS ABI has default constructor closures, so we don't need to do
5941   // this semantic checking anywhere else.
5942   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5943     return;
5944 
5945   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5946   for (Decl *Member : Class->decls()) {
5947     // Look for exported default constructors.
5948     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5949     if (!CD || !CD->isDefaultConstructor())
5950       continue;
5951     auto *Attr = CD->getAttr<DLLExportAttr>();
5952     if (!Attr)
5953       continue;
5954 
5955     // If the class is non-dependent, mark the default arguments as ODR-used so
5956     // that we can properly codegen the constructor closure.
5957     if (!Class->isDependentContext()) {
5958       for (ParmVarDecl *PD : CD->parameters()) {
5959         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5960         S.DiscardCleanupsInEvaluationContext();
5961       }
5962     }
5963 
5964     if (LastExportedDefaultCtor) {
5965       S.Diag(LastExportedDefaultCtor->getLocation(),
5966              diag::err_attribute_dll_ambiguous_default_ctor)
5967           << Class;
5968       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5969           << CD->getDeclName();
5970       return;
5971     }
5972     LastExportedDefaultCtor = CD;
5973   }
5974 }
5975 
checkCUDADeviceBuiltinSurfaceClassTemplate(Sema & S,CXXRecordDecl * Class)5976 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
5977                                                        CXXRecordDecl *Class) {
5978   bool ErrorReported = false;
5979   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5980                                                      ClassTemplateDecl *TD) {
5981     if (ErrorReported)
5982       return;
5983     S.Diag(TD->getLocation(),
5984            diag::err_cuda_device_builtin_surftex_cls_template)
5985         << /*surface*/ 0 << TD;
5986     ErrorReported = true;
5987   };
5988 
5989   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5990   if (!TD) {
5991     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5992     if (!SD) {
5993       S.Diag(Class->getLocation(),
5994              diag::err_cuda_device_builtin_surftex_ref_decl)
5995           << /*surface*/ 0 << Class;
5996       S.Diag(Class->getLocation(),
5997              diag::note_cuda_device_builtin_surftex_should_be_template_class)
5998           << Class;
5999       return;
6000     }
6001     TD = SD->getSpecializedTemplate();
6002   }
6003 
6004   TemplateParameterList *Params = TD->getTemplateParameters();
6005   unsigned N = Params->size();
6006 
6007   if (N != 2) {
6008     reportIllegalClassTemplate(S, TD);
6009     S.Diag(TD->getLocation(),
6010            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6011         << TD << 2;
6012   }
6013   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6014     reportIllegalClassTemplate(S, TD);
6015     S.Diag(TD->getLocation(),
6016            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6017         << TD << /*1st*/ 0 << /*type*/ 0;
6018   }
6019   if (N > 1) {
6020     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6021     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6022       reportIllegalClassTemplate(S, TD);
6023       S.Diag(TD->getLocation(),
6024              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6025           << TD << /*2nd*/ 1 << /*integer*/ 1;
6026     }
6027   }
6028 }
6029 
checkCUDADeviceBuiltinTextureClassTemplate(Sema & S,CXXRecordDecl * Class)6030 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6031                                                        CXXRecordDecl *Class) {
6032   bool ErrorReported = false;
6033   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6034                                                      ClassTemplateDecl *TD) {
6035     if (ErrorReported)
6036       return;
6037     S.Diag(TD->getLocation(),
6038            diag::err_cuda_device_builtin_surftex_cls_template)
6039         << /*texture*/ 1 << TD;
6040     ErrorReported = true;
6041   };
6042 
6043   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6044   if (!TD) {
6045     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6046     if (!SD) {
6047       S.Diag(Class->getLocation(),
6048              diag::err_cuda_device_builtin_surftex_ref_decl)
6049           << /*texture*/ 1 << Class;
6050       S.Diag(Class->getLocation(),
6051              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6052           << Class;
6053       return;
6054     }
6055     TD = SD->getSpecializedTemplate();
6056   }
6057 
6058   TemplateParameterList *Params = TD->getTemplateParameters();
6059   unsigned N = Params->size();
6060 
6061   if (N != 3) {
6062     reportIllegalClassTemplate(S, TD);
6063     S.Diag(TD->getLocation(),
6064            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6065         << TD << 3;
6066   }
6067   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6068     reportIllegalClassTemplate(S, TD);
6069     S.Diag(TD->getLocation(),
6070            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6071         << TD << /*1st*/ 0 << /*type*/ 0;
6072   }
6073   if (N > 1) {
6074     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6075     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6076       reportIllegalClassTemplate(S, TD);
6077       S.Diag(TD->getLocation(),
6078              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6079           << TD << /*2nd*/ 1 << /*integer*/ 1;
6080     }
6081   }
6082   if (N > 2) {
6083     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6084     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6085       reportIllegalClassTemplate(S, TD);
6086       S.Diag(TD->getLocation(),
6087              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6088           << TD << /*3rd*/ 2 << /*integer*/ 1;
6089     }
6090   }
6091 }
6092 
checkClassLevelCodeSegAttribute(CXXRecordDecl * Class)6093 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6094   // Mark any compiler-generated routines with the implicit code_seg attribute.
6095   for (auto *Method : Class->methods()) {
6096     if (Method->isUserProvided())
6097       continue;
6098     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6099       Method->addAttr(A);
6100   }
6101 }
6102 
6103 /// Check class-level dllimport/dllexport attribute.
checkClassLevelDLLAttribute(CXXRecordDecl * Class)6104 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6105   Attr *ClassAttr = getDLLAttr(Class);
6106 
6107   // MSVC inherits DLL attributes to partial class template specializations.
6108   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6109     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6110       if (Attr *TemplateAttr =
6111               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6112         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6113         A->setInherited(true);
6114         ClassAttr = A;
6115       }
6116     }
6117   }
6118 
6119   if (!ClassAttr)
6120     return;
6121 
6122   if (!Class->isExternallyVisible()) {
6123     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6124         << Class << ClassAttr;
6125     return;
6126   }
6127 
6128   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6129       !ClassAttr->isInherited()) {
6130     // Diagnose dll attributes on members of class with dll attribute.
6131     for (Decl *Member : Class->decls()) {
6132       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6133         continue;
6134       InheritableAttr *MemberAttr = getDLLAttr(Member);
6135       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6136         continue;
6137 
6138       Diag(MemberAttr->getLocation(),
6139              diag::err_attribute_dll_member_of_dll_class)
6140           << MemberAttr << ClassAttr;
6141       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6142       Member->setInvalidDecl();
6143     }
6144   }
6145 
6146   if (Class->getDescribedClassTemplate())
6147     // Don't inherit dll attribute until the template is instantiated.
6148     return;
6149 
6150   // The class is either imported or exported.
6151   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6152 
6153   // Check if this was a dllimport attribute propagated from a derived class to
6154   // a base class template specialization. We don't apply these attributes to
6155   // static data members.
6156   const bool PropagatedImport =
6157       !ClassExported &&
6158       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6159 
6160   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6161 
6162   // Ignore explicit dllexport on explicit class template instantiation
6163   // declarations, except in MinGW mode.
6164   if (ClassExported && !ClassAttr->isInherited() &&
6165       TSK == TSK_ExplicitInstantiationDeclaration &&
6166       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6167     Class->dropAttr<DLLExportAttr>();
6168     return;
6169   }
6170 
6171   // Force declaration of implicit members so they can inherit the attribute.
6172   ForceDeclarationOfImplicitMembers(Class);
6173 
6174   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6175   // seem to be true in practice?
6176 
6177   for (Decl *Member : Class->decls()) {
6178     VarDecl *VD = dyn_cast<VarDecl>(Member);
6179     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6180 
6181     // Only methods and static fields inherit the attributes.
6182     if (!VD && !MD)
6183       continue;
6184 
6185     if (MD) {
6186       // Don't process deleted methods.
6187       if (MD->isDeleted())
6188         continue;
6189 
6190       if (MD->isInlined()) {
6191         // MinGW does not import or export inline methods. But do it for
6192         // template instantiations.
6193         if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6194             TSK != TSK_ExplicitInstantiationDeclaration &&
6195             TSK != TSK_ExplicitInstantiationDefinition)
6196           continue;
6197 
6198         // MSVC versions before 2015 don't export the move assignment operators
6199         // and move constructor, so don't attempt to import/export them if
6200         // we have a definition.
6201         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6202         if ((MD->isMoveAssignmentOperator() ||
6203              (Ctor && Ctor->isMoveConstructor())) &&
6204             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6205           continue;
6206 
6207         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6208         // operator is exported anyway.
6209         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6210             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6211           continue;
6212       }
6213     }
6214 
6215     // Don't apply dllimport attributes to static data members of class template
6216     // instantiations when the attribute is propagated from a derived class.
6217     if (VD && PropagatedImport)
6218       continue;
6219 
6220     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6221       continue;
6222 
6223     if (!getDLLAttr(Member)) {
6224       InheritableAttr *NewAttr = nullptr;
6225 
6226       // Do not export/import inline function when -fno-dllexport-inlines is
6227       // passed. But add attribute for later local static var check.
6228       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6229           TSK != TSK_ExplicitInstantiationDeclaration &&
6230           TSK != TSK_ExplicitInstantiationDefinition) {
6231         if (ClassExported) {
6232           NewAttr = ::new (getASTContext())
6233               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6234         } else {
6235           NewAttr = ::new (getASTContext())
6236               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6237         }
6238       } else {
6239         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6240       }
6241 
6242       NewAttr->setInherited(true);
6243       Member->addAttr(NewAttr);
6244 
6245       if (MD) {
6246         // Propagate DLLAttr to friend re-declarations of MD that have already
6247         // been constructed.
6248         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6249              FD = FD->getPreviousDecl()) {
6250           if (FD->getFriendObjectKind() == Decl::FOK_None)
6251             continue;
6252           assert(!getDLLAttr(FD) &&
6253                  "friend re-decl should not already have a DLLAttr");
6254           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6255           NewAttr->setInherited(true);
6256           FD->addAttr(NewAttr);
6257         }
6258       }
6259     }
6260   }
6261 
6262   if (ClassExported)
6263     DelayedDllExportClasses.push_back(Class);
6264 }
6265 
6266 /// Perform propagation of DLL attributes from a derived class to a
6267 /// templated base class for MS compatibility.
propagateDLLAttrToBaseClassTemplate(CXXRecordDecl * Class,Attr * ClassAttr,ClassTemplateSpecializationDecl * BaseTemplateSpec,SourceLocation BaseLoc)6268 void Sema::propagateDLLAttrToBaseClassTemplate(
6269     CXXRecordDecl *Class, Attr *ClassAttr,
6270     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6271   if (getDLLAttr(
6272           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6273     // If the base class template has a DLL attribute, don't try to change it.
6274     return;
6275   }
6276 
6277   auto TSK = BaseTemplateSpec->getSpecializationKind();
6278   if (!getDLLAttr(BaseTemplateSpec) &&
6279       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6280        TSK == TSK_ImplicitInstantiation)) {
6281     // The template hasn't been instantiated yet (or it has, but only as an
6282     // explicit instantiation declaration or implicit instantiation, which means
6283     // we haven't codegenned any members yet), so propagate the attribute.
6284     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6285     NewAttr->setInherited(true);
6286     BaseTemplateSpec->addAttr(NewAttr);
6287 
6288     // If this was an import, mark that we propagated it from a derived class to
6289     // a base class template specialization.
6290     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6291       ImportAttr->setPropagatedToBaseTemplate();
6292 
6293     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6294     // needs to be run again to work see the new attribute. Otherwise this will
6295     // get run whenever the template is instantiated.
6296     if (TSK != TSK_Undeclared)
6297       checkClassLevelDLLAttribute(BaseTemplateSpec);
6298 
6299     return;
6300   }
6301 
6302   if (getDLLAttr(BaseTemplateSpec)) {
6303     // The template has already been specialized or instantiated with an
6304     // attribute, explicitly or through propagation. We should not try to change
6305     // it.
6306     return;
6307   }
6308 
6309   // The template was previously instantiated or explicitly specialized without
6310   // a dll attribute, It's too late for us to add an attribute, so warn that
6311   // this is unsupported.
6312   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6313       << BaseTemplateSpec->isExplicitSpecialization();
6314   Diag(ClassAttr->getLocation(), diag::note_attribute);
6315   if (BaseTemplateSpec->isExplicitSpecialization()) {
6316     Diag(BaseTemplateSpec->getLocation(),
6317            diag::note_template_class_explicit_specialization_was_here)
6318         << BaseTemplateSpec;
6319   } else {
6320     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6321            diag::note_template_class_instantiation_was_here)
6322         << BaseTemplateSpec;
6323   }
6324 }
6325 
6326 /// Determine the kind of defaulting that would be done for a given function.
6327 ///
6328 /// If the function is both a default constructor and a copy / move constructor
6329 /// (due to having a default argument for the first parameter), this picks
6330 /// CXXDefaultConstructor.
6331 ///
6332 /// FIXME: Check that case is properly handled by all callers.
6333 Sema::DefaultedFunctionKind
getDefaultedFunctionKind(const FunctionDecl * FD)6334 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6335   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6336     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6337       if (Ctor->isDefaultConstructor())
6338         return Sema::CXXDefaultConstructor;
6339 
6340       if (Ctor->isCopyConstructor())
6341         return Sema::CXXCopyConstructor;
6342 
6343       if (Ctor->isMoveConstructor())
6344         return Sema::CXXMoveConstructor;
6345     }
6346 
6347     if (MD->isCopyAssignmentOperator())
6348       return Sema::CXXCopyAssignment;
6349 
6350     if (MD->isMoveAssignmentOperator())
6351       return Sema::CXXMoveAssignment;
6352 
6353     if (isa<CXXDestructorDecl>(FD))
6354       return Sema::CXXDestructor;
6355   }
6356 
6357   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6358   case OO_EqualEqual:
6359     return DefaultedComparisonKind::Equal;
6360 
6361   case OO_ExclaimEqual:
6362     return DefaultedComparisonKind::NotEqual;
6363 
6364   case OO_Spaceship:
6365     // No point allowing this if <=> doesn't exist in the current language mode.
6366     if (!getLangOpts().CPlusPlus20)
6367       break;
6368     return DefaultedComparisonKind::ThreeWay;
6369 
6370   case OO_Less:
6371   case OO_LessEqual:
6372   case OO_Greater:
6373   case OO_GreaterEqual:
6374     // No point allowing this if <=> doesn't exist in the current language mode.
6375     if (!getLangOpts().CPlusPlus20)
6376       break;
6377     return DefaultedComparisonKind::Relational;
6378 
6379   default:
6380     break;
6381   }
6382 
6383   // Not defaultable.
6384   return DefaultedFunctionKind();
6385 }
6386 
DefineDefaultedFunction(Sema & S,FunctionDecl * FD,SourceLocation DefaultLoc)6387 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6388                                     SourceLocation DefaultLoc) {
6389   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6390   if (DFK.isComparison())
6391     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6392 
6393   switch (DFK.asSpecialMember()) {
6394   case Sema::CXXDefaultConstructor:
6395     S.DefineImplicitDefaultConstructor(DefaultLoc,
6396                                        cast<CXXConstructorDecl>(FD));
6397     break;
6398   case Sema::CXXCopyConstructor:
6399     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6400     break;
6401   case Sema::CXXCopyAssignment:
6402     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6403     break;
6404   case Sema::CXXDestructor:
6405     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6406     break;
6407   case Sema::CXXMoveConstructor:
6408     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6409     break;
6410   case Sema::CXXMoveAssignment:
6411     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6412     break;
6413   case Sema::CXXInvalid:
6414     llvm_unreachable("Invalid special member.");
6415   }
6416 }
6417 
6418 /// Determine whether a type is permitted to be passed or returned in
6419 /// registers, per C++ [class.temporary]p3.
canPassInRegisters(Sema & S,CXXRecordDecl * D,TargetInfo::CallingConvKind CCK)6420 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6421                                TargetInfo::CallingConvKind CCK) {
6422   if (D->isDependentType() || D->isInvalidDecl())
6423     return false;
6424 
6425   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6426   // The PS4 platform ABI follows the behavior of Clang 3.2.
6427   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6428     return !D->hasNonTrivialDestructorForCall() &&
6429            !D->hasNonTrivialCopyConstructorForCall();
6430 
6431   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6432     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6433     bool DtorIsTrivialForCall = false;
6434 
6435     // If a class has at least one non-deleted, trivial copy constructor, it
6436     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6437     //
6438     // Note: This permits classes with non-trivial copy or move ctors to be
6439     // passed in registers, so long as they *also* have a trivial copy ctor,
6440     // which is non-conforming.
6441     if (D->needsImplicitCopyConstructor()) {
6442       if (!D->defaultedCopyConstructorIsDeleted()) {
6443         if (D->hasTrivialCopyConstructor())
6444           CopyCtorIsTrivial = true;
6445         if (D->hasTrivialCopyConstructorForCall())
6446           CopyCtorIsTrivialForCall = true;
6447       }
6448     } else {
6449       for (const CXXConstructorDecl *CD : D->ctors()) {
6450         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6451           if (CD->isTrivial())
6452             CopyCtorIsTrivial = true;
6453           if (CD->isTrivialForCall())
6454             CopyCtorIsTrivialForCall = true;
6455         }
6456       }
6457     }
6458 
6459     if (D->needsImplicitDestructor()) {
6460       if (!D->defaultedDestructorIsDeleted() &&
6461           D->hasTrivialDestructorForCall())
6462         DtorIsTrivialForCall = true;
6463     } else if (const auto *DD = D->getDestructor()) {
6464       if (!DD->isDeleted() && DD->isTrivialForCall())
6465         DtorIsTrivialForCall = true;
6466     }
6467 
6468     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6469     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6470       return true;
6471 
6472     // If a class has a destructor, we'd really like to pass it indirectly
6473     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6474     // impossible for small types, which it will pass in a single register or
6475     // stack slot. Most objects with dtors are large-ish, so handle that early.
6476     // We can't call out all large objects as being indirect because there are
6477     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6478     // how we pass large POD types.
6479 
6480     // Note: This permits small classes with nontrivial destructors to be
6481     // passed in registers, which is non-conforming.
6482     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6483     uint64_t TypeSize = isAArch64 ? 128 : 64;
6484 
6485     if (CopyCtorIsTrivial &&
6486         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6487       return true;
6488     return false;
6489   }
6490 
6491   // Per C++ [class.temporary]p3, the relevant condition is:
6492   //   each copy constructor, move constructor, and destructor of X is
6493   //   either trivial or deleted, and X has at least one non-deleted copy
6494   //   or move constructor
6495   bool HasNonDeletedCopyOrMove = false;
6496 
6497   if (D->needsImplicitCopyConstructor() &&
6498       !D->defaultedCopyConstructorIsDeleted()) {
6499     if (!D->hasTrivialCopyConstructorForCall())
6500       return false;
6501     HasNonDeletedCopyOrMove = true;
6502   }
6503 
6504   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6505       !D->defaultedMoveConstructorIsDeleted()) {
6506     if (!D->hasTrivialMoveConstructorForCall())
6507       return false;
6508     HasNonDeletedCopyOrMove = true;
6509   }
6510 
6511   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6512       !D->hasTrivialDestructorForCall())
6513     return false;
6514 
6515   for (const CXXMethodDecl *MD : D->methods()) {
6516     if (MD->isDeleted())
6517       continue;
6518 
6519     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6520     if (CD && CD->isCopyOrMoveConstructor())
6521       HasNonDeletedCopyOrMove = true;
6522     else if (!isa<CXXDestructorDecl>(MD))
6523       continue;
6524 
6525     if (!MD->isTrivialForCall())
6526       return false;
6527   }
6528 
6529   return HasNonDeletedCopyOrMove;
6530 }
6531 
6532 /// Report an error regarding overriding, along with any relevant
6533 /// overridden methods.
6534 ///
6535 /// \param DiagID the primary error to report.
6536 /// \param MD the overriding method.
6537 static bool
ReportOverrides(Sema & S,unsigned DiagID,const CXXMethodDecl * MD,llvm::function_ref<bool (const CXXMethodDecl *)> Report)6538 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6539                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6540   bool IssuedDiagnostic = false;
6541   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6542     if (Report(O)) {
6543       if (!IssuedDiagnostic) {
6544         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6545         IssuedDiagnostic = true;
6546       }
6547       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6548     }
6549   }
6550   return IssuedDiagnostic;
6551 }
6552 
6553 /// Perform semantic checks on a class definition that has been
6554 /// completing, introducing implicitly-declared members, checking for
6555 /// abstract types, etc.
6556 ///
6557 /// \param S The scope in which the class was parsed. Null if we didn't just
6558 ///        parse a class definition.
6559 /// \param Record The completed class.
CheckCompletedCXXClass(Scope * S,CXXRecordDecl * Record)6560 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6561   if (!Record)
6562     return;
6563 
6564   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6565     AbstractUsageInfo Info(*this, Record);
6566     CheckAbstractClassUsage(Info, Record);
6567   }
6568 
6569   // If this is not an aggregate type and has no user-declared constructor,
6570   // complain about any non-static data members of reference or const scalar
6571   // type, since they will never get initializers.
6572   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6573       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6574       !Record->isLambda()) {
6575     bool Complained = false;
6576     for (const auto *F : Record->fields()) {
6577       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6578         continue;
6579 
6580       if (F->getType()->isReferenceType() ||
6581           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6582         if (!Complained) {
6583           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6584             << Record->getTagKind() << Record;
6585           Complained = true;
6586         }
6587 
6588         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6589           << F->getType()->isReferenceType()
6590           << F->getDeclName();
6591       }
6592     }
6593   }
6594 
6595   if (Record->getIdentifier()) {
6596     // C++ [class.mem]p13:
6597     //   If T is the name of a class, then each of the following shall have a
6598     //   name different from T:
6599     //     - every member of every anonymous union that is a member of class T.
6600     //
6601     // C++ [class.mem]p14:
6602     //   In addition, if class T has a user-declared constructor (12.1), every
6603     //   non-static data member of class T shall have a name different from T.
6604     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6605     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6606          ++I) {
6607       NamedDecl *D = (*I)->getUnderlyingDecl();
6608       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6609            Record->hasUserDeclaredConstructor()) ||
6610           isa<IndirectFieldDecl>(D)) {
6611         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6612           << D->getDeclName();
6613         break;
6614       }
6615     }
6616   }
6617 
6618   // Warn if the class has virtual methods but non-virtual public destructor.
6619   if (Record->isPolymorphic() && !Record->isDependentType()) {
6620     CXXDestructorDecl *dtor = Record->getDestructor();
6621     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6622         !Record->hasAttr<FinalAttr>())
6623       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6624            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6625   }
6626 
6627   if (Record->isAbstract()) {
6628     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6629       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6630         << FA->isSpelledAsSealed();
6631       DiagnoseAbstractType(Record);
6632     }
6633   }
6634 
6635   // Warn if the class has a final destructor but is not itself marked final.
6636   if (!Record->hasAttr<FinalAttr>()) {
6637     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6638       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6639         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6640             << FA->isSpelledAsSealed()
6641             << FixItHint::CreateInsertion(
6642                    getLocForEndOfToken(Record->getLocation()),
6643                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6644         Diag(Record->getLocation(),
6645              diag::note_final_dtor_non_final_class_silence)
6646             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6647       }
6648     }
6649   }
6650 
6651   // See if trivial_abi has to be dropped.
6652   if (Record->hasAttr<TrivialABIAttr>())
6653     checkIllFormedTrivialABIStruct(*Record);
6654 
6655   // Set HasTrivialSpecialMemberForCall if the record has attribute
6656   // "trivial_abi".
6657   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6658 
6659   if (HasTrivialABI)
6660     Record->setHasTrivialSpecialMemberForCall();
6661 
6662   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6663   // We check these last because they can depend on the properties of the
6664   // primary comparison functions (==, <=>).
6665   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6666 
6667   // Perform checks that can't be done until we know all the properties of a
6668   // member function (whether it's defaulted, deleted, virtual, overriding,
6669   // ...).
6670   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6671     // A static function cannot override anything.
6672     if (MD->getStorageClass() == SC_Static) {
6673       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6674                           [](const CXXMethodDecl *) { return true; }))
6675         return;
6676     }
6677 
6678     // A deleted function cannot override a non-deleted function and vice
6679     // versa.
6680     if (ReportOverrides(*this,
6681                         MD->isDeleted() ? diag::err_deleted_override
6682                                         : diag::err_non_deleted_override,
6683                         MD, [&](const CXXMethodDecl *V) {
6684                           return MD->isDeleted() != V->isDeleted();
6685                         })) {
6686       if (MD->isDefaulted() && MD->isDeleted())
6687         // Explain why this defaulted function was deleted.
6688         DiagnoseDeletedDefaultedFunction(MD);
6689       return;
6690     }
6691 
6692     // A consteval function cannot override a non-consteval function and vice
6693     // versa.
6694     if (ReportOverrides(*this,
6695                         MD->isConsteval() ? diag::err_consteval_override
6696                                           : diag::err_non_consteval_override,
6697                         MD, [&](const CXXMethodDecl *V) {
6698                           return MD->isConsteval() != V->isConsteval();
6699                         })) {
6700       if (MD->isDefaulted() && MD->isDeleted())
6701         // Explain why this defaulted function was deleted.
6702         DiagnoseDeletedDefaultedFunction(MD);
6703       return;
6704     }
6705   };
6706 
6707   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6708     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6709       return false;
6710 
6711     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6712     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6713         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6714       DefaultedSecondaryComparisons.push_back(FD);
6715       return true;
6716     }
6717 
6718     CheckExplicitlyDefaultedFunction(S, FD);
6719     return false;
6720   };
6721 
6722   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6723     // Check whether the explicitly-defaulted members are valid.
6724     bool Incomplete = CheckForDefaultedFunction(M);
6725 
6726     // Skip the rest of the checks for a member of a dependent class.
6727     if (Record->isDependentType())
6728       return;
6729 
6730     // For an explicitly defaulted or deleted special member, we defer
6731     // determining triviality until the class is complete. That time is now!
6732     CXXSpecialMember CSM = getSpecialMember(M);
6733     if (!M->isImplicit() && !M->isUserProvided()) {
6734       if (CSM != CXXInvalid) {
6735         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6736         // Inform the class that we've finished declaring this member.
6737         Record->finishedDefaultedOrDeletedMember(M);
6738         M->setTrivialForCall(
6739             HasTrivialABI ||
6740             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6741         Record->setTrivialForCallFlags(M);
6742       }
6743     }
6744 
6745     // Set triviality for the purpose of calls if this is a user-provided
6746     // copy/move constructor or destructor.
6747     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6748          CSM == CXXDestructor) && M->isUserProvided()) {
6749       M->setTrivialForCall(HasTrivialABI);
6750       Record->setTrivialForCallFlags(M);
6751     }
6752 
6753     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6754         M->hasAttr<DLLExportAttr>()) {
6755       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6756           M->isTrivial() &&
6757           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6758            CSM == CXXDestructor))
6759         M->dropAttr<DLLExportAttr>();
6760 
6761       if (M->hasAttr<DLLExportAttr>()) {
6762         // Define after any fields with in-class initializers have been parsed.
6763         DelayedDllExportMemberFunctions.push_back(M);
6764       }
6765     }
6766 
6767     // Define defaulted constexpr virtual functions that override a base class
6768     // function right away.
6769     // FIXME: We can defer doing this until the vtable is marked as used.
6770     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6771       DefineDefaultedFunction(*this, M, M->getLocation());
6772 
6773     if (!Incomplete)
6774       CheckCompletedMemberFunction(M);
6775   };
6776 
6777   // Check the destructor before any other member function. We need to
6778   // determine whether it's trivial in order to determine whether the claas
6779   // type is a literal type, which is a prerequisite for determining whether
6780   // other special member functions are valid and whether they're implicitly
6781   // 'constexpr'.
6782   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6783     CompleteMemberFunction(Dtor);
6784 
6785   bool HasMethodWithOverrideControl = false,
6786        HasOverridingMethodWithoutOverrideControl = false;
6787   for (auto *D : Record->decls()) {
6788     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6789       // FIXME: We could do this check for dependent types with non-dependent
6790       // bases.
6791       if (!Record->isDependentType()) {
6792         // See if a method overloads virtual methods in a base
6793         // class without overriding any.
6794         if (!M->isStatic())
6795           DiagnoseHiddenVirtualMethods(M);
6796         if (M->hasAttr<OverrideAttr>())
6797           HasMethodWithOverrideControl = true;
6798         else if (M->size_overridden_methods() > 0)
6799           HasOverridingMethodWithoutOverrideControl = true;
6800       }
6801 
6802       if (!isa<CXXDestructorDecl>(M))
6803         CompleteMemberFunction(M);
6804     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6805       CheckForDefaultedFunction(
6806           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6807     }
6808   }
6809 
6810   if (HasOverridingMethodWithoutOverrideControl) {
6811     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6812     for (auto *M : Record->methods())
6813       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6814   }
6815 
6816   // Check the defaulted secondary comparisons after any other member functions.
6817   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6818     CheckExplicitlyDefaultedFunction(S, FD);
6819 
6820     // If this is a member function, we deferred checking it until now.
6821     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6822       CheckCompletedMemberFunction(MD);
6823   }
6824 
6825   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6826   // whether this class uses any C++ features that are implemented
6827   // completely differently in MSVC, and if so, emit a diagnostic.
6828   // That diagnostic defaults to an error, but we allow projects to
6829   // map it down to a warning (or ignore it).  It's a fairly common
6830   // practice among users of the ms_struct pragma to mass-annotate
6831   // headers, sweeping up a bunch of types that the project doesn't
6832   // really rely on MSVC-compatible layout for.  We must therefore
6833   // support "ms_struct except for C++ stuff" as a secondary ABI.
6834   // Don't emit this diagnostic if the feature was enabled as a
6835   // language option (as opposed to via a pragma or attribute), as
6836   // the option -mms-bitfields otherwise essentially makes it impossible
6837   // to build C++ code, unless this diagnostic is turned off.
6838   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6839       (Record->isPolymorphic() || Record->getNumBases())) {
6840     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6841   }
6842 
6843   checkClassLevelDLLAttribute(Record);
6844   checkClassLevelCodeSegAttribute(Record);
6845 
6846   bool ClangABICompat4 =
6847       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6848   TargetInfo::CallingConvKind CCK =
6849       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6850   bool CanPass = canPassInRegisters(*this, Record, CCK);
6851 
6852   // Do not change ArgPassingRestrictions if it has already been set to
6853   // APK_CanNeverPassInRegs.
6854   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6855     Record->setArgPassingRestrictions(CanPass
6856                                           ? RecordDecl::APK_CanPassInRegs
6857                                           : RecordDecl::APK_CannotPassInRegs);
6858 
6859   // If canPassInRegisters returns true despite the record having a non-trivial
6860   // destructor, the record is destructed in the callee. This happens only when
6861   // the record or one of its subobjects has a field annotated with trivial_abi
6862   // or a field qualified with ObjC __strong/__weak.
6863   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6864     Record->setParamDestroyedInCallee(true);
6865   else if (Record->hasNonTrivialDestructor())
6866     Record->setParamDestroyedInCallee(CanPass);
6867 
6868   if (getLangOpts().ForceEmitVTables) {
6869     // If we want to emit all the vtables, we need to mark it as used.  This
6870     // is especially required for cases like vtable assumption loads.
6871     MarkVTableUsed(Record->getInnerLocStart(), Record);
6872   }
6873 
6874   if (getLangOpts().CUDA) {
6875     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6876       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6877     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6878       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6879   }
6880 }
6881 
6882 /// Look up the special member function that would be called by a special
6883 /// member function for a subobject of class type.
6884 ///
6885 /// \param Class The class type of the subobject.
6886 /// \param CSM The kind of special member function.
6887 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6888 /// \param ConstRHS True if this is a copy operation with a const object
6889 ///        on its RHS, that is, if the argument to the outer special member
6890 ///        function is 'const' and this is not a field marked 'mutable'.
lookupCallFromSpecialMember(Sema & S,CXXRecordDecl * Class,Sema::CXXSpecialMember CSM,unsigned FieldQuals,bool ConstRHS)6891 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6892     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6893     unsigned FieldQuals, bool ConstRHS) {
6894   unsigned LHSQuals = 0;
6895   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6896     LHSQuals = FieldQuals;
6897 
6898   unsigned RHSQuals = FieldQuals;
6899   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6900     RHSQuals = 0;
6901   else if (ConstRHS)
6902     RHSQuals |= Qualifiers::Const;
6903 
6904   return S.LookupSpecialMember(Class, CSM,
6905                                RHSQuals & Qualifiers::Const,
6906                                RHSQuals & Qualifiers::Volatile,
6907                                false,
6908                                LHSQuals & Qualifiers::Const,
6909                                LHSQuals & Qualifiers::Volatile);
6910 }
6911 
6912 class Sema::InheritedConstructorInfo {
6913   Sema &S;
6914   SourceLocation UseLoc;
6915 
6916   /// A mapping from the base classes through which the constructor was
6917   /// inherited to the using shadow declaration in that base class (or a null
6918   /// pointer if the constructor was declared in that base class).
6919   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6920       InheritedFromBases;
6921 
6922 public:
InheritedConstructorInfo(Sema & S,SourceLocation UseLoc,ConstructorUsingShadowDecl * Shadow)6923   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6924                            ConstructorUsingShadowDecl *Shadow)
6925       : S(S), UseLoc(UseLoc) {
6926     bool DiagnosedMultipleConstructedBases = false;
6927     CXXRecordDecl *ConstructedBase = nullptr;
6928     UsingDecl *ConstructedBaseUsing = nullptr;
6929 
6930     // Find the set of such base class subobjects and check that there's a
6931     // unique constructed subobject.
6932     for (auto *D : Shadow->redecls()) {
6933       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6934       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6935       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6936 
6937       InheritedFromBases.insert(
6938           std::make_pair(DNominatedBase->getCanonicalDecl(),
6939                          DShadow->getNominatedBaseClassShadowDecl()));
6940       if (DShadow->constructsVirtualBase())
6941         InheritedFromBases.insert(
6942             std::make_pair(DConstructedBase->getCanonicalDecl(),
6943                            DShadow->getConstructedBaseClassShadowDecl()));
6944       else
6945         assert(DNominatedBase == DConstructedBase);
6946 
6947       // [class.inhctor.init]p2:
6948       //   If the constructor was inherited from multiple base class subobjects
6949       //   of type B, the program is ill-formed.
6950       if (!ConstructedBase) {
6951         ConstructedBase = DConstructedBase;
6952         ConstructedBaseUsing = D->getUsingDecl();
6953       } else if (ConstructedBase != DConstructedBase &&
6954                  !Shadow->isInvalidDecl()) {
6955         if (!DiagnosedMultipleConstructedBases) {
6956           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6957               << Shadow->getTargetDecl();
6958           S.Diag(ConstructedBaseUsing->getLocation(),
6959                diag::note_ambiguous_inherited_constructor_using)
6960               << ConstructedBase;
6961           DiagnosedMultipleConstructedBases = true;
6962         }
6963         S.Diag(D->getUsingDecl()->getLocation(),
6964                diag::note_ambiguous_inherited_constructor_using)
6965             << DConstructedBase;
6966       }
6967     }
6968 
6969     if (DiagnosedMultipleConstructedBases)
6970       Shadow->setInvalidDecl();
6971   }
6972 
6973   /// Find the constructor to use for inherited construction of a base class,
6974   /// and whether that base class constructor inherits the constructor from a
6975   /// virtual base class (in which case it won't actually invoke it).
6976   std::pair<CXXConstructorDecl *, bool>
findConstructorForBase(CXXRecordDecl * Base,CXXConstructorDecl * Ctor) const6977   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6978     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6979     if (It == InheritedFromBases.end())
6980       return std::make_pair(nullptr, false);
6981 
6982     // This is an intermediary class.
6983     if (It->second)
6984       return std::make_pair(
6985           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6986           It->second->constructsVirtualBase());
6987 
6988     // This is the base class from which the constructor was inherited.
6989     return std::make_pair(Ctor, false);
6990   }
6991 };
6992 
6993 /// Is the special member function which would be selected to perform the
6994 /// specified operation on the specified class type a constexpr constructor?
6995 static bool
specialMemberIsConstexpr(Sema & S,CXXRecordDecl * ClassDecl,Sema::CXXSpecialMember CSM,unsigned Quals,bool ConstRHS,CXXConstructorDecl * InheritedCtor=nullptr,Sema::InheritedConstructorInfo * Inherited=nullptr)6996 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6997                          Sema::CXXSpecialMember CSM, unsigned Quals,
6998                          bool ConstRHS,
6999                          CXXConstructorDecl *InheritedCtor = nullptr,
7000                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
7001   // If we're inheriting a constructor, see if we need to call it for this base
7002   // class.
7003   if (InheritedCtor) {
7004     assert(CSM == Sema::CXXDefaultConstructor);
7005     auto BaseCtor =
7006         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7007     if (BaseCtor)
7008       return BaseCtor->isConstexpr();
7009   }
7010 
7011   if (CSM == Sema::CXXDefaultConstructor)
7012     return ClassDecl->hasConstexprDefaultConstructor();
7013   if (CSM == Sema::CXXDestructor)
7014     return ClassDecl->hasConstexprDestructor();
7015 
7016   Sema::SpecialMemberOverloadResult SMOR =
7017       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7018   if (!SMOR.getMethod())
7019     // A constructor we wouldn't select can't be "involved in initializing"
7020     // anything.
7021     return true;
7022   return SMOR.getMethod()->isConstexpr();
7023 }
7024 
7025 /// Determine whether the specified special member function would be constexpr
7026 /// if it were implicitly defined.
defaultedSpecialMemberIsConstexpr(Sema & S,CXXRecordDecl * ClassDecl,Sema::CXXSpecialMember CSM,bool ConstArg,CXXConstructorDecl * InheritedCtor=nullptr,Sema::InheritedConstructorInfo * Inherited=nullptr)7027 static bool defaultedSpecialMemberIsConstexpr(
7028     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7029     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7030     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7031   if (!S.getLangOpts().CPlusPlus11)
7032     return false;
7033 
7034   // C++11 [dcl.constexpr]p4:
7035   // In the definition of a constexpr constructor [...]
7036   bool Ctor = true;
7037   switch (CSM) {
7038   case Sema::CXXDefaultConstructor:
7039     if (Inherited)
7040       break;
7041     // Since default constructor lookup is essentially trivial (and cannot
7042     // involve, for instance, template instantiation), we compute whether a
7043     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7044     //
7045     // This is important for performance; we need to know whether the default
7046     // constructor is constexpr to determine whether the type is a literal type.
7047     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7048 
7049   case Sema::CXXCopyConstructor:
7050   case Sema::CXXMoveConstructor:
7051     // For copy or move constructors, we need to perform overload resolution.
7052     break;
7053 
7054   case Sema::CXXCopyAssignment:
7055   case Sema::CXXMoveAssignment:
7056     if (!S.getLangOpts().CPlusPlus14)
7057       return false;
7058     // In C++1y, we need to perform overload resolution.
7059     Ctor = false;
7060     break;
7061 
7062   case Sema::CXXDestructor:
7063     return ClassDecl->defaultedDestructorIsConstexpr();
7064 
7065   case Sema::CXXInvalid:
7066     return false;
7067   }
7068 
7069   //   -- if the class is a non-empty union, or for each non-empty anonymous
7070   //      union member of a non-union class, exactly one non-static data member
7071   //      shall be initialized; [DR1359]
7072   //
7073   // If we squint, this is guaranteed, since exactly one non-static data member
7074   // will be initialized (if the constructor isn't deleted), we just don't know
7075   // which one.
7076   if (Ctor && ClassDecl->isUnion())
7077     return CSM == Sema::CXXDefaultConstructor
7078                ? ClassDecl->hasInClassInitializer() ||
7079                      !ClassDecl->hasVariantMembers()
7080                : true;
7081 
7082   //   -- the class shall not have any virtual base classes;
7083   if (Ctor && ClassDecl->getNumVBases())
7084     return false;
7085 
7086   // C++1y [class.copy]p26:
7087   //   -- [the class] is a literal type, and
7088   if (!Ctor && !ClassDecl->isLiteral())
7089     return false;
7090 
7091   //   -- every constructor involved in initializing [...] base class
7092   //      sub-objects shall be a constexpr constructor;
7093   //   -- the assignment operator selected to copy/move each direct base
7094   //      class is a constexpr function, and
7095   for (const auto &B : ClassDecl->bases()) {
7096     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7097     if (!BaseType) continue;
7098 
7099     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7100     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7101                                   InheritedCtor, Inherited))
7102       return false;
7103   }
7104 
7105   //   -- every constructor involved in initializing non-static data members
7106   //      [...] shall be a constexpr constructor;
7107   //   -- every non-static data member and base class sub-object shall be
7108   //      initialized
7109   //   -- for each non-static data member of X that is of class type (or array
7110   //      thereof), the assignment operator selected to copy/move that member is
7111   //      a constexpr function
7112   for (const auto *F : ClassDecl->fields()) {
7113     if (F->isInvalidDecl())
7114       continue;
7115     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7116       continue;
7117     QualType BaseType = S.Context.getBaseElementType(F->getType());
7118     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7119       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7120       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7121                                     BaseType.getCVRQualifiers(),
7122                                     ConstArg && !F->isMutable()))
7123         return false;
7124     } else if (CSM == Sema::CXXDefaultConstructor) {
7125       return false;
7126     }
7127   }
7128 
7129   // All OK, it's constexpr!
7130   return true;
7131 }
7132 
7133 namespace {
7134 /// RAII object to register a defaulted function as having its exception
7135 /// specification computed.
7136 struct ComputingExceptionSpec {
7137   Sema &S;
7138 
ComputingExceptionSpec__anonedc74bd71d11::ComputingExceptionSpec7139   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7140       : S(S) {
7141     Sema::CodeSynthesisContext Ctx;
7142     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7143     Ctx.PointOfInstantiation = Loc;
7144     Ctx.Entity = FD;
7145     S.pushCodeSynthesisContext(Ctx);
7146   }
~ComputingExceptionSpec__anonedc74bd71d11::ComputingExceptionSpec7147   ~ComputingExceptionSpec() {
7148     S.popCodeSynthesisContext();
7149   }
7150 };
7151 }
7152 
7153 static Sema::ImplicitExceptionSpecification
7154 ComputeDefaultedSpecialMemberExceptionSpec(
7155     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7156     Sema::InheritedConstructorInfo *ICI);
7157 
7158 static Sema::ImplicitExceptionSpecification
7159 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7160                                         FunctionDecl *FD,
7161                                         Sema::DefaultedComparisonKind DCK);
7162 
7163 static Sema::ImplicitExceptionSpecification
computeImplicitExceptionSpec(Sema & S,SourceLocation Loc,FunctionDecl * FD)7164 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7165   auto DFK = S.getDefaultedFunctionKind(FD);
7166   if (DFK.isSpecialMember())
7167     return ComputeDefaultedSpecialMemberExceptionSpec(
7168         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7169   if (DFK.isComparison())
7170     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7171                                                    DFK.asComparison());
7172 
7173   auto *CD = cast<CXXConstructorDecl>(FD);
7174   assert(CD->getInheritedConstructor() &&
7175          "only defaulted functions and inherited constructors have implicit "
7176          "exception specs");
7177   Sema::InheritedConstructorInfo ICI(
7178       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7179   return ComputeDefaultedSpecialMemberExceptionSpec(
7180       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7181 }
7182 
getImplicitMethodEPI(Sema & S,CXXMethodDecl * MD)7183 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7184                                                             CXXMethodDecl *MD) {
7185   FunctionProtoType::ExtProtoInfo EPI;
7186 
7187   // Build an exception specification pointing back at this member.
7188   EPI.ExceptionSpec.Type = EST_Unevaluated;
7189   EPI.ExceptionSpec.SourceDecl = MD;
7190 
7191   // Set the calling convention to the default for C++ instance methods.
7192   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7193       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7194                                             /*IsCXXMethod=*/true));
7195   return EPI;
7196 }
7197 
EvaluateImplicitExceptionSpec(SourceLocation Loc,FunctionDecl * FD)7198 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7199   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7200   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7201     return;
7202 
7203   // Evaluate the exception specification.
7204   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7205   auto ESI = IES.getExceptionSpec();
7206 
7207   // Update the type of the special member to use it.
7208   UpdateExceptionSpec(FD, ESI);
7209 }
7210 
CheckExplicitlyDefaultedFunction(Scope * S,FunctionDecl * FD)7211 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7212   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7213 
7214   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7215   if (!DefKind) {
7216     assert(FD->getDeclContext()->isDependentContext());
7217     return;
7218   }
7219 
7220   if (DefKind.isSpecialMember()
7221           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7222                                                   DefKind.asSpecialMember())
7223           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7224     FD->setInvalidDecl();
7225 }
7226 
CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl * MD,CXXSpecialMember CSM)7227 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7228                                                  CXXSpecialMember CSM) {
7229   CXXRecordDecl *RD = MD->getParent();
7230 
7231   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7232          "not an explicitly-defaulted special member");
7233 
7234   // Defer all checking for special members of a dependent type.
7235   if (RD->isDependentType())
7236     return false;
7237 
7238   // Whether this was the first-declared instance of the constructor.
7239   // This affects whether we implicitly add an exception spec and constexpr.
7240   bool First = MD == MD->getCanonicalDecl();
7241 
7242   bool HadError = false;
7243 
7244   // C++11 [dcl.fct.def.default]p1:
7245   //   A function that is explicitly defaulted shall
7246   //     -- be a special member function [...] (checked elsewhere),
7247   //     -- have the same type (except for ref-qualifiers, and except that a
7248   //        copy operation can take a non-const reference) as an implicit
7249   //        declaration, and
7250   //     -- not have default arguments.
7251   // C++2a changes the second bullet to instead delete the function if it's
7252   // defaulted on its first declaration, unless it's "an assignment operator,
7253   // and its return type differs or its parameter type is not a reference".
7254   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7255   bool ShouldDeleteForTypeMismatch = false;
7256   unsigned ExpectedParams = 1;
7257   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7258     ExpectedParams = 0;
7259   if (MD->getNumParams() != ExpectedParams) {
7260     // This checks for default arguments: a copy or move constructor with a
7261     // default argument is classified as a default constructor, and assignment
7262     // operations and destructors can't have default arguments.
7263     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7264       << CSM << MD->getSourceRange();
7265     HadError = true;
7266   } else if (MD->isVariadic()) {
7267     if (DeleteOnTypeMismatch)
7268       ShouldDeleteForTypeMismatch = true;
7269     else {
7270       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7271         << CSM << MD->getSourceRange();
7272       HadError = true;
7273     }
7274   }
7275 
7276   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7277 
7278   bool CanHaveConstParam = false;
7279   if (CSM == CXXCopyConstructor)
7280     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7281   else if (CSM == CXXCopyAssignment)
7282     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7283 
7284   QualType ReturnType = Context.VoidTy;
7285   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7286     // Check for return type matching.
7287     ReturnType = Type->getReturnType();
7288 
7289     QualType DeclType = Context.getTypeDeclType(RD);
7290     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7291     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7292 
7293     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7294       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7295         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7296       HadError = true;
7297     }
7298 
7299     // A defaulted special member cannot have cv-qualifiers.
7300     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7301       if (DeleteOnTypeMismatch)
7302         ShouldDeleteForTypeMismatch = true;
7303       else {
7304         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7305           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7306         HadError = true;
7307       }
7308     }
7309   }
7310 
7311   // Check for parameter type matching.
7312   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7313   bool HasConstParam = false;
7314   if (ExpectedParams && ArgType->isReferenceType()) {
7315     // Argument must be reference to possibly-const T.
7316     QualType ReferentType = ArgType->getPointeeType();
7317     HasConstParam = ReferentType.isConstQualified();
7318 
7319     if (ReferentType.isVolatileQualified()) {
7320       if (DeleteOnTypeMismatch)
7321         ShouldDeleteForTypeMismatch = true;
7322       else {
7323         Diag(MD->getLocation(),
7324              diag::err_defaulted_special_member_volatile_param) << CSM;
7325         HadError = true;
7326       }
7327     }
7328 
7329     if (HasConstParam && !CanHaveConstParam) {
7330       if (DeleteOnTypeMismatch)
7331         ShouldDeleteForTypeMismatch = true;
7332       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7333         Diag(MD->getLocation(),
7334              diag::err_defaulted_special_member_copy_const_param)
7335           << (CSM == CXXCopyAssignment);
7336         // FIXME: Explain why this special member can't be const.
7337         HadError = true;
7338       } else {
7339         Diag(MD->getLocation(),
7340              diag::err_defaulted_special_member_move_const_param)
7341           << (CSM == CXXMoveAssignment);
7342         HadError = true;
7343       }
7344     }
7345   } else if (ExpectedParams) {
7346     // A copy assignment operator can take its argument by value, but a
7347     // defaulted one cannot.
7348     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7349     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7350     HadError = true;
7351   }
7352 
7353   // C++11 [dcl.fct.def.default]p2:
7354   //   An explicitly-defaulted function may be declared constexpr only if it
7355   //   would have been implicitly declared as constexpr,
7356   // Do not apply this rule to members of class templates, since core issue 1358
7357   // makes such functions always instantiate to constexpr functions. For
7358   // functions which cannot be constexpr (for non-constructors in C++11 and for
7359   // destructors in C++14 and C++17), this is checked elsewhere.
7360   //
7361   // FIXME: This should not apply if the member is deleted.
7362   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7363                                                      HasConstParam);
7364   if ((getLangOpts().CPlusPlus20 ||
7365        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7366                                   : isa<CXXConstructorDecl>(MD))) &&
7367       MD->isConstexpr() && !Constexpr &&
7368       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7369     Diag(MD->getBeginLoc(), MD->isConsteval()
7370                                 ? diag::err_incorrect_defaulted_consteval
7371                                 : diag::err_incorrect_defaulted_constexpr)
7372         << CSM;
7373     // FIXME: Explain why the special member can't be constexpr.
7374     HadError = true;
7375   }
7376 
7377   if (First) {
7378     // C++2a [dcl.fct.def.default]p3:
7379     //   If a function is explicitly defaulted on its first declaration, it is
7380     //   implicitly considered to be constexpr if the implicit declaration
7381     //   would be.
7382     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7383                                           ? ConstexprSpecKind::Consteval
7384                                           : ConstexprSpecKind::Constexpr)
7385                                    : ConstexprSpecKind::Unspecified);
7386 
7387     if (!Type->hasExceptionSpec()) {
7388       // C++2a [except.spec]p3:
7389       //   If a declaration of a function does not have a noexcept-specifier
7390       //   [and] is defaulted on its first declaration, [...] the exception
7391       //   specification is as specified below
7392       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7393       EPI.ExceptionSpec.Type = EST_Unevaluated;
7394       EPI.ExceptionSpec.SourceDecl = MD;
7395       MD->setType(Context.getFunctionType(ReturnType,
7396                                           llvm::makeArrayRef(&ArgType,
7397                                                              ExpectedParams),
7398                                           EPI));
7399     }
7400   }
7401 
7402   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7403     if (First) {
7404       SetDeclDeleted(MD, MD->getLocation());
7405       if (!inTemplateInstantiation() && !HadError) {
7406         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7407         if (ShouldDeleteForTypeMismatch) {
7408           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7409         } else {
7410           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7411         }
7412       }
7413       if (ShouldDeleteForTypeMismatch && !HadError) {
7414         Diag(MD->getLocation(),
7415              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7416       }
7417     } else {
7418       // C++11 [dcl.fct.def.default]p4:
7419       //   [For a] user-provided explicitly-defaulted function [...] if such a
7420       //   function is implicitly defined as deleted, the program is ill-formed.
7421       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7422       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7423       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7424       HadError = true;
7425     }
7426   }
7427 
7428   return HadError;
7429 }
7430 
7431 namespace {
7432 /// Helper class for building and checking a defaulted comparison.
7433 ///
7434 /// Defaulted functions are built in two phases:
7435 ///
7436 ///  * First, the set of operations that the function will perform are
7437 ///    identified, and some of them are checked. If any of the checked
7438 ///    operations is invalid in certain ways, the comparison function is
7439 ///    defined as deleted and no body is built.
7440 ///  * Then, if the function is not defined as deleted, the body is built.
7441 ///
7442 /// This is accomplished by performing two visitation steps over the eventual
7443 /// body of the function.
7444 template<typename Derived, typename ResultList, typename Result,
7445          typename Subobject>
7446 class DefaultedComparisonVisitor {
7447 public:
7448   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7449 
DefaultedComparisonVisitor(Sema & S,CXXRecordDecl * RD,FunctionDecl * FD,DefaultedComparisonKind DCK)7450   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7451                              DefaultedComparisonKind DCK)
7452       : S(S), RD(RD), FD(FD), DCK(DCK) {
7453     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7454       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7455       // UnresolvedSet to avoid this copy.
7456       Fns.assign(Info->getUnqualifiedLookups().begin(),
7457                  Info->getUnqualifiedLookups().end());
7458     }
7459   }
7460 
visit()7461   ResultList visit() {
7462     // The type of an lvalue naming a parameter of this function.
7463     QualType ParamLvalType =
7464         FD->getParamDecl(0)->getType().getNonReferenceType();
7465 
7466     ResultList Results;
7467 
7468     switch (DCK) {
7469     case DefaultedComparisonKind::None:
7470       llvm_unreachable("not a defaulted comparison");
7471 
7472     case DefaultedComparisonKind::Equal:
7473     case DefaultedComparisonKind::ThreeWay:
7474       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7475       return Results;
7476 
7477     case DefaultedComparisonKind::NotEqual:
7478     case DefaultedComparisonKind::Relational:
7479       Results.add(getDerived().visitExpandedSubobject(
7480           ParamLvalType, getDerived().getCompleteObject()));
7481       return Results;
7482     }
7483     llvm_unreachable("");
7484   }
7485 
7486 protected:
getDerived()7487   Derived &getDerived() { return static_cast<Derived&>(*this); }
7488 
7489   /// Visit the expanded list of subobjects of the given type, as specified in
7490   /// C++2a [class.compare.default].
7491   ///
7492   /// \return \c true if the ResultList object said we're done, \c false if not.
visitSubobjects(ResultList & Results,CXXRecordDecl * Record,Qualifiers Quals)7493   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7494                        Qualifiers Quals) {
7495     // C++2a [class.compare.default]p4:
7496     //   The direct base class subobjects of C
7497     for (CXXBaseSpecifier &Base : Record->bases())
7498       if (Results.add(getDerived().visitSubobject(
7499               S.Context.getQualifiedType(Base.getType(), Quals),
7500               getDerived().getBase(&Base))))
7501         return true;
7502 
7503     //   followed by the non-static data members of C
7504     for (FieldDecl *Field : Record->fields()) {
7505       // Recursively expand anonymous structs.
7506       if (Field->isAnonymousStructOrUnion()) {
7507         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7508                             Quals))
7509           return true;
7510         continue;
7511       }
7512 
7513       // Figure out the type of an lvalue denoting this field.
7514       Qualifiers FieldQuals = Quals;
7515       if (Field->isMutable())
7516         FieldQuals.removeConst();
7517       QualType FieldType =
7518           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7519 
7520       if (Results.add(getDerived().visitSubobject(
7521               FieldType, getDerived().getField(Field))))
7522         return true;
7523     }
7524 
7525     //   form a list of subobjects.
7526     return false;
7527   }
7528 
visitSubobject(QualType Type,Subobject Subobj)7529   Result visitSubobject(QualType Type, Subobject Subobj) {
7530     //   In that list, any subobject of array type is recursively expanded
7531     const ArrayType *AT = S.Context.getAsArrayType(Type);
7532     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7533       return getDerived().visitSubobjectArray(CAT->getElementType(),
7534                                               CAT->getSize(), Subobj);
7535     return getDerived().visitExpandedSubobject(Type, Subobj);
7536   }
7537 
visitSubobjectArray(QualType Type,const llvm::APInt & Size,Subobject Subobj)7538   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7539                              Subobject Subobj) {
7540     return getDerived().visitSubobject(Type, Subobj);
7541   }
7542 
7543 protected:
7544   Sema &S;
7545   CXXRecordDecl *RD;
7546   FunctionDecl *FD;
7547   DefaultedComparisonKind DCK;
7548   UnresolvedSet<16> Fns;
7549 };
7550 
7551 /// Information about a defaulted comparison, as determined by
7552 /// DefaultedComparisonAnalyzer.
7553 struct DefaultedComparisonInfo {
7554   bool Deleted = false;
7555   bool Constexpr = true;
7556   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7557 
deleted__anonedc74bd71e11::DefaultedComparisonInfo7558   static DefaultedComparisonInfo deleted() {
7559     DefaultedComparisonInfo Deleted;
7560     Deleted.Deleted = true;
7561     return Deleted;
7562   }
7563 
add__anonedc74bd71e11::DefaultedComparisonInfo7564   bool add(const DefaultedComparisonInfo &R) {
7565     Deleted |= R.Deleted;
7566     Constexpr &= R.Constexpr;
7567     Category = commonComparisonType(Category, R.Category);
7568     return Deleted;
7569   }
7570 };
7571 
7572 /// An element in the expanded list of subobjects of a defaulted comparison, as
7573 /// specified in C++2a [class.compare.default]p4.
7574 struct DefaultedComparisonSubobject {
7575   enum { CompleteObject, Member, Base } Kind;
7576   NamedDecl *Decl;
7577   SourceLocation Loc;
7578 };
7579 
7580 /// A visitor over the notional body of a defaulted comparison that determines
7581 /// whether that body would be deleted or constexpr.
7582 class DefaultedComparisonAnalyzer
7583     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7584                                         DefaultedComparisonInfo,
7585                                         DefaultedComparisonInfo,
7586                                         DefaultedComparisonSubobject> {
7587 public:
7588   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7589 
7590 private:
7591   DiagnosticKind Diagnose;
7592 
7593 public:
7594   using Base = DefaultedComparisonVisitor;
7595   using Result = DefaultedComparisonInfo;
7596   using Subobject = DefaultedComparisonSubobject;
7597 
7598   friend Base;
7599 
DefaultedComparisonAnalyzer(Sema & S,CXXRecordDecl * RD,FunctionDecl * FD,DefaultedComparisonKind DCK,DiagnosticKind Diagnose=NoDiagnostics)7600   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7601                               DefaultedComparisonKind DCK,
7602                               DiagnosticKind Diagnose = NoDiagnostics)
7603       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7604 
visit()7605   Result visit() {
7606     if ((DCK == DefaultedComparisonKind::Equal ||
7607          DCK == DefaultedComparisonKind::ThreeWay) &&
7608         RD->hasVariantMembers()) {
7609       // C++2a [class.compare.default]p2 [P2002R0]:
7610       //   A defaulted comparison operator function for class C is defined as
7611       //   deleted if [...] C has variant members.
7612       if (Diagnose == ExplainDeleted) {
7613         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7614           << FD << RD->isUnion() << RD;
7615       }
7616       return Result::deleted();
7617     }
7618 
7619     return Base::visit();
7620   }
7621 
7622 private:
getCompleteObject()7623   Subobject getCompleteObject() {
7624     return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()};
7625   }
7626 
getBase(CXXBaseSpecifier * Base)7627   Subobject getBase(CXXBaseSpecifier *Base) {
7628     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7629                      Base->getBaseTypeLoc()};
7630   }
7631 
getField(FieldDecl * Field)7632   Subobject getField(FieldDecl *Field) {
7633     return Subobject{Subobject::Member, Field, Field->getLocation()};
7634   }
7635 
visitExpandedSubobject(QualType Type,Subobject Subobj)7636   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7637     // C++2a [class.compare.default]p2 [P2002R0]:
7638     //   A defaulted <=> or == operator function for class C is defined as
7639     //   deleted if any non-static data member of C is of reference type
7640     if (Type->isReferenceType()) {
7641       if (Diagnose == ExplainDeleted) {
7642         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7643             << FD << RD;
7644       }
7645       return Result::deleted();
7646     }
7647 
7648     // [...] Let xi be an lvalue denoting the ith element [...]
7649     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7650     Expr *Args[] = {&Xi, &Xi};
7651 
7652     // All operators start by trying to apply that same operator recursively.
7653     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7654     assert(OO != OO_None && "not an overloaded operator!");
7655     return visitBinaryOperator(OO, Args, Subobj);
7656   }
7657 
7658   Result
visitBinaryOperator(OverloadedOperatorKind OO,ArrayRef<Expr * > Args,Subobject Subobj,OverloadCandidateSet * SpaceshipCandidates=nullptr)7659   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7660                       Subobject Subobj,
7661                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7662     // Note that there is no need to consider rewritten candidates here if
7663     // we've already found there is no viable 'operator<=>' candidate (and are
7664     // considering synthesizing a '<=>' from '==' and '<').
7665     OverloadCandidateSet CandidateSet(
7666         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7667         OverloadCandidateSet::OperatorRewriteInfo(
7668             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7669 
7670     /// C++2a [class.compare.default]p1 [P2002R0]:
7671     ///   [...] the defaulted function itself is never a candidate for overload
7672     ///   resolution [...]
7673     CandidateSet.exclude(FD);
7674 
7675     if (Args[0]->getType()->isOverloadableType())
7676       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7677     else {
7678       // FIXME: We determine whether this is a valid expression by checking to
7679       // see if there's a viable builtin operator candidate for it. That isn't
7680       // really what the rules ask us to do, but should give the right results.
7681       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7682     }
7683 
7684     Result R;
7685 
7686     OverloadCandidateSet::iterator Best;
7687     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7688     case OR_Success: {
7689       // C++2a [class.compare.secondary]p2 [P2002R0]:
7690       //   The operator function [...] is defined as deleted if [...] the
7691       //   candidate selected by overload resolution is not a rewritten
7692       //   candidate.
7693       if ((DCK == DefaultedComparisonKind::NotEqual ||
7694            DCK == DefaultedComparisonKind::Relational) &&
7695           !Best->RewriteKind) {
7696         if (Diagnose == ExplainDeleted) {
7697           S.Diag(Best->Function->getLocation(),
7698                  diag::note_defaulted_comparison_not_rewritten_callee)
7699               << FD;
7700         }
7701         return Result::deleted();
7702       }
7703 
7704       // Throughout C++2a [class.compare]: if overload resolution does not
7705       // result in a usable function, the candidate function is defined as
7706       // deleted. This requires that we selected an accessible function.
7707       //
7708       // Note that this only considers the access of the function when named
7709       // within the type of the subobject, and not the access path for any
7710       // derived-to-base conversion.
7711       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7712       if (ArgClass && Best->FoundDecl.getDecl() &&
7713           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7714         QualType ObjectType = Subobj.Kind == Subobject::Member
7715                                   ? Args[0]->getType()
7716                                   : S.Context.getRecordType(RD);
7717         if (!S.isMemberAccessibleForDeletion(
7718                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7719                 Diagnose == ExplainDeleted
7720                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7721                           << FD << Subobj.Kind << Subobj.Decl
7722                     : S.PDiag()))
7723           return Result::deleted();
7724       }
7725 
7726       // C++2a [class.compare.default]p3 [P2002R0]:
7727       //   A defaulted comparison function is constexpr-compatible if [...]
7728       //   no overlod resolution performed [...] results in a non-constexpr
7729       //   function.
7730       if (FunctionDecl *BestFD = Best->Function) {
7731         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7732         // If it's not constexpr, explain why not.
7733         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7734           if (Subobj.Kind != Subobject::CompleteObject)
7735             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7736               << Subobj.Kind << Subobj.Decl;
7737           S.Diag(BestFD->getLocation(),
7738                  diag::note_defaulted_comparison_not_constexpr_here);
7739           // Bail out after explaining; we don't want any more notes.
7740           return Result::deleted();
7741         }
7742         R.Constexpr &= BestFD->isConstexpr();
7743       }
7744 
7745       if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) {
7746         if (auto *BestFD = Best->Function) {
7747           // If any callee has an undeduced return type, deduce it now.
7748           // FIXME: It's not clear how a failure here should be handled. For
7749           // now, we produce an eager diagnostic, because that is forward
7750           // compatible with most (all?) other reasonable options.
7751           if (BestFD->getReturnType()->isUndeducedType() &&
7752               S.DeduceReturnType(BestFD, FD->getLocation(),
7753                                  /*Diagnose=*/false)) {
7754             // Don't produce a duplicate error when asked to explain why the
7755             // comparison is deleted: we diagnosed that when initially checking
7756             // the defaulted operator.
7757             if (Diagnose == NoDiagnostics) {
7758               S.Diag(
7759                   FD->getLocation(),
7760                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7761                   << Subobj.Kind << Subobj.Decl;
7762               S.Diag(
7763                   Subobj.Loc,
7764                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7765                   << Subobj.Kind << Subobj.Decl;
7766               S.Diag(BestFD->getLocation(),
7767                      diag::note_defaulted_comparison_cannot_deduce_callee)
7768                   << Subobj.Kind << Subobj.Decl;
7769             }
7770             return Result::deleted();
7771           }
7772           if (auto *Info = S.Context.CompCategories.lookupInfoForType(
7773               BestFD->getCallResultType())) {
7774             R.Category = Info->Kind;
7775           } else {
7776             if (Diagnose == ExplainDeleted) {
7777               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7778                   << Subobj.Kind << Subobj.Decl
7779                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7780               S.Diag(BestFD->getLocation(),
7781                      diag::note_defaulted_comparison_cannot_deduce_callee)
7782                   << Subobj.Kind << Subobj.Decl;
7783             }
7784             return Result::deleted();
7785           }
7786         } else {
7787           Optional<ComparisonCategoryType> Cat =
7788               getComparisonCategoryForBuiltinCmp(Args[0]->getType());
7789           assert(Cat && "no category for builtin comparison?");
7790           R.Category = *Cat;
7791         }
7792       }
7793 
7794       // Note that we might be rewriting to a different operator. That call is
7795       // not considered until we come to actually build the comparison function.
7796       break;
7797     }
7798 
7799     case OR_Ambiguous:
7800       if (Diagnose == ExplainDeleted) {
7801         unsigned Kind = 0;
7802         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7803           Kind = OO == OO_EqualEqual ? 1 : 2;
7804         CandidateSet.NoteCandidates(
7805             PartialDiagnosticAt(
7806                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7807                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
7808             S, OCD_AmbiguousCandidates, Args);
7809       }
7810       R = Result::deleted();
7811       break;
7812 
7813     case OR_Deleted:
7814       if (Diagnose == ExplainDeleted) {
7815         if ((DCK == DefaultedComparisonKind::NotEqual ||
7816              DCK == DefaultedComparisonKind::Relational) &&
7817             !Best->RewriteKind) {
7818           S.Diag(Best->Function->getLocation(),
7819                  diag::note_defaulted_comparison_not_rewritten_callee)
7820               << FD;
7821         } else {
7822           S.Diag(Subobj.Loc,
7823                  diag::note_defaulted_comparison_calls_deleted)
7824               << FD << Subobj.Kind << Subobj.Decl;
7825           S.NoteDeletedFunction(Best->Function);
7826         }
7827       }
7828       R = Result::deleted();
7829       break;
7830 
7831     case OR_No_Viable_Function:
7832       // If there's no usable candidate, we're done unless we can rewrite a
7833       // '<=>' in terms of '==' and '<'.
7834       if (OO == OO_Spaceship &&
7835           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7836         // For any kind of comparison category return type, we need a usable
7837         // '==' and a usable '<'.
7838         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7839                                        &CandidateSet)))
7840           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7841         break;
7842       }
7843 
7844       if (Diagnose == ExplainDeleted) {
7845         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7846             << FD << Subobj.Kind << Subobj.Decl;
7847 
7848         // For a three-way comparison, list both the candidates for the
7849         // original operator and the candidates for the synthesized operator.
7850         if (SpaceshipCandidates) {
7851           SpaceshipCandidates->NoteCandidates(
7852               S, Args,
7853               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7854                                                       Args, FD->getLocation()));
7855           S.Diag(Subobj.Loc,
7856                  diag::note_defaulted_comparison_no_viable_function_synthesized)
7857               << (OO == OO_EqualEqual ? 0 : 1);
7858         }
7859 
7860         CandidateSet.NoteCandidates(
7861             S, Args,
7862             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7863                                             FD->getLocation()));
7864       }
7865       R = Result::deleted();
7866       break;
7867     }
7868 
7869     return R;
7870   }
7871 };
7872 
7873 /// A list of statements.
7874 struct StmtListResult {
7875   bool IsInvalid = false;
7876   llvm::SmallVector<Stmt*, 16> Stmts;
7877 
add__anonedc74bd71e11::StmtListResult7878   bool add(const StmtResult &S) {
7879     IsInvalid |= S.isInvalid();
7880     if (IsInvalid)
7881       return true;
7882     Stmts.push_back(S.get());
7883     return false;
7884   }
7885 };
7886 
7887 /// A visitor over the notional body of a defaulted comparison that synthesizes
7888 /// the actual body.
7889 class DefaultedComparisonSynthesizer
7890     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
7891                                         StmtListResult, StmtResult,
7892                                         std::pair<ExprResult, ExprResult>> {
7893   SourceLocation Loc;
7894   unsigned ArrayDepth = 0;
7895 
7896 public:
7897   using Base = DefaultedComparisonVisitor;
7898   using ExprPair = std::pair<ExprResult, ExprResult>;
7899 
7900   friend Base;
7901 
DefaultedComparisonSynthesizer(Sema & S,CXXRecordDecl * RD,FunctionDecl * FD,DefaultedComparisonKind DCK,SourceLocation BodyLoc)7902   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7903                                  DefaultedComparisonKind DCK,
7904                                  SourceLocation BodyLoc)
7905       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
7906 
7907   /// Build a suitable function body for this defaulted comparison operator.
build()7908   StmtResult build() {
7909     Sema::CompoundScopeRAII CompoundScope(S);
7910 
7911     StmtListResult Stmts = visit();
7912     if (Stmts.IsInvalid)
7913       return StmtError();
7914 
7915     ExprResult RetVal;
7916     switch (DCK) {
7917     case DefaultedComparisonKind::None:
7918       llvm_unreachable("not a defaulted comparison");
7919 
7920     case DefaultedComparisonKind::Equal: {
7921       // C++2a [class.eq]p3:
7922       //   [...] compar[e] the corresponding elements [...] until the first
7923       //   index i where xi == yi yields [...] false. If no such index exists,
7924       //   V is true. Otherwise, V is false.
7925       //
7926       // Join the comparisons with '&&'s and return the result. Use a right
7927       // fold (traversing the conditions right-to-left), because that
7928       // short-circuits more naturally.
7929       auto OldStmts = std::move(Stmts.Stmts);
7930       Stmts.Stmts.clear();
7931       ExprResult CmpSoFar;
7932       // Finish a particular comparison chain.
7933       auto FinishCmp = [&] {
7934         if (Expr *Prior = CmpSoFar.get()) {
7935           // Convert the last expression to 'return ...;'
7936           if (RetVal.isUnset() && Stmts.Stmts.empty())
7937             RetVal = CmpSoFar;
7938           // Convert any prior comparison to 'if (!(...)) return false;'
7939           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
7940             return true;
7941           CmpSoFar = ExprResult();
7942         }
7943         return false;
7944       };
7945       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
7946         Expr *E = dyn_cast<Expr>(EAsStmt);
7947         if (!E) {
7948           // Found an array comparison.
7949           if (FinishCmp() || Stmts.add(EAsStmt))
7950             return StmtError();
7951           continue;
7952         }
7953 
7954         if (CmpSoFar.isUnset()) {
7955           CmpSoFar = E;
7956           continue;
7957         }
7958         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
7959         if (CmpSoFar.isInvalid())
7960           return StmtError();
7961       }
7962       if (FinishCmp())
7963         return StmtError();
7964       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
7965       //   If no such index exists, V is true.
7966       if (RetVal.isUnset())
7967         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
7968       break;
7969     }
7970 
7971     case DefaultedComparisonKind::ThreeWay: {
7972       // Per C++2a [class.spaceship]p3, as a fallback add:
7973       // return static_cast<R>(std::strong_ordering::equal);
7974       QualType StrongOrdering = S.CheckComparisonCategoryType(
7975           ComparisonCategoryType::StrongOrdering, Loc,
7976           Sema::ComparisonCategoryUsage::DefaultedOperator);
7977       if (StrongOrdering.isNull())
7978         return StmtError();
7979       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
7980                              .getValueInfo(ComparisonCategoryResult::Equal)
7981                              ->VD;
7982       RetVal = getDecl(EqualVD);
7983       if (RetVal.isInvalid())
7984         return StmtError();
7985       RetVal = buildStaticCastToR(RetVal.get());
7986       break;
7987     }
7988 
7989     case DefaultedComparisonKind::NotEqual:
7990     case DefaultedComparisonKind::Relational:
7991       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
7992       break;
7993     }
7994 
7995     // Build the final return statement.
7996     if (RetVal.isInvalid())
7997       return StmtError();
7998     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
7999     if (ReturnStmt.isInvalid())
8000       return StmtError();
8001     Stmts.Stmts.push_back(ReturnStmt.get());
8002 
8003     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8004   }
8005 
8006 private:
getDecl(ValueDecl * VD)8007   ExprResult getDecl(ValueDecl *VD) {
8008     return S.BuildDeclarationNameExpr(
8009         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8010   }
8011 
getParam(unsigned I)8012   ExprResult getParam(unsigned I) {
8013     ParmVarDecl *PD = FD->getParamDecl(I);
8014     return getDecl(PD);
8015   }
8016 
getCompleteObject()8017   ExprPair getCompleteObject() {
8018     unsigned Param = 0;
8019     ExprResult LHS;
8020     if (isa<CXXMethodDecl>(FD)) {
8021       // LHS is '*this'.
8022       LHS = S.ActOnCXXThis(Loc);
8023       if (!LHS.isInvalid())
8024         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8025     } else {
8026       LHS = getParam(Param++);
8027     }
8028     ExprResult RHS = getParam(Param++);
8029     assert(Param == FD->getNumParams());
8030     return {LHS, RHS};
8031   }
8032 
getBase(CXXBaseSpecifier * Base)8033   ExprPair getBase(CXXBaseSpecifier *Base) {
8034     ExprPair Obj = getCompleteObject();
8035     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8036       return {ExprError(), ExprError()};
8037     CXXCastPath Path = {Base};
8038     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8039                                 CK_DerivedToBase, VK_LValue, &Path),
8040             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8041                                 CK_DerivedToBase, VK_LValue, &Path)};
8042   }
8043 
getField(FieldDecl * Field)8044   ExprPair getField(FieldDecl *Field) {
8045     ExprPair Obj = getCompleteObject();
8046     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8047       return {ExprError(), ExprError()};
8048 
8049     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8050     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8051     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8052                                       CXXScopeSpec(), Field, Found, NameInfo),
8053             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8054                                       CXXScopeSpec(), Field, Found, NameInfo)};
8055   }
8056 
8057   // FIXME: When expanding a subobject, register a note in the code synthesis
8058   // stack to say which subobject we're comparing.
8059 
buildIfNotCondReturnFalse(ExprResult Cond)8060   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8061     if (Cond.isInvalid())
8062       return StmtError();
8063 
8064     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8065     if (NotCond.isInvalid())
8066       return StmtError();
8067 
8068     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8069     assert(!False.isInvalid() && "should never fail");
8070     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8071     if (ReturnFalse.isInvalid())
8072       return StmtError();
8073 
8074     return S.ActOnIfStmt(Loc, false, Loc, nullptr,
8075                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8076                                           Sema::ConditionKind::Boolean),
8077                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8078   }
8079 
visitSubobjectArray(QualType Type,llvm::APInt Size,ExprPair Subobj)8080   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8081                                  ExprPair Subobj) {
8082     QualType SizeType = S.Context.getSizeType();
8083     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8084 
8085     // Build 'size_t i$n = 0'.
8086     IdentifierInfo *IterationVarName = nullptr;
8087     {
8088       SmallString<8> Str;
8089       llvm::raw_svector_ostream OS(Str);
8090       OS << "i" << ArrayDepth;
8091       IterationVarName = &S.Context.Idents.get(OS.str());
8092     }
8093     VarDecl *IterationVar = VarDecl::Create(
8094         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8095         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8096     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8097     IterationVar->setInit(
8098         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8099     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8100 
8101     auto IterRef = [&] {
8102       ExprResult Ref = S.BuildDeclarationNameExpr(
8103           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8104           IterationVar);
8105       assert(!Ref.isInvalid() && "can't reference our own variable?");
8106       return Ref.get();
8107     };
8108 
8109     // Build 'i$n != Size'.
8110     ExprResult Cond = S.CreateBuiltinBinOp(
8111         Loc, BO_NE, IterRef(),
8112         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8113     assert(!Cond.isInvalid() && "should never fail");
8114 
8115     // Build '++i$n'.
8116     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8117     assert(!Inc.isInvalid() && "should never fail");
8118 
8119     // Build 'a[i$n]' and 'b[i$n]'.
8120     auto Index = [&](ExprResult E) {
8121       if (E.isInvalid())
8122         return ExprError();
8123       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8124     };
8125     Subobj.first = Index(Subobj.first);
8126     Subobj.second = Index(Subobj.second);
8127 
8128     // Compare the array elements.
8129     ++ArrayDepth;
8130     StmtResult Substmt = visitSubobject(Type, Subobj);
8131     --ArrayDepth;
8132 
8133     if (Substmt.isInvalid())
8134       return StmtError();
8135 
8136     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8137     // For outer levels or for an 'operator<=>' we already have a suitable
8138     // statement that returns as necessary.
8139     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8140       assert(DCK == DefaultedComparisonKind::Equal &&
8141              "should have non-expression statement");
8142       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8143       if (Substmt.isInvalid())
8144         return StmtError();
8145     }
8146 
8147     // Build 'for (...) ...'
8148     return S.ActOnForStmt(Loc, Loc, Init,
8149                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8150                                            Sema::ConditionKind::Boolean),
8151                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8152                           Substmt.get());
8153   }
8154 
visitExpandedSubobject(QualType Type,ExprPair Obj)8155   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8156     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8157       return StmtError();
8158 
8159     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8160     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8161     ExprResult Op;
8162     if (Type->isOverloadableType())
8163       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8164                                    Obj.second.get(), /*PerformADL=*/true,
8165                                    /*AllowRewrittenCandidates=*/true, FD);
8166     else
8167       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8168     if (Op.isInvalid())
8169       return StmtError();
8170 
8171     switch (DCK) {
8172     case DefaultedComparisonKind::None:
8173       llvm_unreachable("not a defaulted comparison");
8174 
8175     case DefaultedComparisonKind::Equal:
8176       // Per C++2a [class.eq]p2, each comparison is individually contextually
8177       // converted to bool.
8178       Op = S.PerformContextuallyConvertToBool(Op.get());
8179       if (Op.isInvalid())
8180         return StmtError();
8181       return Op.get();
8182 
8183     case DefaultedComparisonKind::ThreeWay: {
8184       // Per C++2a [class.spaceship]p3, form:
8185       //   if (R cmp = static_cast<R>(op); cmp != 0)
8186       //     return cmp;
8187       QualType R = FD->getReturnType();
8188       Op = buildStaticCastToR(Op.get());
8189       if (Op.isInvalid())
8190         return StmtError();
8191 
8192       // R cmp = ...;
8193       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8194       VarDecl *VD =
8195           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8196                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8197       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8198       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8199 
8200       // cmp != 0
8201       ExprResult VDRef = getDecl(VD);
8202       if (VDRef.isInvalid())
8203         return StmtError();
8204       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8205       Expr *Zero =
8206           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8207       ExprResult Comp;
8208       if (VDRef.get()->getType()->isOverloadableType())
8209         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8210                                        true, FD);
8211       else
8212         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8213       if (Comp.isInvalid())
8214         return StmtError();
8215       Sema::ConditionResult Cond = S.ActOnCondition(
8216           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8217       if (Cond.isInvalid())
8218         return StmtError();
8219 
8220       // return cmp;
8221       VDRef = getDecl(VD);
8222       if (VDRef.isInvalid())
8223         return StmtError();
8224       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8225       if (ReturnStmt.isInvalid())
8226         return StmtError();
8227 
8228       // if (...)
8229       return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc,
8230                            ReturnStmt.get(),
8231                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8232     }
8233 
8234     case DefaultedComparisonKind::NotEqual:
8235     case DefaultedComparisonKind::Relational:
8236       // C++2a [class.compare.secondary]p2:
8237       //   Otherwise, the operator function yields x @ y.
8238       return Op.get();
8239     }
8240     llvm_unreachable("");
8241   }
8242 
8243   /// Build "static_cast<R>(E)".
buildStaticCastToR(Expr * E)8244   ExprResult buildStaticCastToR(Expr *E) {
8245     QualType R = FD->getReturnType();
8246     assert(!R->isUndeducedType() && "type should have been deduced already");
8247 
8248     // Don't bother forming a no-op cast in the common case.
8249     if (E->isRValue() && S.Context.hasSameType(E->getType(), R))
8250       return E;
8251     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8252                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8253                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8254   }
8255 };
8256 }
8257 
8258 /// Perform the unqualified lookups that might be needed to form a defaulted
8259 /// comparison function for the given operator.
lookupOperatorsForDefaultedComparison(Sema & Self,Scope * S,UnresolvedSetImpl & Operators,OverloadedOperatorKind Op)8260 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8261                                                   UnresolvedSetImpl &Operators,
8262                                                   OverloadedOperatorKind Op) {
8263   auto Lookup = [&](OverloadedOperatorKind OO) {
8264     Self.LookupOverloadedOperatorName(OO, S, Operators);
8265   };
8266 
8267   // Every defaulted operator looks up itself.
8268   Lookup(Op);
8269   // ... and the rewritten form of itself, if any.
8270   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8271     Lookup(ExtraOp);
8272 
8273   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8274   // synthesize a three-way comparison from '<' and '=='. In a dependent
8275   // context, we also need to look up '==' in case we implicitly declare a
8276   // defaulted 'operator=='.
8277   if (Op == OO_Spaceship) {
8278     Lookup(OO_ExclaimEqual);
8279     Lookup(OO_Less);
8280     Lookup(OO_EqualEqual);
8281   }
8282 }
8283 
CheckExplicitlyDefaultedComparison(Scope * S,FunctionDecl * FD,DefaultedComparisonKind DCK)8284 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8285                                               DefaultedComparisonKind DCK) {
8286   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8287 
8288   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8289   assert(RD && "defaulted comparison is not defaulted in a class");
8290 
8291   // Perform any unqualified lookups we're going to need to default this
8292   // function.
8293   if (S) {
8294     UnresolvedSet<32> Operators;
8295     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8296                                           FD->getOverloadedOperator());
8297     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8298         Context, Operators.pairs()));
8299   }
8300 
8301   // C++2a [class.compare.default]p1:
8302   //   A defaulted comparison operator function for some class C shall be a
8303   //   non-template function declared in the member-specification of C that is
8304   //    -- a non-static const member of C having one parameter of type
8305   //       const C&, or
8306   //    -- a friend of C having two parameters of type const C& or two
8307   //       parameters of type C.
8308   QualType ExpectedParmType1 = Context.getRecordType(RD);
8309   QualType ExpectedParmType2 =
8310       Context.getLValueReferenceType(ExpectedParmType1.withConst());
8311   if (isa<CXXMethodDecl>(FD))
8312     ExpectedParmType1 = ExpectedParmType2;
8313   for (const ParmVarDecl *Param : FD->parameters()) {
8314     if (!Param->getType()->isDependentType() &&
8315         !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8316         !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8317       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8318       // corresponding defaulted 'operator<=>' already.
8319       if (!FD->isImplicit()) {
8320         Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8321             << (int)DCK << Param->getType() << ExpectedParmType1
8322             << !isa<CXXMethodDecl>(FD)
8323             << ExpectedParmType2 << Param->getSourceRange();
8324       }
8325       return true;
8326     }
8327   }
8328   if (FD->getNumParams() == 2 &&
8329       !Context.hasSameType(FD->getParamDecl(0)->getType(),
8330                            FD->getParamDecl(1)->getType())) {
8331     if (!FD->isImplicit()) {
8332       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8333           << (int)DCK
8334           << FD->getParamDecl(0)->getType()
8335           << FD->getParamDecl(0)->getSourceRange()
8336           << FD->getParamDecl(1)->getType()
8337           << FD->getParamDecl(1)->getSourceRange();
8338     }
8339     return true;
8340   }
8341 
8342   // ... non-static const member ...
8343   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8344     assert(!MD->isStatic() && "comparison function cannot be a static member");
8345     if (!MD->isConst()) {
8346       SourceLocation InsertLoc;
8347       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8348         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8349       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8350       // corresponding defaulted 'operator<=>' already.
8351       if (!MD->isImplicit()) {
8352         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8353           << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8354       }
8355 
8356       // Add the 'const' to the type to recover.
8357       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8358       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8359       EPI.TypeQuals.addConst();
8360       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8361                                           FPT->getParamTypes(), EPI));
8362     }
8363   } else {
8364     // A non-member function declared in a class must be a friend.
8365     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8366   }
8367 
8368   // C++2a [class.eq]p1, [class.rel]p1:
8369   //   A [defaulted comparison other than <=>] shall have a declared return
8370   //   type bool.
8371   if (DCK != DefaultedComparisonKind::ThreeWay &&
8372       !FD->getDeclaredReturnType()->isDependentType() &&
8373       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8374     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8375         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8376         << FD->getReturnTypeSourceRange();
8377     return true;
8378   }
8379   // C++2a [class.spaceship]p2 [P2002R0]:
8380   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8381   //   R shall not contain a placeholder type.
8382   if (DCK == DefaultedComparisonKind::ThreeWay &&
8383       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8384       !Context.hasSameType(FD->getDeclaredReturnType(),
8385                            Context.getAutoDeductType())) {
8386     Diag(FD->getLocation(),
8387          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8388         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8389         << FD->getReturnTypeSourceRange();
8390     return true;
8391   }
8392 
8393   // For a defaulted function in a dependent class, defer all remaining checks
8394   // until instantiation.
8395   if (RD->isDependentType())
8396     return false;
8397 
8398   // Determine whether the function should be defined as deleted.
8399   DefaultedComparisonInfo Info =
8400       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8401 
8402   bool First = FD == FD->getCanonicalDecl();
8403 
8404   // If we want to delete the function, then do so; there's nothing else to
8405   // check in that case.
8406   if (Info.Deleted) {
8407     if (!First) {
8408       // C++11 [dcl.fct.def.default]p4:
8409       //   [For a] user-provided explicitly-defaulted function [...] if such a
8410       //   function is implicitly defined as deleted, the program is ill-formed.
8411       //
8412       // This is really just a consequence of the general rule that you can
8413       // only delete a function on its first declaration.
8414       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8415           << FD->isImplicit() << (int)DCK;
8416       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8417                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8418           .visit();
8419       return true;
8420     }
8421 
8422     SetDeclDeleted(FD, FD->getLocation());
8423     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8424       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8425           << (int)DCK;
8426       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8427                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8428           .visit();
8429     }
8430     return false;
8431   }
8432 
8433   // C++2a [class.spaceship]p2:
8434   //   The return type is deduced as the common comparison type of R0, R1, ...
8435   if (DCK == DefaultedComparisonKind::ThreeWay &&
8436       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8437     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8438     if (RetLoc.isInvalid())
8439       RetLoc = FD->getBeginLoc();
8440     // FIXME: Should we really care whether we have the complete type and the
8441     // 'enumerator' constants here? A forward declaration seems sufficient.
8442     QualType Cat = CheckComparisonCategoryType(
8443         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8444     if (Cat.isNull())
8445       return true;
8446     Context.adjustDeducedFunctionResultType(
8447         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8448   }
8449 
8450   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8451   //   An explicitly-defaulted function that is not defined as deleted may be
8452   //   declared constexpr or consteval only if it is constexpr-compatible.
8453   // C++2a [class.compare.default]p3 [P2002R0]:
8454   //   A defaulted comparison function is constexpr-compatible if it satisfies
8455   //   the requirements for a constexpr function [...]
8456   // The only relevant requirements are that the parameter and return types are
8457   // literal types. The remaining conditions are checked by the analyzer.
8458   if (FD->isConstexpr()) {
8459     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8460         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8461         !Info.Constexpr) {
8462       Diag(FD->getBeginLoc(),
8463            diag::err_incorrect_defaulted_comparison_constexpr)
8464           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8465       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8466                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8467           .visit();
8468     }
8469   }
8470 
8471   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8472   //   If a constexpr-compatible function is explicitly defaulted on its first
8473   //   declaration, it is implicitly considered to be constexpr.
8474   // FIXME: Only applying this to the first declaration seems problematic, as
8475   // simple reorderings can affect the meaning of the program.
8476   if (First && !FD->isConstexpr() && Info.Constexpr)
8477     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8478 
8479   // C++2a [except.spec]p3:
8480   //   If a declaration of a function does not have a noexcept-specifier
8481   //   [and] is defaulted on its first declaration, [...] the exception
8482   //   specification is as specified below
8483   if (FD->getExceptionSpecType() == EST_None) {
8484     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8485     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8486     EPI.ExceptionSpec.Type = EST_Unevaluated;
8487     EPI.ExceptionSpec.SourceDecl = FD;
8488     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8489                                         FPT->getParamTypes(), EPI));
8490   }
8491 
8492   return false;
8493 }
8494 
DeclareImplicitEqualityComparison(CXXRecordDecl * RD,FunctionDecl * Spaceship)8495 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8496                                              FunctionDecl *Spaceship) {
8497   Sema::CodeSynthesisContext Ctx;
8498   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8499   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8500   Ctx.Entity = Spaceship;
8501   pushCodeSynthesisContext(Ctx);
8502 
8503   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8504     EqualEqual->setImplicit();
8505 
8506   popCodeSynthesisContext();
8507 }
8508 
DefineDefaultedComparison(SourceLocation UseLoc,FunctionDecl * FD,DefaultedComparisonKind DCK)8509 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8510                                      DefaultedComparisonKind DCK) {
8511   assert(FD->isDefaulted() && !FD->isDeleted() &&
8512          !FD->doesThisDeclarationHaveABody());
8513   if (FD->willHaveBody() || FD->isInvalidDecl())
8514     return;
8515 
8516   SynthesizedFunctionScope Scope(*this, FD);
8517 
8518   // Add a context note for diagnostics produced after this point.
8519   Scope.addContextNote(UseLoc);
8520 
8521   {
8522     // Build and set up the function body.
8523     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8524     SourceLocation BodyLoc =
8525         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8526     StmtResult Body =
8527         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8528     if (Body.isInvalid()) {
8529       FD->setInvalidDecl();
8530       return;
8531     }
8532     FD->setBody(Body.get());
8533     FD->markUsed(Context);
8534   }
8535 
8536   // The exception specification is needed because we are defining the
8537   // function. Note that this will reuse the body we just built.
8538   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8539 
8540   if (ASTMutationListener *L = getASTMutationListener())
8541     L->CompletedImplicitDefinition(FD);
8542 }
8543 
8544 static Sema::ImplicitExceptionSpecification
ComputeDefaultedComparisonExceptionSpec(Sema & S,SourceLocation Loc,FunctionDecl * FD,Sema::DefaultedComparisonKind DCK)8545 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8546                                         FunctionDecl *FD,
8547                                         Sema::DefaultedComparisonKind DCK) {
8548   ComputingExceptionSpec CES(S, FD, Loc);
8549   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8550 
8551   if (FD->isInvalidDecl())
8552     return ExceptSpec;
8553 
8554   // The common case is that we just defined the comparison function. In that
8555   // case, just look at whether the body can throw.
8556   if (FD->hasBody()) {
8557     ExceptSpec.CalledStmt(FD->getBody());
8558   } else {
8559     // Otherwise, build a body so we can check it. This should ideally only
8560     // happen when we're not actually marking the function referenced. (This is
8561     // only really important for efficiency: we don't want to build and throw
8562     // away bodies for comparison functions more than we strictly need to.)
8563 
8564     // Pretend to synthesize the function body in an unevaluated context.
8565     // Note that we can't actually just go ahead and define the function here:
8566     // we are not permitted to mark its callees as referenced.
8567     Sema::SynthesizedFunctionScope Scope(S, FD);
8568     EnterExpressionEvaluationContext Context(
8569         S, Sema::ExpressionEvaluationContext::Unevaluated);
8570 
8571     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8572     SourceLocation BodyLoc =
8573         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8574     StmtResult Body =
8575         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8576     if (!Body.isInvalid())
8577       ExceptSpec.CalledStmt(Body.get());
8578 
8579     // FIXME: Can we hold onto this body and just transform it to potentially
8580     // evaluated when we're asked to define the function rather than rebuilding
8581     // it? Either that, or we should only build the bits of the body that we
8582     // need (the expressions, not the statements).
8583   }
8584 
8585   return ExceptSpec;
8586 }
8587 
CheckDelayedMemberExceptionSpecs()8588 void Sema::CheckDelayedMemberExceptionSpecs() {
8589   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8590   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8591 
8592   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8593   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8594 
8595   // Perform any deferred checking of exception specifications for virtual
8596   // destructors.
8597   for (auto &Check : Overriding)
8598     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8599 
8600   // Perform any deferred checking of exception specifications for befriended
8601   // special members.
8602   for (auto &Check : Equivalent)
8603     CheckEquivalentExceptionSpec(Check.second, Check.first);
8604 }
8605 
8606 namespace {
8607 /// CRTP base class for visiting operations performed by a special member
8608 /// function (or inherited constructor).
8609 template<typename Derived>
8610 struct SpecialMemberVisitor {
8611   Sema &S;
8612   CXXMethodDecl *MD;
8613   Sema::CXXSpecialMember CSM;
8614   Sema::InheritedConstructorInfo *ICI;
8615 
8616   // Properties of the special member, computed for convenience.
8617   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8618 
SpecialMemberVisitor__anonedc74bd72411::SpecialMemberVisitor8619   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8620                        Sema::InheritedConstructorInfo *ICI)
8621       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8622     switch (CSM) {
8623     case Sema::CXXDefaultConstructor:
8624     case Sema::CXXCopyConstructor:
8625     case Sema::CXXMoveConstructor:
8626       IsConstructor = true;
8627       break;
8628     case Sema::CXXCopyAssignment:
8629     case Sema::CXXMoveAssignment:
8630       IsAssignment = true;
8631       break;
8632     case Sema::CXXDestructor:
8633       break;
8634     case Sema::CXXInvalid:
8635       llvm_unreachable("invalid special member kind");
8636     }
8637 
8638     if (MD->getNumParams()) {
8639       if (const ReferenceType *RT =
8640               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8641         ConstArg = RT->getPointeeType().isConstQualified();
8642     }
8643   }
8644 
getDerived__anonedc74bd72411::SpecialMemberVisitor8645   Derived &getDerived() { return static_cast<Derived&>(*this); }
8646 
8647   /// Is this a "move" special member?
isMove__anonedc74bd72411::SpecialMemberVisitor8648   bool isMove() const {
8649     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8650   }
8651 
8652   /// Look up the corresponding special member in the given class.
lookupIn__anonedc74bd72411::SpecialMemberVisitor8653   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8654                                              unsigned Quals, bool IsMutable) {
8655     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8656                                        ConstArg && !IsMutable);
8657   }
8658 
8659   /// Look up the constructor for the specified base class to see if it's
8660   /// overridden due to this being an inherited constructor.
lookupInheritedCtor__anonedc74bd72411::SpecialMemberVisitor8661   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8662     if (!ICI)
8663       return {};
8664     assert(CSM == Sema::CXXDefaultConstructor);
8665     auto *BaseCtor =
8666       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8667     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8668       return MD;
8669     return {};
8670   }
8671 
8672   /// A base or member subobject.
8673   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8674 
8675   /// Get the location to use for a subobject in diagnostics.
getSubobjectLoc__anonedc74bd72411::SpecialMemberVisitor8676   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8677     // FIXME: For an indirect virtual base, the direct base leading to
8678     // the indirect virtual base would be a more useful choice.
8679     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8680       return B->getBaseTypeLoc();
8681     else
8682       return Subobj.get<FieldDecl*>()->getLocation();
8683   }
8684 
8685   enum BasesToVisit {
8686     /// Visit all non-virtual (direct) bases.
8687     VisitNonVirtualBases,
8688     /// Visit all direct bases, virtual or not.
8689     VisitDirectBases,
8690     /// Visit all non-virtual bases, and all virtual bases if the class
8691     /// is not abstract.
8692     VisitPotentiallyConstructedBases,
8693     /// Visit all direct or virtual bases.
8694     VisitAllBases
8695   };
8696 
8697   // Visit the bases and members of the class.
visit__anonedc74bd72411::SpecialMemberVisitor8698   bool visit(BasesToVisit Bases) {
8699     CXXRecordDecl *RD = MD->getParent();
8700 
8701     if (Bases == VisitPotentiallyConstructedBases)
8702       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8703 
8704     for (auto &B : RD->bases())
8705       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8706           getDerived().visitBase(&B))
8707         return true;
8708 
8709     if (Bases == VisitAllBases)
8710       for (auto &B : RD->vbases())
8711         if (getDerived().visitBase(&B))
8712           return true;
8713 
8714     for (auto *F : RD->fields())
8715       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8716           getDerived().visitField(F))
8717         return true;
8718 
8719     return false;
8720   }
8721 };
8722 }
8723 
8724 namespace {
8725 struct SpecialMemberDeletionInfo
8726     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8727   bool Diagnose;
8728 
8729   SourceLocation Loc;
8730 
8731   bool AllFieldsAreConst;
8732 
SpecialMemberDeletionInfo__anonedc74bd72511::SpecialMemberDeletionInfo8733   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8734                             Sema::CXXSpecialMember CSM,
8735                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8736       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8737         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8738 
inUnion__anonedc74bd72511::SpecialMemberDeletionInfo8739   bool inUnion() const { return MD->getParent()->isUnion(); }
8740 
getEffectiveCSM__anonedc74bd72511::SpecialMemberDeletionInfo8741   Sema::CXXSpecialMember getEffectiveCSM() {
8742     return ICI ? Sema::CXXInvalid : CSM;
8743   }
8744 
8745   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8746 
visitBase__anonedc74bd72511::SpecialMemberDeletionInfo8747   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
visitField__anonedc74bd72511::SpecialMemberDeletionInfo8748   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8749 
8750   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8751   bool shouldDeleteForField(FieldDecl *FD);
8752   bool shouldDeleteForAllConstMembers();
8753 
8754   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8755                                      unsigned Quals);
8756   bool shouldDeleteForSubobjectCall(Subobject Subobj,
8757                                     Sema::SpecialMemberOverloadResult SMOR,
8758                                     bool IsDtorCallInCtor);
8759 
8760   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8761 };
8762 }
8763 
8764 /// Is the given special member inaccessible when used on the given
8765 /// sub-object.
isAccessible(Subobject Subobj,CXXMethodDecl * target)8766 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8767                                              CXXMethodDecl *target) {
8768   /// If we're operating on a base class, the object type is the
8769   /// type of this special member.
8770   QualType objectTy;
8771   AccessSpecifier access = target->getAccess();
8772   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8773     objectTy = S.Context.getTypeDeclType(MD->getParent());
8774     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8775 
8776   // If we're operating on a field, the object type is the type of the field.
8777   } else {
8778     objectTy = S.Context.getTypeDeclType(target->getParent());
8779   }
8780 
8781   return S.isMemberAccessibleForDeletion(
8782       target->getParent(), DeclAccessPair::make(target, access), objectTy);
8783 }
8784 
8785 /// Check whether we should delete a special member due to the implicit
8786 /// definition containing a call to a special member of a subobject.
shouldDeleteForSubobjectCall(Subobject Subobj,Sema::SpecialMemberOverloadResult SMOR,bool IsDtorCallInCtor)8787 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8788     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8789     bool IsDtorCallInCtor) {
8790   CXXMethodDecl *Decl = SMOR.getMethod();
8791   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8792 
8793   int DiagKind = -1;
8794 
8795   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8796     DiagKind = !Decl ? 0 : 1;
8797   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8798     DiagKind = 2;
8799   else if (!isAccessible(Subobj, Decl))
8800     DiagKind = 3;
8801   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8802            !Decl->isTrivial()) {
8803     // A member of a union must have a trivial corresponding special member.
8804     // As a weird special case, a destructor call from a union's constructor
8805     // must be accessible and non-deleted, but need not be trivial. Such a
8806     // destructor is never actually called, but is semantically checked as
8807     // if it were.
8808     DiagKind = 4;
8809   }
8810 
8811   if (DiagKind == -1)
8812     return false;
8813 
8814   if (Diagnose) {
8815     if (Field) {
8816       S.Diag(Field->getLocation(),
8817              diag::note_deleted_special_member_class_subobject)
8818         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8819         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8820     } else {
8821       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8822       S.Diag(Base->getBeginLoc(),
8823              diag::note_deleted_special_member_class_subobject)
8824           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8825           << Base->getType() << DiagKind << IsDtorCallInCtor
8826           << /*IsObjCPtr*/false;
8827     }
8828 
8829     if (DiagKind == 1)
8830       S.NoteDeletedFunction(Decl);
8831     // FIXME: Explain inaccessibility if DiagKind == 3.
8832   }
8833 
8834   return true;
8835 }
8836 
8837 /// Check whether we should delete a special member function due to having a
8838 /// direct or virtual base class or non-static data member of class type M.
shouldDeleteForClassSubobject(CXXRecordDecl * Class,Subobject Subobj,unsigned Quals)8839 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8840     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8841   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8842   bool IsMutable = Field && Field->isMutable();
8843 
8844   // C++11 [class.ctor]p5:
8845   // -- any direct or virtual base class, or non-static data member with no
8846   //    brace-or-equal-initializer, has class type M (or array thereof) and
8847   //    either M has no default constructor or overload resolution as applied
8848   //    to M's default constructor results in an ambiguity or in a function
8849   //    that is deleted or inaccessible
8850   // C++11 [class.copy]p11, C++11 [class.copy]p23:
8851   // -- a direct or virtual base class B that cannot be copied/moved because
8852   //    overload resolution, as applied to B's corresponding special member,
8853   //    results in an ambiguity or a function that is deleted or inaccessible
8854   //    from the defaulted special member
8855   // C++11 [class.dtor]p5:
8856   // -- any direct or virtual base class [...] has a type with a destructor
8857   //    that is deleted or inaccessible
8858   if (!(CSM == Sema::CXXDefaultConstructor &&
8859         Field && Field->hasInClassInitializer()) &&
8860       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8861                                    false))
8862     return true;
8863 
8864   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8865   // -- any direct or virtual base class or non-static data member has a
8866   //    type with a destructor that is deleted or inaccessible
8867   if (IsConstructor) {
8868     Sema::SpecialMemberOverloadResult SMOR =
8869         S.LookupSpecialMember(Class, Sema::CXXDestructor,
8870                               false, false, false, false, false);
8871     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8872       return true;
8873   }
8874 
8875   return false;
8876 }
8877 
shouldDeleteForVariantObjCPtrMember(FieldDecl * FD,QualType FieldType)8878 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8879     FieldDecl *FD, QualType FieldType) {
8880   // The defaulted special functions are defined as deleted if this is a variant
8881   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
8882   // type under ARC.
8883   if (!FieldType.hasNonTrivialObjCLifetime())
8884     return false;
8885 
8886   // Don't make the defaulted default constructor defined as deleted if the
8887   // member has an in-class initializer.
8888   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
8889     return false;
8890 
8891   if (Diagnose) {
8892     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
8893     S.Diag(FD->getLocation(),
8894            diag::note_deleted_special_member_class_subobject)
8895         << getEffectiveCSM() << ParentClass << /*IsField*/true
8896         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
8897   }
8898 
8899   return true;
8900 }
8901 
8902 /// Check whether we should delete a special member function due to the class
8903 /// having a particular direct or virtual base class.
shouldDeleteForBase(CXXBaseSpecifier * Base)8904 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
8905   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
8906   // If program is correct, BaseClass cannot be null, but if it is, the error
8907   // must be reported elsewhere.
8908   if (!BaseClass)
8909     return false;
8910   // If we have an inheriting constructor, check whether we're calling an
8911   // inherited constructor instead of a default constructor.
8912   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
8913   if (auto *BaseCtor = SMOR.getMethod()) {
8914     // Note that we do not check access along this path; other than that,
8915     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
8916     // FIXME: Check that the base has a usable destructor! Sink this into
8917     // shouldDeleteForClassSubobject.
8918     if (BaseCtor->isDeleted() && Diagnose) {
8919       S.Diag(Base->getBeginLoc(),
8920              diag::note_deleted_special_member_class_subobject)
8921           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8922           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
8923           << /*IsObjCPtr*/false;
8924       S.NoteDeletedFunction(BaseCtor);
8925     }
8926     return BaseCtor->isDeleted();
8927   }
8928   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
8929 }
8930 
8931 /// Check whether we should delete a special member function due to the class
8932 /// having a particular non-static data member.
shouldDeleteForField(FieldDecl * FD)8933 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
8934   QualType FieldType = S.Context.getBaseElementType(FD->getType());
8935   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
8936 
8937   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
8938     return true;
8939 
8940   if (CSM == Sema::CXXDefaultConstructor) {
8941     // For a default constructor, all references must be initialized in-class
8942     // and, if a union, it must have a non-const member.
8943     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
8944       if (Diagnose)
8945         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8946           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
8947       return true;
8948     }
8949     // C++11 [class.ctor]p5: any non-variant non-static data member of
8950     // const-qualified type (or array thereof) with no
8951     // brace-or-equal-initializer does not have a user-provided default
8952     // constructor.
8953     if (!inUnion() && FieldType.isConstQualified() &&
8954         !FD->hasInClassInitializer() &&
8955         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
8956       if (Diagnose)
8957         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8958           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
8959       return true;
8960     }
8961 
8962     if (inUnion() && !FieldType.isConstQualified())
8963       AllFieldsAreConst = false;
8964   } else if (CSM == Sema::CXXCopyConstructor) {
8965     // For a copy constructor, data members must not be of rvalue reference
8966     // type.
8967     if (FieldType->isRValueReferenceType()) {
8968       if (Diagnose)
8969         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
8970           << MD->getParent() << FD << FieldType;
8971       return true;
8972     }
8973   } else if (IsAssignment) {
8974     // For an assignment operator, data members must not be of reference type.
8975     if (FieldType->isReferenceType()) {
8976       if (Diagnose)
8977         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8978           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
8979       return true;
8980     }
8981     if (!FieldRecord && FieldType.isConstQualified()) {
8982       // C++11 [class.copy]p23:
8983       // -- a non-static data member of const non-class type (or array thereof)
8984       if (Diagnose)
8985         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8986           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
8987       return true;
8988     }
8989   }
8990 
8991   if (FieldRecord) {
8992     // Some additional restrictions exist on the variant members.
8993     if (!inUnion() && FieldRecord->isUnion() &&
8994         FieldRecord->isAnonymousStructOrUnion()) {
8995       bool AllVariantFieldsAreConst = true;
8996 
8997       // FIXME: Handle anonymous unions declared within anonymous unions.
8998       for (auto *UI : FieldRecord->fields()) {
8999         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9000 
9001         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9002           return true;
9003 
9004         if (!UnionFieldType.isConstQualified())
9005           AllVariantFieldsAreConst = false;
9006 
9007         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9008         if (UnionFieldRecord &&
9009             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9010                                           UnionFieldType.getCVRQualifiers()))
9011           return true;
9012       }
9013 
9014       // At least one member in each anonymous union must be non-const
9015       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9016           !FieldRecord->field_empty()) {
9017         if (Diagnose)
9018           S.Diag(FieldRecord->getLocation(),
9019                  diag::note_deleted_default_ctor_all_const)
9020             << !!ICI << MD->getParent() << /*anonymous union*/1;
9021         return true;
9022       }
9023 
9024       // Don't check the implicit member of the anonymous union type.
9025       // This is technically non-conformant, but sanity demands it.
9026       return false;
9027     }
9028 
9029     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9030                                       FieldType.getCVRQualifiers()))
9031       return true;
9032   }
9033 
9034   return false;
9035 }
9036 
9037 /// C++11 [class.ctor] p5:
9038 ///   A defaulted default constructor for a class X is defined as deleted if
9039 /// X is a union and all of its variant members are of const-qualified type.
shouldDeleteForAllConstMembers()9040 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9041   // This is a silly definition, because it gives an empty union a deleted
9042   // default constructor. Don't do that.
9043   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9044     bool AnyFields = false;
9045     for (auto *F : MD->getParent()->fields())
9046       if ((AnyFields = !F->isUnnamedBitfield()))
9047         break;
9048     if (!AnyFields)
9049       return false;
9050     if (Diagnose)
9051       S.Diag(MD->getParent()->getLocation(),
9052              diag::note_deleted_default_ctor_all_const)
9053         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9054     return true;
9055   }
9056   return false;
9057 }
9058 
9059 /// Determine whether a defaulted special member function should be defined as
9060 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9061 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
ShouldDeleteSpecialMember(CXXMethodDecl * MD,CXXSpecialMember CSM,InheritedConstructorInfo * ICI,bool Diagnose)9062 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9063                                      InheritedConstructorInfo *ICI,
9064                                      bool Diagnose) {
9065   if (MD->isInvalidDecl())
9066     return false;
9067   CXXRecordDecl *RD = MD->getParent();
9068   assert(!RD->isDependentType() && "do deletion after instantiation");
9069   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9070     return false;
9071 
9072   // C++11 [expr.lambda.prim]p19:
9073   //   The closure type associated with a lambda-expression has a
9074   //   deleted (8.4.3) default constructor and a deleted copy
9075   //   assignment operator.
9076   // C++2a adds back these operators if the lambda has no lambda-capture.
9077   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9078       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9079     if (Diagnose)
9080       Diag(RD->getLocation(), diag::note_lambda_decl);
9081     return true;
9082   }
9083 
9084   // For an anonymous struct or union, the copy and assignment special members
9085   // will never be used, so skip the check. For an anonymous union declared at
9086   // namespace scope, the constructor and destructor are used.
9087   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9088       RD->isAnonymousStructOrUnion())
9089     return false;
9090 
9091   // C++11 [class.copy]p7, p18:
9092   //   If the class definition declares a move constructor or move assignment
9093   //   operator, an implicitly declared copy constructor or copy assignment
9094   //   operator is defined as deleted.
9095   if (MD->isImplicit() &&
9096       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9097     CXXMethodDecl *UserDeclaredMove = nullptr;
9098 
9099     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9100     // deletion of the corresponding copy operation, not both copy operations.
9101     // MSVC 2015 has adopted the standards conforming behavior.
9102     bool DeletesOnlyMatchingCopy =
9103         getLangOpts().MSVCCompat &&
9104         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9105 
9106     if (RD->hasUserDeclaredMoveConstructor() &&
9107         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9108       if (!Diagnose) return true;
9109 
9110       // Find any user-declared move constructor.
9111       for (auto *I : RD->ctors()) {
9112         if (I->isMoveConstructor()) {
9113           UserDeclaredMove = I;
9114           break;
9115         }
9116       }
9117       assert(UserDeclaredMove);
9118     } else if (RD->hasUserDeclaredMoveAssignment() &&
9119                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9120       if (!Diagnose) return true;
9121 
9122       // Find any user-declared move assignment operator.
9123       for (auto *I : RD->methods()) {
9124         if (I->isMoveAssignmentOperator()) {
9125           UserDeclaredMove = I;
9126           break;
9127         }
9128       }
9129       assert(UserDeclaredMove);
9130     }
9131 
9132     if (UserDeclaredMove) {
9133       Diag(UserDeclaredMove->getLocation(),
9134            diag::note_deleted_copy_user_declared_move)
9135         << (CSM == CXXCopyAssignment) << RD
9136         << UserDeclaredMove->isMoveAssignmentOperator();
9137       return true;
9138     }
9139   }
9140 
9141   // Do access control from the special member function
9142   ContextRAII MethodContext(*this, MD);
9143 
9144   // C++11 [class.dtor]p5:
9145   // -- for a virtual destructor, lookup of the non-array deallocation function
9146   //    results in an ambiguity or in a function that is deleted or inaccessible
9147   if (CSM == CXXDestructor && MD->isVirtual()) {
9148     FunctionDecl *OperatorDelete = nullptr;
9149     DeclarationName Name =
9150       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9151     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9152                                  OperatorDelete, /*Diagnose*/false)) {
9153       if (Diagnose)
9154         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9155       return true;
9156     }
9157   }
9158 
9159   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9160 
9161   // Per DR1611, do not consider virtual bases of constructors of abstract
9162   // classes, since we are not going to construct them.
9163   // Per DR1658, do not consider virtual bases of destructors of abstract
9164   // classes either.
9165   // Per DR2180, for assignment operators we only assign (and thus only
9166   // consider) direct bases.
9167   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9168                                  : SMI.VisitPotentiallyConstructedBases))
9169     return true;
9170 
9171   if (SMI.shouldDeleteForAllConstMembers())
9172     return true;
9173 
9174   if (getLangOpts().CUDA) {
9175     // We should delete the special member in CUDA mode if target inference
9176     // failed.
9177     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9178     // is treated as certain special member, which may not reflect what special
9179     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9180     // expects CSM to match MD, therefore recalculate CSM.
9181     assert(ICI || CSM == getSpecialMember(MD));
9182     auto RealCSM = CSM;
9183     if (ICI)
9184       RealCSM = getSpecialMember(MD);
9185 
9186     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9187                                                    SMI.ConstArg, Diagnose);
9188   }
9189 
9190   return false;
9191 }
9192 
DiagnoseDeletedDefaultedFunction(FunctionDecl * FD)9193 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9194   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9195   assert(DFK && "not a defaultable function");
9196   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9197 
9198   if (DFK.isSpecialMember()) {
9199     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9200                               nullptr, /*Diagnose=*/true);
9201   } else {
9202     DefaultedComparisonAnalyzer(
9203         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9204         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9205         .visit();
9206   }
9207 }
9208 
9209 /// Perform lookup for a special member of the specified kind, and determine
9210 /// whether it is trivial. If the triviality can be determined without the
9211 /// lookup, skip it. This is intended for use when determining whether a
9212 /// special member of a containing object is trivial, and thus does not ever
9213 /// perform overload resolution for default constructors.
9214 ///
9215 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9216 /// member that was most likely to be intended to be trivial, if any.
9217 ///
9218 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9219 /// determine whether the special member is trivial.
findTrivialSpecialMember(Sema & S,CXXRecordDecl * RD,Sema::CXXSpecialMember CSM,unsigned Quals,bool ConstRHS,Sema::TrivialABIHandling TAH,CXXMethodDecl ** Selected)9220 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9221                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9222                                      bool ConstRHS,
9223                                      Sema::TrivialABIHandling TAH,
9224                                      CXXMethodDecl **Selected) {
9225   if (Selected)
9226     *Selected = nullptr;
9227 
9228   switch (CSM) {
9229   case Sema::CXXInvalid:
9230     llvm_unreachable("not a special member");
9231 
9232   case Sema::CXXDefaultConstructor:
9233     // C++11 [class.ctor]p5:
9234     //   A default constructor is trivial if:
9235     //    - all the [direct subobjects] have trivial default constructors
9236     //
9237     // Note, no overload resolution is performed in this case.
9238     if (RD->hasTrivialDefaultConstructor())
9239       return true;
9240 
9241     if (Selected) {
9242       // If there's a default constructor which could have been trivial, dig it
9243       // out. Otherwise, if there's any user-provided default constructor, point
9244       // to that as an example of why there's not a trivial one.
9245       CXXConstructorDecl *DefCtor = nullptr;
9246       if (RD->needsImplicitDefaultConstructor())
9247         S.DeclareImplicitDefaultConstructor(RD);
9248       for (auto *CI : RD->ctors()) {
9249         if (!CI->isDefaultConstructor())
9250           continue;
9251         DefCtor = CI;
9252         if (!DefCtor->isUserProvided())
9253           break;
9254       }
9255 
9256       *Selected = DefCtor;
9257     }
9258 
9259     return false;
9260 
9261   case Sema::CXXDestructor:
9262     // C++11 [class.dtor]p5:
9263     //   A destructor is trivial if:
9264     //    - all the direct [subobjects] have trivial destructors
9265     if (RD->hasTrivialDestructor() ||
9266         (TAH == Sema::TAH_ConsiderTrivialABI &&
9267          RD->hasTrivialDestructorForCall()))
9268       return true;
9269 
9270     if (Selected) {
9271       if (RD->needsImplicitDestructor())
9272         S.DeclareImplicitDestructor(RD);
9273       *Selected = RD->getDestructor();
9274     }
9275 
9276     return false;
9277 
9278   case Sema::CXXCopyConstructor:
9279     // C++11 [class.copy]p12:
9280     //   A copy constructor is trivial if:
9281     //    - the constructor selected to copy each direct [subobject] is trivial
9282     if (RD->hasTrivialCopyConstructor() ||
9283         (TAH == Sema::TAH_ConsiderTrivialABI &&
9284          RD->hasTrivialCopyConstructorForCall())) {
9285       if (Quals == Qualifiers::Const)
9286         // We must either select the trivial copy constructor or reach an
9287         // ambiguity; no need to actually perform overload resolution.
9288         return true;
9289     } else if (!Selected) {
9290       return false;
9291     }
9292     // In C++98, we are not supposed to perform overload resolution here, but we
9293     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9294     // cases like B as having a non-trivial copy constructor:
9295     //   struct A { template<typename T> A(T&); };
9296     //   struct B { mutable A a; };
9297     goto NeedOverloadResolution;
9298 
9299   case Sema::CXXCopyAssignment:
9300     // C++11 [class.copy]p25:
9301     //   A copy assignment operator is trivial if:
9302     //    - the assignment operator selected to copy each direct [subobject] is
9303     //      trivial
9304     if (RD->hasTrivialCopyAssignment()) {
9305       if (Quals == Qualifiers::Const)
9306         return true;
9307     } else if (!Selected) {
9308       return false;
9309     }
9310     // In C++98, we are not supposed to perform overload resolution here, but we
9311     // treat that as a language defect.
9312     goto NeedOverloadResolution;
9313 
9314   case Sema::CXXMoveConstructor:
9315   case Sema::CXXMoveAssignment:
9316   NeedOverloadResolution:
9317     Sema::SpecialMemberOverloadResult SMOR =
9318         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9319 
9320     // The standard doesn't describe how to behave if the lookup is ambiguous.
9321     // We treat it as not making the member non-trivial, just like the standard
9322     // mandates for the default constructor. This should rarely matter, because
9323     // the member will also be deleted.
9324     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9325       return true;
9326 
9327     if (!SMOR.getMethod()) {
9328       assert(SMOR.getKind() ==
9329              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9330       return false;
9331     }
9332 
9333     // We deliberately don't check if we found a deleted special member. We're
9334     // not supposed to!
9335     if (Selected)
9336       *Selected = SMOR.getMethod();
9337 
9338     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9339         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9340       return SMOR.getMethod()->isTrivialForCall();
9341     return SMOR.getMethod()->isTrivial();
9342   }
9343 
9344   llvm_unreachable("unknown special method kind");
9345 }
9346 
findUserDeclaredCtor(CXXRecordDecl * RD)9347 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9348   for (auto *CI : RD->ctors())
9349     if (!CI->isImplicit())
9350       return CI;
9351 
9352   // Look for constructor templates.
9353   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9354   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9355     if (CXXConstructorDecl *CD =
9356           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9357       return CD;
9358   }
9359 
9360   return nullptr;
9361 }
9362 
9363 /// The kind of subobject we are checking for triviality. The values of this
9364 /// enumeration are used in diagnostics.
9365 enum TrivialSubobjectKind {
9366   /// The subobject is a base class.
9367   TSK_BaseClass,
9368   /// The subobject is a non-static data member.
9369   TSK_Field,
9370   /// The object is actually the complete object.
9371   TSK_CompleteObject
9372 };
9373 
9374 /// Check whether the special member selected for a given type would be trivial.
checkTrivialSubobjectCall(Sema & S,SourceLocation SubobjLoc,QualType SubType,bool ConstRHS,Sema::CXXSpecialMember CSM,TrivialSubobjectKind Kind,Sema::TrivialABIHandling TAH,bool Diagnose)9375 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9376                                       QualType SubType, bool ConstRHS,
9377                                       Sema::CXXSpecialMember CSM,
9378                                       TrivialSubobjectKind Kind,
9379                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9380   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9381   if (!SubRD)
9382     return true;
9383 
9384   CXXMethodDecl *Selected;
9385   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9386                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9387     return true;
9388 
9389   if (Diagnose) {
9390     if (ConstRHS)
9391       SubType.addConst();
9392 
9393     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9394       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9395         << Kind << SubType.getUnqualifiedType();
9396       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9397         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9398     } else if (!Selected)
9399       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9400         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9401     else if (Selected->isUserProvided()) {
9402       if (Kind == TSK_CompleteObject)
9403         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9404           << Kind << SubType.getUnqualifiedType() << CSM;
9405       else {
9406         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9407           << Kind << SubType.getUnqualifiedType() << CSM;
9408         S.Diag(Selected->getLocation(), diag::note_declared_at);
9409       }
9410     } else {
9411       if (Kind != TSK_CompleteObject)
9412         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9413           << Kind << SubType.getUnqualifiedType() << CSM;
9414 
9415       // Explain why the defaulted or deleted special member isn't trivial.
9416       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9417                                Diagnose);
9418     }
9419   }
9420 
9421   return false;
9422 }
9423 
9424 /// Check whether the members of a class type allow a special member to be
9425 /// trivial.
checkTrivialClassMembers(Sema & S,CXXRecordDecl * RD,Sema::CXXSpecialMember CSM,bool ConstArg,Sema::TrivialABIHandling TAH,bool Diagnose)9426 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9427                                      Sema::CXXSpecialMember CSM,
9428                                      bool ConstArg,
9429                                      Sema::TrivialABIHandling TAH,
9430                                      bool Diagnose) {
9431   for (const auto *FI : RD->fields()) {
9432     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9433       continue;
9434 
9435     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9436 
9437     // Pretend anonymous struct or union members are members of this class.
9438     if (FI->isAnonymousStructOrUnion()) {
9439       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9440                                     CSM, ConstArg, TAH, Diagnose))
9441         return false;
9442       continue;
9443     }
9444 
9445     // C++11 [class.ctor]p5:
9446     //   A default constructor is trivial if [...]
9447     //    -- no non-static data member of its class has a
9448     //       brace-or-equal-initializer
9449     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9450       if (Diagnose)
9451         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9452             << FI;
9453       return false;
9454     }
9455 
9456     // Objective C ARC 4.3.5:
9457     //   [...] nontrivally ownership-qualified types are [...] not trivially
9458     //   default constructible, copy constructible, move constructible, copy
9459     //   assignable, move assignable, or destructible [...]
9460     if (FieldType.hasNonTrivialObjCLifetime()) {
9461       if (Diagnose)
9462         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9463           << RD << FieldType.getObjCLifetime();
9464       return false;
9465     }
9466 
9467     bool ConstRHS = ConstArg && !FI->isMutable();
9468     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9469                                    CSM, TSK_Field, TAH, Diagnose))
9470       return false;
9471   }
9472 
9473   return true;
9474 }
9475 
9476 /// Diagnose why the specified class does not have a trivial special member of
9477 /// the given kind.
DiagnoseNontrivial(const CXXRecordDecl * RD,CXXSpecialMember CSM)9478 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9479   QualType Ty = Context.getRecordType(RD);
9480 
9481   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9482   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9483                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9484                             /*Diagnose*/true);
9485 }
9486 
9487 /// Determine whether a defaulted or deleted special member function is trivial,
9488 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9489 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
SpecialMemberIsTrivial(CXXMethodDecl * MD,CXXSpecialMember CSM,TrivialABIHandling TAH,bool Diagnose)9490 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9491                                   TrivialABIHandling TAH, bool Diagnose) {
9492   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9493 
9494   CXXRecordDecl *RD = MD->getParent();
9495 
9496   bool ConstArg = false;
9497 
9498   // C++11 [class.copy]p12, p25: [DR1593]
9499   //   A [special member] is trivial if [...] its parameter-type-list is
9500   //   equivalent to the parameter-type-list of an implicit declaration [...]
9501   switch (CSM) {
9502   case CXXDefaultConstructor:
9503   case CXXDestructor:
9504     // Trivial default constructors and destructors cannot have parameters.
9505     break;
9506 
9507   case CXXCopyConstructor:
9508   case CXXCopyAssignment: {
9509     // Trivial copy operations always have const, non-volatile parameter types.
9510     ConstArg = true;
9511     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9512     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9513     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9514       if (Diagnose)
9515         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9516           << Param0->getSourceRange() << Param0->getType()
9517           << Context.getLValueReferenceType(
9518                Context.getRecordType(RD).withConst());
9519       return false;
9520     }
9521     break;
9522   }
9523 
9524   case CXXMoveConstructor:
9525   case CXXMoveAssignment: {
9526     // Trivial move operations always have non-cv-qualified parameters.
9527     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9528     const RValueReferenceType *RT =
9529       Param0->getType()->getAs<RValueReferenceType>();
9530     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9531       if (Diagnose)
9532         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9533           << Param0->getSourceRange() << Param0->getType()
9534           << Context.getRValueReferenceType(Context.getRecordType(RD));
9535       return false;
9536     }
9537     break;
9538   }
9539 
9540   case CXXInvalid:
9541     llvm_unreachable("not a special member");
9542   }
9543 
9544   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9545     if (Diagnose)
9546       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9547            diag::note_nontrivial_default_arg)
9548         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9549     return false;
9550   }
9551   if (MD->isVariadic()) {
9552     if (Diagnose)
9553       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9554     return false;
9555   }
9556 
9557   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9558   //   A copy/move [constructor or assignment operator] is trivial if
9559   //    -- the [member] selected to copy/move each direct base class subobject
9560   //       is trivial
9561   //
9562   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9563   //   A [default constructor or destructor] is trivial if
9564   //    -- all the direct base classes have trivial [default constructors or
9565   //       destructors]
9566   for (const auto &BI : RD->bases())
9567     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9568                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9569       return false;
9570 
9571   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9572   //   A copy/move [constructor or assignment operator] for a class X is
9573   //   trivial if
9574   //    -- for each non-static data member of X that is of class type (or array
9575   //       thereof), the constructor selected to copy/move that member is
9576   //       trivial
9577   //
9578   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9579   //   A [default constructor or destructor] is trivial if
9580   //    -- for all of the non-static data members of its class that are of class
9581   //       type (or array thereof), each such class has a trivial [default
9582   //       constructor or destructor]
9583   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9584     return false;
9585 
9586   // C++11 [class.dtor]p5:
9587   //   A destructor is trivial if [...]
9588   //    -- the destructor is not virtual
9589   if (CSM == CXXDestructor && MD->isVirtual()) {
9590     if (Diagnose)
9591       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9592     return false;
9593   }
9594 
9595   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9596   //   A [special member] for class X is trivial if [...]
9597   //    -- class X has no virtual functions and no virtual base classes
9598   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9599     if (!Diagnose)
9600       return false;
9601 
9602     if (RD->getNumVBases()) {
9603       // Check for virtual bases. We already know that the corresponding
9604       // member in all bases is trivial, so vbases must all be direct.
9605       CXXBaseSpecifier &BS = *RD->vbases_begin();
9606       assert(BS.isVirtual());
9607       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9608       return false;
9609     }
9610 
9611     // Must have a virtual method.
9612     for (const auto *MI : RD->methods()) {
9613       if (MI->isVirtual()) {
9614         SourceLocation MLoc = MI->getBeginLoc();
9615         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9616         return false;
9617       }
9618     }
9619 
9620     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9621   }
9622 
9623   // Looks like it's trivial!
9624   return true;
9625 }
9626 
9627 namespace {
9628 struct FindHiddenVirtualMethod {
9629   Sema *S;
9630   CXXMethodDecl *Method;
9631   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9632   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9633 
9634 private:
9635   /// Check whether any most overridden method from MD in Methods
CheckMostOverridenMethods__anonedc74bd72611::FindHiddenVirtualMethod9636   static bool CheckMostOverridenMethods(
9637       const CXXMethodDecl *MD,
9638       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9639     if (MD->size_overridden_methods() == 0)
9640       return Methods.count(MD->getCanonicalDecl());
9641     for (const CXXMethodDecl *O : MD->overridden_methods())
9642       if (CheckMostOverridenMethods(O, Methods))
9643         return true;
9644     return false;
9645   }
9646 
9647 public:
9648   /// Member lookup function that determines whether a given C++
9649   /// method overloads virtual methods in a base class without overriding any,
9650   /// to be used with CXXRecordDecl::lookupInBases().
operator ()__anonedc74bd72611::FindHiddenVirtualMethod9651   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9652     RecordDecl *BaseRecord =
9653         Specifier->getType()->castAs<RecordType>()->getDecl();
9654 
9655     DeclarationName Name = Method->getDeclName();
9656     assert(Name.getNameKind() == DeclarationName::Identifier);
9657 
9658     bool foundSameNameMethod = false;
9659     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9660     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
9661          Path.Decls = Path.Decls.slice(1)) {
9662       NamedDecl *D = Path.Decls.front();
9663       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9664         MD = MD->getCanonicalDecl();
9665         foundSameNameMethod = true;
9666         // Interested only in hidden virtual methods.
9667         if (!MD->isVirtual())
9668           continue;
9669         // If the method we are checking overrides a method from its base
9670         // don't warn about the other overloaded methods. Clang deviates from
9671         // GCC by only diagnosing overloads of inherited virtual functions that
9672         // do not override any other virtual functions in the base. GCC's
9673         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9674         // function from a base class. These cases may be better served by a
9675         // warning (not specific to virtual functions) on call sites when the
9676         // call would select a different function from the base class, were it
9677         // visible.
9678         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9679         if (!S->IsOverload(Method, MD, false))
9680           return true;
9681         // Collect the overload only if its hidden.
9682         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9683           overloadedMethods.push_back(MD);
9684       }
9685     }
9686 
9687     if (foundSameNameMethod)
9688       OverloadedMethods.append(overloadedMethods.begin(),
9689                                overloadedMethods.end());
9690     return foundSameNameMethod;
9691   }
9692 };
9693 } // end anonymous namespace
9694 
9695 /// Add the most overriden methods from MD to Methods
AddMostOverridenMethods(const CXXMethodDecl * MD,llvm::SmallPtrSetImpl<const CXXMethodDecl * > & Methods)9696 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9697                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9698   if (MD->size_overridden_methods() == 0)
9699     Methods.insert(MD->getCanonicalDecl());
9700   else
9701     for (const CXXMethodDecl *O : MD->overridden_methods())
9702       AddMostOverridenMethods(O, Methods);
9703 }
9704 
9705 /// Check if a method overloads virtual methods in a base class without
9706 /// overriding any.
FindHiddenVirtualMethods(CXXMethodDecl * MD,SmallVectorImpl<CXXMethodDecl * > & OverloadedMethods)9707 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9708                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9709   if (!MD->getDeclName().isIdentifier())
9710     return;
9711 
9712   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9713                      /*bool RecordPaths=*/false,
9714                      /*bool DetectVirtual=*/false);
9715   FindHiddenVirtualMethod FHVM;
9716   FHVM.Method = MD;
9717   FHVM.S = this;
9718 
9719   // Keep the base methods that were overridden or introduced in the subclass
9720   // by 'using' in a set. A base method not in this set is hidden.
9721   CXXRecordDecl *DC = MD->getParent();
9722   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9723   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9724     NamedDecl *ND = *I;
9725     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9726       ND = shad->getTargetDecl();
9727     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9728       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9729   }
9730 
9731   if (DC->lookupInBases(FHVM, Paths))
9732     OverloadedMethods = FHVM.OverloadedMethods;
9733 }
9734 
NoteHiddenVirtualMethods(CXXMethodDecl * MD,SmallVectorImpl<CXXMethodDecl * > & OverloadedMethods)9735 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9736                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9737   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9738     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9739     PartialDiagnostic PD = PDiag(
9740          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9741     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9742     Diag(overloadedMD->getLocation(), PD);
9743   }
9744 }
9745 
9746 /// Diagnose methods which overload virtual methods in a base class
9747 /// without overriding any.
DiagnoseHiddenVirtualMethods(CXXMethodDecl * MD)9748 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9749   if (MD->isInvalidDecl())
9750     return;
9751 
9752   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9753     return;
9754 
9755   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9756   FindHiddenVirtualMethods(MD, OverloadedMethods);
9757   if (!OverloadedMethods.empty()) {
9758     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9759       << MD << (OverloadedMethods.size() > 1);
9760 
9761     NoteHiddenVirtualMethods(MD, OverloadedMethods);
9762   }
9763 }
9764 
checkIllFormedTrivialABIStruct(CXXRecordDecl & RD)9765 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9766   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9767     // No diagnostics if this is a template instantiation.
9768     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9769       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9770            diag::ext_cannot_use_trivial_abi) << &RD;
9771       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9772            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9773     }
9774     RD.dropAttr<TrivialABIAttr>();
9775   };
9776 
9777   // Ill-formed if the copy and move constructors are deleted.
9778   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9779     // If the type is dependent, then assume it might have
9780     // implicit copy or move ctor because we won't know yet at this point.
9781     if (RD.isDependentType())
9782       return true;
9783     if (RD.needsImplicitCopyConstructor() &&
9784         !RD.defaultedCopyConstructorIsDeleted())
9785       return true;
9786     if (RD.needsImplicitMoveConstructor() &&
9787         !RD.defaultedMoveConstructorIsDeleted())
9788       return true;
9789     for (const CXXConstructorDecl *CD : RD.ctors())
9790       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9791         return true;
9792     return false;
9793   };
9794 
9795   if (!HasNonDeletedCopyOrMoveConstructor()) {
9796     PrintDiagAndRemoveAttr(0);
9797     return;
9798   }
9799 
9800   // Ill-formed if the struct has virtual functions.
9801   if (RD.isPolymorphic()) {
9802     PrintDiagAndRemoveAttr(1);
9803     return;
9804   }
9805 
9806   for (const auto &B : RD.bases()) {
9807     // Ill-formed if the base class is non-trivial for the purpose of calls or a
9808     // virtual base.
9809     if (!B.getType()->isDependentType() &&
9810         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9811       PrintDiagAndRemoveAttr(2);
9812       return;
9813     }
9814 
9815     if (B.isVirtual()) {
9816       PrintDiagAndRemoveAttr(3);
9817       return;
9818     }
9819   }
9820 
9821   for (const auto *FD : RD.fields()) {
9822     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9823     // non-trivial for the purpose of calls.
9824     QualType FT = FD->getType();
9825     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9826       PrintDiagAndRemoveAttr(4);
9827       return;
9828     }
9829 
9830     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9831       if (!RT->isDependentType() &&
9832           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9833         PrintDiagAndRemoveAttr(5);
9834         return;
9835       }
9836   }
9837 }
9838 
ActOnFinishCXXMemberSpecification(Scope * S,SourceLocation RLoc,Decl * TagDecl,SourceLocation LBrac,SourceLocation RBrac,const ParsedAttributesView & AttrList)9839 void Sema::ActOnFinishCXXMemberSpecification(
9840     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9841     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9842   if (!TagDecl)
9843     return;
9844 
9845   AdjustDeclIfTemplate(TagDecl);
9846 
9847   for (const ParsedAttr &AL : AttrList) {
9848     if (AL.getKind() != ParsedAttr::AT_Visibility)
9849       continue;
9850     AL.setInvalid();
9851     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9852   }
9853 
9854   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9855               // strict aliasing violation!
9856               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9857               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9858 
9859   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9860 }
9861 
9862 /// Find the equality comparison functions that should be implicitly declared
9863 /// in a given class definition, per C++2a [class.compare.default]p3.
findImplicitlyDeclaredEqualityComparisons(ASTContext & Ctx,CXXRecordDecl * RD,llvm::SmallVectorImpl<FunctionDecl * > & Spaceships)9864 static void findImplicitlyDeclaredEqualityComparisons(
9865     ASTContext &Ctx, CXXRecordDecl *RD,
9866     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9867   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9868   if (!RD->lookup(EqEq).empty())
9869     // Member operator== explicitly declared: no implicit operator==s.
9870     return;
9871 
9872   // Traverse friends looking for an '==' or a '<=>'.
9873   for (FriendDecl *Friend : RD->friends()) {
9874     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9875     if (!FD) continue;
9876 
9877     if (FD->getOverloadedOperator() == OO_EqualEqual) {
9878       // Friend operator== explicitly declared: no implicit operator==s.
9879       Spaceships.clear();
9880       return;
9881     }
9882 
9883     if (FD->getOverloadedOperator() == OO_Spaceship &&
9884         FD->isExplicitlyDefaulted())
9885       Spaceships.push_back(FD);
9886   }
9887 
9888   // Look for members named 'operator<=>'.
9889   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9890   for (NamedDecl *ND : RD->lookup(Cmp)) {
9891     // Note that we could find a non-function here (either a function template
9892     // or a using-declaration). Neither case results in an implicit
9893     // 'operator=='.
9894     if (auto *FD = dyn_cast<FunctionDecl>(ND))
9895       if (FD->isExplicitlyDefaulted())
9896         Spaceships.push_back(FD);
9897   }
9898 }
9899 
9900 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9901 /// special functions, such as the default constructor, copy
9902 /// constructor, or destructor, to the given C++ class (C++
9903 /// [special]p1).  This routine can only be executed just before the
9904 /// definition of the class is complete.
AddImplicitlyDeclaredMembersToClass(CXXRecordDecl * ClassDecl)9905 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9906   // Don't add implicit special members to templated classes.
9907   // FIXME: This means unqualified lookups for 'operator=' within a class
9908   // template don't work properly.
9909   if (!ClassDecl->isDependentType()) {
9910     if (ClassDecl->needsImplicitDefaultConstructor()) {
9911       ++getASTContext().NumImplicitDefaultConstructors;
9912 
9913       if (ClassDecl->hasInheritedConstructor())
9914         DeclareImplicitDefaultConstructor(ClassDecl);
9915     }
9916 
9917     if (ClassDecl->needsImplicitCopyConstructor()) {
9918       ++getASTContext().NumImplicitCopyConstructors;
9919 
9920       // If the properties or semantics of the copy constructor couldn't be
9921       // determined while the class was being declared, force a declaration
9922       // of it now.
9923       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
9924           ClassDecl->hasInheritedConstructor())
9925         DeclareImplicitCopyConstructor(ClassDecl);
9926       // For the MS ABI we need to know whether the copy ctor is deleted. A
9927       // prerequisite for deleting the implicit copy ctor is that the class has
9928       // a move ctor or move assignment that is either user-declared or whose
9929       // semantics are inherited from a subobject. FIXME: We should provide a
9930       // more direct way for CodeGen to ask whether the constructor was deleted.
9931       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9932                (ClassDecl->hasUserDeclaredMoveConstructor() ||
9933                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9934                 ClassDecl->hasUserDeclaredMoveAssignment() ||
9935                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
9936         DeclareImplicitCopyConstructor(ClassDecl);
9937     }
9938 
9939     if (getLangOpts().CPlusPlus11 &&
9940         ClassDecl->needsImplicitMoveConstructor()) {
9941       ++getASTContext().NumImplicitMoveConstructors;
9942 
9943       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9944           ClassDecl->hasInheritedConstructor())
9945         DeclareImplicitMoveConstructor(ClassDecl);
9946     }
9947 
9948     if (ClassDecl->needsImplicitCopyAssignment()) {
9949       ++getASTContext().NumImplicitCopyAssignmentOperators;
9950 
9951       // If we have a dynamic class, then the copy assignment operator may be
9952       // virtual, so we have to declare it immediately. This ensures that, e.g.,
9953       // it shows up in the right place in the vtable and that we diagnose
9954       // problems with the implicit exception specification.
9955       if (ClassDecl->isDynamicClass() ||
9956           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
9957           ClassDecl->hasInheritedAssignment())
9958         DeclareImplicitCopyAssignment(ClassDecl);
9959     }
9960 
9961     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
9962       ++getASTContext().NumImplicitMoveAssignmentOperators;
9963 
9964       // Likewise for the move assignment operator.
9965       if (ClassDecl->isDynamicClass() ||
9966           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
9967           ClassDecl->hasInheritedAssignment())
9968         DeclareImplicitMoveAssignment(ClassDecl);
9969     }
9970 
9971     if (ClassDecl->needsImplicitDestructor()) {
9972       ++getASTContext().NumImplicitDestructors;
9973 
9974       // If we have a dynamic class, then the destructor may be virtual, so we
9975       // have to declare the destructor immediately. This ensures that, e.g., it
9976       // shows up in the right place in the vtable and that we diagnose problems
9977       // with the implicit exception specification.
9978       if (ClassDecl->isDynamicClass() ||
9979           ClassDecl->needsOverloadResolutionForDestructor())
9980         DeclareImplicitDestructor(ClassDecl);
9981     }
9982   }
9983 
9984   // C++2a [class.compare.default]p3:
9985   //   If the member-specification does not explicitly declare any member or
9986   //   friend named operator==, an == operator function is declared implicitly
9987   //   for each defaulted three-way comparison operator function defined in
9988   //   the member-specification
9989   // FIXME: Consider doing this lazily.
9990   // We do this during the initial parse for a class template, not during
9991   // instantiation, so that we can handle unqualified lookups for 'operator=='
9992   // when parsing the template.
9993   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
9994     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
9995     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
9996                                               DefaultedSpaceships);
9997     for (auto *FD : DefaultedSpaceships)
9998       DeclareImplicitEqualityComparison(ClassDecl, FD);
9999   }
10000 }
10001 
10002 unsigned
ActOnReenterTemplateScope(Decl * D,llvm::function_ref<Scope * ()> EnterScope)10003 Sema::ActOnReenterTemplateScope(Decl *D,
10004                                 llvm::function_ref<Scope *()> EnterScope) {
10005   if (!D)
10006     return 0;
10007   AdjustDeclIfTemplate(D);
10008 
10009   // In order to get name lookup right, reenter template scopes in order from
10010   // outermost to innermost.
10011   SmallVector<TemplateParameterList *, 4> ParameterLists;
10012   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10013 
10014   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10015     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10016       ParameterLists.push_back(DD->getTemplateParameterList(i));
10017 
10018     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10019       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10020         ParameterLists.push_back(FTD->getTemplateParameters());
10021     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10022       LookupDC = VD->getDeclContext();
10023 
10024       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10025         ParameterLists.push_back(VTD->getTemplateParameters());
10026       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10027         ParameterLists.push_back(PSD->getTemplateParameters());
10028     }
10029   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10030     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10031       ParameterLists.push_back(TD->getTemplateParameterList(i));
10032 
10033     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10034       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10035         ParameterLists.push_back(CTD->getTemplateParameters());
10036       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10037         ParameterLists.push_back(PSD->getTemplateParameters());
10038     }
10039   }
10040   // FIXME: Alias declarations and concepts.
10041 
10042   unsigned Count = 0;
10043   Scope *InnermostTemplateScope = nullptr;
10044   for (TemplateParameterList *Params : ParameterLists) {
10045     // Ignore explicit specializations; they don't contribute to the template
10046     // depth.
10047     if (Params->size() == 0)
10048       continue;
10049 
10050     InnermostTemplateScope = EnterScope();
10051     for (NamedDecl *Param : *Params) {
10052       if (Param->getDeclName()) {
10053         InnermostTemplateScope->AddDecl(Param);
10054         IdResolver.AddDecl(Param);
10055       }
10056     }
10057     ++Count;
10058   }
10059 
10060   // Associate the new template scopes with the corresponding entities.
10061   if (InnermostTemplateScope) {
10062     assert(LookupDC && "no enclosing DeclContext for template lookup");
10063     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10064   }
10065 
10066   return Count;
10067 }
10068 
ActOnStartDelayedMemberDeclarations(Scope * S,Decl * RecordD)10069 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10070   if (!RecordD) return;
10071   AdjustDeclIfTemplate(RecordD);
10072   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10073   PushDeclContext(S, Record);
10074 }
10075 
ActOnFinishDelayedMemberDeclarations(Scope * S,Decl * RecordD)10076 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10077   if (!RecordD) return;
10078   PopDeclContext();
10079 }
10080 
10081 /// This is used to implement the constant expression evaluation part of the
10082 /// attribute enable_if extension. There is nothing in standard C++ which would
10083 /// require reentering parameters.
ActOnReenterCXXMethodParameter(Scope * S,ParmVarDecl * Param)10084 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10085   if (!Param)
10086     return;
10087 
10088   S->AddDecl(Param);
10089   if (Param->getDeclName())
10090     IdResolver.AddDecl(Param);
10091 }
10092 
10093 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10094 /// parsing a top-level (non-nested) C++ class, and we are now
10095 /// parsing those parts of the given Method declaration that could
10096 /// not be parsed earlier (C++ [class.mem]p2), such as default
10097 /// arguments. This action should enter the scope of the given
10098 /// Method declaration as if we had just parsed the qualified method
10099 /// name. However, it should not bring the parameters into scope;
10100 /// that will be performed by ActOnDelayedCXXMethodParameter.
ActOnStartDelayedCXXMethodDeclaration(Scope * S,Decl * MethodD)10101 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10102 }
10103 
10104 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10105 /// C++ method declaration. We're (re-)introducing the given
10106 /// function parameter into scope for use in parsing later parts of
10107 /// the method declaration. For example, we could see an
10108 /// ActOnParamDefaultArgument event for this parameter.
ActOnDelayedCXXMethodParameter(Scope * S,Decl * ParamD)10109 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10110   if (!ParamD)
10111     return;
10112 
10113   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10114 
10115   S->AddDecl(Param);
10116   if (Param->getDeclName())
10117     IdResolver.AddDecl(Param);
10118 }
10119 
10120 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10121 /// processing the delayed method declaration for Method. The method
10122 /// declaration is now considered finished. There may be a separate
10123 /// ActOnStartOfFunctionDef action later (not necessarily
10124 /// immediately!) for this method, if it was also defined inside the
10125 /// class body.
ActOnFinishDelayedCXXMethodDeclaration(Scope * S,Decl * MethodD)10126 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10127   if (!MethodD)
10128     return;
10129 
10130   AdjustDeclIfTemplate(MethodD);
10131 
10132   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10133 
10134   // Now that we have our default arguments, check the constructor
10135   // again. It could produce additional diagnostics or affect whether
10136   // the class has implicitly-declared destructors, among other
10137   // things.
10138   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10139     CheckConstructor(Constructor);
10140 
10141   // Check the default arguments, which we may have added.
10142   if (!Method->isInvalidDecl())
10143     CheckCXXDefaultArguments(Method);
10144 }
10145 
10146 // Emit the given diagnostic for each non-address-space qualifier.
10147 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
checkMethodTypeQualifiers(Sema & S,Declarator & D,unsigned DiagID)10148 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10149   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10150   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10151     bool DiagOccured = false;
10152     FTI.MethodQualifiers->forEachQualifier(
10153         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10154                                    SourceLocation SL) {
10155           // This diagnostic should be emitted on any qualifier except an addr
10156           // space qualifier. However, forEachQualifier currently doesn't visit
10157           // addr space qualifiers, so there's no way to write this condition
10158           // right now; we just diagnose on everything.
10159           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10160           DiagOccured = true;
10161         });
10162     if (DiagOccured)
10163       D.setInvalidType();
10164   }
10165 }
10166 
10167 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10168 /// the well-formedness of the constructor declarator @p D with type @p
10169 /// R. If there are any errors in the declarator, this routine will
10170 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10171 /// will be updated to reflect a well-formed type for the constructor and
10172 /// returned.
CheckConstructorDeclarator(Declarator & D,QualType R,StorageClass & SC)10173 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10174                                           StorageClass &SC) {
10175   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10176 
10177   // C++ [class.ctor]p3:
10178   //   A constructor shall not be virtual (10.3) or static (9.4). A
10179   //   constructor can be invoked for a const, volatile or const
10180   //   volatile object. A constructor shall not be declared const,
10181   //   volatile, or const volatile (9.3.2).
10182   if (isVirtual) {
10183     if (!D.isInvalidType())
10184       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10185         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10186         << SourceRange(D.getIdentifierLoc());
10187     D.setInvalidType();
10188   }
10189   if (SC == SC_Static) {
10190     if (!D.isInvalidType())
10191       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10192         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10193         << SourceRange(D.getIdentifierLoc());
10194     D.setInvalidType();
10195     SC = SC_None;
10196   }
10197 
10198   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10199     diagnoseIgnoredQualifiers(
10200         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10201         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10202         D.getDeclSpec().getRestrictSpecLoc(),
10203         D.getDeclSpec().getAtomicSpecLoc());
10204     D.setInvalidType();
10205   }
10206 
10207   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10208 
10209   // C++0x [class.ctor]p4:
10210   //   A constructor shall not be declared with a ref-qualifier.
10211   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10212   if (FTI.hasRefQualifier()) {
10213     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10214       << FTI.RefQualifierIsLValueRef
10215       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10216     D.setInvalidType();
10217   }
10218 
10219   // Rebuild the function type "R" without any type qualifiers (in
10220   // case any of the errors above fired) and with "void" as the
10221   // return type, since constructors don't have return types.
10222   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10223   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10224     return R;
10225 
10226   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10227   EPI.TypeQuals = Qualifiers();
10228   EPI.RefQualifier = RQ_None;
10229 
10230   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10231 }
10232 
10233 /// CheckConstructor - Checks a fully-formed constructor for
10234 /// well-formedness, issuing any diagnostics required. Returns true if
10235 /// the constructor declarator is invalid.
CheckConstructor(CXXConstructorDecl * Constructor)10236 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10237   CXXRecordDecl *ClassDecl
10238     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10239   if (!ClassDecl)
10240     return Constructor->setInvalidDecl();
10241 
10242   // C++ [class.copy]p3:
10243   //   A declaration of a constructor for a class X is ill-formed if
10244   //   its first parameter is of type (optionally cv-qualified) X and
10245   //   either there are no other parameters or else all other
10246   //   parameters have default arguments.
10247   if (!Constructor->isInvalidDecl() &&
10248       Constructor->hasOneParamOrDefaultArgs() &&
10249       Constructor->getTemplateSpecializationKind() !=
10250           TSK_ImplicitInstantiation) {
10251     QualType ParamType = Constructor->getParamDecl(0)->getType();
10252     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10253     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10254       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10255       const char *ConstRef
10256         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10257                                                         : " const &";
10258       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10259         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10260 
10261       // FIXME: Rather that making the constructor invalid, we should endeavor
10262       // to fix the type.
10263       Constructor->setInvalidDecl();
10264     }
10265   }
10266 }
10267 
10268 /// CheckDestructor - Checks a fully-formed destructor definition for
10269 /// well-formedness, issuing any diagnostics required.  Returns true
10270 /// on error.
CheckDestructor(CXXDestructorDecl * Destructor)10271 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10272   CXXRecordDecl *RD = Destructor->getParent();
10273 
10274   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10275     SourceLocation Loc;
10276 
10277     if (!Destructor->isImplicit())
10278       Loc = Destructor->getLocation();
10279     else
10280       Loc = RD->getLocation();
10281 
10282     // If we have a virtual destructor, look up the deallocation function
10283     if (FunctionDecl *OperatorDelete =
10284             FindDeallocationFunctionForDestructor(Loc, RD)) {
10285       Expr *ThisArg = nullptr;
10286 
10287       // If the notional 'delete this' expression requires a non-trivial
10288       // conversion from 'this' to the type of a destroying operator delete's
10289       // first parameter, perform that conversion now.
10290       if (OperatorDelete->isDestroyingOperatorDelete()) {
10291         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10292         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10293           // C++ [class.dtor]p13:
10294           //   ... as if for the expression 'delete this' appearing in a
10295           //   non-virtual destructor of the destructor's class.
10296           ContextRAII SwitchContext(*this, Destructor);
10297           ExprResult This =
10298               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10299           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10300           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10301           if (This.isInvalid()) {
10302             // FIXME: Register this as a context note so that it comes out
10303             // in the right order.
10304             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10305             return true;
10306           }
10307           ThisArg = This.get();
10308         }
10309       }
10310 
10311       DiagnoseUseOfDecl(OperatorDelete, Loc);
10312       MarkFunctionReferenced(Loc, OperatorDelete);
10313       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10314     }
10315   }
10316 
10317   return false;
10318 }
10319 
10320 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10321 /// the well-formednes of the destructor declarator @p D with type @p
10322 /// R. If there are any errors in the declarator, this routine will
10323 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10324 /// will be updated to reflect a well-formed type for the destructor and
10325 /// returned.
CheckDestructorDeclarator(Declarator & D,QualType R,StorageClass & SC)10326 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10327                                          StorageClass& SC) {
10328   // C++ [class.dtor]p1:
10329   //   [...] A typedef-name that names a class is a class-name
10330   //   (7.1.3); however, a typedef-name that names a class shall not
10331   //   be used as the identifier in the declarator for a destructor
10332   //   declaration.
10333   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10334   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10335     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10336       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10337   else if (const TemplateSpecializationType *TST =
10338              DeclaratorType->getAs<TemplateSpecializationType>())
10339     if (TST->isTypeAlias())
10340       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10341         << DeclaratorType << 1;
10342 
10343   // C++ [class.dtor]p2:
10344   //   A destructor is used to destroy objects of its class type. A
10345   //   destructor takes no parameters, and no return type can be
10346   //   specified for it (not even void). The address of a destructor
10347   //   shall not be taken. A destructor shall not be static. A
10348   //   destructor can be invoked for a const, volatile or const
10349   //   volatile object. A destructor shall not be declared const,
10350   //   volatile or const volatile (9.3.2).
10351   if (SC == SC_Static) {
10352     if (!D.isInvalidType())
10353       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10354         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10355         << SourceRange(D.getIdentifierLoc())
10356         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10357 
10358     SC = SC_None;
10359   }
10360   if (!D.isInvalidType()) {
10361     // Destructors don't have return types, but the parser will
10362     // happily parse something like:
10363     //
10364     //   class X {
10365     //     float ~X();
10366     //   };
10367     //
10368     // The return type will be eliminated later.
10369     if (D.getDeclSpec().hasTypeSpecifier())
10370       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10371         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10372         << SourceRange(D.getIdentifierLoc());
10373     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10374       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10375                                 SourceLocation(),
10376                                 D.getDeclSpec().getConstSpecLoc(),
10377                                 D.getDeclSpec().getVolatileSpecLoc(),
10378                                 D.getDeclSpec().getRestrictSpecLoc(),
10379                                 D.getDeclSpec().getAtomicSpecLoc());
10380       D.setInvalidType();
10381     }
10382   }
10383 
10384   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10385 
10386   // C++0x [class.dtor]p2:
10387   //   A destructor shall not be declared with a ref-qualifier.
10388   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10389   if (FTI.hasRefQualifier()) {
10390     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10391       << FTI.RefQualifierIsLValueRef
10392       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10393     D.setInvalidType();
10394   }
10395 
10396   // Make sure we don't have any parameters.
10397   if (FTIHasNonVoidParameters(FTI)) {
10398     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10399 
10400     // Delete the parameters.
10401     FTI.freeParams();
10402     D.setInvalidType();
10403   }
10404 
10405   // Make sure the destructor isn't variadic.
10406   if (FTI.isVariadic) {
10407     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10408     D.setInvalidType();
10409   }
10410 
10411   // Rebuild the function type "R" without any type qualifiers or
10412   // parameters (in case any of the errors above fired) and with
10413   // "void" as the return type, since destructors don't have return
10414   // types.
10415   if (!D.isInvalidType())
10416     return R;
10417 
10418   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10419   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10420   EPI.Variadic = false;
10421   EPI.TypeQuals = Qualifiers();
10422   EPI.RefQualifier = RQ_None;
10423   return Context.getFunctionType(Context.VoidTy, None, EPI);
10424 }
10425 
extendLeft(SourceRange & R,SourceRange Before)10426 static void extendLeft(SourceRange &R, SourceRange Before) {
10427   if (Before.isInvalid())
10428     return;
10429   R.setBegin(Before.getBegin());
10430   if (R.getEnd().isInvalid())
10431     R.setEnd(Before.getEnd());
10432 }
10433 
extendRight(SourceRange & R,SourceRange After)10434 static void extendRight(SourceRange &R, SourceRange After) {
10435   if (After.isInvalid())
10436     return;
10437   if (R.getBegin().isInvalid())
10438     R.setBegin(After.getBegin());
10439   R.setEnd(After.getEnd());
10440 }
10441 
10442 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10443 /// well-formednes of the conversion function declarator @p D with
10444 /// type @p R. If there are any errors in the declarator, this routine
10445 /// will emit diagnostics and return true. Otherwise, it will return
10446 /// false. Either way, the type @p R will be updated to reflect a
10447 /// well-formed type for the conversion operator.
CheckConversionDeclarator(Declarator & D,QualType & R,StorageClass & SC)10448 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10449                                      StorageClass& SC) {
10450   // C++ [class.conv.fct]p1:
10451   //   Neither parameter types nor return type can be specified. The
10452   //   type of a conversion function (8.3.5) is "function taking no
10453   //   parameter returning conversion-type-id."
10454   if (SC == SC_Static) {
10455     if (!D.isInvalidType())
10456       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10457         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10458         << D.getName().getSourceRange();
10459     D.setInvalidType();
10460     SC = SC_None;
10461   }
10462 
10463   TypeSourceInfo *ConvTSI = nullptr;
10464   QualType ConvType =
10465       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10466 
10467   const DeclSpec &DS = D.getDeclSpec();
10468   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10469     // Conversion functions don't have return types, but the parser will
10470     // happily parse something like:
10471     //
10472     //   class X {
10473     //     float operator bool();
10474     //   };
10475     //
10476     // The return type will be changed later anyway.
10477     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10478       << SourceRange(DS.getTypeSpecTypeLoc())
10479       << SourceRange(D.getIdentifierLoc());
10480     D.setInvalidType();
10481   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10482     // It's also plausible that the user writes type qualifiers in the wrong
10483     // place, such as:
10484     //   struct S { const operator int(); };
10485     // FIXME: we could provide a fixit to move the qualifiers onto the
10486     // conversion type.
10487     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10488         << SourceRange(D.getIdentifierLoc()) << 0;
10489     D.setInvalidType();
10490   }
10491 
10492   const auto *Proto = R->castAs<FunctionProtoType>();
10493 
10494   // Make sure we don't have any parameters.
10495   if (Proto->getNumParams() > 0) {
10496     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10497 
10498     // Delete the parameters.
10499     D.getFunctionTypeInfo().freeParams();
10500     D.setInvalidType();
10501   } else if (Proto->isVariadic()) {
10502     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10503     D.setInvalidType();
10504   }
10505 
10506   // Diagnose "&operator bool()" and other such nonsense.  This
10507   // is actually a gcc extension which we don't support.
10508   if (Proto->getReturnType() != ConvType) {
10509     bool NeedsTypedef = false;
10510     SourceRange Before, After;
10511 
10512     // Walk the chunks and extract information on them for our diagnostic.
10513     bool PastFunctionChunk = false;
10514     for (auto &Chunk : D.type_objects()) {
10515       switch (Chunk.Kind) {
10516       case DeclaratorChunk::Function:
10517         if (!PastFunctionChunk) {
10518           if (Chunk.Fun.HasTrailingReturnType) {
10519             TypeSourceInfo *TRT = nullptr;
10520             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10521             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10522           }
10523           PastFunctionChunk = true;
10524           break;
10525         }
10526         LLVM_FALLTHROUGH;
10527       case DeclaratorChunk::Array:
10528         NeedsTypedef = true;
10529         extendRight(After, Chunk.getSourceRange());
10530         break;
10531 
10532       case DeclaratorChunk::Pointer:
10533       case DeclaratorChunk::BlockPointer:
10534       case DeclaratorChunk::Reference:
10535       case DeclaratorChunk::MemberPointer:
10536       case DeclaratorChunk::Pipe:
10537         extendLeft(Before, Chunk.getSourceRange());
10538         break;
10539 
10540       case DeclaratorChunk::Paren:
10541         extendLeft(Before, Chunk.Loc);
10542         extendRight(After, Chunk.EndLoc);
10543         break;
10544       }
10545     }
10546 
10547     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10548                          After.isValid()  ? After.getBegin() :
10549                                             D.getIdentifierLoc();
10550     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10551     DB << Before << After;
10552 
10553     if (!NeedsTypedef) {
10554       DB << /*don't need a typedef*/0;
10555 
10556       // If we can provide a correct fix-it hint, do so.
10557       if (After.isInvalid() && ConvTSI) {
10558         SourceLocation InsertLoc =
10559             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10560         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10561            << FixItHint::CreateInsertionFromRange(
10562                   InsertLoc, CharSourceRange::getTokenRange(Before))
10563            << FixItHint::CreateRemoval(Before);
10564       }
10565     } else if (!Proto->getReturnType()->isDependentType()) {
10566       DB << /*typedef*/1 << Proto->getReturnType();
10567     } else if (getLangOpts().CPlusPlus11) {
10568       DB << /*alias template*/2 << Proto->getReturnType();
10569     } else {
10570       DB << /*might not be fixable*/3;
10571     }
10572 
10573     // Recover by incorporating the other type chunks into the result type.
10574     // Note, this does *not* change the name of the function. This is compatible
10575     // with the GCC extension:
10576     //   struct S { &operator int(); } s;
10577     //   int &r = s.operator int(); // ok in GCC
10578     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10579     ConvType = Proto->getReturnType();
10580   }
10581 
10582   // C++ [class.conv.fct]p4:
10583   //   The conversion-type-id shall not represent a function type nor
10584   //   an array type.
10585   if (ConvType->isArrayType()) {
10586     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10587     ConvType = Context.getPointerType(ConvType);
10588     D.setInvalidType();
10589   } else if (ConvType->isFunctionType()) {
10590     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10591     ConvType = Context.getPointerType(ConvType);
10592     D.setInvalidType();
10593   }
10594 
10595   // Rebuild the function type "R" without any parameters (in case any
10596   // of the errors above fired) and with the conversion type as the
10597   // return type.
10598   if (D.isInvalidType())
10599     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10600 
10601   // C++0x explicit conversion operators.
10602   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10603     Diag(DS.getExplicitSpecLoc(),
10604          getLangOpts().CPlusPlus11
10605              ? diag::warn_cxx98_compat_explicit_conversion_functions
10606              : diag::ext_explicit_conversion_functions)
10607         << SourceRange(DS.getExplicitSpecRange());
10608 }
10609 
10610 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10611 /// the declaration of the given C++ conversion function. This routine
10612 /// is responsible for recording the conversion function in the C++
10613 /// class, if possible.
ActOnConversionDeclarator(CXXConversionDecl * Conversion)10614 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10615   assert(Conversion && "Expected to receive a conversion function declaration");
10616 
10617   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10618 
10619   // Make sure we aren't redeclaring the conversion function.
10620   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10621   // C++ [class.conv.fct]p1:
10622   //   [...] A conversion function is never used to convert a
10623   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10624   //   same object type (or a reference to it), to a (possibly
10625   //   cv-qualified) base class of that type (or a reference to it),
10626   //   or to (possibly cv-qualified) void.
10627   QualType ClassType
10628     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10629   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10630     ConvType = ConvTypeRef->getPointeeType();
10631   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10632       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10633     /* Suppress diagnostics for instantiations. */;
10634   else if (Conversion->size_overridden_methods() != 0)
10635     /* Suppress diagnostics for overriding virtual function in a base class. */;
10636   else if (ConvType->isRecordType()) {
10637     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10638     if (ConvType == ClassType)
10639       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10640         << ClassType;
10641     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10642       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10643         <<  ClassType << ConvType;
10644   } else if (ConvType->isVoidType()) {
10645     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10646       << ClassType << ConvType;
10647   }
10648 
10649   if (FunctionTemplateDecl *ConversionTemplate
10650                                 = Conversion->getDescribedFunctionTemplate())
10651     return ConversionTemplate;
10652 
10653   return Conversion;
10654 }
10655 
10656 namespace {
10657 /// Utility class to accumulate and print a diagnostic listing the invalid
10658 /// specifier(s) on a declaration.
10659 struct BadSpecifierDiagnoser {
BadSpecifierDiagnoser__anonedc74bd72a11::BadSpecifierDiagnoser10660   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10661       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
~BadSpecifierDiagnoser__anonedc74bd72a11::BadSpecifierDiagnoser10662   ~BadSpecifierDiagnoser() {
10663     Diagnostic << Specifiers;
10664   }
10665 
check__anonedc74bd72a11::BadSpecifierDiagnoser10666   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10667     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10668   }
check__anonedc74bd72a11::BadSpecifierDiagnoser10669   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10670     return check(SpecLoc,
10671                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10672   }
check__anonedc74bd72a11::BadSpecifierDiagnoser10673   void check(SourceLocation SpecLoc, const char *Spec) {
10674     if (SpecLoc.isInvalid()) return;
10675     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10676     if (!Specifiers.empty()) Specifiers += " ";
10677     Specifiers += Spec;
10678   }
10679 
10680   Sema &S;
10681   Sema::SemaDiagnosticBuilder Diagnostic;
10682   std::string Specifiers;
10683 };
10684 }
10685 
10686 /// Check the validity of a declarator that we parsed for a deduction-guide.
10687 /// These aren't actually declarators in the grammar, so we need to check that
10688 /// the user didn't specify any pieces that are not part of the deduction-guide
10689 /// grammar.
CheckDeductionGuideDeclarator(Declarator & D,QualType & R,StorageClass & SC)10690 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10691                                          StorageClass &SC) {
10692   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10693   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10694   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10695 
10696   // C++ [temp.deduct.guide]p3:
10697   //   A deduction-gide shall be declared in the same scope as the
10698   //   corresponding class template.
10699   if (!CurContext->getRedeclContext()->Equals(
10700           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10701     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10702       << GuidedTemplateDecl;
10703     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10704   }
10705 
10706   auto &DS = D.getMutableDeclSpec();
10707   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10708   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10709       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10710       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10711     BadSpecifierDiagnoser Diagnoser(
10712         *this, D.getIdentifierLoc(),
10713         diag::err_deduction_guide_invalid_specifier);
10714 
10715     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10716     DS.ClearStorageClassSpecs();
10717     SC = SC_None;
10718 
10719     // 'explicit' is permitted.
10720     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10721     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10722     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10723     DS.ClearConstexprSpec();
10724 
10725     Diagnoser.check(DS.getConstSpecLoc(), "const");
10726     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10727     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10728     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10729     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10730     DS.ClearTypeQualifiers();
10731 
10732     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10733     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10734     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10735     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10736     DS.ClearTypeSpecType();
10737   }
10738 
10739   if (D.isInvalidType())
10740     return;
10741 
10742   // Check the declarator is simple enough.
10743   bool FoundFunction = false;
10744   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10745     if (Chunk.Kind == DeclaratorChunk::Paren)
10746       continue;
10747     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10748       Diag(D.getDeclSpec().getBeginLoc(),
10749            diag::err_deduction_guide_with_complex_decl)
10750           << D.getSourceRange();
10751       break;
10752     }
10753     if (!Chunk.Fun.hasTrailingReturnType()) {
10754       Diag(D.getName().getBeginLoc(),
10755            diag::err_deduction_guide_no_trailing_return_type);
10756       break;
10757     }
10758 
10759     // Check that the return type is written as a specialization of
10760     // the template specified as the deduction-guide's name.
10761     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10762     TypeSourceInfo *TSI = nullptr;
10763     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10764     assert(TSI && "deduction guide has valid type but invalid return type?");
10765     bool AcceptableReturnType = false;
10766     bool MightInstantiateToSpecialization = false;
10767     if (auto RetTST =
10768             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10769       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10770       bool TemplateMatches =
10771           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10772       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10773         AcceptableReturnType = true;
10774       else {
10775         // This could still instantiate to the right type, unless we know it
10776         // names the wrong class template.
10777         auto *TD = SpecifiedName.getAsTemplateDecl();
10778         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10779                                              !TemplateMatches);
10780       }
10781     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10782       MightInstantiateToSpecialization = true;
10783     }
10784 
10785     if (!AcceptableReturnType) {
10786       Diag(TSI->getTypeLoc().getBeginLoc(),
10787            diag::err_deduction_guide_bad_trailing_return_type)
10788           << GuidedTemplate << TSI->getType()
10789           << MightInstantiateToSpecialization
10790           << TSI->getTypeLoc().getSourceRange();
10791     }
10792 
10793     // Keep going to check that we don't have any inner declarator pieces (we
10794     // could still have a function returning a pointer to a function).
10795     FoundFunction = true;
10796   }
10797 
10798   if (D.isFunctionDefinition())
10799     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10800 }
10801 
10802 //===----------------------------------------------------------------------===//
10803 // Namespace Handling
10804 //===----------------------------------------------------------------------===//
10805 
10806 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10807 /// reopened.
DiagnoseNamespaceInlineMismatch(Sema & S,SourceLocation KeywordLoc,SourceLocation Loc,IdentifierInfo * II,bool * IsInline,NamespaceDecl * PrevNS)10808 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10809                                             SourceLocation Loc,
10810                                             IdentifierInfo *II, bool *IsInline,
10811                                             NamespaceDecl *PrevNS) {
10812   assert(*IsInline != PrevNS->isInline());
10813 
10814   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
10815   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
10816   // inline namespaces, with the intention of bringing names into namespace std.
10817   //
10818   // We support this just well enough to get that case working; this is not
10819   // sufficient to support reopening namespaces as inline in general.
10820   if (*IsInline && II && II->getName().startswith("__atomic") &&
10821       S.getSourceManager().isInSystemHeader(Loc)) {
10822     // Mark all prior declarations of the namespace as inline.
10823     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
10824          NS = NS->getPreviousDecl())
10825       NS->setInline(*IsInline);
10826     // Patch up the lookup table for the containing namespace. This isn't really
10827     // correct, but it's good enough for this particular case.
10828     for (auto *I : PrevNS->decls())
10829       if (auto *ND = dyn_cast<NamedDecl>(I))
10830         PrevNS->getParent()->makeDeclVisibleInContext(ND);
10831     return;
10832   }
10833 
10834   if (PrevNS->isInline())
10835     // The user probably just forgot the 'inline', so suggest that it
10836     // be added back.
10837     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10838       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10839   else
10840     S.Diag(Loc, diag::err_inline_namespace_mismatch);
10841 
10842   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10843   *IsInline = PrevNS->isInline();
10844 }
10845 
10846 /// ActOnStartNamespaceDef - This is called at the start of a namespace
10847 /// definition.
ActOnStartNamespaceDef(Scope * NamespcScope,SourceLocation InlineLoc,SourceLocation NamespaceLoc,SourceLocation IdentLoc,IdentifierInfo * II,SourceLocation LBrace,const ParsedAttributesView & AttrList,UsingDirectiveDecl * & UD)10848 Decl *Sema::ActOnStartNamespaceDef(
10849     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10850     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10851     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10852   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10853   // For anonymous namespace, take the location of the left brace.
10854   SourceLocation Loc = II ? IdentLoc : LBrace;
10855   bool IsInline = InlineLoc.isValid();
10856   bool IsInvalid = false;
10857   bool IsStd = false;
10858   bool AddToKnown = false;
10859   Scope *DeclRegionScope = NamespcScope->getParent();
10860 
10861   NamespaceDecl *PrevNS = nullptr;
10862   if (II) {
10863     // C++ [namespace.def]p2:
10864     //   The identifier in an original-namespace-definition shall not
10865     //   have been previously defined in the declarative region in
10866     //   which the original-namespace-definition appears. The
10867     //   identifier in an original-namespace-definition is the name of
10868     //   the namespace. Subsequently in that declarative region, it is
10869     //   treated as an original-namespace-name.
10870     //
10871     // Since namespace names are unique in their scope, and we don't
10872     // look through using directives, just look for any ordinary names
10873     // as if by qualified name lookup.
10874     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10875                    ForExternalRedeclaration);
10876     LookupQualifiedName(R, CurContext->getRedeclContext());
10877     NamedDecl *PrevDecl =
10878         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10879     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10880 
10881     if (PrevNS) {
10882       // This is an extended namespace definition.
10883       if (IsInline != PrevNS->isInline())
10884         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10885                                         &IsInline, PrevNS);
10886     } else if (PrevDecl) {
10887       // This is an invalid name redefinition.
10888       Diag(Loc, diag::err_redefinition_different_kind)
10889         << II;
10890       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10891       IsInvalid = true;
10892       // Continue on to push Namespc as current DeclContext and return it.
10893     } else if (II->isStr("std") &&
10894                CurContext->getRedeclContext()->isTranslationUnit()) {
10895       // This is the first "real" definition of the namespace "std", so update
10896       // our cache of the "std" namespace to point at this definition.
10897       PrevNS = getStdNamespace();
10898       IsStd = true;
10899       AddToKnown = !IsInline;
10900     } else {
10901       // We've seen this namespace for the first time.
10902       AddToKnown = !IsInline;
10903     }
10904   } else {
10905     // Anonymous namespaces.
10906 
10907     // Determine whether the parent already has an anonymous namespace.
10908     DeclContext *Parent = CurContext->getRedeclContext();
10909     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10910       PrevNS = TU->getAnonymousNamespace();
10911     } else {
10912       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10913       PrevNS = ND->getAnonymousNamespace();
10914     }
10915 
10916     if (PrevNS && IsInline != PrevNS->isInline())
10917       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10918                                       &IsInline, PrevNS);
10919   }
10920 
10921   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10922                                                  StartLoc, Loc, II, PrevNS);
10923   if (IsInvalid)
10924     Namespc->setInvalidDecl();
10925 
10926   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10927   AddPragmaAttributes(DeclRegionScope, Namespc);
10928 
10929   // FIXME: Should we be merging attributes?
10930   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10931     PushNamespaceVisibilityAttr(Attr, Loc);
10932 
10933   if (IsStd)
10934     StdNamespace = Namespc;
10935   if (AddToKnown)
10936     KnownNamespaces[Namespc] = false;
10937 
10938   if (II) {
10939     PushOnScopeChains(Namespc, DeclRegionScope);
10940   } else {
10941     // Link the anonymous namespace into its parent.
10942     DeclContext *Parent = CurContext->getRedeclContext();
10943     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10944       TU->setAnonymousNamespace(Namespc);
10945     } else {
10946       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
10947     }
10948 
10949     CurContext->addDecl(Namespc);
10950 
10951     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
10952     //   behaves as if it were replaced by
10953     //     namespace unique { /* empty body */ }
10954     //     using namespace unique;
10955     //     namespace unique { namespace-body }
10956     //   where all occurrences of 'unique' in a translation unit are
10957     //   replaced by the same identifier and this identifier differs
10958     //   from all other identifiers in the entire program.
10959 
10960     // We just create the namespace with an empty name and then add an
10961     // implicit using declaration, just like the standard suggests.
10962     //
10963     // CodeGen enforces the "universally unique" aspect by giving all
10964     // declarations semantically contained within an anonymous
10965     // namespace internal linkage.
10966 
10967     if (!PrevNS) {
10968       UD = UsingDirectiveDecl::Create(Context, Parent,
10969                                       /* 'using' */ LBrace,
10970                                       /* 'namespace' */ SourceLocation(),
10971                                       /* qualifier */ NestedNameSpecifierLoc(),
10972                                       /* identifier */ SourceLocation(),
10973                                       Namespc,
10974                                       /* Ancestor */ Parent);
10975       UD->setImplicit();
10976       Parent->addDecl(UD);
10977     }
10978   }
10979 
10980   ActOnDocumentableDecl(Namespc);
10981 
10982   // Although we could have an invalid decl (i.e. the namespace name is a
10983   // redefinition), push it as current DeclContext and try to continue parsing.
10984   // FIXME: We should be able to push Namespc here, so that the each DeclContext
10985   // for the namespace has the declarations that showed up in that particular
10986   // namespace definition.
10987   PushDeclContext(NamespcScope, Namespc);
10988   return Namespc;
10989 }
10990 
10991 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
10992 /// is a namespace alias, returns the namespace it points to.
getNamespaceDecl(NamedDecl * D)10993 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
10994   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
10995     return AD->getNamespace();
10996   return dyn_cast_or_null<NamespaceDecl>(D);
10997 }
10998 
10999 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11000 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
ActOnFinishNamespaceDef(Decl * Dcl,SourceLocation RBrace)11001 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11002   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11003   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11004   Namespc->setRBraceLoc(RBrace);
11005   PopDeclContext();
11006   if (Namespc->hasAttr<VisibilityAttr>())
11007     PopPragmaVisibility(true, RBrace);
11008   // If this namespace contains an export-declaration, export it now.
11009   if (DeferredExportedNamespaces.erase(Namespc))
11010     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11011 }
11012 
getStdBadAlloc() const11013 CXXRecordDecl *Sema::getStdBadAlloc() const {
11014   return cast_or_null<CXXRecordDecl>(
11015                                   StdBadAlloc.get(Context.getExternalSource()));
11016 }
11017 
getStdAlignValT() const11018 EnumDecl *Sema::getStdAlignValT() const {
11019   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11020 }
11021 
getStdNamespace() const11022 NamespaceDecl *Sema::getStdNamespace() const {
11023   return cast_or_null<NamespaceDecl>(
11024                                  StdNamespace.get(Context.getExternalSource()));
11025 }
11026 
lookupStdExperimentalNamespace()11027 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11028   if (!StdExperimentalNamespaceCache) {
11029     if (auto Std = getStdNamespace()) {
11030       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11031                           SourceLocation(), LookupNamespaceName);
11032       if (!LookupQualifiedName(Result, Std) ||
11033           !(StdExperimentalNamespaceCache =
11034                 Result.getAsSingle<NamespaceDecl>()))
11035         Result.suppressDiagnostics();
11036     }
11037   }
11038   return StdExperimentalNamespaceCache;
11039 }
11040 
11041 namespace {
11042 
11043 enum UnsupportedSTLSelect {
11044   USS_InvalidMember,
11045   USS_MissingMember,
11046   USS_NonTrivial,
11047   USS_Other
11048 };
11049 
11050 struct InvalidSTLDiagnoser {
11051   Sema &S;
11052   SourceLocation Loc;
11053   QualType TyForDiags;
11054 
operator ()__anonedc74bd72b11::InvalidSTLDiagnoser11055   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11056                       const VarDecl *VD = nullptr) {
11057     {
11058       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11059                << TyForDiags << ((int)Sel);
11060       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11061         assert(!Name.empty());
11062         D << Name;
11063       }
11064     }
11065     if (Sel == USS_InvalidMember) {
11066       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11067           << VD << VD->getSourceRange();
11068     }
11069     return QualType();
11070   }
11071 };
11072 } // namespace
11073 
CheckComparisonCategoryType(ComparisonCategoryType Kind,SourceLocation Loc,ComparisonCategoryUsage Usage)11074 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11075                                            SourceLocation Loc,
11076                                            ComparisonCategoryUsage Usage) {
11077   assert(getLangOpts().CPlusPlus &&
11078          "Looking for comparison category type outside of C++.");
11079 
11080   // Use an elaborated type for diagnostics which has a name containing the
11081   // prepended 'std' namespace but not any inline namespace names.
11082   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11083     auto *NNS =
11084         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11085     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11086   };
11087 
11088   // Check if we've already successfully checked the comparison category type
11089   // before. If so, skip checking it again.
11090   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11091   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11092     // The only thing we need to check is that the type has a reachable
11093     // definition in the current context.
11094     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11095       return QualType();
11096 
11097     return Info->getType();
11098   }
11099 
11100   // If lookup failed
11101   if (!Info) {
11102     std::string NameForDiags = "std::";
11103     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11104     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11105         << NameForDiags << (int)Usage;
11106     return QualType();
11107   }
11108 
11109   assert(Info->Kind == Kind);
11110   assert(Info->Record);
11111 
11112   // Update the Record decl in case we encountered a forward declaration on our
11113   // first pass. FIXME: This is a bit of a hack.
11114   if (Info->Record->hasDefinition())
11115     Info->Record = Info->Record->getDefinition();
11116 
11117   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11118     return QualType();
11119 
11120   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11121 
11122   if (!Info->Record->isTriviallyCopyable())
11123     return UnsupportedSTLError(USS_NonTrivial);
11124 
11125   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11126     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11127     // Tolerate empty base classes.
11128     if (Base->isEmpty())
11129       continue;
11130     // Reject STL implementations which have at least one non-empty base.
11131     return UnsupportedSTLError();
11132   }
11133 
11134   // Check that the STL has implemented the types using a single integer field.
11135   // This expectation allows better codegen for builtin operators. We require:
11136   //   (1) The class has exactly one field.
11137   //   (2) The field is an integral or enumeration type.
11138   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11139   if (std::distance(FIt, FEnd) != 1 ||
11140       !FIt->getType()->isIntegralOrEnumerationType()) {
11141     return UnsupportedSTLError();
11142   }
11143 
11144   // Build each of the require values and store them in Info.
11145   for (ComparisonCategoryResult CCR :
11146        ComparisonCategories::getPossibleResultsForType(Kind)) {
11147     StringRef MemName = ComparisonCategories::getResultString(CCR);
11148     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11149 
11150     if (!ValInfo)
11151       return UnsupportedSTLError(USS_MissingMember, MemName);
11152 
11153     VarDecl *VD = ValInfo->VD;
11154     assert(VD && "should not be null!");
11155 
11156     // Attempt to diagnose reasons why the STL definition of this type
11157     // might be foobar, including it failing to be a constant expression.
11158     // TODO Handle more ways the lookup or result can be invalid.
11159     if (!VD->isStaticDataMember() ||
11160         !VD->isUsableInConstantExpressions(Context))
11161       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11162 
11163     // Attempt to evaluate the var decl as a constant expression and extract
11164     // the value of its first field as a ICE. If this fails, the STL
11165     // implementation is not supported.
11166     if (!ValInfo->hasValidIntValue())
11167       return UnsupportedSTLError();
11168 
11169     MarkVariableReferenced(Loc, VD);
11170   }
11171 
11172   // We've successfully built the required types and expressions. Update
11173   // the cache and return the newly cached value.
11174   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11175   return Info->getType();
11176 }
11177 
11178 /// Retrieve the special "std" namespace, which may require us to
11179 /// implicitly define the namespace.
getOrCreateStdNamespace()11180 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11181   if (!StdNamespace) {
11182     // The "std" namespace has not yet been defined, so build one implicitly.
11183     StdNamespace = NamespaceDecl::Create(Context,
11184                                          Context.getTranslationUnitDecl(),
11185                                          /*Inline=*/false,
11186                                          SourceLocation(), SourceLocation(),
11187                                          &PP.getIdentifierTable().get("std"),
11188                                          /*PrevDecl=*/nullptr);
11189     getStdNamespace()->setImplicit(true);
11190   }
11191 
11192   return getStdNamespace();
11193 }
11194 
isStdInitializerList(QualType Ty,QualType * Element)11195 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11196   assert(getLangOpts().CPlusPlus &&
11197          "Looking for std::initializer_list outside of C++.");
11198 
11199   // We're looking for implicit instantiations of
11200   // template <typename E> class std::initializer_list.
11201 
11202   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11203     return false;
11204 
11205   ClassTemplateDecl *Template = nullptr;
11206   const TemplateArgument *Arguments = nullptr;
11207 
11208   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11209 
11210     ClassTemplateSpecializationDecl *Specialization =
11211         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11212     if (!Specialization)
11213       return false;
11214 
11215     Template = Specialization->getSpecializedTemplate();
11216     Arguments = Specialization->getTemplateArgs().data();
11217   } else if (const TemplateSpecializationType *TST =
11218                  Ty->getAs<TemplateSpecializationType>()) {
11219     Template = dyn_cast_or_null<ClassTemplateDecl>(
11220         TST->getTemplateName().getAsTemplateDecl());
11221     Arguments = TST->getArgs();
11222   }
11223   if (!Template)
11224     return false;
11225 
11226   if (!StdInitializerList) {
11227     // Haven't recognized std::initializer_list yet, maybe this is it.
11228     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11229     if (TemplateClass->getIdentifier() !=
11230             &PP.getIdentifierTable().get("initializer_list") ||
11231         !getStdNamespace()->InEnclosingNamespaceSetOf(
11232             TemplateClass->getDeclContext()))
11233       return false;
11234     // This is a template called std::initializer_list, but is it the right
11235     // template?
11236     TemplateParameterList *Params = Template->getTemplateParameters();
11237     if (Params->getMinRequiredArguments() != 1)
11238       return false;
11239     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11240       return false;
11241 
11242     // It's the right template.
11243     StdInitializerList = Template;
11244   }
11245 
11246   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11247     return false;
11248 
11249   // This is an instance of std::initializer_list. Find the argument type.
11250   if (Element)
11251     *Element = Arguments[0].getAsType();
11252   return true;
11253 }
11254 
LookupStdInitializerList(Sema & S,SourceLocation Loc)11255 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11256   NamespaceDecl *Std = S.getStdNamespace();
11257   if (!Std) {
11258     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11259     return nullptr;
11260   }
11261 
11262   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11263                       Loc, Sema::LookupOrdinaryName);
11264   if (!S.LookupQualifiedName(Result, Std)) {
11265     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11266     return nullptr;
11267   }
11268   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11269   if (!Template) {
11270     Result.suppressDiagnostics();
11271     // We found something weird. Complain about the first thing we found.
11272     NamedDecl *Found = *Result.begin();
11273     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11274     return nullptr;
11275   }
11276 
11277   // We found some template called std::initializer_list. Now verify that it's
11278   // correct.
11279   TemplateParameterList *Params = Template->getTemplateParameters();
11280   if (Params->getMinRequiredArguments() != 1 ||
11281       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11282     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11283     return nullptr;
11284   }
11285 
11286   return Template;
11287 }
11288 
BuildStdInitializerList(QualType Element,SourceLocation Loc)11289 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11290   if (!StdInitializerList) {
11291     StdInitializerList = LookupStdInitializerList(*this, Loc);
11292     if (!StdInitializerList)
11293       return QualType();
11294   }
11295 
11296   TemplateArgumentListInfo Args(Loc, Loc);
11297   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11298                                        Context.getTrivialTypeSourceInfo(Element,
11299                                                                         Loc)));
11300   return Context.getCanonicalType(
11301       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11302 }
11303 
isInitListConstructor(const FunctionDecl * Ctor)11304 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11305   // C++ [dcl.init.list]p2:
11306   //   A constructor is an initializer-list constructor if its first parameter
11307   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11308   //   std::initializer_list<E> for some type E, and either there are no other
11309   //   parameters or else all other parameters have default arguments.
11310   if (!Ctor->hasOneParamOrDefaultArgs())
11311     return false;
11312 
11313   QualType ArgType = Ctor->getParamDecl(0)->getType();
11314   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11315     ArgType = RT->getPointeeType().getUnqualifiedType();
11316 
11317   return isStdInitializerList(ArgType, nullptr);
11318 }
11319 
11320 /// Determine whether a using statement is in a context where it will be
11321 /// apply in all contexts.
IsUsingDirectiveInToplevelContext(DeclContext * CurContext)11322 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11323   switch (CurContext->getDeclKind()) {
11324     case Decl::TranslationUnit:
11325       return true;
11326     case Decl::LinkageSpec:
11327       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11328     default:
11329       return false;
11330   }
11331 }
11332 
11333 namespace {
11334 
11335 // Callback to only accept typo corrections that are namespaces.
11336 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11337 public:
ValidateCandidate(const TypoCorrection & candidate)11338   bool ValidateCandidate(const TypoCorrection &candidate) override {
11339     if (NamedDecl *ND = candidate.getCorrectionDecl())
11340       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11341     return false;
11342   }
11343 
clone()11344   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11345     return std::make_unique<NamespaceValidatorCCC>(*this);
11346   }
11347 };
11348 
11349 }
11350 
TryNamespaceTypoCorrection(Sema & S,LookupResult & R,Scope * Sc,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * Ident)11351 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11352                                        CXXScopeSpec &SS,
11353                                        SourceLocation IdentLoc,
11354                                        IdentifierInfo *Ident) {
11355   R.clear();
11356   NamespaceValidatorCCC CCC{};
11357   if (TypoCorrection Corrected =
11358           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11359                         Sema::CTK_ErrorRecovery)) {
11360     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11361       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11362       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11363                               Ident->getName().equals(CorrectedStr);
11364       S.diagnoseTypo(Corrected,
11365                      S.PDiag(diag::err_using_directive_member_suggest)
11366                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11367                      S.PDiag(diag::note_namespace_defined_here));
11368     } else {
11369       S.diagnoseTypo(Corrected,
11370                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11371                      S.PDiag(diag::note_namespace_defined_here));
11372     }
11373     R.addDecl(Corrected.getFoundDecl());
11374     return true;
11375   }
11376   return false;
11377 }
11378 
ActOnUsingDirective(Scope * S,SourceLocation UsingLoc,SourceLocation NamespcLoc,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * NamespcName,const ParsedAttributesView & AttrList)11379 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11380                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11381                                 SourceLocation IdentLoc,
11382                                 IdentifierInfo *NamespcName,
11383                                 const ParsedAttributesView &AttrList) {
11384   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11385   assert(NamespcName && "Invalid NamespcName.");
11386   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11387 
11388   // This can only happen along a recovery path.
11389   while (S->isTemplateParamScope())
11390     S = S->getParent();
11391   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11392 
11393   UsingDirectiveDecl *UDir = nullptr;
11394   NestedNameSpecifier *Qualifier = nullptr;
11395   if (SS.isSet())
11396     Qualifier = SS.getScopeRep();
11397 
11398   // Lookup namespace name.
11399   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11400   LookupParsedName(R, S, &SS);
11401   if (R.isAmbiguous())
11402     return nullptr;
11403 
11404   if (R.empty()) {
11405     R.clear();
11406     // Allow "using namespace std;" or "using namespace ::std;" even if
11407     // "std" hasn't been defined yet, for GCC compatibility.
11408     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11409         NamespcName->isStr("std")) {
11410       Diag(IdentLoc, diag::ext_using_undefined_std);
11411       R.addDecl(getOrCreateStdNamespace());
11412       R.resolveKind();
11413     }
11414     // Otherwise, attempt typo correction.
11415     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11416   }
11417 
11418   if (!R.empty()) {
11419     NamedDecl *Named = R.getRepresentativeDecl();
11420     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11421     assert(NS && "expected namespace decl");
11422 
11423     // The use of a nested name specifier may trigger deprecation warnings.
11424     DiagnoseUseOfDecl(Named, IdentLoc);
11425 
11426     // C++ [namespace.udir]p1:
11427     //   A using-directive specifies that the names in the nominated
11428     //   namespace can be used in the scope in which the
11429     //   using-directive appears after the using-directive. During
11430     //   unqualified name lookup (3.4.1), the names appear as if they
11431     //   were declared in the nearest enclosing namespace which
11432     //   contains both the using-directive and the nominated
11433     //   namespace. [Note: in this context, "contains" means "contains
11434     //   directly or indirectly". ]
11435 
11436     // Find enclosing context containing both using-directive and
11437     // nominated namespace.
11438     DeclContext *CommonAncestor = NS;
11439     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11440       CommonAncestor = CommonAncestor->getParent();
11441 
11442     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11443                                       SS.getWithLocInContext(Context),
11444                                       IdentLoc, Named, CommonAncestor);
11445 
11446     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11447         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11448       Diag(IdentLoc, diag::warn_using_directive_in_header);
11449     }
11450 
11451     PushUsingDirective(S, UDir);
11452   } else {
11453     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11454   }
11455 
11456   if (UDir)
11457     ProcessDeclAttributeList(S, UDir, AttrList);
11458 
11459   return UDir;
11460 }
11461 
PushUsingDirective(Scope * S,UsingDirectiveDecl * UDir)11462 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11463   // If the scope has an associated entity and the using directive is at
11464   // namespace or translation unit scope, add the UsingDirectiveDecl into
11465   // its lookup structure so qualified name lookup can find it.
11466   DeclContext *Ctx = S->getEntity();
11467   if (Ctx && !Ctx->isFunctionOrMethod())
11468     Ctx->addDecl(UDir);
11469   else
11470     // Otherwise, it is at block scope. The using-directives will affect lookup
11471     // only to the end of the scope.
11472     S->PushUsingDirective(UDir);
11473 }
11474 
ActOnUsingDeclaration(Scope * S,AccessSpecifier AS,SourceLocation UsingLoc,SourceLocation TypenameLoc,CXXScopeSpec & SS,UnqualifiedId & Name,SourceLocation EllipsisLoc,const ParsedAttributesView & AttrList)11475 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11476                                   SourceLocation UsingLoc,
11477                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11478                                   UnqualifiedId &Name,
11479                                   SourceLocation EllipsisLoc,
11480                                   const ParsedAttributesView &AttrList) {
11481   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11482 
11483   if (SS.isEmpty()) {
11484     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11485     return nullptr;
11486   }
11487 
11488   switch (Name.getKind()) {
11489   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11490   case UnqualifiedIdKind::IK_Identifier:
11491   case UnqualifiedIdKind::IK_OperatorFunctionId:
11492   case UnqualifiedIdKind::IK_LiteralOperatorId:
11493   case UnqualifiedIdKind::IK_ConversionFunctionId:
11494     break;
11495 
11496   case UnqualifiedIdKind::IK_ConstructorName:
11497   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11498     // C++11 inheriting constructors.
11499     Diag(Name.getBeginLoc(),
11500          getLangOpts().CPlusPlus11
11501              ? diag::warn_cxx98_compat_using_decl_constructor
11502              : diag::err_using_decl_constructor)
11503         << SS.getRange();
11504 
11505     if (getLangOpts().CPlusPlus11) break;
11506 
11507     return nullptr;
11508 
11509   case UnqualifiedIdKind::IK_DestructorName:
11510     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11511     return nullptr;
11512 
11513   case UnqualifiedIdKind::IK_TemplateId:
11514     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11515         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11516     return nullptr;
11517 
11518   case UnqualifiedIdKind::IK_DeductionGuideName:
11519     llvm_unreachable("cannot parse qualified deduction guide name");
11520   }
11521 
11522   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11523   DeclarationName TargetName = TargetNameInfo.getName();
11524   if (!TargetName)
11525     return nullptr;
11526 
11527   // Warn about access declarations.
11528   if (UsingLoc.isInvalid()) {
11529     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11530                                  ? diag::err_access_decl
11531                                  : diag::warn_access_decl_deprecated)
11532         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11533   }
11534 
11535   if (EllipsisLoc.isInvalid()) {
11536     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11537         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11538       return nullptr;
11539   } else {
11540     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11541         !TargetNameInfo.containsUnexpandedParameterPack()) {
11542       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11543         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11544       EllipsisLoc = SourceLocation();
11545     }
11546   }
11547 
11548   NamedDecl *UD =
11549       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11550                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11551                             /*IsInstantiation*/false);
11552   if (UD)
11553     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11554 
11555   return UD;
11556 }
11557 
11558 /// Determine whether a using declaration considers the given
11559 /// declarations as "equivalent", e.g., if they are redeclarations of
11560 /// the same entity or are both typedefs of the same type.
11561 static bool
IsEquivalentForUsingDecl(ASTContext & Context,NamedDecl * D1,NamedDecl * D2)11562 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11563   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11564     return true;
11565 
11566   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11567     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11568       return Context.hasSameType(TD1->getUnderlyingType(),
11569                                  TD2->getUnderlyingType());
11570 
11571   return false;
11572 }
11573 
11574 
11575 /// Determines whether to create a using shadow decl for a particular
11576 /// decl, given the set of decls existing prior to this using lookup.
CheckUsingShadowDecl(UsingDecl * Using,NamedDecl * Orig,const LookupResult & Previous,UsingShadowDecl * & PrevShadow)11577 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
11578                                 const LookupResult &Previous,
11579                                 UsingShadowDecl *&PrevShadow) {
11580   // Diagnose finding a decl which is not from a base class of the
11581   // current class.  We do this now because there are cases where this
11582   // function will silently decide not to build a shadow decl, which
11583   // will pre-empt further diagnostics.
11584   //
11585   // We don't need to do this in C++11 because we do the check once on
11586   // the qualifier.
11587   //
11588   // FIXME: diagnose the following if we care enough:
11589   //   struct A { int foo; };
11590   //   struct B : A { using A::foo; };
11591   //   template <class T> struct C : A {};
11592   //   template <class T> struct D : C<T> { using B::foo; } // <---
11593   // This is invalid (during instantiation) in C++03 because B::foo
11594   // resolves to the using decl in B, which is not a base class of D<T>.
11595   // We can't diagnose it immediately because C<T> is an unknown
11596   // specialization.  The UsingShadowDecl in D<T> then points directly
11597   // to A::foo, which will look well-formed when we instantiate.
11598   // The right solution is to not collapse the shadow-decl chain.
11599   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
11600     DeclContext *OrigDC = Orig->getDeclContext();
11601 
11602     // Handle enums and anonymous structs.
11603     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
11604     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11605     while (OrigRec->isAnonymousStructOrUnion())
11606       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11607 
11608     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11609       if (OrigDC == CurContext) {
11610         Diag(Using->getLocation(),
11611              diag::err_using_decl_nested_name_specifier_is_current_class)
11612           << Using->getQualifierLoc().getSourceRange();
11613         Diag(Orig->getLocation(), diag::note_using_decl_target);
11614         Using->setInvalidDecl();
11615         return true;
11616       }
11617 
11618       Diag(Using->getQualifierLoc().getBeginLoc(),
11619            diag::err_using_decl_nested_name_specifier_is_not_base_class)
11620         << Using->getQualifier()
11621         << cast<CXXRecordDecl>(CurContext)
11622         << Using->getQualifierLoc().getSourceRange();
11623       Diag(Orig->getLocation(), diag::note_using_decl_target);
11624       Using->setInvalidDecl();
11625       return true;
11626     }
11627   }
11628 
11629   if (Previous.empty()) return false;
11630 
11631   NamedDecl *Target = Orig;
11632   if (isa<UsingShadowDecl>(Target))
11633     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11634 
11635   // If the target happens to be one of the previous declarations, we
11636   // don't have a conflict.
11637   //
11638   // FIXME: but we might be increasing its access, in which case we
11639   // should redeclare it.
11640   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11641   bool FoundEquivalentDecl = false;
11642   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11643          I != E; ++I) {
11644     NamedDecl *D = (*I)->getUnderlyingDecl();
11645     // We can have UsingDecls in our Previous results because we use the same
11646     // LookupResult for checking whether the UsingDecl itself is a valid
11647     // redeclaration.
11648     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
11649       continue;
11650 
11651     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11652       // C++ [class.mem]p19:
11653       //   If T is the name of a class, then [every named member other than
11654       //   a non-static data member] shall have a name different from T
11655       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11656           !isa<IndirectFieldDecl>(Target) &&
11657           !isa<UnresolvedUsingValueDecl>(Target) &&
11658           DiagnoseClassNameShadow(
11659               CurContext,
11660               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
11661         return true;
11662     }
11663 
11664     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11665       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11666         PrevShadow = Shadow;
11667       FoundEquivalentDecl = true;
11668     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11669       // We don't conflict with an existing using shadow decl of an equivalent
11670       // declaration, but we're not a redeclaration of it.
11671       FoundEquivalentDecl = true;
11672     }
11673 
11674     if (isVisible(D))
11675       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11676   }
11677 
11678   if (FoundEquivalentDecl)
11679     return false;
11680 
11681   if (FunctionDecl *FD = Target->getAsFunction()) {
11682     NamedDecl *OldDecl = nullptr;
11683     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11684                           /*IsForUsingDecl*/ true)) {
11685     case Ovl_Overload:
11686       return false;
11687 
11688     case Ovl_NonFunction:
11689       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11690       break;
11691 
11692     // We found a decl with the exact signature.
11693     case Ovl_Match:
11694       // If we're in a record, we want to hide the target, so we
11695       // return true (without a diagnostic) to tell the caller not to
11696       // build a shadow decl.
11697       if (CurContext->isRecord())
11698         return true;
11699 
11700       // If we're not in a record, this is an error.
11701       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11702       break;
11703     }
11704 
11705     Diag(Target->getLocation(), diag::note_using_decl_target);
11706     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11707     Using->setInvalidDecl();
11708     return true;
11709   }
11710 
11711   // Target is not a function.
11712 
11713   if (isa<TagDecl>(Target)) {
11714     // No conflict between a tag and a non-tag.
11715     if (!Tag) return false;
11716 
11717     Diag(Using->getLocation(), diag::err_using_decl_conflict);
11718     Diag(Target->getLocation(), diag::note_using_decl_target);
11719     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11720     Using->setInvalidDecl();
11721     return true;
11722   }
11723 
11724   // No conflict between a tag and a non-tag.
11725   if (!NonTag) return false;
11726 
11727   Diag(Using->getLocation(), diag::err_using_decl_conflict);
11728   Diag(Target->getLocation(), diag::note_using_decl_target);
11729   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11730   Using->setInvalidDecl();
11731   return true;
11732 }
11733 
11734 /// Determine whether a direct base class is a virtual base class.
isVirtualDirectBase(CXXRecordDecl * Derived,CXXRecordDecl * Base)11735 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11736   if (!Derived->getNumVBases())
11737     return false;
11738   for (auto &B : Derived->bases())
11739     if (B.getType()->getAsCXXRecordDecl() == Base)
11740       return B.isVirtual();
11741   llvm_unreachable("not a direct base class");
11742 }
11743 
11744 /// Builds a shadow declaration corresponding to a 'using' declaration.
BuildUsingShadowDecl(Scope * S,UsingDecl * UD,NamedDecl * Orig,UsingShadowDecl * PrevDecl)11745 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
11746                                             UsingDecl *UD,
11747                                             NamedDecl *Orig,
11748                                             UsingShadowDecl *PrevDecl) {
11749   // If we resolved to another shadow declaration, just coalesce them.
11750   NamedDecl *Target = Orig;
11751   if (isa<UsingShadowDecl>(Target)) {
11752     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11753     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
11754   }
11755 
11756   NamedDecl *NonTemplateTarget = Target;
11757   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11758     NonTemplateTarget = TargetTD->getTemplatedDecl();
11759 
11760   UsingShadowDecl *Shadow;
11761   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11762     bool IsVirtualBase =
11763         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11764                             UD->getQualifier()->getAsRecordDecl());
11765     Shadow = ConstructorUsingShadowDecl::Create(
11766         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
11767   } else {
11768     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
11769                                      Target);
11770   }
11771   UD->addShadowDecl(Shadow);
11772 
11773   Shadow->setAccess(UD->getAccess());
11774   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
11775     Shadow->setInvalidDecl();
11776 
11777   Shadow->setPreviousDecl(PrevDecl);
11778 
11779   if (S)
11780     PushOnScopeChains(Shadow, S);
11781   else
11782     CurContext->addDecl(Shadow);
11783 
11784 
11785   return Shadow;
11786 }
11787 
11788 /// Hides a using shadow declaration.  This is required by the current
11789 /// using-decl implementation when a resolvable using declaration in a
11790 /// class is followed by a declaration which would hide or override
11791 /// one or more of the using decl's targets; for example:
11792 ///
11793 ///   struct Base { void foo(int); };
11794 ///   struct Derived : Base {
11795 ///     using Base::foo;
11796 ///     void foo(int);
11797 ///   };
11798 ///
11799 /// The governing language is C++03 [namespace.udecl]p12:
11800 ///
11801 ///   When a using-declaration brings names from a base class into a
11802 ///   derived class scope, member functions in the derived class
11803 ///   override and/or hide member functions with the same name and
11804 ///   parameter types in a base class (rather than conflicting).
11805 ///
11806 /// There are two ways to implement this:
11807 ///   (1) optimistically create shadow decls when they're not hidden
11808 ///       by existing declarations, or
11809 ///   (2) don't create any shadow decls (or at least don't make them
11810 ///       visible) until we've fully parsed/instantiated the class.
11811 /// The problem with (1) is that we might have to retroactively remove
11812 /// a shadow decl, which requires several O(n) operations because the
11813 /// decl structures are (very reasonably) not designed for removal.
11814 /// (2) avoids this but is very fiddly and phase-dependent.
HideUsingShadowDecl(Scope * S,UsingShadowDecl * Shadow)11815 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11816   if (Shadow->getDeclName().getNameKind() ==
11817         DeclarationName::CXXConversionFunctionName)
11818     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11819 
11820   // Remove it from the DeclContext...
11821   Shadow->getDeclContext()->removeDecl(Shadow);
11822 
11823   // ...and the scope, if applicable...
11824   if (S) {
11825     S->RemoveDecl(Shadow);
11826     IdResolver.RemoveDecl(Shadow);
11827   }
11828 
11829   // ...and the using decl.
11830   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
11831 
11832   // TODO: complain somehow if Shadow was used.  It shouldn't
11833   // be possible for this to happen, because...?
11834 }
11835 
11836 /// Find the base specifier for a base class with the given type.
findDirectBaseWithType(CXXRecordDecl * Derived,QualType DesiredBase,bool & AnyDependentBases)11837 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11838                                                 QualType DesiredBase,
11839                                                 bool &AnyDependentBases) {
11840   // Check whether the named type is a direct base class.
11841   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11842     .getUnqualifiedType();
11843   for (auto &Base : Derived->bases()) {
11844     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11845     if (CanonicalDesiredBase == BaseType)
11846       return &Base;
11847     if (BaseType->isDependentType())
11848       AnyDependentBases = true;
11849   }
11850   return nullptr;
11851 }
11852 
11853 namespace {
11854 class UsingValidatorCCC final : public CorrectionCandidateCallback {
11855 public:
UsingValidatorCCC(bool HasTypenameKeyword,bool IsInstantiation,NestedNameSpecifier * NNS,CXXRecordDecl * RequireMemberOf)11856   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11857                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11858       : HasTypenameKeyword(HasTypenameKeyword),
11859         IsInstantiation(IsInstantiation), OldNNS(NNS),
11860         RequireMemberOf(RequireMemberOf) {}
11861 
ValidateCandidate(const TypoCorrection & Candidate)11862   bool ValidateCandidate(const TypoCorrection &Candidate) override {
11863     NamedDecl *ND = Candidate.getCorrectionDecl();
11864 
11865     // Keywords are not valid here.
11866     if (!ND || isa<NamespaceDecl>(ND))
11867       return false;
11868 
11869     // Completely unqualified names are invalid for a 'using' declaration.
11870     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11871       return false;
11872 
11873     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11874     // reject.
11875 
11876     if (RequireMemberOf) {
11877       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11878       if (FoundRecord && FoundRecord->isInjectedClassName()) {
11879         // No-one ever wants a using-declaration to name an injected-class-name
11880         // of a base class, unless they're declaring an inheriting constructor.
11881         ASTContext &Ctx = ND->getASTContext();
11882         if (!Ctx.getLangOpts().CPlusPlus11)
11883           return false;
11884         QualType FoundType = Ctx.getRecordType(FoundRecord);
11885 
11886         // Check that the injected-class-name is named as a member of its own
11887         // type; we don't want to suggest 'using Derived::Base;', since that
11888         // means something else.
11889         NestedNameSpecifier *Specifier =
11890             Candidate.WillReplaceSpecifier()
11891                 ? Candidate.getCorrectionSpecifier()
11892                 : OldNNS;
11893         if (!Specifier->getAsType() ||
11894             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
11895           return false;
11896 
11897         // Check that this inheriting constructor declaration actually names a
11898         // direct base class of the current class.
11899         bool AnyDependentBases = false;
11900         if (!findDirectBaseWithType(RequireMemberOf,
11901                                     Ctx.getRecordType(FoundRecord),
11902                                     AnyDependentBases) &&
11903             !AnyDependentBases)
11904           return false;
11905       } else {
11906         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
11907         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
11908           return false;
11909 
11910         // FIXME: Check that the base class member is accessible?
11911       }
11912     } else {
11913       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11914       if (FoundRecord && FoundRecord->isInjectedClassName())
11915         return false;
11916     }
11917 
11918     if (isa<TypeDecl>(ND))
11919       return HasTypenameKeyword || !IsInstantiation;
11920 
11921     return !HasTypenameKeyword;
11922   }
11923 
clone()11924   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11925     return std::make_unique<UsingValidatorCCC>(*this);
11926   }
11927 
11928 private:
11929   bool HasTypenameKeyword;
11930   bool IsInstantiation;
11931   NestedNameSpecifier *OldNNS;
11932   CXXRecordDecl *RequireMemberOf;
11933 };
11934 } // end anonymous namespace
11935 
11936 /// Builds a using declaration.
11937 ///
11938 /// \param IsInstantiation - Whether this call arises from an
11939 ///   instantiation of an unresolved using declaration.  We treat
11940 ///   the lookup differently for these declarations.
BuildUsingDeclaration(Scope * S,AccessSpecifier AS,SourceLocation UsingLoc,bool HasTypenameKeyword,SourceLocation TypenameLoc,CXXScopeSpec & SS,DeclarationNameInfo NameInfo,SourceLocation EllipsisLoc,const ParsedAttributesView & AttrList,bool IsInstantiation)11941 NamedDecl *Sema::BuildUsingDeclaration(
11942     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
11943     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
11944     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
11945     const ParsedAttributesView &AttrList, bool IsInstantiation) {
11946   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11947   SourceLocation IdentLoc = NameInfo.getLoc();
11948   assert(IdentLoc.isValid() && "Invalid TargetName location.");
11949 
11950   // FIXME: We ignore attributes for now.
11951 
11952   // For an inheriting constructor declaration, the name of the using
11953   // declaration is the name of a constructor in this class, not in the
11954   // base class.
11955   DeclarationNameInfo UsingName = NameInfo;
11956   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
11957     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
11958       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
11959           Context.getCanonicalType(Context.getRecordType(RD))));
11960 
11961   // Do the redeclaration lookup in the current scope.
11962   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
11963                         ForVisibleRedeclaration);
11964   Previous.setHideTags(false);
11965   if (S) {
11966     LookupName(Previous, S);
11967 
11968     // It is really dumb that we have to do this.
11969     LookupResult::Filter F = Previous.makeFilter();
11970     while (F.hasNext()) {
11971       NamedDecl *D = F.next();
11972       if (!isDeclInScope(D, CurContext, S))
11973         F.erase();
11974       // If we found a local extern declaration that's not ordinarily visible,
11975       // and this declaration is being added to a non-block scope, ignore it.
11976       // We're only checking for scope conflicts here, not also for violations
11977       // of the linkage rules.
11978       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
11979                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
11980         F.erase();
11981     }
11982     F.done();
11983   } else {
11984     assert(IsInstantiation && "no scope in non-instantiation");
11985     if (CurContext->isRecord())
11986       LookupQualifiedName(Previous, CurContext);
11987     else {
11988       // No redeclaration check is needed here; in non-member contexts we
11989       // diagnosed all possible conflicts with other using-declarations when
11990       // building the template:
11991       //
11992       // For a dependent non-type using declaration, the only valid case is
11993       // if we instantiate to a single enumerator. We check for conflicts
11994       // between shadow declarations we introduce, and we check in the template
11995       // definition for conflicts between a non-type using declaration and any
11996       // other declaration, which together covers all cases.
11997       //
11998       // A dependent typename using declaration will never successfully
11999       // instantiate, since it will always name a class member, so we reject
12000       // that in the template definition.
12001     }
12002   }
12003 
12004   // Check for invalid redeclarations.
12005   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12006                                   SS, IdentLoc, Previous))
12007     return nullptr;
12008 
12009   // Check for bad qualifiers.
12010   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12011                               IdentLoc))
12012     return nullptr;
12013 
12014   DeclContext *LookupContext = computeDeclContext(SS);
12015   NamedDecl *D;
12016   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12017   if (!LookupContext || EllipsisLoc.isValid()) {
12018     if (HasTypenameKeyword) {
12019       // FIXME: not all declaration name kinds are legal here
12020       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12021                                               UsingLoc, TypenameLoc,
12022                                               QualifierLoc,
12023                                               IdentLoc, NameInfo.getName(),
12024                                               EllipsisLoc);
12025     } else {
12026       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12027                                            QualifierLoc, NameInfo, EllipsisLoc);
12028     }
12029     D->setAccess(AS);
12030     CurContext->addDecl(D);
12031     return D;
12032   }
12033 
12034   auto Build = [&](bool Invalid) {
12035     UsingDecl *UD =
12036         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12037                           UsingName, HasTypenameKeyword);
12038     UD->setAccess(AS);
12039     CurContext->addDecl(UD);
12040     UD->setInvalidDecl(Invalid);
12041     return UD;
12042   };
12043   auto BuildInvalid = [&]{ return Build(true); };
12044   auto BuildValid = [&]{ return Build(false); };
12045 
12046   if (RequireCompleteDeclContext(SS, LookupContext))
12047     return BuildInvalid();
12048 
12049   // Look up the target name.
12050   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12051 
12052   // Unlike most lookups, we don't always want to hide tag
12053   // declarations: tag names are visible through the using declaration
12054   // even if hidden by ordinary names, *except* in a dependent context
12055   // where it's important for the sanity of two-phase lookup.
12056   if (!IsInstantiation)
12057     R.setHideTags(false);
12058 
12059   // For the purposes of this lookup, we have a base object type
12060   // equal to that of the current context.
12061   if (CurContext->isRecord()) {
12062     R.setBaseObjectType(
12063                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12064   }
12065 
12066   LookupQualifiedName(R, LookupContext);
12067 
12068   // Try to correct typos if possible. If constructor name lookup finds no
12069   // results, that means the named class has no explicit constructors, and we
12070   // suppressed declaring implicit ones (probably because it's dependent or
12071   // invalid).
12072   if (R.empty() &&
12073       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12074     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
12075     // it will believe that glibc provides a ::gets in cases where it does not,
12076     // and will try to pull it into namespace std with a using-declaration.
12077     // Just ignore the using-declaration in that case.
12078     auto *II = NameInfo.getName().getAsIdentifierInfo();
12079     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12080         CurContext->isStdNamespace() &&
12081         isa<TranslationUnitDecl>(LookupContext) &&
12082         getSourceManager().isInSystemHeader(UsingLoc))
12083       return nullptr;
12084     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12085                           dyn_cast<CXXRecordDecl>(CurContext));
12086     if (TypoCorrection Corrected =
12087             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12088                         CTK_ErrorRecovery)) {
12089       // We reject candidates where DroppedSpecifier == true, hence the
12090       // literal '0' below.
12091       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12092                                 << NameInfo.getName() << LookupContext << 0
12093                                 << SS.getRange());
12094 
12095       // If we picked a correction with no attached Decl we can't do anything
12096       // useful with it, bail out.
12097       NamedDecl *ND = Corrected.getCorrectionDecl();
12098       if (!ND)
12099         return BuildInvalid();
12100 
12101       // If we corrected to an inheriting constructor, handle it as one.
12102       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12103       if (RD && RD->isInjectedClassName()) {
12104         // The parent of the injected class name is the class itself.
12105         RD = cast<CXXRecordDecl>(RD->getParent());
12106 
12107         // Fix up the information we'll use to build the using declaration.
12108         if (Corrected.WillReplaceSpecifier()) {
12109           NestedNameSpecifierLocBuilder Builder;
12110           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12111                               QualifierLoc.getSourceRange());
12112           QualifierLoc = Builder.getWithLocInContext(Context);
12113         }
12114 
12115         // In this case, the name we introduce is the name of a derived class
12116         // constructor.
12117         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12118         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12119             Context.getCanonicalType(Context.getRecordType(CurClass))));
12120         UsingName.setNamedTypeInfo(nullptr);
12121         for (auto *Ctor : LookupConstructors(RD))
12122           R.addDecl(Ctor);
12123         R.resolveKind();
12124       } else {
12125         // FIXME: Pick up all the declarations if we found an overloaded
12126         // function.
12127         UsingName.setName(ND->getDeclName());
12128         R.addDecl(ND);
12129       }
12130     } else {
12131       Diag(IdentLoc, diag::err_no_member)
12132         << NameInfo.getName() << LookupContext << SS.getRange();
12133       return BuildInvalid();
12134     }
12135   }
12136 
12137   if (R.isAmbiguous())
12138     return BuildInvalid();
12139 
12140   if (HasTypenameKeyword) {
12141     // If we asked for a typename and got a non-type decl, error out.
12142     if (!R.getAsSingle<TypeDecl>()) {
12143       Diag(IdentLoc, diag::err_using_typename_non_type);
12144       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12145         Diag((*I)->getUnderlyingDecl()->getLocation(),
12146              diag::note_using_decl_target);
12147       return BuildInvalid();
12148     }
12149   } else {
12150     // If we asked for a non-typename and we got a type, error out,
12151     // but only if this is an instantiation of an unresolved using
12152     // decl.  Otherwise just silently find the type name.
12153     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12154       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12155       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12156       return BuildInvalid();
12157     }
12158   }
12159 
12160   // C++14 [namespace.udecl]p6:
12161   // A using-declaration shall not name a namespace.
12162   if (R.getAsSingle<NamespaceDecl>()) {
12163     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12164       << SS.getRange();
12165     return BuildInvalid();
12166   }
12167 
12168   // C++14 [namespace.udecl]p7:
12169   // A using-declaration shall not name a scoped enumerator.
12170   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
12171     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
12172       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
12173         << SS.getRange();
12174       return BuildInvalid();
12175     }
12176   }
12177 
12178   UsingDecl *UD = BuildValid();
12179 
12180   // Some additional rules apply to inheriting constructors.
12181   if (UsingName.getName().getNameKind() ==
12182         DeclarationName::CXXConstructorName) {
12183     // Suppress access diagnostics; the access check is instead performed at the
12184     // point of use for an inheriting constructor.
12185     R.suppressDiagnostics();
12186     if (CheckInheritingConstructorUsingDecl(UD))
12187       return UD;
12188   }
12189 
12190   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12191     UsingShadowDecl *PrevDecl = nullptr;
12192     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12193       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12194   }
12195 
12196   return UD;
12197 }
12198 
BuildUsingPackDecl(NamedDecl * InstantiatedFrom,ArrayRef<NamedDecl * > Expansions)12199 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12200                                     ArrayRef<NamedDecl *> Expansions) {
12201   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12202          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12203          isa<UsingPackDecl>(InstantiatedFrom));
12204 
12205   auto *UPD =
12206       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12207   UPD->setAccess(InstantiatedFrom->getAccess());
12208   CurContext->addDecl(UPD);
12209   return UPD;
12210 }
12211 
12212 /// Additional checks for a using declaration referring to a constructor name.
CheckInheritingConstructorUsingDecl(UsingDecl * UD)12213 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12214   assert(!UD->hasTypename() && "expecting a constructor name");
12215 
12216   const Type *SourceType = UD->getQualifier()->getAsType();
12217   assert(SourceType &&
12218          "Using decl naming constructor doesn't have type in scope spec.");
12219   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12220 
12221   // Check whether the named type is a direct base class.
12222   bool AnyDependentBases = false;
12223   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12224                                       AnyDependentBases);
12225   if (!Base && !AnyDependentBases) {
12226     Diag(UD->getUsingLoc(),
12227          diag::err_using_decl_constructor_not_in_direct_base)
12228       << UD->getNameInfo().getSourceRange()
12229       << QualType(SourceType, 0) << TargetClass;
12230     UD->setInvalidDecl();
12231     return true;
12232   }
12233 
12234   if (Base)
12235     Base->setInheritConstructors();
12236 
12237   return false;
12238 }
12239 
12240 /// Checks that the given using declaration is not an invalid
12241 /// redeclaration.  Note that this is checking only for the using decl
12242 /// itself, not for any ill-formedness among the UsingShadowDecls.
CheckUsingDeclRedeclaration(SourceLocation UsingLoc,bool HasTypenameKeyword,const CXXScopeSpec & SS,SourceLocation NameLoc,const LookupResult & Prev)12243 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12244                                        bool HasTypenameKeyword,
12245                                        const CXXScopeSpec &SS,
12246                                        SourceLocation NameLoc,
12247                                        const LookupResult &Prev) {
12248   NestedNameSpecifier *Qual = SS.getScopeRep();
12249 
12250   // C++03 [namespace.udecl]p8:
12251   // C++0x [namespace.udecl]p10:
12252   //   A using-declaration is a declaration and can therefore be used
12253   //   repeatedly where (and only where) multiple declarations are
12254   //   allowed.
12255   //
12256   // That's in non-member contexts.
12257   if (!CurContext->getRedeclContext()->isRecord()) {
12258     // A dependent qualifier outside a class can only ever resolve to an
12259     // enumeration type. Therefore it conflicts with any other non-type
12260     // declaration in the same scope.
12261     // FIXME: How should we check for dependent type-type conflicts at block
12262     // scope?
12263     if (Qual->isDependent() && !HasTypenameKeyword) {
12264       for (auto *D : Prev) {
12265         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12266           bool OldCouldBeEnumerator =
12267               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12268           Diag(NameLoc,
12269                OldCouldBeEnumerator ? diag::err_redefinition
12270                                     : diag::err_redefinition_different_kind)
12271               << Prev.getLookupName();
12272           Diag(D->getLocation(), diag::note_previous_definition);
12273           return true;
12274         }
12275       }
12276     }
12277     return false;
12278   }
12279 
12280   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12281     NamedDecl *D = *I;
12282 
12283     bool DTypename;
12284     NestedNameSpecifier *DQual;
12285     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12286       DTypename = UD->hasTypename();
12287       DQual = UD->getQualifier();
12288     } else if (UnresolvedUsingValueDecl *UD
12289                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12290       DTypename = false;
12291       DQual = UD->getQualifier();
12292     } else if (UnresolvedUsingTypenameDecl *UD
12293                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12294       DTypename = true;
12295       DQual = UD->getQualifier();
12296     } else continue;
12297 
12298     // using decls differ if one says 'typename' and the other doesn't.
12299     // FIXME: non-dependent using decls?
12300     if (HasTypenameKeyword != DTypename) continue;
12301 
12302     // using decls differ if they name different scopes (but note that
12303     // template instantiation can cause this check to trigger when it
12304     // didn't before instantiation).
12305     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12306         Context.getCanonicalNestedNameSpecifier(DQual))
12307       continue;
12308 
12309     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12310     Diag(D->getLocation(), diag::note_using_decl) << 1;
12311     return true;
12312   }
12313 
12314   return false;
12315 }
12316 
12317 
12318 /// Checks that the given nested-name qualifier used in a using decl
12319 /// in the current context is appropriately related to the current
12320 /// scope.  If an error is found, diagnoses it and returns true.
CheckUsingDeclQualifier(SourceLocation UsingLoc,bool HasTypename,const CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,SourceLocation NameLoc)12321 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
12322                                    bool HasTypename,
12323                                    const CXXScopeSpec &SS,
12324                                    const DeclarationNameInfo &NameInfo,
12325                                    SourceLocation NameLoc) {
12326   DeclContext *NamedContext = computeDeclContext(SS);
12327 
12328   if (!CurContext->isRecord()) {
12329     // C++03 [namespace.udecl]p3:
12330     // C++0x [namespace.udecl]p8:
12331     //   A using-declaration for a class member shall be a member-declaration.
12332 
12333     // If we weren't able to compute a valid scope, it might validly be a
12334     // dependent class scope or a dependent enumeration unscoped scope. If
12335     // we have a 'typename' keyword, the scope must resolve to a class type.
12336     if ((HasTypename && !NamedContext) ||
12337         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
12338       auto *RD = NamedContext
12339                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12340                      : nullptr;
12341       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
12342         RD = nullptr;
12343 
12344       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
12345         << SS.getRange();
12346 
12347       // If we have a complete, non-dependent source type, try to suggest a
12348       // way to get the same effect.
12349       if (!RD)
12350         return true;
12351 
12352       // Find what this using-declaration was referring to.
12353       LookupResult R(*this, NameInfo, LookupOrdinaryName);
12354       R.setHideTags(false);
12355       R.suppressDiagnostics();
12356       LookupQualifiedName(R, RD);
12357 
12358       if (R.getAsSingle<TypeDecl>()) {
12359         if (getLangOpts().CPlusPlus11) {
12360           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12361           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12362             << 0 // alias declaration
12363             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12364                                           NameInfo.getName().getAsString() +
12365                                               " = ");
12366         } else {
12367           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12368           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12369           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12370             << 1 // typedef declaration
12371             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12372             << FixItHint::CreateInsertion(
12373                    InsertLoc, " " + NameInfo.getName().getAsString());
12374         }
12375       } else if (R.getAsSingle<VarDecl>()) {
12376         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12377         // repeating the type of the static data member here.
12378         FixItHint FixIt;
12379         if (getLangOpts().CPlusPlus11) {
12380           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12381           FixIt = FixItHint::CreateReplacement(
12382               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12383         }
12384 
12385         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12386           << 2 // reference declaration
12387           << FixIt;
12388       } else if (R.getAsSingle<EnumConstantDecl>()) {
12389         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12390         // repeating the type of the enumeration here, and we can't do so if
12391         // the type is anonymous.
12392         FixItHint FixIt;
12393         if (getLangOpts().CPlusPlus11) {
12394           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12395           FixIt = FixItHint::CreateReplacement(
12396               UsingLoc,
12397               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12398         }
12399 
12400         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12401           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12402           << FixIt;
12403       }
12404       return true;
12405     }
12406 
12407     // Otherwise, this might be valid.
12408     return false;
12409   }
12410 
12411   // The current scope is a record.
12412 
12413   // If the named context is dependent, we can't decide much.
12414   if (!NamedContext) {
12415     // FIXME: in C++0x, we can diagnose if we can prove that the
12416     // nested-name-specifier does not refer to a base class, which is
12417     // still possible in some cases.
12418 
12419     // Otherwise we have to conservatively report that things might be
12420     // okay.
12421     return false;
12422   }
12423 
12424   if (!NamedContext->isRecord()) {
12425     // Ideally this would point at the last name in the specifier,
12426     // but we don't have that level of source info.
12427     Diag(SS.getRange().getBegin(),
12428          diag::err_using_decl_nested_name_specifier_is_not_class)
12429       << SS.getScopeRep() << SS.getRange();
12430     return true;
12431   }
12432 
12433   if (!NamedContext->isDependentContext() &&
12434       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12435     return true;
12436 
12437   if (getLangOpts().CPlusPlus11) {
12438     // C++11 [namespace.udecl]p3:
12439     //   In a using-declaration used as a member-declaration, the
12440     //   nested-name-specifier shall name a base class of the class
12441     //   being defined.
12442 
12443     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12444                                  cast<CXXRecordDecl>(NamedContext))) {
12445       if (CurContext == NamedContext) {
12446         Diag(NameLoc,
12447              diag::err_using_decl_nested_name_specifier_is_current_class)
12448           << SS.getRange();
12449         return true;
12450       }
12451 
12452       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12453         Diag(SS.getRange().getBegin(),
12454              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12455           << SS.getScopeRep()
12456           << cast<CXXRecordDecl>(CurContext)
12457           << SS.getRange();
12458       }
12459       return true;
12460     }
12461 
12462     return false;
12463   }
12464 
12465   // C++03 [namespace.udecl]p4:
12466   //   A using-declaration used as a member-declaration shall refer
12467   //   to a member of a base class of the class being defined [etc.].
12468 
12469   // Salient point: SS doesn't have to name a base class as long as
12470   // lookup only finds members from base classes.  Therefore we can
12471   // diagnose here only if we can prove that that can't happen,
12472   // i.e. if the class hierarchies provably don't intersect.
12473 
12474   // TODO: it would be nice if "definitely valid" results were cached
12475   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12476   // need to be repeated.
12477 
12478   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12479   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12480     Bases.insert(Base);
12481     return true;
12482   };
12483 
12484   // Collect all bases. Return false if we find a dependent base.
12485   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12486     return false;
12487 
12488   // Returns true if the base is dependent or is one of the accumulated base
12489   // classes.
12490   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12491     return !Bases.count(Base);
12492   };
12493 
12494   // Return false if the class has a dependent base or if it or one
12495   // of its bases is present in the base set of the current context.
12496   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12497       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12498     return false;
12499 
12500   Diag(SS.getRange().getBegin(),
12501        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12502     << SS.getScopeRep()
12503     << cast<CXXRecordDecl>(CurContext)
12504     << SS.getRange();
12505 
12506   return true;
12507 }
12508 
ActOnAliasDeclaration(Scope * S,AccessSpecifier AS,MultiTemplateParamsArg TemplateParamLists,SourceLocation UsingLoc,UnqualifiedId & Name,const ParsedAttributesView & AttrList,TypeResult Type,Decl * DeclFromDeclSpec)12509 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12510                                   MultiTemplateParamsArg TemplateParamLists,
12511                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12512                                   const ParsedAttributesView &AttrList,
12513                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12514   // Skip up to the relevant declaration scope.
12515   while (S->isTemplateParamScope())
12516     S = S->getParent();
12517   assert((S->getFlags() & Scope::DeclScope) &&
12518          "got alias-declaration outside of declaration scope");
12519 
12520   if (Type.isInvalid())
12521     return nullptr;
12522 
12523   bool Invalid = false;
12524   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12525   TypeSourceInfo *TInfo = nullptr;
12526   GetTypeFromParser(Type.get(), &TInfo);
12527 
12528   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12529     return nullptr;
12530 
12531   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12532                                       UPPC_DeclarationType)) {
12533     Invalid = true;
12534     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12535                                              TInfo->getTypeLoc().getBeginLoc());
12536   }
12537 
12538   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12539                         TemplateParamLists.size()
12540                             ? forRedeclarationInCurContext()
12541                             : ForVisibleRedeclaration);
12542   LookupName(Previous, S);
12543 
12544   // Warn about shadowing the name of a template parameter.
12545   if (Previous.isSingleResult() &&
12546       Previous.getFoundDecl()->isTemplateParameter()) {
12547     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12548     Previous.clear();
12549   }
12550 
12551   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12552          "name in alias declaration must be an identifier");
12553   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12554                                                Name.StartLocation,
12555                                                Name.Identifier, TInfo);
12556 
12557   NewTD->setAccess(AS);
12558 
12559   if (Invalid)
12560     NewTD->setInvalidDecl();
12561 
12562   ProcessDeclAttributeList(S, NewTD, AttrList);
12563   AddPragmaAttributes(S, NewTD);
12564 
12565   CheckTypedefForVariablyModifiedType(S, NewTD);
12566   Invalid |= NewTD->isInvalidDecl();
12567 
12568   bool Redeclaration = false;
12569 
12570   NamedDecl *NewND;
12571   if (TemplateParamLists.size()) {
12572     TypeAliasTemplateDecl *OldDecl = nullptr;
12573     TemplateParameterList *OldTemplateParams = nullptr;
12574 
12575     if (TemplateParamLists.size() != 1) {
12576       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12577         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12578          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12579     }
12580     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12581 
12582     // Check that we can declare a template here.
12583     if (CheckTemplateDeclScope(S, TemplateParams))
12584       return nullptr;
12585 
12586     // Only consider previous declarations in the same scope.
12587     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12588                          /*ExplicitInstantiationOrSpecialization*/false);
12589     if (!Previous.empty()) {
12590       Redeclaration = true;
12591 
12592       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12593       if (!OldDecl && !Invalid) {
12594         Diag(UsingLoc, diag::err_redefinition_different_kind)
12595           << Name.Identifier;
12596 
12597         NamedDecl *OldD = Previous.getRepresentativeDecl();
12598         if (OldD->getLocation().isValid())
12599           Diag(OldD->getLocation(), diag::note_previous_definition);
12600 
12601         Invalid = true;
12602       }
12603 
12604       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12605         if (TemplateParameterListsAreEqual(TemplateParams,
12606                                            OldDecl->getTemplateParameters(),
12607                                            /*Complain=*/true,
12608                                            TPL_TemplateMatch))
12609           OldTemplateParams =
12610               OldDecl->getMostRecentDecl()->getTemplateParameters();
12611         else
12612           Invalid = true;
12613 
12614         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12615         if (!Invalid &&
12616             !Context.hasSameType(OldTD->getUnderlyingType(),
12617                                  NewTD->getUnderlyingType())) {
12618           // FIXME: The C++0x standard does not clearly say this is ill-formed,
12619           // but we can't reasonably accept it.
12620           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12621             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12622           if (OldTD->getLocation().isValid())
12623             Diag(OldTD->getLocation(), diag::note_previous_definition);
12624           Invalid = true;
12625         }
12626       }
12627     }
12628 
12629     // Merge any previous default template arguments into our parameters,
12630     // and check the parameter list.
12631     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12632                                    TPC_TypeAliasTemplate))
12633       return nullptr;
12634 
12635     TypeAliasTemplateDecl *NewDecl =
12636       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12637                                     Name.Identifier, TemplateParams,
12638                                     NewTD);
12639     NewTD->setDescribedAliasTemplate(NewDecl);
12640 
12641     NewDecl->setAccess(AS);
12642 
12643     if (Invalid)
12644       NewDecl->setInvalidDecl();
12645     else if (OldDecl) {
12646       NewDecl->setPreviousDecl(OldDecl);
12647       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12648     }
12649 
12650     NewND = NewDecl;
12651   } else {
12652     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12653       setTagNameForLinkagePurposes(TD, NewTD);
12654       handleTagNumbering(TD, S);
12655     }
12656     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12657     NewND = NewTD;
12658   }
12659 
12660   PushOnScopeChains(NewND, S);
12661   ActOnDocumentableDecl(NewND);
12662   return NewND;
12663 }
12664 
ActOnNamespaceAliasDef(Scope * S,SourceLocation NamespaceLoc,SourceLocation AliasLoc,IdentifierInfo * Alias,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * Ident)12665 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12666                                    SourceLocation AliasLoc,
12667                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
12668                                    SourceLocation IdentLoc,
12669                                    IdentifierInfo *Ident) {
12670 
12671   // Lookup the namespace name.
12672   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12673   LookupParsedName(R, S, &SS);
12674 
12675   if (R.isAmbiguous())
12676     return nullptr;
12677 
12678   if (R.empty()) {
12679     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12680       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12681       return nullptr;
12682     }
12683   }
12684   assert(!R.isAmbiguous() && !R.empty());
12685   NamedDecl *ND = R.getRepresentativeDecl();
12686 
12687   // Check if we have a previous declaration with the same name.
12688   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12689                      ForVisibleRedeclaration);
12690   LookupName(PrevR, S);
12691 
12692   // Check we're not shadowing a template parameter.
12693   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12694     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12695     PrevR.clear();
12696   }
12697 
12698   // Filter out any other lookup result from an enclosing scope.
12699   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12700                        /*AllowInlineNamespace*/false);
12701 
12702   // Find the previous declaration and check that we can redeclare it.
12703   NamespaceAliasDecl *Prev = nullptr;
12704   if (PrevR.isSingleResult()) {
12705     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12706     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12707       // We already have an alias with the same name that points to the same
12708       // namespace; check that it matches.
12709       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12710         Prev = AD;
12711       } else if (isVisible(PrevDecl)) {
12712         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12713           << Alias;
12714         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12715           << AD->getNamespace();
12716         return nullptr;
12717       }
12718     } else if (isVisible(PrevDecl)) {
12719       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12720                             ? diag::err_redefinition
12721                             : diag::err_redefinition_different_kind;
12722       Diag(AliasLoc, DiagID) << Alias;
12723       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12724       return nullptr;
12725     }
12726   }
12727 
12728   // The use of a nested name specifier may trigger deprecation warnings.
12729   DiagnoseUseOfDecl(ND, IdentLoc);
12730 
12731   NamespaceAliasDecl *AliasDecl =
12732     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12733                                Alias, SS.getWithLocInContext(Context),
12734                                IdentLoc, ND);
12735   if (Prev)
12736     AliasDecl->setPreviousDecl(Prev);
12737 
12738   PushOnScopeChains(AliasDecl, S);
12739   return AliasDecl;
12740 }
12741 
12742 namespace {
12743 struct SpecialMemberExceptionSpecInfo
12744     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12745   SourceLocation Loc;
12746   Sema::ImplicitExceptionSpecification ExceptSpec;
12747 
SpecialMemberExceptionSpecInfo__anonedc74bd73411::SpecialMemberExceptionSpecInfo12748   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12749                                  Sema::CXXSpecialMember CSM,
12750                                  Sema::InheritedConstructorInfo *ICI,
12751                                  SourceLocation Loc)
12752       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12753 
12754   bool visitBase(CXXBaseSpecifier *Base);
12755   bool visitField(FieldDecl *FD);
12756 
12757   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12758                            unsigned Quals);
12759 
12760   void visitSubobjectCall(Subobject Subobj,
12761                           Sema::SpecialMemberOverloadResult SMOR);
12762 };
12763 }
12764 
visitBase(CXXBaseSpecifier * Base)12765 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
12766   auto *RT = Base->getType()->getAs<RecordType>();
12767   if (!RT)
12768     return false;
12769 
12770   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
12771   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
12772   if (auto *BaseCtor = SMOR.getMethod()) {
12773     visitSubobjectCall(Base, BaseCtor);
12774     return false;
12775   }
12776 
12777   visitClassSubobject(BaseClass, Base, 0);
12778   return false;
12779 }
12780 
visitField(FieldDecl * FD)12781 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
12782   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
12783     Expr *E = FD->getInClassInitializer();
12784     if (!E)
12785       // FIXME: It's a little wasteful to build and throw away a
12786       // CXXDefaultInitExpr here.
12787       // FIXME: We should have a single context note pointing at Loc, and
12788       // this location should be MD->getLocation() instead, since that's
12789       // the location where we actually use the default init expression.
12790       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
12791     if (E)
12792       ExceptSpec.CalledExpr(E);
12793   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
12794                             ->getAs<RecordType>()) {
12795     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
12796                         FD->getType().getCVRQualifiers());
12797   }
12798   return false;
12799 }
12800 
visitClassSubobject(CXXRecordDecl * Class,Subobject Subobj,unsigned Quals)12801 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
12802                                                          Subobject Subobj,
12803                                                          unsigned Quals) {
12804   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
12805   bool IsMutable = Field && Field->isMutable();
12806   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
12807 }
12808 
visitSubobjectCall(Subobject Subobj,Sema::SpecialMemberOverloadResult SMOR)12809 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
12810     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
12811   // Note, if lookup fails, it doesn't matter what exception specification we
12812   // choose because the special member will be deleted.
12813   if (CXXMethodDecl *MD = SMOR.getMethod())
12814     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
12815 }
12816 
tryResolveExplicitSpecifier(ExplicitSpecifier & ExplicitSpec)12817 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
12818   llvm::APSInt Result;
12819   ExprResult Converted = CheckConvertedConstantExpression(
12820       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
12821   ExplicitSpec.setExpr(Converted.get());
12822   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
12823     ExplicitSpec.setKind(Result.getBoolValue()
12824                              ? ExplicitSpecKind::ResolvedTrue
12825                              : ExplicitSpecKind::ResolvedFalse);
12826     return true;
12827   }
12828   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
12829   return false;
12830 }
12831 
ActOnExplicitBoolSpecifier(Expr * ExplicitExpr)12832 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
12833   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
12834   if (!ExplicitExpr->isTypeDependent())
12835     tryResolveExplicitSpecifier(ES);
12836   return ES;
12837 }
12838 
12839 static Sema::ImplicitExceptionSpecification
ComputeDefaultedSpecialMemberExceptionSpec(Sema & S,SourceLocation Loc,CXXMethodDecl * MD,Sema::CXXSpecialMember CSM,Sema::InheritedConstructorInfo * ICI)12840 ComputeDefaultedSpecialMemberExceptionSpec(
12841     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
12842     Sema::InheritedConstructorInfo *ICI) {
12843   ComputingExceptionSpec CES(S, MD, Loc);
12844 
12845   CXXRecordDecl *ClassDecl = MD->getParent();
12846 
12847   // C++ [except.spec]p14:
12848   //   An implicitly declared special member function (Clause 12) shall have an
12849   //   exception-specification. [...]
12850   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
12851   if (ClassDecl->isInvalidDecl())
12852     return Info.ExceptSpec;
12853 
12854   // FIXME: If this diagnostic fires, we're probably missing a check for
12855   // attempting to resolve an exception specification before it's known
12856   // at a higher level.
12857   if (S.RequireCompleteType(MD->getLocation(),
12858                             S.Context.getRecordType(ClassDecl),
12859                             diag::err_exception_spec_incomplete_type))
12860     return Info.ExceptSpec;
12861 
12862   // C++1z [except.spec]p7:
12863   //   [Look for exceptions thrown by] a constructor selected [...] to
12864   //   initialize a potentially constructed subobject,
12865   // C++1z [except.spec]p8:
12866   //   The exception specification for an implicitly-declared destructor, or a
12867   //   destructor without a noexcept-specifier, is potentially-throwing if and
12868   //   only if any of the destructors for any of its potentially constructed
12869   //   subojects is potentially throwing.
12870   // FIXME: We respect the first rule but ignore the "potentially constructed"
12871   // in the second rule to resolve a core issue (no number yet) that would have
12872   // us reject:
12873   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
12874   //   struct B : A {};
12875   //   struct C : B { void f(); };
12876   // ... due to giving B::~B() a non-throwing exception specification.
12877   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
12878                                 : Info.VisitAllBases);
12879 
12880   return Info.ExceptSpec;
12881 }
12882 
12883 namespace {
12884 /// RAII object to register a special member as being currently declared.
12885 struct DeclaringSpecialMember {
12886   Sema &S;
12887   Sema::SpecialMemberDecl D;
12888   Sema::ContextRAII SavedContext;
12889   bool WasAlreadyBeingDeclared;
12890 
DeclaringSpecialMember__anonedc74bd73511::DeclaringSpecialMember12891   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
12892       : S(S), D(RD, CSM), SavedContext(S, RD) {
12893     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
12894     if (WasAlreadyBeingDeclared)
12895       // This almost never happens, but if it does, ensure that our cache
12896       // doesn't contain a stale result.
12897       S.SpecialMemberCache.clear();
12898     else {
12899       // Register a note to be produced if we encounter an error while
12900       // declaring the special member.
12901       Sema::CodeSynthesisContext Ctx;
12902       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
12903       // FIXME: We don't have a location to use here. Using the class's
12904       // location maintains the fiction that we declare all special members
12905       // with the class, but (1) it's not clear that lying about that helps our
12906       // users understand what's going on, and (2) there may be outer contexts
12907       // on the stack (some of which are relevant) and printing them exposes
12908       // our lies.
12909       Ctx.PointOfInstantiation = RD->getLocation();
12910       Ctx.Entity = RD;
12911       Ctx.SpecialMember = CSM;
12912       S.pushCodeSynthesisContext(Ctx);
12913     }
12914   }
~DeclaringSpecialMember__anonedc74bd73511::DeclaringSpecialMember12915   ~DeclaringSpecialMember() {
12916     if (!WasAlreadyBeingDeclared) {
12917       S.SpecialMembersBeingDeclared.erase(D);
12918       S.popCodeSynthesisContext();
12919     }
12920   }
12921 
12922   /// Are we already trying to declare this special member?
isAlreadyBeingDeclared__anonedc74bd73511::DeclaringSpecialMember12923   bool isAlreadyBeingDeclared() const {
12924     return WasAlreadyBeingDeclared;
12925   }
12926 };
12927 }
12928 
CheckImplicitSpecialMemberDeclaration(Scope * S,FunctionDecl * FD)12929 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
12930   // Look up any existing declarations, but don't trigger declaration of all
12931   // implicit special members with this name.
12932   DeclarationName Name = FD->getDeclName();
12933   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
12934                  ForExternalRedeclaration);
12935   for (auto *D : FD->getParent()->lookup(Name))
12936     if (auto *Acceptable = R.getAcceptableDecl(D))
12937       R.addDecl(Acceptable);
12938   R.resolveKind();
12939   R.suppressDiagnostics();
12940 
12941   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
12942 }
12943 
setupImplicitSpecialMemberType(CXXMethodDecl * SpecialMem,QualType ResultTy,ArrayRef<QualType> Args)12944 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
12945                                           QualType ResultTy,
12946                                           ArrayRef<QualType> Args) {
12947   // Build an exception specification pointing back at this constructor.
12948   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
12949 
12950   LangAS AS = getDefaultCXXMethodAddrSpace();
12951   if (AS != LangAS::Default) {
12952     EPI.TypeQuals.addAddressSpace(AS);
12953   }
12954 
12955   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
12956   SpecialMem->setType(QT);
12957 }
12958 
DeclareImplicitDefaultConstructor(CXXRecordDecl * ClassDecl)12959 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
12960                                                      CXXRecordDecl *ClassDecl) {
12961   // C++ [class.ctor]p5:
12962   //   A default constructor for a class X is a constructor of class X
12963   //   that can be called without an argument. If there is no
12964   //   user-declared constructor for class X, a default constructor is
12965   //   implicitly declared. An implicitly-declared default constructor
12966   //   is an inline public member of its class.
12967   assert(ClassDecl->needsImplicitDefaultConstructor() &&
12968          "Should not build implicit default constructor!");
12969 
12970   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
12971   if (DSM.isAlreadyBeingDeclared())
12972     return nullptr;
12973 
12974   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12975                                                      CXXDefaultConstructor,
12976                                                      false);
12977 
12978   // Create the actual constructor declaration.
12979   CanQualType ClassType
12980     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
12981   SourceLocation ClassLoc = ClassDecl->getLocation();
12982   DeclarationName Name
12983     = Context.DeclarationNames.getCXXConstructorName(ClassType);
12984   DeclarationNameInfo NameInfo(Name, ClassLoc);
12985   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
12986       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
12987       /*TInfo=*/nullptr, ExplicitSpecifier(),
12988       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12989       Constexpr ? ConstexprSpecKind::Constexpr
12990                 : ConstexprSpecKind::Unspecified);
12991   DefaultCon->setAccess(AS_public);
12992   DefaultCon->setDefaulted();
12993 
12994   if (getLangOpts().CUDA) {
12995     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
12996                                             DefaultCon,
12997                                             /* ConstRHS */ false,
12998                                             /* Diagnose */ false);
12999   }
13000 
13001   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13002 
13003   // We don't need to use SpecialMemberIsTrivial here; triviality for default
13004   // constructors is easy to compute.
13005   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13006 
13007   // Note that we have declared this constructor.
13008   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13009 
13010   Scope *S = getScopeForContext(ClassDecl);
13011   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13012 
13013   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13014     SetDeclDeleted(DefaultCon, ClassLoc);
13015 
13016   if (S)
13017     PushOnScopeChains(DefaultCon, S, false);
13018   ClassDecl->addDecl(DefaultCon);
13019 
13020   return DefaultCon;
13021 }
13022 
DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * Constructor)13023 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13024                                             CXXConstructorDecl *Constructor) {
13025   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13026           !Constructor->doesThisDeclarationHaveABody() &&
13027           !Constructor->isDeleted()) &&
13028     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13029   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13030     return;
13031 
13032   CXXRecordDecl *ClassDecl = Constructor->getParent();
13033   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13034 
13035   SynthesizedFunctionScope Scope(*this, Constructor);
13036 
13037   // The exception specification is needed because we are defining the
13038   // function.
13039   ResolveExceptionSpec(CurrentLocation,
13040                        Constructor->getType()->castAs<FunctionProtoType>());
13041   MarkVTableUsed(CurrentLocation, ClassDecl);
13042 
13043   // Add a context note for diagnostics produced after this point.
13044   Scope.addContextNote(CurrentLocation);
13045 
13046   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13047     Constructor->setInvalidDecl();
13048     return;
13049   }
13050 
13051   SourceLocation Loc = Constructor->getEndLoc().isValid()
13052                            ? Constructor->getEndLoc()
13053                            : Constructor->getLocation();
13054   Constructor->setBody(new (Context) CompoundStmt(Loc));
13055   Constructor->markUsed(Context);
13056 
13057   if (ASTMutationListener *L = getASTMutationListener()) {
13058     L->CompletedImplicitDefinition(Constructor);
13059   }
13060 
13061   DiagnoseUninitializedFields(*this, Constructor);
13062 }
13063 
ActOnFinishDelayedMemberInitializers(Decl * D)13064 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13065   // Perform any delayed checks on exception specifications.
13066   CheckDelayedMemberExceptionSpecs();
13067 }
13068 
13069 /// Find or create the fake constructor we synthesize to model constructing an
13070 /// object of a derived class via a constructor of a base class.
13071 CXXConstructorDecl *
findInheritingConstructor(SourceLocation Loc,CXXConstructorDecl * BaseCtor,ConstructorUsingShadowDecl * Shadow)13072 Sema::findInheritingConstructor(SourceLocation Loc,
13073                                 CXXConstructorDecl *BaseCtor,
13074                                 ConstructorUsingShadowDecl *Shadow) {
13075   CXXRecordDecl *Derived = Shadow->getParent();
13076   SourceLocation UsingLoc = Shadow->getLocation();
13077 
13078   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13079   // For now we use the name of the base class constructor as a member of the
13080   // derived class to indicate a (fake) inherited constructor name.
13081   DeclarationName Name = BaseCtor->getDeclName();
13082 
13083   // Check to see if we already have a fake constructor for this inherited
13084   // constructor call.
13085   for (NamedDecl *Ctor : Derived->lookup(Name))
13086     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13087                                ->getInheritedConstructor()
13088                                .getConstructor(),
13089                            BaseCtor))
13090       return cast<CXXConstructorDecl>(Ctor);
13091 
13092   DeclarationNameInfo NameInfo(Name, UsingLoc);
13093   TypeSourceInfo *TInfo =
13094       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13095   FunctionProtoTypeLoc ProtoLoc =
13096       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13097 
13098   // Check the inherited constructor is valid and find the list of base classes
13099   // from which it was inherited.
13100   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13101 
13102   bool Constexpr =
13103       BaseCtor->isConstexpr() &&
13104       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13105                                         false, BaseCtor, &ICI);
13106 
13107   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13108       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13109       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
13110       /*isImplicitlyDeclared=*/true,
13111       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13112       InheritedConstructor(Shadow, BaseCtor),
13113       BaseCtor->getTrailingRequiresClause());
13114   if (Shadow->isInvalidDecl())
13115     DerivedCtor->setInvalidDecl();
13116 
13117   // Build an unevaluated exception specification for this fake constructor.
13118   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13119   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13120   EPI.ExceptionSpec.Type = EST_Unevaluated;
13121   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13122   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13123                                                FPT->getParamTypes(), EPI));
13124 
13125   // Build the parameter declarations.
13126   SmallVector<ParmVarDecl *, 16> ParamDecls;
13127   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13128     TypeSourceInfo *TInfo =
13129         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13130     ParmVarDecl *PD = ParmVarDecl::Create(
13131         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13132         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13133     PD->setScopeInfo(0, I);
13134     PD->setImplicit();
13135     // Ensure attributes are propagated onto parameters (this matters for
13136     // format, pass_object_size, ...).
13137     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13138     ParamDecls.push_back(PD);
13139     ProtoLoc.setParam(I, PD);
13140   }
13141 
13142   // Set up the new constructor.
13143   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13144   DerivedCtor->setAccess(BaseCtor->getAccess());
13145   DerivedCtor->setParams(ParamDecls);
13146   Derived->addDecl(DerivedCtor);
13147 
13148   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13149     SetDeclDeleted(DerivedCtor, UsingLoc);
13150 
13151   return DerivedCtor;
13152 }
13153 
NoteDeletedInheritingConstructor(CXXConstructorDecl * Ctor)13154 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13155   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13156                                Ctor->getInheritedConstructor().getShadowDecl());
13157   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13158                             /*Diagnose*/true);
13159 }
13160 
DefineInheritingConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * Constructor)13161 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13162                                        CXXConstructorDecl *Constructor) {
13163   CXXRecordDecl *ClassDecl = Constructor->getParent();
13164   assert(Constructor->getInheritedConstructor() &&
13165          !Constructor->doesThisDeclarationHaveABody() &&
13166          !Constructor->isDeleted());
13167   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13168     return;
13169 
13170   // Initializations are performed "as if by a defaulted default constructor",
13171   // so enter the appropriate scope.
13172   SynthesizedFunctionScope Scope(*this, Constructor);
13173 
13174   // The exception specification is needed because we are defining the
13175   // function.
13176   ResolveExceptionSpec(CurrentLocation,
13177                        Constructor->getType()->castAs<FunctionProtoType>());
13178   MarkVTableUsed(CurrentLocation, ClassDecl);
13179 
13180   // Add a context note for diagnostics produced after this point.
13181   Scope.addContextNote(CurrentLocation);
13182 
13183   ConstructorUsingShadowDecl *Shadow =
13184       Constructor->getInheritedConstructor().getShadowDecl();
13185   CXXConstructorDecl *InheritedCtor =
13186       Constructor->getInheritedConstructor().getConstructor();
13187 
13188   // [class.inhctor.init]p1:
13189   //   initialization proceeds as if a defaulted default constructor is used to
13190   //   initialize the D object and each base class subobject from which the
13191   //   constructor was inherited
13192 
13193   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13194   CXXRecordDecl *RD = Shadow->getParent();
13195   SourceLocation InitLoc = Shadow->getLocation();
13196 
13197   // Build explicit initializers for all base classes from which the
13198   // constructor was inherited.
13199   SmallVector<CXXCtorInitializer*, 8> Inits;
13200   for (bool VBase : {false, true}) {
13201     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13202       if (B.isVirtual() != VBase)
13203         continue;
13204 
13205       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13206       if (!BaseRD)
13207         continue;
13208 
13209       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13210       if (!BaseCtor.first)
13211         continue;
13212 
13213       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13214       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13215           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13216 
13217       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13218       Inits.push_back(new (Context) CXXCtorInitializer(
13219           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13220           SourceLocation()));
13221     }
13222   }
13223 
13224   // We now proceed as if for a defaulted default constructor, with the relevant
13225   // initializers replaced.
13226 
13227   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13228     Constructor->setInvalidDecl();
13229     return;
13230   }
13231 
13232   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13233   Constructor->markUsed(Context);
13234 
13235   if (ASTMutationListener *L = getASTMutationListener()) {
13236     L->CompletedImplicitDefinition(Constructor);
13237   }
13238 
13239   DiagnoseUninitializedFields(*this, Constructor);
13240 }
13241 
DeclareImplicitDestructor(CXXRecordDecl * ClassDecl)13242 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13243   // C++ [class.dtor]p2:
13244   //   If a class has no user-declared destructor, a destructor is
13245   //   declared implicitly. An implicitly-declared destructor is an
13246   //   inline public member of its class.
13247   assert(ClassDecl->needsImplicitDestructor());
13248 
13249   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13250   if (DSM.isAlreadyBeingDeclared())
13251     return nullptr;
13252 
13253   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13254                                                      CXXDestructor,
13255                                                      false);
13256 
13257   // Create the actual destructor declaration.
13258   CanQualType ClassType
13259     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13260   SourceLocation ClassLoc = ClassDecl->getLocation();
13261   DeclarationName Name
13262     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13263   DeclarationNameInfo NameInfo(Name, ClassLoc);
13264   CXXDestructorDecl *Destructor =
13265       CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13266                                 QualType(), nullptr, /*isInline=*/true,
13267                                 /*isImplicitlyDeclared=*/true,
13268                                 Constexpr ? ConstexprSpecKind::Constexpr
13269                                           : ConstexprSpecKind::Unspecified);
13270   Destructor->setAccess(AS_public);
13271   Destructor->setDefaulted();
13272 
13273   if (getLangOpts().CUDA) {
13274     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13275                                             Destructor,
13276                                             /* ConstRHS */ false,
13277                                             /* Diagnose */ false);
13278   }
13279 
13280   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13281 
13282   // We don't need to use SpecialMemberIsTrivial here; triviality for
13283   // destructors is easy to compute.
13284   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13285   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13286                                 ClassDecl->hasTrivialDestructorForCall());
13287 
13288   // Note that we have declared this destructor.
13289   ++getASTContext().NumImplicitDestructorsDeclared;
13290 
13291   Scope *S = getScopeForContext(ClassDecl);
13292   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13293 
13294   // We can't check whether an implicit destructor is deleted before we complete
13295   // the definition of the class, because its validity depends on the alignment
13296   // of the class. We'll check this from ActOnFields once the class is complete.
13297   if (ClassDecl->isCompleteDefinition() &&
13298       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13299     SetDeclDeleted(Destructor, ClassLoc);
13300 
13301   // Introduce this destructor into its scope.
13302   if (S)
13303     PushOnScopeChains(Destructor, S, false);
13304   ClassDecl->addDecl(Destructor);
13305 
13306   return Destructor;
13307 }
13308 
DefineImplicitDestructor(SourceLocation CurrentLocation,CXXDestructorDecl * Destructor)13309 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13310                                     CXXDestructorDecl *Destructor) {
13311   assert((Destructor->isDefaulted() &&
13312           !Destructor->doesThisDeclarationHaveABody() &&
13313           !Destructor->isDeleted()) &&
13314          "DefineImplicitDestructor - call it for implicit default dtor");
13315   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13316     return;
13317 
13318   CXXRecordDecl *ClassDecl = Destructor->getParent();
13319   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13320 
13321   SynthesizedFunctionScope Scope(*this, Destructor);
13322 
13323   // The exception specification is needed because we are defining the
13324   // function.
13325   ResolveExceptionSpec(CurrentLocation,
13326                        Destructor->getType()->castAs<FunctionProtoType>());
13327   MarkVTableUsed(CurrentLocation, ClassDecl);
13328 
13329   // Add a context note for diagnostics produced after this point.
13330   Scope.addContextNote(CurrentLocation);
13331 
13332   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13333                                          Destructor->getParent());
13334 
13335   if (CheckDestructor(Destructor)) {
13336     Destructor->setInvalidDecl();
13337     return;
13338   }
13339 
13340   SourceLocation Loc = Destructor->getEndLoc().isValid()
13341                            ? Destructor->getEndLoc()
13342                            : Destructor->getLocation();
13343   Destructor->setBody(new (Context) CompoundStmt(Loc));
13344   Destructor->markUsed(Context);
13345 
13346   if (ASTMutationListener *L = getASTMutationListener()) {
13347     L->CompletedImplicitDefinition(Destructor);
13348   }
13349 }
13350 
CheckCompleteDestructorVariant(SourceLocation CurrentLocation,CXXDestructorDecl * Destructor)13351 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13352                                           CXXDestructorDecl *Destructor) {
13353   if (Destructor->isInvalidDecl())
13354     return;
13355 
13356   CXXRecordDecl *ClassDecl = Destructor->getParent();
13357   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13358          "implicit complete dtors unneeded outside MS ABI");
13359   assert(ClassDecl->getNumVBases() > 0 &&
13360          "complete dtor only exists for classes with vbases");
13361 
13362   SynthesizedFunctionScope Scope(*this, Destructor);
13363 
13364   // Add a context note for diagnostics produced after this point.
13365   Scope.addContextNote(CurrentLocation);
13366 
13367   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13368 }
13369 
13370 /// Perform any semantic analysis which needs to be delayed until all
13371 /// pending class member declarations have been parsed.
ActOnFinishCXXMemberDecls()13372 void Sema::ActOnFinishCXXMemberDecls() {
13373   // If the context is an invalid C++ class, just suppress these checks.
13374   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13375     if (Record->isInvalidDecl()) {
13376       DelayedOverridingExceptionSpecChecks.clear();
13377       DelayedEquivalentExceptionSpecChecks.clear();
13378       return;
13379     }
13380     checkForMultipleExportedDefaultConstructors(*this, Record);
13381   }
13382 }
13383 
ActOnFinishCXXNonNestedClass()13384 void Sema::ActOnFinishCXXNonNestedClass() {
13385   referenceDLLExportedClassMethods();
13386 
13387   if (!DelayedDllExportMemberFunctions.empty()) {
13388     SmallVector<CXXMethodDecl*, 4> WorkList;
13389     std::swap(DelayedDllExportMemberFunctions, WorkList);
13390     for (CXXMethodDecl *M : WorkList) {
13391       DefineDefaultedFunction(*this, M, M->getLocation());
13392 
13393       // Pass the method to the consumer to get emitted. This is not necessary
13394       // for explicit instantiation definitions, as they will get emitted
13395       // anyway.
13396       if (M->getParent()->getTemplateSpecializationKind() !=
13397           TSK_ExplicitInstantiationDefinition)
13398         ActOnFinishInlineFunctionDef(M);
13399     }
13400   }
13401 }
13402 
referenceDLLExportedClassMethods()13403 void Sema::referenceDLLExportedClassMethods() {
13404   if (!DelayedDllExportClasses.empty()) {
13405     // Calling ReferenceDllExportedMembers might cause the current function to
13406     // be called again, so use a local copy of DelayedDllExportClasses.
13407     SmallVector<CXXRecordDecl *, 4> WorkList;
13408     std::swap(DelayedDllExportClasses, WorkList);
13409     for (CXXRecordDecl *Class : WorkList)
13410       ReferenceDllExportedMembers(*this, Class);
13411   }
13412 }
13413 
AdjustDestructorExceptionSpec(CXXDestructorDecl * Destructor)13414 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13415   assert(getLangOpts().CPlusPlus11 &&
13416          "adjusting dtor exception specs was introduced in c++11");
13417 
13418   if (Destructor->isDependentContext())
13419     return;
13420 
13421   // C++11 [class.dtor]p3:
13422   //   A declaration of a destructor that does not have an exception-
13423   //   specification is implicitly considered to have the same exception-
13424   //   specification as an implicit declaration.
13425   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13426   if (DtorType->hasExceptionSpec())
13427     return;
13428 
13429   // Replace the destructor's type, building off the existing one. Fortunately,
13430   // the only thing of interest in the destructor type is its extended info.
13431   // The return and arguments are fixed.
13432   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13433   EPI.ExceptionSpec.Type = EST_Unevaluated;
13434   EPI.ExceptionSpec.SourceDecl = Destructor;
13435   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13436 
13437   // FIXME: If the destructor has a body that could throw, and the newly created
13438   // spec doesn't allow exceptions, we should emit a warning, because this
13439   // change in behavior can break conforming C++03 programs at runtime.
13440   // However, we don't have a body or an exception specification yet, so it
13441   // needs to be done somewhere else.
13442 }
13443 
13444 namespace {
13445 /// An abstract base class for all helper classes used in building the
13446 //  copy/move operators. These classes serve as factory functions and help us
13447 //  avoid using the same Expr* in the AST twice.
13448 class ExprBuilder {
13449   ExprBuilder(const ExprBuilder&) = delete;
13450   ExprBuilder &operator=(const ExprBuilder&) = delete;
13451 
13452 protected:
assertNotNull(Expr * E)13453   static Expr *assertNotNull(Expr *E) {
13454     assert(E && "Expression construction must not fail.");
13455     return E;
13456   }
13457 
13458 public:
ExprBuilder()13459   ExprBuilder() {}
~ExprBuilder()13460   virtual ~ExprBuilder() {}
13461 
13462   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13463 };
13464 
13465 class RefBuilder: public ExprBuilder {
13466   VarDecl *Var;
13467   QualType VarType;
13468 
13469 public:
build(Sema & S,SourceLocation Loc) const13470   Expr *build(Sema &S, SourceLocation Loc) const override {
13471     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13472   }
13473 
RefBuilder(VarDecl * Var,QualType VarType)13474   RefBuilder(VarDecl *Var, QualType VarType)
13475       : Var(Var), VarType(VarType) {}
13476 };
13477 
13478 class ThisBuilder: public ExprBuilder {
13479 public:
build(Sema & S,SourceLocation Loc) const13480   Expr *build(Sema &S, SourceLocation Loc) const override {
13481     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13482   }
13483 };
13484 
13485 class CastBuilder: public ExprBuilder {
13486   const ExprBuilder &Builder;
13487   QualType Type;
13488   ExprValueKind Kind;
13489   const CXXCastPath &Path;
13490 
13491 public:
build(Sema & S,SourceLocation Loc) const13492   Expr *build(Sema &S, SourceLocation Loc) const override {
13493     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13494                                              CK_UncheckedDerivedToBase, Kind,
13495                                              &Path).get());
13496   }
13497 
CastBuilder(const ExprBuilder & Builder,QualType Type,ExprValueKind Kind,const CXXCastPath & Path)13498   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13499               const CXXCastPath &Path)
13500       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13501 };
13502 
13503 class DerefBuilder: public ExprBuilder {
13504   const ExprBuilder &Builder;
13505 
13506 public:
build(Sema & S,SourceLocation Loc) const13507   Expr *build(Sema &S, SourceLocation Loc) const override {
13508     return assertNotNull(
13509         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13510   }
13511 
DerefBuilder(const ExprBuilder & Builder)13512   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13513 };
13514 
13515 class MemberBuilder: public ExprBuilder {
13516   const ExprBuilder &Builder;
13517   QualType Type;
13518   CXXScopeSpec SS;
13519   bool IsArrow;
13520   LookupResult &MemberLookup;
13521 
13522 public:
build(Sema & S,SourceLocation Loc) const13523   Expr *build(Sema &S, SourceLocation Loc) const override {
13524     return assertNotNull(S.BuildMemberReferenceExpr(
13525         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13526         nullptr, MemberLookup, nullptr, nullptr).get());
13527   }
13528 
MemberBuilder(const ExprBuilder & Builder,QualType Type,bool IsArrow,LookupResult & MemberLookup)13529   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13530                 LookupResult &MemberLookup)
13531       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13532         MemberLookup(MemberLookup) {}
13533 };
13534 
13535 class MoveCastBuilder: public ExprBuilder {
13536   const ExprBuilder &Builder;
13537 
13538 public:
build(Sema & S,SourceLocation Loc) const13539   Expr *build(Sema &S, SourceLocation Loc) const override {
13540     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13541   }
13542 
MoveCastBuilder(const ExprBuilder & Builder)13543   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13544 };
13545 
13546 class LvalueConvBuilder: public ExprBuilder {
13547   const ExprBuilder &Builder;
13548 
13549 public:
build(Sema & S,SourceLocation Loc) const13550   Expr *build(Sema &S, SourceLocation Loc) const override {
13551     return assertNotNull(
13552         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13553   }
13554 
LvalueConvBuilder(const ExprBuilder & Builder)13555   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13556 };
13557 
13558 class SubscriptBuilder: public ExprBuilder {
13559   const ExprBuilder &Base;
13560   const ExprBuilder &Index;
13561 
13562 public:
build(Sema & S,SourceLocation Loc) const13563   Expr *build(Sema &S, SourceLocation Loc) const override {
13564     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13565         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13566   }
13567 
SubscriptBuilder(const ExprBuilder & Base,const ExprBuilder & Index)13568   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13569       : Base(Base), Index(Index) {}
13570 };
13571 
13572 } // end anonymous namespace
13573 
13574 /// When generating a defaulted copy or move assignment operator, if a field
13575 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13576 /// do so. This optimization only applies for arrays of scalars, and for arrays
13577 /// of class type where the selected copy/move-assignment operator is trivial.
13578 static StmtResult
buildMemcpyForAssignmentOp(Sema & S,SourceLocation Loc,QualType T,const ExprBuilder & ToB,const ExprBuilder & FromB)13579 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13580                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
13581   // Compute the size of the memory buffer to be copied.
13582   QualType SizeType = S.Context.getSizeType();
13583   llvm::APInt Size(S.Context.getTypeSize(SizeType),
13584                    S.Context.getTypeSizeInChars(T).getQuantity());
13585 
13586   // Take the address of the field references for "from" and "to". We
13587   // directly construct UnaryOperators here because semantic analysis
13588   // does not permit us to take the address of an xvalue.
13589   Expr *From = FromB.build(S, Loc);
13590   From = UnaryOperator::Create(
13591       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13592       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13593   Expr *To = ToB.build(S, Loc);
13594   To = UnaryOperator::Create(
13595       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13596       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13597 
13598   const Type *E = T->getBaseElementTypeUnsafe();
13599   bool NeedsCollectableMemCpy =
13600       E->isRecordType() &&
13601       E->castAs<RecordType>()->getDecl()->hasObjectMember();
13602 
13603   // Create a reference to the __builtin_objc_memmove_collectable function
13604   StringRef MemCpyName = NeedsCollectableMemCpy ?
13605     "__builtin_objc_memmove_collectable" :
13606     "__builtin_memcpy";
13607   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13608                  Sema::LookupOrdinaryName);
13609   S.LookupName(R, S.TUScope, true);
13610 
13611   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13612   if (!MemCpy)
13613     // Something went horribly wrong earlier, and we will have complained
13614     // about it.
13615     return StmtError();
13616 
13617   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13618                                             VK_RValue, Loc, nullptr);
13619   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
13620 
13621   Expr *CallArgs[] = {
13622     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13623   };
13624   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13625                                     Loc, CallArgs, Loc);
13626 
13627   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
13628   return Call.getAs<Stmt>();
13629 }
13630 
13631 /// Builds a statement that copies/moves the given entity from \p From to
13632 /// \c To.
13633 ///
13634 /// This routine is used to copy/move the members of a class with an
13635 /// implicitly-declared copy/move assignment operator. When the entities being
13636 /// copied are arrays, this routine builds for loops to copy them.
13637 ///
13638 /// \param S The Sema object used for type-checking.
13639 ///
13640 /// \param Loc The location where the implicit copy/move is being generated.
13641 ///
13642 /// \param T The type of the expressions being copied/moved. Both expressions
13643 /// must have this type.
13644 ///
13645 /// \param To The expression we are copying/moving to.
13646 ///
13647 /// \param From The expression we are copying/moving from.
13648 ///
13649 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13650 /// Otherwise, it's a non-static member subobject.
13651 ///
13652 /// \param Copying Whether we're copying or moving.
13653 ///
13654 /// \param Depth Internal parameter recording the depth of the recursion.
13655 ///
13656 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13657 /// if a memcpy should be used instead.
13658 static StmtResult
buildSingleCopyAssignRecursively(Sema & S,SourceLocation Loc,QualType T,const ExprBuilder & To,const ExprBuilder & From,bool CopyingBaseSubobject,bool Copying,unsigned Depth=0)13659 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13660                                  const ExprBuilder &To, const ExprBuilder &From,
13661                                  bool CopyingBaseSubobject, bool Copying,
13662                                  unsigned Depth = 0) {
13663   // C++11 [class.copy]p28:
13664   //   Each subobject is assigned in the manner appropriate to its type:
13665   //
13666   //     - if the subobject is of class type, as if by a call to operator= with
13667   //       the subobject as the object expression and the corresponding
13668   //       subobject of x as a single function argument (as if by explicit
13669   //       qualification; that is, ignoring any possible virtual overriding
13670   //       functions in more derived classes);
13671   //
13672   // C++03 [class.copy]p13:
13673   //     - if the subobject is of class type, the copy assignment operator for
13674   //       the class is used (as if by explicit qualification; that is,
13675   //       ignoring any possible virtual overriding functions in more derived
13676   //       classes);
13677   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13678     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13679 
13680     // Look for operator=.
13681     DeclarationName Name
13682       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13683     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13684     S.LookupQualifiedName(OpLookup, ClassDecl, false);
13685 
13686     // Prior to C++11, filter out any result that isn't a copy/move-assignment
13687     // operator.
13688     if (!S.getLangOpts().CPlusPlus11) {
13689       LookupResult::Filter F = OpLookup.makeFilter();
13690       while (F.hasNext()) {
13691         NamedDecl *D = F.next();
13692         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13693           if (Method->isCopyAssignmentOperator() ||
13694               (!Copying && Method->isMoveAssignmentOperator()))
13695             continue;
13696 
13697         F.erase();
13698       }
13699       F.done();
13700     }
13701 
13702     // Suppress the protected check (C++ [class.protected]) for each of the
13703     // assignment operators we found. This strange dance is required when
13704     // we're assigning via a base classes's copy-assignment operator. To
13705     // ensure that we're getting the right base class subobject (without
13706     // ambiguities), we need to cast "this" to that subobject type; to
13707     // ensure that we don't go through the virtual call mechanism, we need
13708     // to qualify the operator= name with the base class (see below). However,
13709     // this means that if the base class has a protected copy assignment
13710     // operator, the protected member access check will fail. So, we
13711     // rewrite "protected" access to "public" access in this case, since we
13712     // know by construction that we're calling from a derived class.
13713     if (CopyingBaseSubobject) {
13714       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13715            L != LEnd; ++L) {
13716         if (L.getAccess() == AS_protected)
13717           L.setAccess(AS_public);
13718       }
13719     }
13720 
13721     // Create the nested-name-specifier that will be used to qualify the
13722     // reference to operator=; this is required to suppress the virtual
13723     // call mechanism.
13724     CXXScopeSpec SS;
13725     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13726     SS.MakeTrivial(S.Context,
13727                    NestedNameSpecifier::Create(S.Context, nullptr, false,
13728                                                CanonicalT),
13729                    Loc);
13730 
13731     // Create the reference to operator=.
13732     ExprResult OpEqualRef
13733       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13734                                    SS, /*TemplateKWLoc=*/SourceLocation(),
13735                                    /*FirstQualifierInScope=*/nullptr,
13736                                    OpLookup,
13737                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
13738                                    /*SuppressQualifierCheck=*/true);
13739     if (OpEqualRef.isInvalid())
13740       return StmtError();
13741 
13742     // Build the call to the assignment operator.
13743 
13744     Expr *FromInst = From.build(S, Loc);
13745     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13746                                                   OpEqualRef.getAs<Expr>(),
13747                                                   Loc, FromInst, Loc);
13748     if (Call.isInvalid())
13749       return StmtError();
13750 
13751     // If we built a call to a trivial 'operator=' while copying an array,
13752     // bail out. We'll replace the whole shebang with a memcpy.
13753     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
13754     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
13755       return StmtResult((Stmt*)nullptr);
13756 
13757     // Convert to an expression-statement, and clean up any produced
13758     // temporaries.
13759     return S.ActOnExprStmt(Call);
13760   }
13761 
13762   //     - if the subobject is of scalar type, the built-in assignment
13763   //       operator is used.
13764   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
13765   if (!ArrayTy) {
13766     ExprResult Assignment = S.CreateBuiltinBinOp(
13767         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
13768     if (Assignment.isInvalid())
13769       return StmtError();
13770     return S.ActOnExprStmt(Assignment);
13771   }
13772 
13773   //     - if the subobject is an array, each element is assigned, in the
13774   //       manner appropriate to the element type;
13775 
13776   // Construct a loop over the array bounds, e.g.,
13777   //
13778   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
13779   //
13780   // that will copy each of the array elements.
13781   QualType SizeType = S.Context.getSizeType();
13782 
13783   // Create the iteration variable.
13784   IdentifierInfo *IterationVarName = nullptr;
13785   {
13786     SmallString<8> Str;
13787     llvm::raw_svector_ostream OS(Str);
13788     OS << "__i" << Depth;
13789     IterationVarName = &S.Context.Idents.get(OS.str());
13790   }
13791   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
13792                                           IterationVarName, SizeType,
13793                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
13794                                           SC_None);
13795 
13796   // Initialize the iteration variable to zero.
13797   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
13798   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
13799 
13800   // Creates a reference to the iteration variable.
13801   RefBuilder IterationVarRef(IterationVar, SizeType);
13802   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
13803 
13804   // Create the DeclStmt that holds the iteration variable.
13805   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
13806 
13807   // Subscript the "from" and "to" expressions with the iteration variable.
13808   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
13809   MoveCastBuilder FromIndexMove(FromIndexCopy);
13810   const ExprBuilder *FromIndex;
13811   if (Copying)
13812     FromIndex = &FromIndexCopy;
13813   else
13814     FromIndex = &FromIndexMove;
13815 
13816   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
13817 
13818   // Build the copy/move for an individual element of the array.
13819   StmtResult Copy =
13820     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
13821                                      ToIndex, *FromIndex, CopyingBaseSubobject,
13822                                      Copying, Depth + 1);
13823   // Bail out if copying fails or if we determined that we should use memcpy.
13824   if (Copy.isInvalid() || !Copy.get())
13825     return Copy;
13826 
13827   // Create the comparison against the array bound.
13828   llvm::APInt Upper
13829     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
13830   Expr *Comparison = BinaryOperator::Create(
13831       S.Context, IterationVarRefRVal.build(S, Loc),
13832       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
13833       S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides());
13834 
13835   // Create the pre-increment of the iteration variable. We can determine
13836   // whether the increment will overflow based on the value of the array
13837   // bound.
13838   Expr *Increment = UnaryOperator::Create(
13839       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
13840       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
13841 
13842   // Construct the loop that copies all elements of this array.
13843   return S.ActOnForStmt(
13844       Loc, Loc, InitStmt,
13845       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
13846       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
13847 }
13848 
13849 static StmtResult
buildSingleCopyAssign(Sema & S,SourceLocation Loc,QualType T,const ExprBuilder & To,const ExprBuilder & From,bool CopyingBaseSubobject,bool Copying)13850 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
13851                       const ExprBuilder &To, const ExprBuilder &From,
13852                       bool CopyingBaseSubobject, bool Copying) {
13853   // Maybe we should use a memcpy?
13854   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
13855       T.isTriviallyCopyableType(S.Context))
13856     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13857 
13858   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
13859                                                      CopyingBaseSubobject,
13860                                                      Copying, 0));
13861 
13862   // If we ended up picking a trivial assignment operator for an array of a
13863   // non-trivially-copyable class type, just emit a memcpy.
13864   if (!Result.isInvalid() && !Result.get())
13865     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13866 
13867   return Result;
13868 }
13869 
DeclareImplicitCopyAssignment(CXXRecordDecl * ClassDecl)13870 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
13871   // Note: The following rules are largely analoguous to the copy
13872   // constructor rules. Note that virtual bases are not taken into account
13873   // for determining the argument type of the operator. Note also that
13874   // operators taking an object instead of a reference are allowed.
13875   assert(ClassDecl->needsImplicitCopyAssignment());
13876 
13877   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
13878   if (DSM.isAlreadyBeingDeclared())
13879     return nullptr;
13880 
13881   QualType ArgType = Context.getTypeDeclType(ClassDecl);
13882   LangAS AS = getDefaultCXXMethodAddrSpace();
13883   if (AS != LangAS::Default)
13884     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
13885   QualType RetType = Context.getLValueReferenceType(ArgType);
13886   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
13887   if (Const)
13888     ArgType = ArgType.withConst();
13889 
13890   ArgType = Context.getLValueReferenceType(ArgType);
13891 
13892   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13893                                                      CXXCopyAssignment,
13894                                                      Const);
13895 
13896   //   An implicitly-declared copy assignment operator is an inline public
13897   //   member of its class.
13898   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13899   SourceLocation ClassLoc = ClassDecl->getLocation();
13900   DeclarationNameInfo NameInfo(Name, ClassLoc);
13901   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
13902       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
13903       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
13904       /*isInline=*/true,
13905       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
13906       SourceLocation());
13907   CopyAssignment->setAccess(AS_public);
13908   CopyAssignment->setDefaulted();
13909   CopyAssignment->setImplicit();
13910 
13911   if (getLangOpts().CUDA) {
13912     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
13913                                             CopyAssignment,
13914                                             /* ConstRHS */ Const,
13915                                             /* Diagnose */ false);
13916   }
13917 
13918   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
13919 
13920   // Add the parameter to the operator.
13921   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
13922                                                ClassLoc, ClassLoc,
13923                                                /*Id=*/nullptr, ArgType,
13924                                                /*TInfo=*/nullptr, SC_None,
13925                                                nullptr);
13926   CopyAssignment->setParams(FromParam);
13927 
13928   CopyAssignment->setTrivial(
13929     ClassDecl->needsOverloadResolutionForCopyAssignment()
13930       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
13931       : ClassDecl->hasTrivialCopyAssignment());
13932 
13933   // Note that we have added this copy-assignment operator.
13934   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
13935 
13936   Scope *S = getScopeForContext(ClassDecl);
13937   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
13938 
13939   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
13940     ClassDecl->setImplicitCopyAssignmentIsDeleted();
13941     SetDeclDeleted(CopyAssignment, ClassLoc);
13942   }
13943 
13944   if (S)
13945     PushOnScopeChains(CopyAssignment, S, false);
13946   ClassDecl->addDecl(CopyAssignment);
13947 
13948   return CopyAssignment;
13949 }
13950 
13951 /// Diagnose an implicit copy operation for a class which is odr-used, but
13952 /// which is deprecated because the class has a user-declared copy constructor,
13953 /// copy assignment operator, or destructor.
diagnoseDeprecatedCopyOperation(Sema & S,CXXMethodDecl * CopyOp)13954 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
13955   assert(CopyOp->isImplicit());
13956 
13957   CXXRecordDecl *RD = CopyOp->getParent();
13958   CXXMethodDecl *UserDeclaredOperation = nullptr;
13959 
13960   // In Microsoft mode, assignment operations don't affect constructors and
13961   // vice versa.
13962   if (RD->hasUserDeclaredDestructor()) {
13963     UserDeclaredOperation = RD->getDestructor();
13964   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
13965              RD->hasUserDeclaredCopyConstructor() &&
13966              !S.getLangOpts().MSVCCompat) {
13967     // Find any user-declared copy constructor.
13968     for (auto *I : RD->ctors()) {
13969       if (I->isCopyConstructor()) {
13970         UserDeclaredOperation = I;
13971         break;
13972       }
13973     }
13974     assert(UserDeclaredOperation);
13975   } else if (isa<CXXConstructorDecl>(CopyOp) &&
13976              RD->hasUserDeclaredCopyAssignment() &&
13977              !S.getLangOpts().MSVCCompat) {
13978     // Find any user-declared move assignment operator.
13979     for (auto *I : RD->methods()) {
13980       if (I->isCopyAssignmentOperator()) {
13981         UserDeclaredOperation = I;
13982         break;
13983       }
13984     }
13985     assert(UserDeclaredOperation);
13986   }
13987 
13988   if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) {
13989     S.Diag(UserDeclaredOperation->getLocation(),
13990            isa<CXXDestructorDecl>(UserDeclaredOperation)
13991                ? diag::warn_deprecated_copy_dtor_operation
13992                : diag::warn_deprecated_copy_operation)
13993         << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp);
13994   }
13995 }
13996 
DefineImplicitCopyAssignment(SourceLocation CurrentLocation,CXXMethodDecl * CopyAssignOperator)13997 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
13998                                         CXXMethodDecl *CopyAssignOperator) {
13999   assert((CopyAssignOperator->isDefaulted() &&
14000           CopyAssignOperator->isOverloadedOperator() &&
14001           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14002           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14003           !CopyAssignOperator->isDeleted()) &&
14004          "DefineImplicitCopyAssignment called for wrong function");
14005   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14006     return;
14007 
14008   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14009   if (ClassDecl->isInvalidDecl()) {
14010     CopyAssignOperator->setInvalidDecl();
14011     return;
14012   }
14013 
14014   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14015 
14016   // The exception specification is needed because we are defining the
14017   // function.
14018   ResolveExceptionSpec(CurrentLocation,
14019                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14020 
14021   // Add a context note for diagnostics produced after this point.
14022   Scope.addContextNote(CurrentLocation);
14023 
14024   // C++11 [class.copy]p18:
14025   //   The [definition of an implicitly declared copy assignment operator] is
14026   //   deprecated if the class has a user-declared copy constructor or a
14027   //   user-declared destructor.
14028   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14029     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14030 
14031   // C++0x [class.copy]p30:
14032   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14033   //   for a non-union class X performs memberwise copy assignment of its
14034   //   subobjects. The direct base classes of X are assigned first, in the
14035   //   order of their declaration in the base-specifier-list, and then the
14036   //   immediate non-static data members of X are assigned, in the order in
14037   //   which they were declared in the class definition.
14038 
14039   // The statements that form the synthesized function body.
14040   SmallVector<Stmt*, 8> Statements;
14041 
14042   // The parameter for the "other" object, which we are copying from.
14043   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14044   Qualifiers OtherQuals = Other->getType().getQualifiers();
14045   QualType OtherRefType = Other->getType();
14046   if (const LValueReferenceType *OtherRef
14047                                 = OtherRefType->getAs<LValueReferenceType>()) {
14048     OtherRefType = OtherRef->getPointeeType();
14049     OtherQuals = OtherRefType.getQualifiers();
14050   }
14051 
14052   // Our location for everything implicitly-generated.
14053   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14054                            ? CopyAssignOperator->getEndLoc()
14055                            : CopyAssignOperator->getLocation();
14056 
14057   // Builds a DeclRefExpr for the "other" object.
14058   RefBuilder OtherRef(Other, OtherRefType);
14059 
14060   // Builds the "this" pointer.
14061   ThisBuilder This;
14062 
14063   // Assign base classes.
14064   bool Invalid = false;
14065   for (auto &Base : ClassDecl->bases()) {
14066     // Form the assignment:
14067     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14068     QualType BaseType = Base.getType().getUnqualifiedType();
14069     if (!BaseType->isRecordType()) {
14070       Invalid = true;
14071       continue;
14072     }
14073 
14074     CXXCastPath BasePath;
14075     BasePath.push_back(&Base);
14076 
14077     // Construct the "from" expression, which is an implicit cast to the
14078     // appropriately-qualified base type.
14079     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14080                      VK_LValue, BasePath);
14081 
14082     // Dereference "this".
14083     DerefBuilder DerefThis(This);
14084     CastBuilder To(DerefThis,
14085                    Context.getQualifiedType(
14086                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14087                    VK_LValue, BasePath);
14088 
14089     // Build the copy.
14090     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14091                                             To, From,
14092                                             /*CopyingBaseSubobject=*/true,
14093                                             /*Copying=*/true);
14094     if (Copy.isInvalid()) {
14095       CopyAssignOperator->setInvalidDecl();
14096       return;
14097     }
14098 
14099     // Success! Record the copy.
14100     Statements.push_back(Copy.getAs<Expr>());
14101   }
14102 
14103   // Assign non-static members.
14104   for (auto *Field : ClassDecl->fields()) {
14105     // FIXME: We should form some kind of AST representation for the implied
14106     // memcpy in a union copy operation.
14107     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14108       continue;
14109 
14110     if (Field->isInvalidDecl()) {
14111       Invalid = true;
14112       continue;
14113     }
14114 
14115     // Check for members of reference type; we can't copy those.
14116     if (Field->getType()->isReferenceType()) {
14117       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14118         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14119       Diag(Field->getLocation(), diag::note_declared_at);
14120       Invalid = true;
14121       continue;
14122     }
14123 
14124     // Check for members of const-qualified, non-class type.
14125     QualType BaseType = Context.getBaseElementType(Field->getType());
14126     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14127       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14128         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14129       Diag(Field->getLocation(), diag::note_declared_at);
14130       Invalid = true;
14131       continue;
14132     }
14133 
14134     // Suppress assigning zero-width bitfields.
14135     if (Field->isZeroLengthBitField(Context))
14136       continue;
14137 
14138     QualType FieldType = Field->getType().getNonReferenceType();
14139     if (FieldType->isIncompleteArrayType()) {
14140       assert(ClassDecl->hasFlexibleArrayMember() &&
14141              "Incomplete array type is not valid");
14142       continue;
14143     }
14144 
14145     // Build references to the field in the object we're copying from and to.
14146     CXXScopeSpec SS; // Intentionally empty
14147     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14148                               LookupMemberName);
14149     MemberLookup.addDecl(Field);
14150     MemberLookup.resolveKind();
14151 
14152     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14153 
14154     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14155 
14156     // Build the copy of this field.
14157     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14158                                             To, From,
14159                                             /*CopyingBaseSubobject=*/false,
14160                                             /*Copying=*/true);
14161     if (Copy.isInvalid()) {
14162       CopyAssignOperator->setInvalidDecl();
14163       return;
14164     }
14165 
14166     // Success! Record the copy.
14167     Statements.push_back(Copy.getAs<Stmt>());
14168   }
14169 
14170   if (!Invalid) {
14171     // Add a "return *this;"
14172     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14173 
14174     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14175     if (Return.isInvalid())
14176       Invalid = true;
14177     else
14178       Statements.push_back(Return.getAs<Stmt>());
14179   }
14180 
14181   if (Invalid) {
14182     CopyAssignOperator->setInvalidDecl();
14183     return;
14184   }
14185 
14186   StmtResult Body;
14187   {
14188     CompoundScopeRAII CompoundScope(*this);
14189     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14190                              /*isStmtExpr=*/false);
14191     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14192   }
14193   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14194   CopyAssignOperator->markUsed(Context);
14195 
14196   if (ASTMutationListener *L = getASTMutationListener()) {
14197     L->CompletedImplicitDefinition(CopyAssignOperator);
14198   }
14199 }
14200 
DeclareImplicitMoveAssignment(CXXRecordDecl * ClassDecl)14201 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14202   assert(ClassDecl->needsImplicitMoveAssignment());
14203 
14204   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14205   if (DSM.isAlreadyBeingDeclared())
14206     return nullptr;
14207 
14208   // Note: The following rules are largely analoguous to the move
14209   // constructor rules.
14210 
14211   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14212   LangAS AS = getDefaultCXXMethodAddrSpace();
14213   if (AS != LangAS::Default)
14214     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14215   QualType RetType = Context.getLValueReferenceType(ArgType);
14216   ArgType = Context.getRValueReferenceType(ArgType);
14217 
14218   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14219                                                      CXXMoveAssignment,
14220                                                      false);
14221 
14222   //   An implicitly-declared move assignment operator is an inline public
14223   //   member of its class.
14224   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14225   SourceLocation ClassLoc = ClassDecl->getLocation();
14226   DeclarationNameInfo NameInfo(Name, ClassLoc);
14227   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14228       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14229       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14230       /*isInline=*/true,
14231       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14232       SourceLocation());
14233   MoveAssignment->setAccess(AS_public);
14234   MoveAssignment->setDefaulted();
14235   MoveAssignment->setImplicit();
14236 
14237   if (getLangOpts().CUDA) {
14238     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14239                                             MoveAssignment,
14240                                             /* ConstRHS */ false,
14241                                             /* Diagnose */ false);
14242   }
14243 
14244   // Build an exception specification pointing back at this member.
14245   FunctionProtoType::ExtProtoInfo EPI =
14246       getImplicitMethodEPI(*this, MoveAssignment);
14247   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
14248 
14249   // Add the parameter to the operator.
14250   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14251                                                ClassLoc, ClassLoc,
14252                                                /*Id=*/nullptr, ArgType,
14253                                                /*TInfo=*/nullptr, SC_None,
14254                                                nullptr);
14255   MoveAssignment->setParams(FromParam);
14256 
14257   MoveAssignment->setTrivial(
14258     ClassDecl->needsOverloadResolutionForMoveAssignment()
14259       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14260       : ClassDecl->hasTrivialMoveAssignment());
14261 
14262   // Note that we have added this copy-assignment operator.
14263   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14264 
14265   Scope *S = getScopeForContext(ClassDecl);
14266   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14267 
14268   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14269     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14270     SetDeclDeleted(MoveAssignment, ClassLoc);
14271   }
14272 
14273   if (S)
14274     PushOnScopeChains(MoveAssignment, S, false);
14275   ClassDecl->addDecl(MoveAssignment);
14276 
14277   return MoveAssignment;
14278 }
14279 
14280 /// Check if we're implicitly defining a move assignment operator for a class
14281 /// with virtual bases. Such a move assignment might move-assign the virtual
14282 /// base multiple times.
checkMoveAssignmentForRepeatedMove(Sema & S,CXXRecordDecl * Class,SourceLocation CurrentLocation)14283 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14284                                                SourceLocation CurrentLocation) {
14285   assert(!Class->isDependentContext() && "should not define dependent move");
14286 
14287   // Only a virtual base could get implicitly move-assigned multiple times.
14288   // Only a non-trivial move assignment can observe this. We only want to
14289   // diagnose if we implicitly define an assignment operator that assigns
14290   // two base classes, both of which move-assign the same virtual base.
14291   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14292       Class->getNumBases() < 2)
14293     return;
14294 
14295   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14296   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14297   VBaseMap VBases;
14298 
14299   for (auto &BI : Class->bases()) {
14300     Worklist.push_back(&BI);
14301     while (!Worklist.empty()) {
14302       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14303       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14304 
14305       // If the base has no non-trivial move assignment operators,
14306       // we don't care about moves from it.
14307       if (!Base->hasNonTrivialMoveAssignment())
14308         continue;
14309 
14310       // If there's nothing virtual here, skip it.
14311       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14312         continue;
14313 
14314       // If we're not actually going to call a move assignment for this base,
14315       // or the selected move assignment is trivial, skip it.
14316       Sema::SpecialMemberOverloadResult SMOR =
14317         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14318                               /*ConstArg*/false, /*VolatileArg*/false,
14319                               /*RValueThis*/true, /*ConstThis*/false,
14320                               /*VolatileThis*/false);
14321       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14322           !SMOR.getMethod()->isMoveAssignmentOperator())
14323         continue;
14324 
14325       if (BaseSpec->isVirtual()) {
14326         // We're going to move-assign this virtual base, and its move
14327         // assignment operator is not trivial. If this can happen for
14328         // multiple distinct direct bases of Class, diagnose it. (If it
14329         // only happens in one base, we'll diagnose it when synthesizing
14330         // that base class's move assignment operator.)
14331         CXXBaseSpecifier *&Existing =
14332             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14333                 .first->second;
14334         if (Existing && Existing != &BI) {
14335           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14336             << Class << Base;
14337           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14338               << (Base->getCanonicalDecl() ==
14339                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14340               << Base << Existing->getType() << Existing->getSourceRange();
14341           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14342               << (Base->getCanonicalDecl() ==
14343                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14344               << Base << BI.getType() << BaseSpec->getSourceRange();
14345 
14346           // Only diagnose each vbase once.
14347           Existing = nullptr;
14348         }
14349       } else {
14350         // Only walk over bases that have defaulted move assignment operators.
14351         // We assume that any user-provided move assignment operator handles
14352         // the multiple-moves-of-vbase case itself somehow.
14353         if (!SMOR.getMethod()->isDefaulted())
14354           continue;
14355 
14356         // We're going to move the base classes of Base. Add them to the list.
14357         for (auto &BI : Base->bases())
14358           Worklist.push_back(&BI);
14359       }
14360     }
14361   }
14362 }
14363 
DefineImplicitMoveAssignment(SourceLocation CurrentLocation,CXXMethodDecl * MoveAssignOperator)14364 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14365                                         CXXMethodDecl *MoveAssignOperator) {
14366   assert((MoveAssignOperator->isDefaulted() &&
14367           MoveAssignOperator->isOverloadedOperator() &&
14368           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14369           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14370           !MoveAssignOperator->isDeleted()) &&
14371          "DefineImplicitMoveAssignment called for wrong function");
14372   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14373     return;
14374 
14375   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14376   if (ClassDecl->isInvalidDecl()) {
14377     MoveAssignOperator->setInvalidDecl();
14378     return;
14379   }
14380 
14381   // C++0x [class.copy]p28:
14382   //   The implicitly-defined or move assignment operator for a non-union class
14383   //   X performs memberwise move assignment of its subobjects. The direct base
14384   //   classes of X are assigned first, in the order of their declaration in the
14385   //   base-specifier-list, and then the immediate non-static data members of X
14386   //   are assigned, in the order in which they were declared in the class
14387   //   definition.
14388 
14389   // Issue a warning if our implicit move assignment operator will move
14390   // from a virtual base more than once.
14391   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14392 
14393   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14394 
14395   // The exception specification is needed because we are defining the
14396   // function.
14397   ResolveExceptionSpec(CurrentLocation,
14398                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14399 
14400   // Add a context note for diagnostics produced after this point.
14401   Scope.addContextNote(CurrentLocation);
14402 
14403   // The statements that form the synthesized function body.
14404   SmallVector<Stmt*, 8> Statements;
14405 
14406   // The parameter for the "other" object, which we are move from.
14407   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14408   QualType OtherRefType =
14409       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14410 
14411   // Our location for everything implicitly-generated.
14412   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14413                            ? MoveAssignOperator->getEndLoc()
14414                            : MoveAssignOperator->getLocation();
14415 
14416   // Builds a reference to the "other" object.
14417   RefBuilder OtherRef(Other, OtherRefType);
14418   // Cast to rvalue.
14419   MoveCastBuilder MoveOther(OtherRef);
14420 
14421   // Builds the "this" pointer.
14422   ThisBuilder This;
14423 
14424   // Assign base classes.
14425   bool Invalid = false;
14426   for (auto &Base : ClassDecl->bases()) {
14427     // C++11 [class.copy]p28:
14428     //   It is unspecified whether subobjects representing virtual base classes
14429     //   are assigned more than once by the implicitly-defined copy assignment
14430     //   operator.
14431     // FIXME: Do not assign to a vbase that will be assigned by some other base
14432     // class. For a move-assignment, this can result in the vbase being moved
14433     // multiple times.
14434 
14435     // Form the assignment:
14436     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14437     QualType BaseType = Base.getType().getUnqualifiedType();
14438     if (!BaseType->isRecordType()) {
14439       Invalid = true;
14440       continue;
14441     }
14442 
14443     CXXCastPath BasePath;
14444     BasePath.push_back(&Base);
14445 
14446     // Construct the "from" expression, which is an implicit cast to the
14447     // appropriately-qualified base type.
14448     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14449 
14450     // Dereference "this".
14451     DerefBuilder DerefThis(This);
14452 
14453     // Implicitly cast "this" to the appropriately-qualified base type.
14454     CastBuilder To(DerefThis,
14455                    Context.getQualifiedType(
14456                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14457                    VK_LValue, BasePath);
14458 
14459     // Build the move.
14460     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14461                                             To, From,
14462                                             /*CopyingBaseSubobject=*/true,
14463                                             /*Copying=*/false);
14464     if (Move.isInvalid()) {
14465       MoveAssignOperator->setInvalidDecl();
14466       return;
14467     }
14468 
14469     // Success! Record the move.
14470     Statements.push_back(Move.getAs<Expr>());
14471   }
14472 
14473   // Assign non-static members.
14474   for (auto *Field : ClassDecl->fields()) {
14475     // FIXME: We should form some kind of AST representation for the implied
14476     // memcpy in a union copy operation.
14477     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14478       continue;
14479 
14480     if (Field->isInvalidDecl()) {
14481       Invalid = true;
14482       continue;
14483     }
14484 
14485     // Check for members of reference type; we can't move those.
14486     if (Field->getType()->isReferenceType()) {
14487       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14488         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14489       Diag(Field->getLocation(), diag::note_declared_at);
14490       Invalid = true;
14491       continue;
14492     }
14493 
14494     // Check for members of const-qualified, non-class type.
14495     QualType BaseType = Context.getBaseElementType(Field->getType());
14496     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14497       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14498         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14499       Diag(Field->getLocation(), diag::note_declared_at);
14500       Invalid = true;
14501       continue;
14502     }
14503 
14504     // Suppress assigning zero-width bitfields.
14505     if (Field->isZeroLengthBitField(Context))
14506       continue;
14507 
14508     QualType FieldType = Field->getType().getNonReferenceType();
14509     if (FieldType->isIncompleteArrayType()) {
14510       assert(ClassDecl->hasFlexibleArrayMember() &&
14511              "Incomplete array type is not valid");
14512       continue;
14513     }
14514 
14515     // Build references to the field in the object we're copying from and to.
14516     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14517                               LookupMemberName);
14518     MemberLookup.addDecl(Field);
14519     MemberLookup.resolveKind();
14520     MemberBuilder From(MoveOther, OtherRefType,
14521                        /*IsArrow=*/false, MemberLookup);
14522     MemberBuilder To(This, getCurrentThisType(),
14523                      /*IsArrow=*/true, MemberLookup);
14524 
14525     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14526         "Member reference with rvalue base must be rvalue except for reference "
14527         "members, which aren't allowed for move assignment.");
14528 
14529     // Build the move of this field.
14530     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14531                                             To, From,
14532                                             /*CopyingBaseSubobject=*/false,
14533                                             /*Copying=*/false);
14534     if (Move.isInvalid()) {
14535       MoveAssignOperator->setInvalidDecl();
14536       return;
14537     }
14538 
14539     // Success! Record the copy.
14540     Statements.push_back(Move.getAs<Stmt>());
14541   }
14542 
14543   if (!Invalid) {
14544     // Add a "return *this;"
14545     ExprResult ThisObj =
14546         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14547 
14548     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14549     if (Return.isInvalid())
14550       Invalid = true;
14551     else
14552       Statements.push_back(Return.getAs<Stmt>());
14553   }
14554 
14555   if (Invalid) {
14556     MoveAssignOperator->setInvalidDecl();
14557     return;
14558   }
14559 
14560   StmtResult Body;
14561   {
14562     CompoundScopeRAII CompoundScope(*this);
14563     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14564                              /*isStmtExpr=*/false);
14565     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14566   }
14567   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14568   MoveAssignOperator->markUsed(Context);
14569 
14570   if (ASTMutationListener *L = getASTMutationListener()) {
14571     L->CompletedImplicitDefinition(MoveAssignOperator);
14572   }
14573 }
14574 
DeclareImplicitCopyConstructor(CXXRecordDecl * ClassDecl)14575 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14576                                                     CXXRecordDecl *ClassDecl) {
14577   // C++ [class.copy]p4:
14578   //   If the class definition does not explicitly declare a copy
14579   //   constructor, one is declared implicitly.
14580   assert(ClassDecl->needsImplicitCopyConstructor());
14581 
14582   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14583   if (DSM.isAlreadyBeingDeclared())
14584     return nullptr;
14585 
14586   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14587   QualType ArgType = ClassType;
14588   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14589   if (Const)
14590     ArgType = ArgType.withConst();
14591 
14592   LangAS AS = getDefaultCXXMethodAddrSpace();
14593   if (AS != LangAS::Default)
14594     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14595 
14596   ArgType = Context.getLValueReferenceType(ArgType);
14597 
14598   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14599                                                      CXXCopyConstructor,
14600                                                      Const);
14601 
14602   DeclarationName Name
14603     = Context.DeclarationNames.getCXXConstructorName(
14604                                            Context.getCanonicalType(ClassType));
14605   SourceLocation ClassLoc = ClassDecl->getLocation();
14606   DeclarationNameInfo NameInfo(Name, ClassLoc);
14607 
14608   //   An implicitly-declared copy constructor is an inline public
14609   //   member of its class.
14610   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14611       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14612       ExplicitSpecifier(),
14613       /*isInline=*/true,
14614       /*isImplicitlyDeclared=*/true,
14615       Constexpr ? ConstexprSpecKind::Constexpr
14616                 : ConstexprSpecKind::Unspecified);
14617   CopyConstructor->setAccess(AS_public);
14618   CopyConstructor->setDefaulted();
14619 
14620   if (getLangOpts().CUDA) {
14621     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14622                                             CopyConstructor,
14623                                             /* ConstRHS */ Const,
14624                                             /* Diagnose */ false);
14625   }
14626 
14627   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14628 
14629   // Add the parameter to the constructor.
14630   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
14631                                                ClassLoc, ClassLoc,
14632                                                /*IdentifierInfo=*/nullptr,
14633                                                ArgType, /*TInfo=*/nullptr,
14634                                                SC_None, nullptr);
14635   CopyConstructor->setParams(FromParam);
14636 
14637   CopyConstructor->setTrivial(
14638       ClassDecl->needsOverloadResolutionForCopyConstructor()
14639           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14640           : ClassDecl->hasTrivialCopyConstructor());
14641 
14642   CopyConstructor->setTrivialForCall(
14643       ClassDecl->hasAttr<TrivialABIAttr>() ||
14644       (ClassDecl->needsOverloadResolutionForCopyConstructor()
14645            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14646              TAH_ConsiderTrivialABI)
14647            : ClassDecl->hasTrivialCopyConstructorForCall()));
14648 
14649   // Note that we have declared this constructor.
14650   ++getASTContext().NumImplicitCopyConstructorsDeclared;
14651 
14652   Scope *S = getScopeForContext(ClassDecl);
14653   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14654 
14655   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14656     ClassDecl->setImplicitCopyConstructorIsDeleted();
14657     SetDeclDeleted(CopyConstructor, ClassLoc);
14658   }
14659 
14660   if (S)
14661     PushOnScopeChains(CopyConstructor, S, false);
14662   ClassDecl->addDecl(CopyConstructor);
14663 
14664   return CopyConstructor;
14665 }
14666 
DefineImplicitCopyConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * CopyConstructor)14667 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14668                                          CXXConstructorDecl *CopyConstructor) {
14669   assert((CopyConstructor->isDefaulted() &&
14670           CopyConstructor->isCopyConstructor() &&
14671           !CopyConstructor->doesThisDeclarationHaveABody() &&
14672           !CopyConstructor->isDeleted()) &&
14673          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
14674   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14675     return;
14676 
14677   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14678   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
14679 
14680   SynthesizedFunctionScope Scope(*this, CopyConstructor);
14681 
14682   // The exception specification is needed because we are defining the
14683   // function.
14684   ResolveExceptionSpec(CurrentLocation,
14685                        CopyConstructor->getType()->castAs<FunctionProtoType>());
14686   MarkVTableUsed(CurrentLocation, ClassDecl);
14687 
14688   // Add a context note for diagnostics produced after this point.
14689   Scope.addContextNote(CurrentLocation);
14690 
14691   // C++11 [class.copy]p7:
14692   //   The [definition of an implicitly declared copy constructor] is
14693   //   deprecated if the class has a user-declared copy assignment operator
14694   //   or a user-declared destructor.
14695   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14696     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14697 
14698   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14699     CopyConstructor->setInvalidDecl();
14700   }  else {
14701     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14702                              ? CopyConstructor->getEndLoc()
14703                              : CopyConstructor->getLocation();
14704     Sema::CompoundScopeRAII CompoundScope(*this);
14705     CopyConstructor->setBody(
14706         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14707     CopyConstructor->markUsed(Context);
14708   }
14709 
14710   if (ASTMutationListener *L = getASTMutationListener()) {
14711     L->CompletedImplicitDefinition(CopyConstructor);
14712   }
14713 }
14714 
DeclareImplicitMoveConstructor(CXXRecordDecl * ClassDecl)14715 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14716                                                     CXXRecordDecl *ClassDecl) {
14717   assert(ClassDecl->needsImplicitMoveConstructor());
14718 
14719   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14720   if (DSM.isAlreadyBeingDeclared())
14721     return nullptr;
14722 
14723   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14724 
14725   QualType ArgType = ClassType;
14726   LangAS AS = getDefaultCXXMethodAddrSpace();
14727   if (AS != LangAS::Default)
14728     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14729   ArgType = Context.getRValueReferenceType(ArgType);
14730 
14731   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14732                                                      CXXMoveConstructor,
14733                                                      false);
14734 
14735   DeclarationName Name
14736     = Context.DeclarationNames.getCXXConstructorName(
14737                                            Context.getCanonicalType(ClassType));
14738   SourceLocation ClassLoc = ClassDecl->getLocation();
14739   DeclarationNameInfo NameInfo(Name, ClassLoc);
14740 
14741   // C++11 [class.copy]p11:
14742   //   An implicitly-declared copy/move constructor is an inline public
14743   //   member of its class.
14744   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
14745       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14746       ExplicitSpecifier(),
14747       /*isInline=*/true,
14748       /*isImplicitlyDeclared=*/true,
14749       Constexpr ? ConstexprSpecKind::Constexpr
14750                 : ConstexprSpecKind::Unspecified);
14751   MoveConstructor->setAccess(AS_public);
14752   MoveConstructor->setDefaulted();
14753 
14754   if (getLangOpts().CUDA) {
14755     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
14756                                             MoveConstructor,
14757                                             /* ConstRHS */ false,
14758                                             /* Diagnose */ false);
14759   }
14760 
14761   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
14762 
14763   // Add the parameter to the constructor.
14764   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
14765                                                ClassLoc, ClassLoc,
14766                                                /*IdentifierInfo=*/nullptr,
14767                                                ArgType, /*TInfo=*/nullptr,
14768                                                SC_None, nullptr);
14769   MoveConstructor->setParams(FromParam);
14770 
14771   MoveConstructor->setTrivial(
14772       ClassDecl->needsOverloadResolutionForMoveConstructor()
14773           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
14774           : ClassDecl->hasTrivialMoveConstructor());
14775 
14776   MoveConstructor->setTrivialForCall(
14777       ClassDecl->hasAttr<TrivialABIAttr>() ||
14778       (ClassDecl->needsOverloadResolutionForMoveConstructor()
14779            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
14780                                     TAH_ConsiderTrivialABI)
14781            : ClassDecl->hasTrivialMoveConstructorForCall()));
14782 
14783   // Note that we have declared this constructor.
14784   ++getASTContext().NumImplicitMoveConstructorsDeclared;
14785 
14786   Scope *S = getScopeForContext(ClassDecl);
14787   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
14788 
14789   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
14790     ClassDecl->setImplicitMoveConstructorIsDeleted();
14791     SetDeclDeleted(MoveConstructor, ClassLoc);
14792   }
14793 
14794   if (S)
14795     PushOnScopeChains(MoveConstructor, S, false);
14796   ClassDecl->addDecl(MoveConstructor);
14797 
14798   return MoveConstructor;
14799 }
14800 
DefineImplicitMoveConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * MoveConstructor)14801 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
14802                                          CXXConstructorDecl *MoveConstructor) {
14803   assert((MoveConstructor->isDefaulted() &&
14804           MoveConstructor->isMoveConstructor() &&
14805           !MoveConstructor->doesThisDeclarationHaveABody() &&
14806           !MoveConstructor->isDeleted()) &&
14807          "DefineImplicitMoveConstructor - call it for implicit move ctor");
14808   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
14809     return;
14810 
14811   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
14812   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
14813 
14814   SynthesizedFunctionScope Scope(*this, MoveConstructor);
14815 
14816   // The exception specification is needed because we are defining the
14817   // function.
14818   ResolveExceptionSpec(CurrentLocation,
14819                        MoveConstructor->getType()->castAs<FunctionProtoType>());
14820   MarkVTableUsed(CurrentLocation, ClassDecl);
14821 
14822   // Add a context note for diagnostics produced after this point.
14823   Scope.addContextNote(CurrentLocation);
14824 
14825   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
14826     MoveConstructor->setInvalidDecl();
14827   } else {
14828     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
14829                              ? MoveConstructor->getEndLoc()
14830                              : MoveConstructor->getLocation();
14831     Sema::CompoundScopeRAII CompoundScope(*this);
14832     MoveConstructor->setBody(ActOnCompoundStmt(
14833         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
14834     MoveConstructor->markUsed(Context);
14835   }
14836 
14837   if (ASTMutationListener *L = getASTMutationListener()) {
14838     L->CompletedImplicitDefinition(MoveConstructor);
14839   }
14840 }
14841 
isImplicitlyDeleted(FunctionDecl * FD)14842 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
14843   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
14844 }
14845 
DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLocation,CXXConversionDecl * Conv)14846 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
14847                             SourceLocation CurrentLocation,
14848                             CXXConversionDecl *Conv) {
14849   SynthesizedFunctionScope Scope(*this, Conv);
14850   assert(!Conv->getReturnType()->isUndeducedType());
14851 
14852   QualType ConvRT = Conv->getType()->getAs<FunctionType>()->getReturnType();
14853   CallingConv CC =
14854       ConvRT->getPointeeType()->getAs<FunctionType>()->getCallConv();
14855 
14856   CXXRecordDecl *Lambda = Conv->getParent();
14857   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
14858   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
14859 
14860   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
14861     CallOp = InstantiateFunctionDeclaration(
14862         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14863     if (!CallOp)
14864       return;
14865 
14866     Invoker = InstantiateFunctionDeclaration(
14867         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14868     if (!Invoker)
14869       return;
14870   }
14871 
14872   if (CallOp->isInvalidDecl())
14873     return;
14874 
14875   // Mark the call operator referenced (and add to pending instantiations
14876   // if necessary).
14877   // For both the conversion and static-invoker template specializations
14878   // we construct their body's in this function, so no need to add them
14879   // to the PendingInstantiations.
14880   MarkFunctionReferenced(CurrentLocation, CallOp);
14881 
14882   // Fill in the __invoke function with a dummy implementation. IR generation
14883   // will fill in the actual details. Update its type in case it contained
14884   // an 'auto'.
14885   Invoker->markUsed(Context);
14886   Invoker->setReferenced();
14887   Invoker->setType(Conv->getReturnType()->getPointeeType());
14888   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
14889 
14890   // Construct the body of the conversion function { return __invoke; }.
14891   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
14892                                        VK_LValue, Conv->getLocation());
14893   assert(FunctionRef && "Can't refer to __invoke function?");
14894   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
14895   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
14896                                      Conv->getLocation()));
14897   Conv->markUsed(Context);
14898   Conv->setReferenced();
14899 
14900   if (ASTMutationListener *L = getASTMutationListener()) {
14901     L->CompletedImplicitDefinition(Conv);
14902     L->CompletedImplicitDefinition(Invoker);
14903   }
14904 }
14905 
14906 
14907 
DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLocation,CXXConversionDecl * Conv)14908 void Sema::DefineImplicitLambdaToBlockPointerConversion(
14909        SourceLocation CurrentLocation,
14910        CXXConversionDecl *Conv)
14911 {
14912   assert(!Conv->getParent()->isGenericLambda());
14913 
14914   SynthesizedFunctionScope Scope(*this, Conv);
14915 
14916   // Copy-initialize the lambda object as needed to capture it.
14917   Expr *This = ActOnCXXThis(CurrentLocation).get();
14918   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
14919 
14920   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
14921                                                         Conv->getLocation(),
14922                                                         Conv, DerefThis);
14923 
14924   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
14925   // behavior.  Note that only the general conversion function does this
14926   // (since it's unusable otherwise); in the case where we inline the
14927   // block literal, it has block literal lifetime semantics.
14928   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
14929     BuildBlock = ImplicitCastExpr::Create(
14930         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
14931         BuildBlock.get(), nullptr, VK_RValue, FPOptionsOverride());
14932 
14933   if (BuildBlock.isInvalid()) {
14934     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14935     Conv->setInvalidDecl();
14936     return;
14937   }
14938 
14939   // Create the return statement that returns the block from the conversion
14940   // function.
14941   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
14942   if (Return.isInvalid()) {
14943     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14944     Conv->setInvalidDecl();
14945     return;
14946   }
14947 
14948   // Set the body of the conversion function.
14949   Stmt *ReturnS = Return.get();
14950   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
14951                                      Conv->getLocation()));
14952   Conv->markUsed(Context);
14953 
14954   // We're done; notify the mutation listener, if any.
14955   if (ASTMutationListener *L = getASTMutationListener()) {
14956     L->CompletedImplicitDefinition(Conv);
14957   }
14958 }
14959 
14960 /// Determine whether the given list arguments contains exactly one
14961 /// "real" (non-default) argument.
hasOneRealArgument(MultiExprArg Args)14962 static bool hasOneRealArgument(MultiExprArg Args) {
14963   switch (Args.size()) {
14964   case 0:
14965     return false;
14966 
14967   default:
14968     if (!Args[1]->isDefaultArgument())
14969       return false;
14970 
14971     LLVM_FALLTHROUGH;
14972   case 1:
14973     return !Args[0]->isDefaultArgument();
14974   }
14975 
14976   return false;
14977 }
14978 
14979 ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,NamedDecl * FoundDecl,CXXConstructorDecl * Constructor,MultiExprArg ExprArgs,bool HadMultipleCandidates,bool IsListInitialization,bool IsStdInitListInitialization,bool RequiresZeroInit,unsigned ConstructKind,SourceRange ParenRange)14980 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14981                             NamedDecl *FoundDecl,
14982                             CXXConstructorDecl *Constructor,
14983                             MultiExprArg ExprArgs,
14984                             bool HadMultipleCandidates,
14985                             bool IsListInitialization,
14986                             bool IsStdInitListInitialization,
14987                             bool RequiresZeroInit,
14988                             unsigned ConstructKind,
14989                             SourceRange ParenRange) {
14990   bool Elidable = false;
14991 
14992   // C++0x [class.copy]p34:
14993   //   When certain criteria are met, an implementation is allowed to
14994   //   omit the copy/move construction of a class object, even if the
14995   //   copy/move constructor and/or destructor for the object have
14996   //   side effects. [...]
14997   //     - when a temporary class object that has not been bound to a
14998   //       reference (12.2) would be copied/moved to a class object
14999   //       with the same cv-unqualified type, the copy/move operation
15000   //       can be omitted by constructing the temporary object
15001   //       directly into the target of the omitted copy/move
15002   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15003       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15004     Expr *SubExpr = ExprArgs[0];
15005     Elidable = SubExpr->isTemporaryObject(
15006         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15007   }
15008 
15009   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15010                                FoundDecl, Constructor,
15011                                Elidable, ExprArgs, HadMultipleCandidates,
15012                                IsListInitialization,
15013                                IsStdInitListInitialization, RequiresZeroInit,
15014                                ConstructKind, ParenRange);
15015 }
15016 
15017 ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,NamedDecl * FoundDecl,CXXConstructorDecl * Constructor,bool Elidable,MultiExprArg ExprArgs,bool HadMultipleCandidates,bool IsListInitialization,bool IsStdInitListInitialization,bool RequiresZeroInit,unsigned ConstructKind,SourceRange ParenRange)15018 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15019                             NamedDecl *FoundDecl,
15020                             CXXConstructorDecl *Constructor,
15021                             bool Elidable,
15022                             MultiExprArg ExprArgs,
15023                             bool HadMultipleCandidates,
15024                             bool IsListInitialization,
15025                             bool IsStdInitListInitialization,
15026                             bool RequiresZeroInit,
15027                             unsigned ConstructKind,
15028                             SourceRange ParenRange) {
15029   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15030     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15031     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15032       return ExprError();
15033   }
15034 
15035   return BuildCXXConstructExpr(
15036       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15037       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15038       RequiresZeroInit, ConstructKind, ParenRange);
15039 }
15040 
15041 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15042 /// including handling of its default argument expressions.
15043 ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,CXXConstructorDecl * Constructor,bool Elidable,MultiExprArg ExprArgs,bool HadMultipleCandidates,bool IsListInitialization,bool IsStdInitListInitialization,bool RequiresZeroInit,unsigned ConstructKind,SourceRange ParenRange)15044 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15045                             CXXConstructorDecl *Constructor,
15046                             bool Elidable,
15047                             MultiExprArg ExprArgs,
15048                             bool HadMultipleCandidates,
15049                             bool IsListInitialization,
15050                             bool IsStdInitListInitialization,
15051                             bool RequiresZeroInit,
15052                             unsigned ConstructKind,
15053                             SourceRange ParenRange) {
15054   assert(declaresSameEntity(
15055              Constructor->getParent(),
15056              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15057          "given constructor for wrong type");
15058   MarkFunctionReferenced(ConstructLoc, Constructor);
15059   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15060     return ExprError();
15061   if (getLangOpts().SYCLIsDevice &&
15062       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15063     return ExprError();
15064 
15065   return CheckForImmediateInvocation(
15066       CXXConstructExpr::Create(
15067           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15068           HadMultipleCandidates, IsListInitialization,
15069           IsStdInitListInitialization, RequiresZeroInit,
15070           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15071           ParenRange),
15072       Constructor);
15073 }
15074 
BuildCXXDefaultInitExpr(SourceLocation Loc,FieldDecl * Field)15075 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15076   assert(Field->hasInClassInitializer());
15077 
15078   // If we already have the in-class initializer nothing needs to be done.
15079   if (Field->getInClassInitializer())
15080     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15081 
15082   // If we might have already tried and failed to instantiate, don't try again.
15083   if (Field->isInvalidDecl())
15084     return ExprError();
15085 
15086   // Maybe we haven't instantiated the in-class initializer. Go check the
15087   // pattern FieldDecl to see if it has one.
15088   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15089 
15090   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15091     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15092     DeclContext::lookup_result Lookup =
15093         ClassPattern->lookup(Field->getDeclName());
15094 
15095     FieldDecl *Pattern = nullptr;
15096     for (auto L : Lookup) {
15097       if (isa<FieldDecl>(L)) {
15098         Pattern = cast<FieldDecl>(L);
15099         break;
15100       }
15101     }
15102     assert(Pattern && "We must have set the Pattern!");
15103 
15104     if (!Pattern->hasInClassInitializer() ||
15105         InstantiateInClassInitializer(Loc, Field, Pattern,
15106                                       getTemplateInstantiationArgs(Field))) {
15107       // Don't diagnose this again.
15108       Field->setInvalidDecl();
15109       return ExprError();
15110     }
15111     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15112   }
15113 
15114   // DR1351:
15115   //   If the brace-or-equal-initializer of a non-static data member
15116   //   invokes a defaulted default constructor of its class or of an
15117   //   enclosing class in a potentially evaluated subexpression, the
15118   //   program is ill-formed.
15119   //
15120   // This resolution is unworkable: the exception specification of the
15121   // default constructor can be needed in an unevaluated context, in
15122   // particular, in the operand of a noexcept-expression, and we can be
15123   // unable to compute an exception specification for an enclosed class.
15124   //
15125   // Any attempt to resolve the exception specification of a defaulted default
15126   // constructor before the initializer is lexically complete will ultimately
15127   // come here at which point we can diagnose it.
15128   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15129   Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15130       << OutermostClass << Field;
15131   Diag(Field->getEndLoc(),
15132        diag::note_default_member_initializer_not_yet_parsed);
15133   // Recover by marking the field invalid, unless we're in a SFINAE context.
15134   if (!isSFINAEContext())
15135     Field->setInvalidDecl();
15136   return ExprError();
15137 }
15138 
FinalizeVarWithDestructor(VarDecl * VD,const RecordType * Record)15139 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15140   if (VD->isInvalidDecl()) return;
15141   // If initializing the variable failed, don't also diagnose problems with
15142   // the desctructor, they're likely related.
15143   if (VD->getInit() && VD->getInit()->containsErrors())
15144     return;
15145 
15146   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15147   if (ClassDecl->isInvalidDecl()) return;
15148   if (ClassDecl->hasIrrelevantDestructor()) return;
15149   if (ClassDecl->isDependentContext()) return;
15150 
15151   if (VD->isNoDestroy(getASTContext()))
15152     return;
15153 
15154   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15155 
15156   // If this is an array, we'll require the destructor during initialization, so
15157   // we can skip over this. We still want to emit exit-time destructor warnings
15158   // though.
15159   if (!VD->getType()->isArrayType()) {
15160     MarkFunctionReferenced(VD->getLocation(), Destructor);
15161     CheckDestructorAccess(VD->getLocation(), Destructor,
15162                           PDiag(diag::err_access_dtor_var)
15163                               << VD->getDeclName() << VD->getType());
15164     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15165   }
15166 
15167   if (Destructor->isTrivial()) return;
15168 
15169   // If the destructor is constexpr, check whether the variable has constant
15170   // destruction now.
15171   if (Destructor->isConstexpr()) {
15172     bool HasConstantInit = false;
15173     if (VD->getInit() && !VD->getInit()->isValueDependent())
15174       HasConstantInit = VD->evaluateValue();
15175     SmallVector<PartialDiagnosticAt, 8> Notes;
15176     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15177         HasConstantInit) {
15178       Diag(VD->getLocation(),
15179            diag::err_constexpr_var_requires_const_destruction) << VD;
15180       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15181         Diag(Notes[I].first, Notes[I].second);
15182     }
15183   }
15184 
15185   if (!VD->hasGlobalStorage()) return;
15186 
15187   // Emit warning for non-trivial dtor in global scope (a real global,
15188   // class-static, function-static).
15189   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15190 
15191   // TODO: this should be re-enabled for static locals by !CXAAtExit
15192   if (!VD->isStaticLocal())
15193     Diag(VD->getLocation(), diag::warn_global_destructor);
15194 }
15195 
15196 /// Given a constructor and the set of arguments provided for the
15197 /// constructor, convert the arguments and add any required default arguments
15198 /// to form a proper call to this constructor.
15199 ///
15200 /// \returns true if an error occurred, false otherwise.
15201 bool
CompleteConstructorCall(CXXConstructorDecl * Constructor,MultiExprArg ArgsPtr,SourceLocation Loc,SmallVectorImpl<Expr * > & ConvertedArgs,bool AllowExplicit,bool IsListInitialization)15202 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15203                               MultiExprArg ArgsPtr,
15204                               SourceLocation Loc,
15205                               SmallVectorImpl<Expr*> &ConvertedArgs,
15206                               bool AllowExplicit,
15207                               bool IsListInitialization) {
15208   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15209   unsigned NumArgs = ArgsPtr.size();
15210   Expr **Args = ArgsPtr.data();
15211 
15212   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15213   unsigned NumParams = Proto->getNumParams();
15214 
15215   // If too few arguments are available, we'll fill in the rest with defaults.
15216   if (NumArgs < NumParams)
15217     ConvertedArgs.reserve(NumParams);
15218   else
15219     ConvertedArgs.reserve(NumArgs);
15220 
15221   VariadicCallType CallType =
15222     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15223   SmallVector<Expr *, 8> AllArgs;
15224   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15225                                         Proto, 0,
15226                                         llvm::makeArrayRef(Args, NumArgs),
15227                                         AllArgs,
15228                                         CallType, AllowExplicit,
15229                                         IsListInitialization);
15230   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15231 
15232   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15233 
15234   CheckConstructorCall(Constructor,
15235                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15236                        Proto, Loc);
15237 
15238   return Invalid;
15239 }
15240 
15241 static inline bool
CheckOperatorNewDeleteDeclarationScope(Sema & SemaRef,const FunctionDecl * FnDecl)15242 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15243                                        const FunctionDecl *FnDecl) {
15244   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15245   if (isa<NamespaceDecl>(DC)) {
15246     return SemaRef.Diag(FnDecl->getLocation(),
15247                         diag::err_operator_new_delete_declared_in_namespace)
15248       << FnDecl->getDeclName();
15249   }
15250 
15251   if (isa<TranslationUnitDecl>(DC) &&
15252       FnDecl->getStorageClass() == SC_Static) {
15253     return SemaRef.Diag(FnDecl->getLocation(),
15254                         diag::err_operator_new_delete_declared_static)
15255       << FnDecl->getDeclName();
15256   }
15257 
15258   return false;
15259 }
15260 
15261 static QualType
RemoveAddressSpaceFromPtr(Sema & SemaRef,const PointerType * PtrTy)15262 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
15263   QualType QTy = PtrTy->getPointeeType();
15264   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
15265   return SemaRef.Context.getPointerType(QTy);
15266 }
15267 
15268 static inline bool
CheckOperatorNewDeleteTypes(Sema & SemaRef,const FunctionDecl * FnDecl,CanQualType ExpectedResultType,CanQualType ExpectedFirstParamType,unsigned DependentParamTypeDiag,unsigned InvalidParamTypeDiag)15269 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15270                             CanQualType ExpectedResultType,
15271                             CanQualType ExpectedFirstParamType,
15272                             unsigned DependentParamTypeDiag,
15273                             unsigned InvalidParamTypeDiag) {
15274   QualType ResultType =
15275       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15276 
15277   // The operator is valid on any address space for OpenCL.
15278   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15279     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
15280       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15281     }
15282   }
15283 
15284   // Check that the result type is what we expect.
15285   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15286     // Reject even if the type is dependent; an operator delete function is
15287     // required to have a non-dependent result type.
15288     return SemaRef.Diag(
15289                FnDecl->getLocation(),
15290                ResultType->isDependentType()
15291                    ? diag::err_operator_new_delete_dependent_result_type
15292                    : diag::err_operator_new_delete_invalid_result_type)
15293            << FnDecl->getDeclName() << ExpectedResultType;
15294   }
15295 
15296   // A function template must have at least 2 parameters.
15297   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15298     return SemaRef.Diag(FnDecl->getLocation(),
15299                       diag::err_operator_new_delete_template_too_few_parameters)
15300         << FnDecl->getDeclName();
15301 
15302   // The function decl must have at least 1 parameter.
15303   if (FnDecl->getNumParams() == 0)
15304     return SemaRef.Diag(FnDecl->getLocation(),
15305                         diag::err_operator_new_delete_too_few_parameters)
15306       << FnDecl->getDeclName();
15307 
15308   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15309   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15310     // The operator is valid on any address space for OpenCL.
15311     if (auto *PtrTy =
15312             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
15313       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15314     }
15315   }
15316 
15317   // Check that the first parameter type is what we expect.
15318   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15319       ExpectedFirstParamType) {
15320     // The first parameter type is not allowed to be dependent. As a tentative
15321     // DR resolution, we allow a dependent parameter type if it is the right
15322     // type anyway, to allow destroying operator delete in class templates.
15323     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15324                                                    ? DependentParamTypeDiag
15325                                                    : InvalidParamTypeDiag)
15326            << FnDecl->getDeclName() << ExpectedFirstParamType;
15327   }
15328 
15329   return false;
15330 }
15331 
15332 static bool
CheckOperatorNewDeclaration(Sema & SemaRef,const FunctionDecl * FnDecl)15333 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15334   // C++ [basic.stc.dynamic.allocation]p1:
15335   //   A program is ill-formed if an allocation function is declared in a
15336   //   namespace scope other than global scope or declared static in global
15337   //   scope.
15338   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15339     return true;
15340 
15341   CanQualType SizeTy =
15342     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15343 
15344   // C++ [basic.stc.dynamic.allocation]p1:
15345   //  The return type shall be void*. The first parameter shall have type
15346   //  std::size_t.
15347   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15348                                   SizeTy,
15349                                   diag::err_operator_new_dependent_param_type,
15350                                   diag::err_operator_new_param_type))
15351     return true;
15352 
15353   // C++ [basic.stc.dynamic.allocation]p1:
15354   //  The first parameter shall not have an associated default argument.
15355   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15356     return SemaRef.Diag(FnDecl->getLocation(),
15357                         diag::err_operator_new_default_arg)
15358       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15359 
15360   return false;
15361 }
15362 
15363 static bool
CheckOperatorDeleteDeclaration(Sema & SemaRef,FunctionDecl * FnDecl)15364 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15365   // C++ [basic.stc.dynamic.deallocation]p1:
15366   //   A program is ill-formed if deallocation functions are declared in a
15367   //   namespace scope other than global scope or declared static in global
15368   //   scope.
15369   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15370     return true;
15371 
15372   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15373 
15374   // C++ P0722:
15375   //   Within a class C, the first parameter of a destroying operator delete
15376   //   shall be of type C *. The first parameter of any other deallocation
15377   //   function shall be of type void *.
15378   CanQualType ExpectedFirstParamType =
15379       MD && MD->isDestroyingOperatorDelete()
15380           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15381                 SemaRef.Context.getRecordType(MD->getParent())))
15382           : SemaRef.Context.VoidPtrTy;
15383 
15384   // C++ [basic.stc.dynamic.deallocation]p2:
15385   //   Each deallocation function shall return void
15386   if (CheckOperatorNewDeleteTypes(
15387           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15388           diag::err_operator_delete_dependent_param_type,
15389           diag::err_operator_delete_param_type))
15390     return true;
15391 
15392   // C++ P0722:
15393   //   A destroying operator delete shall be a usual deallocation function.
15394   if (MD && !MD->getParent()->isDependentContext() &&
15395       MD->isDestroyingOperatorDelete() &&
15396       !SemaRef.isUsualDeallocationFunction(MD)) {
15397     SemaRef.Diag(MD->getLocation(),
15398                  diag::err_destroying_operator_delete_not_usual);
15399     return true;
15400   }
15401 
15402   return false;
15403 }
15404 
15405 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15406 /// of this overloaded operator is well-formed. If so, returns false;
15407 /// otherwise, emits appropriate diagnostics and returns true.
CheckOverloadedOperatorDeclaration(FunctionDecl * FnDecl)15408 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15409   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15410          "Expected an overloaded operator declaration");
15411 
15412   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15413 
15414   // C++ [over.oper]p5:
15415   //   The allocation and deallocation functions, operator new,
15416   //   operator new[], operator delete and operator delete[], are
15417   //   described completely in 3.7.3. The attributes and restrictions
15418   //   found in the rest of this subclause do not apply to them unless
15419   //   explicitly stated in 3.7.3.
15420   if (Op == OO_Delete || Op == OO_Array_Delete)
15421     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15422 
15423   if (Op == OO_New || Op == OO_Array_New)
15424     return CheckOperatorNewDeclaration(*this, FnDecl);
15425 
15426   // C++ [over.oper]p6:
15427   //   An operator function shall either be a non-static member
15428   //   function or be a non-member function and have at least one
15429   //   parameter whose type is a class, a reference to a class, an
15430   //   enumeration, or a reference to an enumeration.
15431   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15432     if (MethodDecl->isStatic())
15433       return Diag(FnDecl->getLocation(),
15434                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15435   } else {
15436     bool ClassOrEnumParam = false;
15437     for (auto Param : FnDecl->parameters()) {
15438       QualType ParamType = Param->getType().getNonReferenceType();
15439       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15440           ParamType->isEnumeralType()) {
15441         ClassOrEnumParam = true;
15442         break;
15443       }
15444     }
15445 
15446     if (!ClassOrEnumParam)
15447       return Diag(FnDecl->getLocation(),
15448                   diag::err_operator_overload_needs_class_or_enum)
15449         << FnDecl->getDeclName();
15450   }
15451 
15452   // C++ [over.oper]p8:
15453   //   An operator function cannot have default arguments (8.3.6),
15454   //   except where explicitly stated below.
15455   //
15456   // Only the function-call operator allows default arguments
15457   // (C++ [over.call]p1).
15458   if (Op != OO_Call) {
15459     for (auto Param : FnDecl->parameters()) {
15460       if (Param->hasDefaultArg())
15461         return Diag(Param->getLocation(),
15462                     diag::err_operator_overload_default_arg)
15463           << FnDecl->getDeclName() << Param->getDefaultArgRange();
15464     }
15465   }
15466 
15467   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15468     { false, false, false }
15469 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15470     , { Unary, Binary, MemberOnly }
15471 #include "clang/Basic/OperatorKinds.def"
15472   };
15473 
15474   bool CanBeUnaryOperator = OperatorUses[Op][0];
15475   bool CanBeBinaryOperator = OperatorUses[Op][1];
15476   bool MustBeMemberOperator = OperatorUses[Op][2];
15477 
15478   // C++ [over.oper]p8:
15479   //   [...] Operator functions cannot have more or fewer parameters
15480   //   than the number required for the corresponding operator, as
15481   //   described in the rest of this subclause.
15482   unsigned NumParams = FnDecl->getNumParams()
15483                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15484   if (Op != OO_Call &&
15485       ((NumParams == 1 && !CanBeUnaryOperator) ||
15486        (NumParams == 2 && !CanBeBinaryOperator) ||
15487        (NumParams < 1) || (NumParams > 2))) {
15488     // We have the wrong number of parameters.
15489     unsigned ErrorKind;
15490     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15491       ErrorKind = 2;  // 2 -> unary or binary.
15492     } else if (CanBeUnaryOperator) {
15493       ErrorKind = 0;  // 0 -> unary
15494     } else {
15495       assert(CanBeBinaryOperator &&
15496              "All non-call overloaded operators are unary or binary!");
15497       ErrorKind = 1;  // 1 -> binary
15498     }
15499 
15500     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15501       << FnDecl->getDeclName() << NumParams << ErrorKind;
15502   }
15503 
15504   // Overloaded operators other than operator() cannot be variadic.
15505   if (Op != OO_Call &&
15506       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15507     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15508       << FnDecl->getDeclName();
15509   }
15510 
15511   // Some operators must be non-static member functions.
15512   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15513     return Diag(FnDecl->getLocation(),
15514                 diag::err_operator_overload_must_be_member)
15515       << FnDecl->getDeclName();
15516   }
15517 
15518   // C++ [over.inc]p1:
15519   //   The user-defined function called operator++ implements the
15520   //   prefix and postfix ++ operator. If this function is a member
15521   //   function with no parameters, or a non-member function with one
15522   //   parameter of class or enumeration type, it defines the prefix
15523   //   increment operator ++ for objects of that type. If the function
15524   //   is a member function with one parameter (which shall be of type
15525   //   int) or a non-member function with two parameters (the second
15526   //   of which shall be of type int), it defines the postfix
15527   //   increment operator ++ for objects of that type.
15528   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15529     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15530     QualType ParamType = LastParam->getType();
15531 
15532     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15533         !ParamType->isDependentType())
15534       return Diag(LastParam->getLocation(),
15535                   diag::err_operator_overload_post_incdec_must_be_int)
15536         << LastParam->getType() << (Op == OO_MinusMinus);
15537   }
15538 
15539   return false;
15540 }
15541 
15542 static bool
checkLiteralOperatorTemplateParameterList(Sema & SemaRef,FunctionTemplateDecl * TpDecl)15543 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15544                                           FunctionTemplateDecl *TpDecl) {
15545   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15546 
15547   // Must have one or two template parameters.
15548   if (TemplateParams->size() == 1) {
15549     NonTypeTemplateParmDecl *PmDecl =
15550         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15551 
15552     // The template parameter must be a char parameter pack.
15553     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15554         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15555       return false;
15556 
15557     // C++20 [over.literal]p5:
15558     //   A string literal operator template is a literal operator template
15559     //   whose template-parameter-list comprises a single non-type
15560     //   template-parameter of class type.
15561     //
15562     // As a DR resolution, we also allow placeholders for deduced class
15563     // template specializations.
15564     if (SemaRef.getLangOpts().CPlusPlus20 &&
15565         !PmDecl->isTemplateParameterPack() &&
15566         (PmDecl->getType()->isRecordType() ||
15567          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
15568       return false;
15569   } else if (TemplateParams->size() == 2) {
15570     TemplateTypeParmDecl *PmType =
15571         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15572     NonTypeTemplateParmDecl *PmArgs =
15573         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15574 
15575     // The second template parameter must be a parameter pack with the
15576     // first template parameter as its type.
15577     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15578         PmArgs->isTemplateParameterPack()) {
15579       const TemplateTypeParmType *TArgs =
15580           PmArgs->getType()->getAs<TemplateTypeParmType>();
15581       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15582           TArgs->getIndex() == PmType->getIndex()) {
15583         if (!SemaRef.inTemplateInstantiation())
15584           SemaRef.Diag(TpDecl->getLocation(),
15585                        diag::ext_string_literal_operator_template);
15586         return false;
15587       }
15588     }
15589   }
15590 
15591   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15592                diag::err_literal_operator_template)
15593       << TpDecl->getTemplateParameters()->getSourceRange();
15594   return true;
15595 }
15596 
15597 /// CheckLiteralOperatorDeclaration - Check whether the declaration
15598 /// of this literal operator function is well-formed. If so, returns
15599 /// false; otherwise, emits appropriate diagnostics and returns true.
CheckLiteralOperatorDeclaration(FunctionDecl * FnDecl)15600 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15601   if (isa<CXXMethodDecl>(FnDecl)) {
15602     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15603       << FnDecl->getDeclName();
15604     return true;
15605   }
15606 
15607   if (FnDecl->isExternC()) {
15608     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15609     if (const LinkageSpecDecl *LSD =
15610             FnDecl->getDeclContext()->getExternCContext())
15611       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15612     return true;
15613   }
15614 
15615   // This might be the definition of a literal operator template.
15616   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15617 
15618   // This might be a specialization of a literal operator template.
15619   if (!TpDecl)
15620     TpDecl = FnDecl->getPrimaryTemplate();
15621 
15622   // template <char...> type operator "" name() and
15623   // template <class T, T...> type operator "" name() are the only valid
15624   // template signatures, and the only valid signatures with no parameters.
15625   //
15626   // C++20 also allows template <SomeClass T> type operator "" name().
15627   if (TpDecl) {
15628     if (FnDecl->param_size() != 0) {
15629       Diag(FnDecl->getLocation(),
15630            diag::err_literal_operator_template_with_params);
15631       return true;
15632     }
15633 
15634     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15635       return true;
15636 
15637   } else if (FnDecl->param_size() == 1) {
15638     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15639 
15640     QualType ParamType = Param->getType().getUnqualifiedType();
15641 
15642     // Only unsigned long long int, long double, any character type, and const
15643     // char * are allowed as the only parameters.
15644     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15645         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15646         Context.hasSameType(ParamType, Context.CharTy) ||
15647         Context.hasSameType(ParamType, Context.WideCharTy) ||
15648         Context.hasSameType(ParamType, Context.Char8Ty) ||
15649         Context.hasSameType(ParamType, Context.Char16Ty) ||
15650         Context.hasSameType(ParamType, Context.Char32Ty)) {
15651     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15652       QualType InnerType = Ptr->getPointeeType();
15653 
15654       // Pointer parameter must be a const char *.
15655       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15656                                 Context.CharTy) &&
15657             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15658         Diag(Param->getSourceRange().getBegin(),
15659              diag::err_literal_operator_param)
15660             << ParamType << "'const char *'" << Param->getSourceRange();
15661         return true;
15662       }
15663 
15664     } else if (ParamType->isRealFloatingType()) {
15665       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15666           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15667       return true;
15668 
15669     } else if (ParamType->isIntegerType()) {
15670       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15671           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15672       return true;
15673 
15674     } else {
15675       Diag(Param->getSourceRange().getBegin(),
15676            diag::err_literal_operator_invalid_param)
15677           << ParamType << Param->getSourceRange();
15678       return true;
15679     }
15680 
15681   } else if (FnDecl->param_size() == 2) {
15682     FunctionDecl::param_iterator Param = FnDecl->param_begin();
15683 
15684     // First, verify that the first parameter is correct.
15685 
15686     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15687 
15688     // Two parameter function must have a pointer to const as a
15689     // first parameter; let's strip those qualifiers.
15690     const PointerType *PT = FirstParamType->getAs<PointerType>();
15691 
15692     if (!PT) {
15693       Diag((*Param)->getSourceRange().getBegin(),
15694            diag::err_literal_operator_param)
15695           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15696       return true;
15697     }
15698 
15699     QualType PointeeType = PT->getPointeeType();
15700     // First parameter must be const
15701     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15702       Diag((*Param)->getSourceRange().getBegin(),
15703            diag::err_literal_operator_param)
15704           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15705       return true;
15706     }
15707 
15708     QualType InnerType = PointeeType.getUnqualifiedType();
15709     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15710     // const char32_t* are allowed as the first parameter to a two-parameter
15711     // function
15712     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15713           Context.hasSameType(InnerType, Context.WideCharTy) ||
15714           Context.hasSameType(InnerType, Context.Char8Ty) ||
15715           Context.hasSameType(InnerType, Context.Char16Ty) ||
15716           Context.hasSameType(InnerType, Context.Char32Ty))) {
15717       Diag((*Param)->getSourceRange().getBegin(),
15718            diag::err_literal_operator_param)
15719           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15720       return true;
15721     }
15722 
15723     // Move on to the second and final parameter.
15724     ++Param;
15725 
15726     // The second parameter must be a std::size_t.
15727     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15728     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15729       Diag((*Param)->getSourceRange().getBegin(),
15730            diag::err_literal_operator_param)
15731           << SecondParamType << Context.getSizeType()
15732           << (*Param)->getSourceRange();
15733       return true;
15734     }
15735   } else {
15736     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15737     return true;
15738   }
15739 
15740   // Parameters are good.
15741 
15742   // A parameter-declaration-clause containing a default argument is not
15743   // equivalent to any of the permitted forms.
15744   for (auto Param : FnDecl->parameters()) {
15745     if (Param->hasDefaultArg()) {
15746       Diag(Param->getDefaultArgRange().getBegin(),
15747            diag::err_literal_operator_default_argument)
15748         << Param->getDefaultArgRange();
15749       break;
15750     }
15751   }
15752 
15753   StringRef LiteralName
15754     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15755   if (LiteralName[0] != '_' &&
15756       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15757     // C++11 [usrlit.suffix]p1:
15758     //   Literal suffix identifiers that do not start with an underscore
15759     //   are reserved for future standardization.
15760     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15761       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15762   }
15763 
15764   return false;
15765 }
15766 
15767 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15768 /// linkage specification, including the language and (if present)
15769 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
15770 /// language string literal. LBraceLoc, if valid, provides the location of
15771 /// the '{' brace. Otherwise, this linkage specification does not
15772 /// have any braces.
ActOnStartLinkageSpecification(Scope * S,SourceLocation ExternLoc,Expr * LangStr,SourceLocation LBraceLoc)15773 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15774                                            Expr *LangStr,
15775                                            SourceLocation LBraceLoc) {
15776   StringLiteral *Lit = cast<StringLiteral>(LangStr);
15777   if (!Lit->isAscii()) {
15778     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15779       << LangStr->getSourceRange();
15780     return nullptr;
15781   }
15782 
15783   StringRef Lang = Lit->getString();
15784   LinkageSpecDecl::LanguageIDs Language;
15785   if (Lang == "C")
15786     Language = LinkageSpecDecl::lang_c;
15787   else if (Lang == "C++")
15788     Language = LinkageSpecDecl::lang_cxx;
15789   else {
15790     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15791       << LangStr->getSourceRange();
15792     return nullptr;
15793   }
15794 
15795   // FIXME: Add all the various semantics of linkage specifications
15796 
15797   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15798                                                LangStr->getExprLoc(), Language,
15799                                                LBraceLoc.isValid());
15800   CurContext->addDecl(D);
15801   PushDeclContext(S, D);
15802   return D;
15803 }
15804 
15805 /// ActOnFinishLinkageSpecification - Complete the definition of
15806 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
15807 /// valid, it's the position of the closing '}' brace in a linkage
15808 /// specification that uses braces.
ActOnFinishLinkageSpecification(Scope * S,Decl * LinkageSpec,SourceLocation RBraceLoc)15809 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15810                                             Decl *LinkageSpec,
15811                                             SourceLocation RBraceLoc) {
15812   if (RBraceLoc.isValid()) {
15813     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15814     LSDecl->setRBraceLoc(RBraceLoc);
15815   }
15816   PopDeclContext();
15817   return LinkageSpec;
15818 }
15819 
ActOnEmptyDeclaration(Scope * S,const ParsedAttributesView & AttrList,SourceLocation SemiLoc)15820 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15821                                   const ParsedAttributesView &AttrList,
15822                                   SourceLocation SemiLoc) {
15823   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15824   // Attribute declarations appertain to empty declaration so we handle
15825   // them here.
15826   ProcessDeclAttributeList(S, ED, AttrList);
15827 
15828   CurContext->addDecl(ED);
15829   return ED;
15830 }
15831 
15832 /// Perform semantic analysis for the variable declaration that
15833 /// occurs within a C++ catch clause, returning the newly-created
15834 /// variable.
BuildExceptionDeclaration(Scope * S,TypeSourceInfo * TInfo,SourceLocation StartLoc,SourceLocation Loc,IdentifierInfo * Name)15835 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15836                                          TypeSourceInfo *TInfo,
15837                                          SourceLocation StartLoc,
15838                                          SourceLocation Loc,
15839                                          IdentifierInfo *Name) {
15840   bool Invalid = false;
15841   QualType ExDeclType = TInfo->getType();
15842 
15843   // Arrays and functions decay.
15844   if (ExDeclType->isArrayType())
15845     ExDeclType = Context.getArrayDecayedType(ExDeclType);
15846   else if (ExDeclType->isFunctionType())
15847     ExDeclType = Context.getPointerType(ExDeclType);
15848 
15849   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15850   // The exception-declaration shall not denote a pointer or reference to an
15851   // incomplete type, other than [cv] void*.
15852   // N2844 forbids rvalue references.
15853   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15854     Diag(Loc, diag::err_catch_rvalue_ref);
15855     Invalid = true;
15856   }
15857 
15858   if (ExDeclType->isVariablyModifiedType()) {
15859     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15860     Invalid = true;
15861   }
15862 
15863   QualType BaseType = ExDeclType;
15864   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15865   unsigned DK = diag::err_catch_incomplete;
15866   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15867     BaseType = Ptr->getPointeeType();
15868     Mode = 1;
15869     DK = diag::err_catch_incomplete_ptr;
15870   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15871     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15872     BaseType = Ref->getPointeeType();
15873     Mode = 2;
15874     DK = diag::err_catch_incomplete_ref;
15875   }
15876   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15877       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15878     Invalid = true;
15879 
15880   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15881     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15882     Invalid = true;
15883   }
15884 
15885   if (!Invalid && !ExDeclType->isDependentType() &&
15886       RequireNonAbstractType(Loc, ExDeclType,
15887                              diag::err_abstract_type_in_decl,
15888                              AbstractVariableType))
15889     Invalid = true;
15890 
15891   // Only the non-fragile NeXT runtime currently supports C++ catches
15892   // of ObjC types, and no runtime supports catching ObjC types by value.
15893   if (!Invalid && getLangOpts().ObjC) {
15894     QualType T = ExDeclType;
15895     if (const ReferenceType *RT = T->getAs<ReferenceType>())
15896       T = RT->getPointeeType();
15897 
15898     if (T->isObjCObjectType()) {
15899       Diag(Loc, diag::err_objc_object_catch);
15900       Invalid = true;
15901     } else if (T->isObjCObjectPointerType()) {
15902       // FIXME: should this be a test for macosx-fragile specifically?
15903       if (getLangOpts().ObjCRuntime.isFragile())
15904         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15905     }
15906   }
15907 
15908   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15909                                     ExDeclType, TInfo, SC_None);
15910   ExDecl->setExceptionVariable(true);
15911 
15912   // In ARC, infer 'retaining' for variables of retainable type.
15913   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15914     Invalid = true;
15915 
15916   if (!Invalid && !ExDeclType->isDependentType()) {
15917     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15918       // Insulate this from anything else we might currently be parsing.
15919       EnterExpressionEvaluationContext scope(
15920           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15921 
15922       // C++ [except.handle]p16:
15923       //   The object declared in an exception-declaration or, if the
15924       //   exception-declaration does not specify a name, a temporary (12.2) is
15925       //   copy-initialized (8.5) from the exception object. [...]
15926       //   The object is destroyed when the handler exits, after the destruction
15927       //   of any automatic objects initialized within the handler.
15928       //
15929       // We just pretend to initialize the object with itself, then make sure
15930       // it can be destroyed later.
15931       QualType initType = Context.getExceptionObjectType(ExDeclType);
15932 
15933       InitializedEntity entity =
15934         InitializedEntity::InitializeVariable(ExDecl);
15935       InitializationKind initKind =
15936         InitializationKind::CreateCopy(Loc, SourceLocation());
15937 
15938       Expr *opaqueValue =
15939         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
15940       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
15941       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
15942       if (result.isInvalid())
15943         Invalid = true;
15944       else {
15945         // If the constructor used was non-trivial, set this as the
15946         // "initializer".
15947         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
15948         if (!construct->getConstructor()->isTrivial()) {
15949           Expr *init = MaybeCreateExprWithCleanups(construct);
15950           ExDecl->setInit(init);
15951         }
15952 
15953         // And make sure it's destructable.
15954         FinalizeVarWithDestructor(ExDecl, recordType);
15955       }
15956     }
15957   }
15958 
15959   if (Invalid)
15960     ExDecl->setInvalidDecl();
15961 
15962   return ExDecl;
15963 }
15964 
15965 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
15966 /// handler.
ActOnExceptionDeclarator(Scope * S,Declarator & D)15967 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
15968   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15969   bool Invalid = D.isInvalidType();
15970 
15971   // Check for unexpanded parameter packs.
15972   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15973                                       UPPC_ExceptionType)) {
15974     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
15975                                              D.getIdentifierLoc());
15976     Invalid = true;
15977   }
15978 
15979   IdentifierInfo *II = D.getIdentifier();
15980   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
15981                                              LookupOrdinaryName,
15982                                              ForVisibleRedeclaration)) {
15983     // The scope should be freshly made just for us. There is just no way
15984     // it contains any previous declaration, except for function parameters in
15985     // a function-try-block's catch statement.
15986     assert(!S->isDeclScope(PrevDecl));
15987     if (isDeclInScope(PrevDecl, CurContext, S)) {
15988       Diag(D.getIdentifierLoc(), diag::err_redefinition)
15989         << D.getIdentifier();
15990       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15991       Invalid = true;
15992     } else if (PrevDecl->isTemplateParameter())
15993       // Maybe we will complain about the shadowed template parameter.
15994       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15995   }
15996 
15997   if (D.getCXXScopeSpec().isSet() && !Invalid) {
15998     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
15999       << D.getCXXScopeSpec().getRange();
16000     Invalid = true;
16001   }
16002 
16003   VarDecl *ExDecl = BuildExceptionDeclaration(
16004       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16005   if (Invalid)
16006     ExDecl->setInvalidDecl();
16007 
16008   // Add the exception declaration into this scope.
16009   if (II)
16010     PushOnScopeChains(ExDecl, S);
16011   else
16012     CurContext->addDecl(ExDecl);
16013 
16014   ProcessDeclAttributes(S, ExDecl, D);
16015   return ExDecl;
16016 }
16017 
ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,Expr * AssertExpr,Expr * AssertMessageExpr,SourceLocation RParenLoc)16018 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16019                                          Expr *AssertExpr,
16020                                          Expr *AssertMessageExpr,
16021                                          SourceLocation RParenLoc) {
16022   StringLiteral *AssertMessage =
16023       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16024 
16025   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16026     return nullptr;
16027 
16028   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16029                                       AssertMessage, RParenLoc, false);
16030 }
16031 
BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,Expr * AssertExpr,StringLiteral * AssertMessage,SourceLocation RParenLoc,bool Failed)16032 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16033                                          Expr *AssertExpr,
16034                                          StringLiteral *AssertMessage,
16035                                          SourceLocation RParenLoc,
16036                                          bool Failed) {
16037   assert(AssertExpr != nullptr && "Expected non-null condition");
16038   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16039       !Failed) {
16040     // In a static_assert-declaration, the constant-expression shall be a
16041     // constant expression that can be contextually converted to bool.
16042     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16043     if (Converted.isInvalid())
16044       Failed = true;
16045 
16046     ExprResult FullAssertExpr =
16047         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16048                             /*DiscardedValue*/ false,
16049                             /*IsConstexpr*/ true);
16050     if (FullAssertExpr.isInvalid())
16051       Failed = true;
16052     else
16053       AssertExpr = FullAssertExpr.get();
16054 
16055     llvm::APSInt Cond;
16056     if (!Failed && VerifyIntegerConstantExpression(
16057                        AssertExpr, &Cond,
16058                        diag::err_static_assert_expression_is_not_constant)
16059                        .isInvalid())
16060       Failed = true;
16061 
16062     if (!Failed && !Cond) {
16063       SmallString<256> MsgBuffer;
16064       llvm::raw_svector_ostream Msg(MsgBuffer);
16065       if (AssertMessage)
16066         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16067 
16068       Expr *InnerCond = nullptr;
16069       std::string InnerCondDescription;
16070       std::tie(InnerCond, InnerCondDescription) =
16071         findFailedBooleanCondition(Converted.get());
16072       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16073         // Drill down into concept specialization expressions to see why they
16074         // weren't satisfied.
16075         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16076           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16077         ConstraintSatisfaction Satisfaction;
16078         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16079           DiagnoseUnsatisfiedConstraint(Satisfaction);
16080       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16081                            && !isa<IntegerLiteral>(InnerCond)) {
16082         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16083           << InnerCondDescription << !AssertMessage
16084           << Msg.str() << InnerCond->getSourceRange();
16085       } else {
16086         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16087           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16088       }
16089       Failed = true;
16090     }
16091   } else {
16092     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16093                                                     /*DiscardedValue*/false,
16094                                                     /*IsConstexpr*/true);
16095     if (FullAssertExpr.isInvalid())
16096       Failed = true;
16097     else
16098       AssertExpr = FullAssertExpr.get();
16099   }
16100 
16101   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16102                                         AssertExpr, AssertMessage, RParenLoc,
16103                                         Failed);
16104 
16105   CurContext->addDecl(Decl);
16106   return Decl;
16107 }
16108 
16109 /// Perform semantic analysis of the given friend type declaration.
16110 ///
16111 /// \returns A friend declaration that.
CheckFriendTypeDecl(SourceLocation LocStart,SourceLocation FriendLoc,TypeSourceInfo * TSInfo)16112 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16113                                       SourceLocation FriendLoc,
16114                                       TypeSourceInfo *TSInfo) {
16115   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16116 
16117   QualType T = TSInfo->getType();
16118   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16119 
16120   // C++03 [class.friend]p2:
16121   //   An elaborated-type-specifier shall be used in a friend declaration
16122   //   for a class.*
16123   //
16124   //   * The class-key of the elaborated-type-specifier is required.
16125   if (!CodeSynthesisContexts.empty()) {
16126     // Do not complain about the form of friend template types during any kind
16127     // of code synthesis. For template instantiation, we will have complained
16128     // when the template was defined.
16129   } else {
16130     if (!T->isElaboratedTypeSpecifier()) {
16131       // If we evaluated the type to a record type, suggest putting
16132       // a tag in front.
16133       if (const RecordType *RT = T->getAs<RecordType>()) {
16134         RecordDecl *RD = RT->getDecl();
16135 
16136         SmallString<16> InsertionText(" ");
16137         InsertionText += RD->getKindName();
16138 
16139         Diag(TypeRange.getBegin(),
16140              getLangOpts().CPlusPlus11 ?
16141                diag::warn_cxx98_compat_unelaborated_friend_type :
16142                diag::ext_unelaborated_friend_type)
16143           << (unsigned) RD->getTagKind()
16144           << T
16145           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16146                                         InsertionText);
16147       } else {
16148         Diag(FriendLoc,
16149              getLangOpts().CPlusPlus11 ?
16150                diag::warn_cxx98_compat_nonclass_type_friend :
16151                diag::ext_nonclass_type_friend)
16152           << T
16153           << TypeRange;
16154       }
16155     } else if (T->getAs<EnumType>()) {
16156       Diag(FriendLoc,
16157            getLangOpts().CPlusPlus11 ?
16158              diag::warn_cxx98_compat_enum_friend :
16159              diag::ext_enum_friend)
16160         << T
16161         << TypeRange;
16162     }
16163 
16164     // C++11 [class.friend]p3:
16165     //   A friend declaration that does not declare a function shall have one
16166     //   of the following forms:
16167     //     friend elaborated-type-specifier ;
16168     //     friend simple-type-specifier ;
16169     //     friend typename-specifier ;
16170     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16171       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16172   }
16173 
16174   //   If the type specifier in a friend declaration designates a (possibly
16175   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16176   //   the friend declaration is ignored.
16177   return FriendDecl::Create(Context, CurContext,
16178                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16179                             FriendLoc);
16180 }
16181 
16182 /// Handle a friend tag declaration where the scope specifier was
16183 /// templated.
ActOnTemplatedFriendTag(Scope * S,SourceLocation FriendLoc,unsigned TagSpec,SourceLocation TagLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,const ParsedAttributesView & Attr,MultiTemplateParamsArg TempParamLists)16184 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16185                                     unsigned TagSpec, SourceLocation TagLoc,
16186                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16187                                     SourceLocation NameLoc,
16188                                     const ParsedAttributesView &Attr,
16189                                     MultiTemplateParamsArg TempParamLists) {
16190   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16191 
16192   bool IsMemberSpecialization = false;
16193   bool Invalid = false;
16194 
16195   if (TemplateParameterList *TemplateParams =
16196           MatchTemplateParametersToScopeSpecifier(
16197               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16198               IsMemberSpecialization, Invalid)) {
16199     if (TemplateParams->size() > 0) {
16200       // This is a declaration of a class template.
16201       if (Invalid)
16202         return nullptr;
16203 
16204       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16205                                 NameLoc, Attr, TemplateParams, AS_public,
16206                                 /*ModulePrivateLoc=*/SourceLocation(),
16207                                 FriendLoc, TempParamLists.size() - 1,
16208                                 TempParamLists.data()).get();
16209     } else {
16210       // The "template<>" header is extraneous.
16211       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16212         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16213       IsMemberSpecialization = true;
16214     }
16215   }
16216 
16217   if (Invalid) return nullptr;
16218 
16219   bool isAllExplicitSpecializations = true;
16220   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16221     if (TempParamLists[I]->size()) {
16222       isAllExplicitSpecializations = false;
16223       break;
16224     }
16225   }
16226 
16227   // FIXME: don't ignore attributes.
16228 
16229   // If it's explicit specializations all the way down, just forget
16230   // about the template header and build an appropriate non-templated
16231   // friend.  TODO: for source fidelity, remember the headers.
16232   if (isAllExplicitSpecializations) {
16233     if (SS.isEmpty()) {
16234       bool Owned = false;
16235       bool IsDependent = false;
16236       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16237                       Attr, AS_public,
16238                       /*ModulePrivateLoc=*/SourceLocation(),
16239                       MultiTemplateParamsArg(), Owned, IsDependent,
16240                       /*ScopedEnumKWLoc=*/SourceLocation(),
16241                       /*ScopedEnumUsesClassTag=*/false,
16242                       /*UnderlyingType=*/TypeResult(),
16243                       /*IsTypeSpecifier=*/false,
16244                       /*IsTemplateParamOrArg=*/false);
16245     }
16246 
16247     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16248     ElaboratedTypeKeyword Keyword
16249       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16250     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16251                                    *Name, NameLoc);
16252     if (T.isNull())
16253       return nullptr;
16254 
16255     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16256     if (isa<DependentNameType>(T)) {
16257       DependentNameTypeLoc TL =
16258           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16259       TL.setElaboratedKeywordLoc(TagLoc);
16260       TL.setQualifierLoc(QualifierLoc);
16261       TL.setNameLoc(NameLoc);
16262     } else {
16263       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16264       TL.setElaboratedKeywordLoc(TagLoc);
16265       TL.setQualifierLoc(QualifierLoc);
16266       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16267     }
16268 
16269     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16270                                             TSI, FriendLoc, TempParamLists);
16271     Friend->setAccess(AS_public);
16272     CurContext->addDecl(Friend);
16273     return Friend;
16274   }
16275 
16276   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16277 
16278 
16279 
16280   // Handle the case of a templated-scope friend class.  e.g.
16281   //   template <class T> class A<T>::B;
16282   // FIXME: we don't support these right now.
16283   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16284     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16285   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16286   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16287   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16288   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16289   TL.setElaboratedKeywordLoc(TagLoc);
16290   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16291   TL.setNameLoc(NameLoc);
16292 
16293   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16294                                           TSI, FriendLoc, TempParamLists);
16295   Friend->setAccess(AS_public);
16296   Friend->setUnsupportedFriend(true);
16297   CurContext->addDecl(Friend);
16298   return Friend;
16299 }
16300 
16301 /// Handle a friend type declaration.  This works in tandem with
16302 /// ActOnTag.
16303 ///
16304 /// Notes on friend class templates:
16305 ///
16306 /// We generally treat friend class declarations as if they were
16307 /// declaring a class.  So, for example, the elaborated type specifier
16308 /// in a friend declaration is required to obey the restrictions of a
16309 /// class-head (i.e. no typedefs in the scope chain), template
16310 /// parameters are required to match up with simple template-ids, &c.
16311 /// However, unlike when declaring a template specialization, it's
16312 /// okay to refer to a template specialization without an empty
16313 /// template parameter declaration, e.g.
16314 ///   friend class A<T>::B<unsigned>;
16315 /// We permit this as a special case; if there are any template
16316 /// parameters present at all, require proper matching, i.e.
16317 ///   template <> template \<class T> friend class A<int>::B;
ActOnFriendTypeDecl(Scope * S,const DeclSpec & DS,MultiTemplateParamsArg TempParams)16318 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16319                                 MultiTemplateParamsArg TempParams) {
16320   SourceLocation Loc = DS.getBeginLoc();
16321 
16322   assert(DS.isFriendSpecified());
16323   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16324 
16325   // C++ [class.friend]p3:
16326   // A friend declaration that does not declare a function shall have one of
16327   // the following forms:
16328   //     friend elaborated-type-specifier ;
16329   //     friend simple-type-specifier ;
16330   //     friend typename-specifier ;
16331   //
16332   // Any declaration with a type qualifier does not have that form. (It's
16333   // legal to specify a qualified type as a friend, you just can't write the
16334   // keywords.)
16335   if (DS.getTypeQualifiers()) {
16336     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16337       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16338     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16339       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16340     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16341       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16342     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16343       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16344     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16345       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16346   }
16347 
16348   // Try to convert the decl specifier to a type.  This works for
16349   // friend templates because ActOnTag never produces a ClassTemplateDecl
16350   // for a TUK_Friend.
16351   Declarator TheDeclarator(DS, DeclaratorContext::Member);
16352   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16353   QualType T = TSI->getType();
16354   if (TheDeclarator.isInvalidType())
16355     return nullptr;
16356 
16357   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16358     return nullptr;
16359 
16360   // This is definitely an error in C++98.  It's probably meant to
16361   // be forbidden in C++0x, too, but the specification is just
16362   // poorly written.
16363   //
16364   // The problem is with declarations like the following:
16365   //   template <T> friend A<T>::foo;
16366   // where deciding whether a class C is a friend or not now hinges
16367   // on whether there exists an instantiation of A that causes
16368   // 'foo' to equal C.  There are restrictions on class-heads
16369   // (which we declare (by fiat) elaborated friend declarations to
16370   // be) that makes this tractable.
16371   //
16372   // FIXME: handle "template <> friend class A<T>;", which
16373   // is possibly well-formed?  Who even knows?
16374   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16375     Diag(Loc, diag::err_tagless_friend_type_template)
16376       << DS.getSourceRange();
16377     return nullptr;
16378   }
16379 
16380   // C++98 [class.friend]p1: A friend of a class is a function
16381   //   or class that is not a member of the class . . .
16382   // This is fixed in DR77, which just barely didn't make the C++03
16383   // deadline.  It's also a very silly restriction that seriously
16384   // affects inner classes and which nobody else seems to implement;
16385   // thus we never diagnose it, not even in -pedantic.
16386   //
16387   // But note that we could warn about it: it's always useless to
16388   // friend one of your own members (it's not, however, worthless to
16389   // friend a member of an arbitrary specialization of your template).
16390 
16391   Decl *D;
16392   if (!TempParams.empty())
16393     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16394                                    TempParams,
16395                                    TSI,
16396                                    DS.getFriendSpecLoc());
16397   else
16398     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16399 
16400   if (!D)
16401     return nullptr;
16402 
16403   D->setAccess(AS_public);
16404   CurContext->addDecl(D);
16405 
16406   return D;
16407 }
16408 
ActOnFriendFunctionDecl(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParams)16409 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16410                                         MultiTemplateParamsArg TemplateParams) {
16411   const DeclSpec &DS = D.getDeclSpec();
16412 
16413   assert(DS.isFriendSpecified());
16414   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16415 
16416   SourceLocation Loc = D.getIdentifierLoc();
16417   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16418 
16419   // C++ [class.friend]p1
16420   //   A friend of a class is a function or class....
16421   // Note that this sees through typedefs, which is intended.
16422   // It *doesn't* see through dependent types, which is correct
16423   // according to [temp.arg.type]p3:
16424   //   If a declaration acquires a function type through a
16425   //   type dependent on a template-parameter and this causes
16426   //   a declaration that does not use the syntactic form of a
16427   //   function declarator to have a function type, the program
16428   //   is ill-formed.
16429   if (!TInfo->getType()->isFunctionType()) {
16430     Diag(Loc, diag::err_unexpected_friend);
16431 
16432     // It might be worthwhile to try to recover by creating an
16433     // appropriate declaration.
16434     return nullptr;
16435   }
16436 
16437   // C++ [namespace.memdef]p3
16438   //  - If a friend declaration in a non-local class first declares a
16439   //    class or function, the friend class or function is a member
16440   //    of the innermost enclosing namespace.
16441   //  - The name of the friend is not found by simple name lookup
16442   //    until a matching declaration is provided in that namespace
16443   //    scope (either before or after the class declaration granting
16444   //    friendship).
16445   //  - If a friend function is called, its name may be found by the
16446   //    name lookup that considers functions from namespaces and
16447   //    classes associated with the types of the function arguments.
16448   //  - When looking for a prior declaration of a class or a function
16449   //    declared as a friend, scopes outside the innermost enclosing
16450   //    namespace scope are not considered.
16451 
16452   CXXScopeSpec &SS = D.getCXXScopeSpec();
16453   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16454   assert(NameInfo.getName());
16455 
16456   // Check for unexpanded parameter packs.
16457   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16458       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16459       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16460     return nullptr;
16461 
16462   // The context we found the declaration in, or in which we should
16463   // create the declaration.
16464   DeclContext *DC;
16465   Scope *DCScope = S;
16466   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16467                         ForExternalRedeclaration);
16468 
16469   // There are five cases here.
16470   //   - There's no scope specifier and we're in a local class. Only look
16471   //     for functions declared in the immediately-enclosing block scope.
16472   // We recover from invalid scope qualifiers as if they just weren't there.
16473   FunctionDecl *FunctionContainingLocalClass = nullptr;
16474   if ((SS.isInvalid() || !SS.isSet()) &&
16475       (FunctionContainingLocalClass =
16476            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16477     // C++11 [class.friend]p11:
16478     //   If a friend declaration appears in a local class and the name
16479     //   specified is an unqualified name, a prior declaration is
16480     //   looked up without considering scopes that are outside the
16481     //   innermost enclosing non-class scope. For a friend function
16482     //   declaration, if there is no prior declaration, the program is
16483     //   ill-formed.
16484 
16485     // Find the innermost enclosing non-class scope. This is the block
16486     // scope containing the local class definition (or for a nested class,
16487     // the outer local class).
16488     DCScope = S->getFnParent();
16489 
16490     // Look up the function name in the scope.
16491     Previous.clear(LookupLocalFriendName);
16492     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16493 
16494     if (!Previous.empty()) {
16495       // All possible previous declarations must have the same context:
16496       // either they were declared at block scope or they are members of
16497       // one of the enclosing local classes.
16498       DC = Previous.getRepresentativeDecl()->getDeclContext();
16499     } else {
16500       // This is ill-formed, but provide the context that we would have
16501       // declared the function in, if we were permitted to, for error recovery.
16502       DC = FunctionContainingLocalClass;
16503     }
16504     adjustContextForLocalExternDecl(DC);
16505 
16506     // C++ [class.friend]p6:
16507     //   A function can be defined in a friend declaration of a class if and
16508     //   only if the class is a non-local class (9.8), the function name is
16509     //   unqualified, and the function has namespace scope.
16510     if (D.isFunctionDefinition()) {
16511       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16512     }
16513 
16514   //   - There's no scope specifier, in which case we just go to the
16515   //     appropriate scope and look for a function or function template
16516   //     there as appropriate.
16517   } else if (SS.isInvalid() || !SS.isSet()) {
16518     // C++11 [namespace.memdef]p3:
16519     //   If the name in a friend declaration is neither qualified nor
16520     //   a template-id and the declaration is a function or an
16521     //   elaborated-type-specifier, the lookup to determine whether
16522     //   the entity has been previously declared shall not consider
16523     //   any scopes outside the innermost enclosing namespace.
16524     bool isTemplateId =
16525         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16526 
16527     // Find the appropriate context according to the above.
16528     DC = CurContext;
16529 
16530     // Skip class contexts.  If someone can cite chapter and verse
16531     // for this behavior, that would be nice --- it's what GCC and
16532     // EDG do, and it seems like a reasonable intent, but the spec
16533     // really only says that checks for unqualified existing
16534     // declarations should stop at the nearest enclosing namespace,
16535     // not that they should only consider the nearest enclosing
16536     // namespace.
16537     while (DC->isRecord())
16538       DC = DC->getParent();
16539 
16540     DeclContext *LookupDC = DC;
16541     while (LookupDC->isTransparentContext())
16542       LookupDC = LookupDC->getParent();
16543 
16544     while (true) {
16545       LookupQualifiedName(Previous, LookupDC);
16546 
16547       if (!Previous.empty()) {
16548         DC = LookupDC;
16549         break;
16550       }
16551 
16552       if (isTemplateId) {
16553         if (isa<TranslationUnitDecl>(LookupDC)) break;
16554       } else {
16555         if (LookupDC->isFileContext()) break;
16556       }
16557       LookupDC = LookupDC->getParent();
16558     }
16559 
16560     DCScope = getScopeForDeclContext(S, DC);
16561 
16562   //   - There's a non-dependent scope specifier, in which case we
16563   //     compute it and do a previous lookup there for a function
16564   //     or function template.
16565   } else if (!SS.getScopeRep()->isDependent()) {
16566     DC = computeDeclContext(SS);
16567     if (!DC) return nullptr;
16568 
16569     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16570 
16571     LookupQualifiedName(Previous, DC);
16572 
16573     // C++ [class.friend]p1: A friend of a class is a function or
16574     //   class that is not a member of the class . . .
16575     if (DC->Equals(CurContext))
16576       Diag(DS.getFriendSpecLoc(),
16577            getLangOpts().CPlusPlus11 ?
16578              diag::warn_cxx98_compat_friend_is_member :
16579              diag::err_friend_is_member);
16580 
16581     if (D.isFunctionDefinition()) {
16582       // C++ [class.friend]p6:
16583       //   A function can be defined in a friend declaration of a class if and
16584       //   only if the class is a non-local class (9.8), the function name is
16585       //   unqualified, and the function has namespace scope.
16586       //
16587       // FIXME: We should only do this if the scope specifier names the
16588       // innermost enclosing namespace; otherwise the fixit changes the
16589       // meaning of the code.
16590       SemaDiagnosticBuilder DB
16591         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16592 
16593       DB << SS.getScopeRep();
16594       if (DC->isFileContext())
16595         DB << FixItHint::CreateRemoval(SS.getRange());
16596       SS.clear();
16597     }
16598 
16599   //   - There's a scope specifier that does not match any template
16600   //     parameter lists, in which case we use some arbitrary context,
16601   //     create a method or method template, and wait for instantiation.
16602   //   - There's a scope specifier that does match some template
16603   //     parameter lists, which we don't handle right now.
16604   } else {
16605     if (D.isFunctionDefinition()) {
16606       // C++ [class.friend]p6:
16607       //   A function can be defined in a friend declaration of a class if and
16608       //   only if the class is a non-local class (9.8), the function name is
16609       //   unqualified, and the function has namespace scope.
16610       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16611         << SS.getScopeRep();
16612     }
16613 
16614     DC = CurContext;
16615     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16616   }
16617 
16618   if (!DC->isRecord()) {
16619     int DiagArg = -1;
16620     switch (D.getName().getKind()) {
16621     case UnqualifiedIdKind::IK_ConstructorTemplateId:
16622     case UnqualifiedIdKind::IK_ConstructorName:
16623       DiagArg = 0;
16624       break;
16625     case UnqualifiedIdKind::IK_DestructorName:
16626       DiagArg = 1;
16627       break;
16628     case UnqualifiedIdKind::IK_ConversionFunctionId:
16629       DiagArg = 2;
16630       break;
16631     case UnqualifiedIdKind::IK_DeductionGuideName:
16632       DiagArg = 3;
16633       break;
16634     case UnqualifiedIdKind::IK_Identifier:
16635     case UnqualifiedIdKind::IK_ImplicitSelfParam:
16636     case UnqualifiedIdKind::IK_LiteralOperatorId:
16637     case UnqualifiedIdKind::IK_OperatorFunctionId:
16638     case UnqualifiedIdKind::IK_TemplateId:
16639       break;
16640     }
16641     // This implies that it has to be an operator or function.
16642     if (DiagArg >= 0) {
16643       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16644       return nullptr;
16645     }
16646   }
16647 
16648   // FIXME: This is an egregious hack to cope with cases where the scope stack
16649   // does not contain the declaration context, i.e., in an out-of-line
16650   // definition of a class.
16651   Scope FakeDCScope(S, Scope::DeclScope, Diags);
16652   if (!DCScope) {
16653     FakeDCScope.setEntity(DC);
16654     DCScope = &FakeDCScope;
16655   }
16656 
16657   bool AddToScope = true;
16658   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16659                                           TemplateParams, AddToScope);
16660   if (!ND) return nullptr;
16661 
16662   assert(ND->getLexicalDeclContext() == CurContext);
16663 
16664   // If we performed typo correction, we might have added a scope specifier
16665   // and changed the decl context.
16666   DC = ND->getDeclContext();
16667 
16668   // Add the function declaration to the appropriate lookup tables,
16669   // adjusting the redeclarations list as necessary.  We don't
16670   // want to do this yet if the friending class is dependent.
16671   //
16672   // Also update the scope-based lookup if the target context's
16673   // lookup context is in lexical scope.
16674   if (!CurContext->isDependentContext()) {
16675     DC = DC->getRedeclContext();
16676     DC->makeDeclVisibleInContext(ND);
16677     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16678       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16679   }
16680 
16681   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16682                                        D.getIdentifierLoc(), ND,
16683                                        DS.getFriendSpecLoc());
16684   FrD->setAccess(AS_public);
16685   CurContext->addDecl(FrD);
16686 
16687   if (ND->isInvalidDecl()) {
16688     FrD->setInvalidDecl();
16689   } else {
16690     if (DC->isRecord()) CheckFriendAccess(ND);
16691 
16692     FunctionDecl *FD;
16693     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16694       FD = FTD->getTemplatedDecl();
16695     else
16696       FD = cast<FunctionDecl>(ND);
16697 
16698     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16699     // default argument expression, that declaration shall be a definition
16700     // and shall be the only declaration of the function or function
16701     // template in the translation unit.
16702     if (functionDeclHasDefaultArgument(FD)) {
16703       // We can't look at FD->getPreviousDecl() because it may not have been set
16704       // if we're in a dependent context. If the function is known to be a
16705       // redeclaration, we will have narrowed Previous down to the right decl.
16706       if (D.isRedeclaration()) {
16707         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16708         Diag(Previous.getRepresentativeDecl()->getLocation(),
16709              diag::note_previous_declaration);
16710       } else if (!D.isFunctionDefinition())
16711         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16712     }
16713 
16714     // Mark templated-scope function declarations as unsupported.
16715     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16716       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16717         << SS.getScopeRep() << SS.getRange()
16718         << cast<CXXRecordDecl>(CurContext);
16719       FrD->setUnsupportedFriend(true);
16720     }
16721   }
16722 
16723   return ND;
16724 }
16725 
SetDeclDeleted(Decl * Dcl,SourceLocation DelLoc)16726 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16727   AdjustDeclIfTemplate(Dcl);
16728 
16729   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16730   if (!Fn) {
16731     Diag(DelLoc, diag::err_deleted_non_function);
16732     return;
16733   }
16734 
16735   // Deleted function does not have a body.
16736   Fn->setWillHaveBody(false);
16737 
16738   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16739     // Don't consider the implicit declaration we generate for explicit
16740     // specializations. FIXME: Do not generate these implicit declarations.
16741     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16742          Prev->getPreviousDecl()) &&
16743         !Prev->isDefined()) {
16744       Diag(DelLoc, diag::err_deleted_decl_not_first);
16745       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16746            Prev->isImplicit() ? diag::note_previous_implicit_declaration
16747                               : diag::note_previous_declaration);
16748       // We can't recover from this; the declaration might have already
16749       // been used.
16750       Fn->setInvalidDecl();
16751       return;
16752     }
16753 
16754     // To maintain the invariant that functions are only deleted on their first
16755     // declaration, mark the implicitly-instantiated declaration of the
16756     // explicitly-specialized function as deleted instead of marking the
16757     // instantiated redeclaration.
16758     Fn = Fn->getCanonicalDecl();
16759   }
16760 
16761   // dllimport/dllexport cannot be deleted.
16762   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16763     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16764     Fn->setInvalidDecl();
16765   }
16766 
16767   // C++11 [basic.start.main]p3:
16768   //   A program that defines main as deleted [...] is ill-formed.
16769   if (Fn->isMain())
16770     Diag(DelLoc, diag::err_deleted_main);
16771 
16772   // C++11 [dcl.fct.def.delete]p4:
16773   //  A deleted function is implicitly inline.
16774   Fn->setImplicitlyInline();
16775   Fn->setDeletedAsWritten();
16776 }
16777 
SetDeclDefaulted(Decl * Dcl,SourceLocation DefaultLoc)16778 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16779   if (!Dcl || Dcl->isInvalidDecl())
16780     return;
16781 
16782   auto *FD = dyn_cast<FunctionDecl>(Dcl);
16783   if (!FD) {
16784     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16785       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16786         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16787         return;
16788       }
16789     }
16790 
16791     Diag(DefaultLoc, diag::err_default_special_members)
16792         << getLangOpts().CPlusPlus20;
16793     return;
16794   }
16795 
16796   // Reject if this can't possibly be a defaultable function.
16797   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16798   if (!DefKind &&
16799       // A dependent function that doesn't locally look defaultable can
16800       // still instantiate to a defaultable function if it's a constructor
16801       // or assignment operator.
16802       (!FD->isDependentContext() ||
16803        (!isa<CXXConstructorDecl>(FD) &&
16804         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16805     Diag(DefaultLoc, diag::err_default_special_members)
16806         << getLangOpts().CPlusPlus20;
16807     return;
16808   }
16809 
16810   if (DefKind.isComparison() &&
16811       !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16812     Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16813         << (int)DefKind.asComparison();
16814     return;
16815   }
16816 
16817   // Issue compatibility warning. We already warned if the operator is
16818   // 'operator<=>' when parsing the '<=>' token.
16819   if (DefKind.isComparison() &&
16820       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16821     Diag(DefaultLoc, getLangOpts().CPlusPlus20
16822                          ? diag::warn_cxx17_compat_defaulted_comparison
16823                          : diag::ext_defaulted_comparison);
16824   }
16825 
16826   FD->setDefaulted();
16827   FD->setExplicitlyDefaulted();
16828 
16829   // Defer checking functions that are defaulted in a dependent context.
16830   if (FD->isDependentContext())
16831     return;
16832 
16833   // Unset that we will have a body for this function. We might not,
16834   // if it turns out to be trivial, and we don't need this marking now
16835   // that we've marked it as defaulted.
16836   FD->setWillHaveBody(false);
16837 
16838   // If this definition appears within the record, do the checking when
16839   // the record is complete. This is always the case for a defaulted
16840   // comparison.
16841   if (DefKind.isComparison())
16842     return;
16843   auto *MD = cast<CXXMethodDecl>(FD);
16844 
16845   const FunctionDecl *Primary = FD;
16846   if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16847     // Ask the template instantiation pattern that actually had the
16848     // '= default' on it.
16849     Primary = Pattern;
16850 
16851   // If the method was defaulted on its first declaration, we will have
16852   // already performed the checking in CheckCompletedCXXClass. Such a
16853   // declaration doesn't trigger an implicit definition.
16854   if (Primary->getCanonicalDecl()->isDefaulted())
16855     return;
16856 
16857   // FIXME: Once we support defining comparisons out of class, check for a
16858   // defaulted comparison here.
16859   if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16860     MD->setInvalidDecl();
16861   else
16862     DefineDefaultedFunction(*this, MD, DefaultLoc);
16863 }
16864 
SearchForReturnInStmt(Sema & Self,Stmt * S)16865 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16866   for (Stmt *SubStmt : S->children()) {
16867     if (!SubStmt)
16868       continue;
16869     if (isa<ReturnStmt>(SubStmt))
16870       Self.Diag(SubStmt->getBeginLoc(),
16871                 diag::err_return_in_constructor_handler);
16872     if (!isa<Expr>(SubStmt))
16873       SearchForReturnInStmt(Self, SubStmt);
16874   }
16875 }
16876 
DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt * TryBlock)16877 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16878   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16879     CXXCatchStmt *Handler = TryBlock->getHandler(I);
16880     SearchForReturnInStmt(*this, Handler);
16881   }
16882 }
16883 
CheckOverridingFunctionAttributes(const CXXMethodDecl * New,const CXXMethodDecl * Old)16884 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16885                                              const CXXMethodDecl *Old) {
16886   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16887   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16888 
16889   if (OldFT->hasExtParameterInfos()) {
16890     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16891       // A parameter of the overriding method should be annotated with noescape
16892       // if the corresponding parameter of the overridden method is annotated.
16893       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16894           !NewFT->getExtParameterInfo(I).isNoEscape()) {
16895         Diag(New->getParamDecl(I)->getLocation(),
16896              diag::warn_overriding_method_missing_noescape);
16897         Diag(Old->getParamDecl(I)->getLocation(),
16898              diag::note_overridden_marked_noescape);
16899       }
16900   }
16901 
16902   // Virtual overrides must have the same code_seg.
16903   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16904   const auto *NewCSA = New->getAttr<CodeSegAttr>();
16905   if ((NewCSA || OldCSA) &&
16906       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16907     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16908     Diag(Old->getLocation(), diag::note_previous_declaration);
16909     return true;
16910   }
16911 
16912   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16913 
16914   // If the calling conventions match, everything is fine
16915   if (NewCC == OldCC)
16916     return false;
16917 
16918   // If the calling conventions mismatch because the new function is static,
16919   // suppress the calling convention mismatch error; the error about static
16920   // function override (err_static_overrides_virtual from
16921   // Sema::CheckFunctionDeclaration) is more clear.
16922   if (New->getStorageClass() == SC_Static)
16923     return false;
16924 
16925   Diag(New->getLocation(),
16926        diag::err_conflicting_overriding_cc_attributes)
16927     << New->getDeclName() << New->getType() << Old->getType();
16928   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16929   return true;
16930 }
16931 
CheckOverridingFunctionReturnType(const CXXMethodDecl * New,const CXXMethodDecl * Old)16932 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
16933                                              const CXXMethodDecl *Old) {
16934   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
16935   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
16936 
16937   if (Context.hasSameType(NewTy, OldTy) ||
16938       NewTy->isDependentType() || OldTy->isDependentType())
16939     return false;
16940 
16941   // Check if the return types are covariant
16942   QualType NewClassTy, OldClassTy;
16943 
16944   /// Both types must be pointers or references to classes.
16945   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
16946     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
16947       NewClassTy = NewPT->getPointeeType();
16948       OldClassTy = OldPT->getPointeeType();
16949     }
16950   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
16951     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
16952       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
16953         NewClassTy = NewRT->getPointeeType();
16954         OldClassTy = OldRT->getPointeeType();
16955       }
16956     }
16957   }
16958 
16959   // The return types aren't either both pointers or references to a class type.
16960   if (NewClassTy.isNull()) {
16961     Diag(New->getLocation(),
16962          diag::err_different_return_type_for_overriding_virtual_function)
16963         << New->getDeclName() << NewTy << OldTy
16964         << New->getReturnTypeSourceRange();
16965     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16966         << Old->getReturnTypeSourceRange();
16967 
16968     return true;
16969   }
16970 
16971   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
16972     // C++14 [class.virtual]p8:
16973     //   If the class type in the covariant return type of D::f differs from
16974     //   that of B::f, the class type in the return type of D::f shall be
16975     //   complete at the point of declaration of D::f or shall be the class
16976     //   type D.
16977     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
16978       if (!RT->isBeingDefined() &&
16979           RequireCompleteType(New->getLocation(), NewClassTy,
16980                               diag::err_covariant_return_incomplete,
16981                               New->getDeclName()))
16982         return true;
16983     }
16984 
16985     // Check if the new class derives from the old class.
16986     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
16987       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
16988           << New->getDeclName() << NewTy << OldTy
16989           << New->getReturnTypeSourceRange();
16990       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16991           << Old->getReturnTypeSourceRange();
16992       return true;
16993     }
16994 
16995     // Check if we the conversion from derived to base is valid.
16996     if (CheckDerivedToBaseConversion(
16997             NewClassTy, OldClassTy,
16998             diag::err_covariant_return_inaccessible_base,
16999             diag::err_covariant_return_ambiguous_derived_to_base_conv,
17000             New->getLocation(), New->getReturnTypeSourceRange(),
17001             New->getDeclName(), nullptr)) {
17002       // FIXME: this note won't trigger for delayed access control
17003       // diagnostics, and it's impossible to get an undelayed error
17004       // here from access control during the original parse because
17005       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17006       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17007           << Old->getReturnTypeSourceRange();
17008       return true;
17009     }
17010   }
17011 
17012   // The qualifiers of the return types must be the same.
17013   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17014     Diag(New->getLocation(),
17015          diag::err_covariant_return_type_different_qualifications)
17016         << New->getDeclName() << NewTy << OldTy
17017         << New->getReturnTypeSourceRange();
17018     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17019         << Old->getReturnTypeSourceRange();
17020     return true;
17021   }
17022 
17023 
17024   // The new class type must have the same or less qualifiers as the old type.
17025   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17026     Diag(New->getLocation(),
17027          diag::err_covariant_return_type_class_type_more_qualified)
17028         << New->getDeclName() << NewTy << OldTy
17029         << New->getReturnTypeSourceRange();
17030     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17031         << Old->getReturnTypeSourceRange();
17032     return true;
17033   }
17034 
17035   return false;
17036 }
17037 
17038 /// Mark the given method pure.
17039 ///
17040 /// \param Method the method to be marked pure.
17041 ///
17042 /// \param InitRange the source range that covers the "0" initializer.
CheckPureMethod(CXXMethodDecl * Method,SourceRange InitRange)17043 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17044   SourceLocation EndLoc = InitRange.getEnd();
17045   if (EndLoc.isValid())
17046     Method->setRangeEnd(EndLoc);
17047 
17048   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17049     Method->setPure();
17050     return false;
17051   }
17052 
17053   if (!Method->isInvalidDecl())
17054     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17055       << Method->getDeclName() << InitRange;
17056   return true;
17057 }
17058 
ActOnPureSpecifier(Decl * D,SourceLocation ZeroLoc)17059 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17060   if (D->getFriendObjectKind())
17061     Diag(D->getLocation(), diag::err_pure_friend);
17062   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17063     CheckPureMethod(M, ZeroLoc);
17064   else
17065     Diag(D->getLocation(), diag::err_illegal_initializer);
17066 }
17067 
17068 /// Determine whether the given declaration is a global variable or
17069 /// static data member.
isNonlocalVariable(const Decl * D)17070 static bool isNonlocalVariable(const Decl *D) {
17071   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17072     return Var->hasGlobalStorage();
17073 
17074   return false;
17075 }
17076 
17077 /// Invoked when we are about to parse an initializer for the declaration
17078 /// 'Dcl'.
17079 ///
17080 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17081 /// static data member of class X, names should be looked up in the scope of
17082 /// class X. If the declaration had a scope specifier, a scope will have
17083 /// been created and passed in for this purpose. Otherwise, S will be null.
ActOnCXXEnterDeclInitializer(Scope * S,Decl * D)17084 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17085   // If there is no declaration, there was an error parsing it.
17086   if (!D || D->isInvalidDecl())
17087     return;
17088 
17089   // We will always have a nested name specifier here, but this declaration
17090   // might not be out of line if the specifier names the current namespace:
17091   //   extern int n;
17092   //   int ::n = 0;
17093   if (S && D->isOutOfLine())
17094     EnterDeclaratorContext(S, D->getDeclContext());
17095 
17096   // If we are parsing the initializer for a static data member, push a
17097   // new expression evaluation context that is associated with this static
17098   // data member.
17099   if (isNonlocalVariable(D))
17100     PushExpressionEvaluationContext(
17101         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17102 }
17103 
17104 /// Invoked after we are finished parsing an initializer for the declaration D.
ActOnCXXExitDeclInitializer(Scope * S,Decl * D)17105 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17106   // If there is no declaration, there was an error parsing it.
17107   if (!D || D->isInvalidDecl())
17108     return;
17109 
17110   if (isNonlocalVariable(D))
17111     PopExpressionEvaluationContext();
17112 
17113   if (S && D->isOutOfLine())
17114     ExitDeclaratorContext(S);
17115 }
17116 
17117 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17118 /// C++ if/switch/while/for statement.
17119 /// e.g: "if (int x = f()) {...}"
ActOnCXXConditionDeclaration(Scope * S,Declarator & D)17120 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17121   // C++ 6.4p2:
17122   // The declarator shall not specify a function or an array.
17123   // The type-specifier-seq shall not contain typedef and shall not declare a
17124   // new class or enumeration.
17125   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17126          "Parser allowed 'typedef' as storage class of condition decl.");
17127 
17128   Decl *Dcl = ActOnDeclarator(S, D);
17129   if (!Dcl)
17130     return true;
17131 
17132   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17133     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17134       << D.getSourceRange();
17135     return true;
17136   }
17137 
17138   return Dcl;
17139 }
17140 
LoadExternalVTableUses()17141 void Sema::LoadExternalVTableUses() {
17142   if (!ExternalSource)
17143     return;
17144 
17145   SmallVector<ExternalVTableUse, 4> VTables;
17146   ExternalSource->ReadUsedVTables(VTables);
17147   SmallVector<VTableUse, 4> NewUses;
17148   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17149     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17150       = VTablesUsed.find(VTables[I].Record);
17151     // Even if a definition wasn't required before, it may be required now.
17152     if (Pos != VTablesUsed.end()) {
17153       if (!Pos->second && VTables[I].DefinitionRequired)
17154         Pos->second = true;
17155       continue;
17156     }
17157 
17158     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17159     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17160   }
17161 
17162   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17163 }
17164 
MarkVTableUsed(SourceLocation Loc,CXXRecordDecl * Class,bool DefinitionRequired)17165 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17166                           bool DefinitionRequired) {
17167   // Ignore any vtable uses in unevaluated operands or for classes that do
17168   // not have a vtable.
17169   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17170       CurContext->isDependentContext() || isUnevaluatedContext())
17171     return;
17172   // Do not mark as used if compiling for the device outside of the target
17173   // region.
17174   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17175       !isInOpenMPDeclareTargetContext() &&
17176       !isInOpenMPTargetExecutionDirective()) {
17177     if (!DefinitionRequired)
17178       MarkVirtualMembersReferenced(Loc, Class);
17179     return;
17180   }
17181 
17182   // Try to insert this class into the map.
17183   LoadExternalVTableUses();
17184   Class = Class->getCanonicalDecl();
17185   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17186     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17187   if (!Pos.second) {
17188     // If we already had an entry, check to see if we are promoting this vtable
17189     // to require a definition. If so, we need to reappend to the VTableUses
17190     // list, since we may have already processed the first entry.
17191     if (DefinitionRequired && !Pos.first->second) {
17192       Pos.first->second = true;
17193     } else {
17194       // Otherwise, we can early exit.
17195       return;
17196     }
17197   } else {
17198     // The Microsoft ABI requires that we perform the destructor body
17199     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17200     // the deleting destructor is emitted with the vtable, not with the
17201     // destructor definition as in the Itanium ABI.
17202     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17203       CXXDestructorDecl *DD = Class->getDestructor();
17204       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17205         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17206           // If this is an out-of-line declaration, marking it referenced will
17207           // not do anything. Manually call CheckDestructor to look up operator
17208           // delete().
17209           ContextRAII SavedContext(*this, DD);
17210           CheckDestructor(DD);
17211         } else {
17212           MarkFunctionReferenced(Loc, Class->getDestructor());
17213         }
17214       }
17215     }
17216   }
17217 
17218   // Local classes need to have their virtual members marked
17219   // immediately. For all other classes, we mark their virtual members
17220   // at the end of the translation unit.
17221   if (Class->isLocalClass())
17222     MarkVirtualMembersReferenced(Loc, Class);
17223   else
17224     VTableUses.push_back(std::make_pair(Class, Loc));
17225 }
17226 
DefineUsedVTables()17227 bool Sema::DefineUsedVTables() {
17228   LoadExternalVTableUses();
17229   if (VTableUses.empty())
17230     return false;
17231 
17232   // Note: The VTableUses vector could grow as a result of marking
17233   // the members of a class as "used", so we check the size each
17234   // time through the loop and prefer indices (which are stable) to
17235   // iterators (which are not).
17236   bool DefinedAnything = false;
17237   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17238     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17239     if (!Class)
17240       continue;
17241     TemplateSpecializationKind ClassTSK =
17242         Class->getTemplateSpecializationKind();
17243 
17244     SourceLocation Loc = VTableUses[I].second;
17245 
17246     bool DefineVTable = true;
17247 
17248     // If this class has a key function, but that key function is
17249     // defined in another translation unit, we don't need to emit the
17250     // vtable even though we're using it.
17251     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17252     if (KeyFunction && !KeyFunction->hasBody()) {
17253       // The key function is in another translation unit.
17254       DefineVTable = false;
17255       TemplateSpecializationKind TSK =
17256           KeyFunction->getTemplateSpecializationKind();
17257       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17258              TSK != TSK_ImplicitInstantiation &&
17259              "Instantiations don't have key functions");
17260       (void)TSK;
17261     } else if (!KeyFunction) {
17262       // If we have a class with no key function that is the subject
17263       // of an explicit instantiation declaration, suppress the
17264       // vtable; it will live with the explicit instantiation
17265       // definition.
17266       bool IsExplicitInstantiationDeclaration =
17267           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17268       for (auto R : Class->redecls()) {
17269         TemplateSpecializationKind TSK
17270           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17271         if (TSK == TSK_ExplicitInstantiationDeclaration)
17272           IsExplicitInstantiationDeclaration = true;
17273         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17274           IsExplicitInstantiationDeclaration = false;
17275           break;
17276         }
17277       }
17278 
17279       if (IsExplicitInstantiationDeclaration)
17280         DefineVTable = false;
17281     }
17282 
17283     // The exception specifications for all virtual members may be needed even
17284     // if we are not providing an authoritative form of the vtable in this TU.
17285     // We may choose to emit it available_externally anyway.
17286     if (!DefineVTable) {
17287       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17288       continue;
17289     }
17290 
17291     // Mark all of the virtual members of this class as referenced, so
17292     // that we can build a vtable. Then, tell the AST consumer that a
17293     // vtable for this class is required.
17294     DefinedAnything = true;
17295     MarkVirtualMembersReferenced(Loc, Class);
17296     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17297     if (VTablesUsed[Canonical])
17298       Consumer.HandleVTable(Class);
17299 
17300     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17301     // no key function or the key function is inlined. Don't warn in C++ ABIs
17302     // that lack key functions, since the user won't be able to make one.
17303     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17304         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17305       const FunctionDecl *KeyFunctionDef = nullptr;
17306       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17307                            KeyFunctionDef->isInlined())) {
17308         Diag(Class->getLocation(),
17309              ClassTSK == TSK_ExplicitInstantiationDefinition
17310                  ? diag::warn_weak_template_vtable
17311                  : diag::warn_weak_vtable)
17312             << Class;
17313       }
17314     }
17315   }
17316   VTableUses.clear();
17317 
17318   return DefinedAnything;
17319 }
17320 
MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,const CXXRecordDecl * RD)17321 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17322                                                  const CXXRecordDecl *RD) {
17323   for (const auto *I : RD->methods())
17324     if (I->isVirtual() && !I->isPure())
17325       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17326 }
17327 
MarkVirtualMembersReferenced(SourceLocation Loc,const CXXRecordDecl * RD,bool ConstexprOnly)17328 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17329                                         const CXXRecordDecl *RD,
17330                                         bool ConstexprOnly) {
17331   // Mark all functions which will appear in RD's vtable as used.
17332   CXXFinalOverriderMap FinalOverriders;
17333   RD->getFinalOverriders(FinalOverriders);
17334   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17335                                             E = FinalOverriders.end();
17336        I != E; ++I) {
17337     for (OverridingMethods::const_iterator OI = I->second.begin(),
17338                                            OE = I->second.end();
17339          OI != OE; ++OI) {
17340       assert(OI->second.size() > 0 && "no final overrider");
17341       CXXMethodDecl *Overrider = OI->second.front().Method;
17342 
17343       // C++ [basic.def.odr]p2:
17344       //   [...] A virtual member function is used if it is not pure. [...]
17345       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17346         MarkFunctionReferenced(Loc, Overrider);
17347     }
17348   }
17349 
17350   // Only classes that have virtual bases need a VTT.
17351   if (RD->getNumVBases() == 0)
17352     return;
17353 
17354   for (const auto &I : RD->bases()) {
17355     const auto *Base =
17356         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17357     if (Base->getNumVBases() == 0)
17358       continue;
17359     MarkVirtualMembersReferenced(Loc, Base);
17360   }
17361 }
17362 
17363 /// SetIvarInitializers - This routine builds initialization ASTs for the
17364 /// Objective-C implementation whose ivars need be initialized.
SetIvarInitializers(ObjCImplementationDecl * ObjCImplementation)17365 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17366   if (!getLangOpts().CPlusPlus)
17367     return;
17368   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17369     SmallVector<ObjCIvarDecl*, 8> ivars;
17370     CollectIvarsToConstructOrDestruct(OID, ivars);
17371     if (ivars.empty())
17372       return;
17373     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17374     for (unsigned i = 0; i < ivars.size(); i++) {
17375       FieldDecl *Field = ivars[i];
17376       if (Field->isInvalidDecl())
17377         continue;
17378 
17379       CXXCtorInitializer *Member;
17380       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17381       InitializationKind InitKind =
17382         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17383 
17384       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17385       ExprResult MemberInit =
17386         InitSeq.Perform(*this, InitEntity, InitKind, None);
17387       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17388       // Note, MemberInit could actually come back empty if no initialization
17389       // is required (e.g., because it would call a trivial default constructor)
17390       if (!MemberInit.get() || MemberInit.isInvalid())
17391         continue;
17392 
17393       Member =
17394         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17395                                          SourceLocation(),
17396                                          MemberInit.getAs<Expr>(),
17397                                          SourceLocation());
17398       AllToInit.push_back(Member);
17399 
17400       // Be sure that the destructor is accessible and is marked as referenced.
17401       if (const RecordType *RecordTy =
17402               Context.getBaseElementType(Field->getType())
17403                   ->getAs<RecordType>()) {
17404         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17405         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17406           MarkFunctionReferenced(Field->getLocation(), Destructor);
17407           CheckDestructorAccess(Field->getLocation(), Destructor,
17408                             PDiag(diag::err_access_dtor_ivar)
17409                               << Context.getBaseElementType(Field->getType()));
17410         }
17411       }
17412     }
17413     ObjCImplementation->setIvarInitializers(Context,
17414                                             AllToInit.data(), AllToInit.size());
17415   }
17416 }
17417 
17418 static
DelegatingCycleHelper(CXXConstructorDecl * Ctor,llvm::SmallPtrSet<CXXConstructorDecl *,4> & Valid,llvm::SmallPtrSet<CXXConstructorDecl *,4> & Invalid,llvm::SmallPtrSet<CXXConstructorDecl *,4> & Current,Sema & S)17419 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17420                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17421                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17422                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17423                            Sema &S) {
17424   if (Ctor->isInvalidDecl())
17425     return;
17426 
17427   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17428 
17429   // Target may not be determinable yet, for instance if this is a dependent
17430   // call in an uninstantiated template.
17431   if (Target) {
17432     const FunctionDecl *FNTarget = nullptr;
17433     (void)Target->hasBody(FNTarget);
17434     Target = const_cast<CXXConstructorDecl*>(
17435       cast_or_null<CXXConstructorDecl>(FNTarget));
17436   }
17437 
17438   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17439                      // Avoid dereferencing a null pointer here.
17440                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17441 
17442   if (!Current.insert(Canonical).second)
17443     return;
17444 
17445   // We know that beyond here, we aren't chaining into a cycle.
17446   if (!Target || !Target->isDelegatingConstructor() ||
17447       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17448     Valid.insert(Current.begin(), Current.end());
17449     Current.clear();
17450   // We've hit a cycle.
17451   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17452              Current.count(TCanonical)) {
17453     // If we haven't diagnosed this cycle yet, do so now.
17454     if (!Invalid.count(TCanonical)) {
17455       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17456              diag::warn_delegating_ctor_cycle)
17457         << Ctor;
17458 
17459       // Don't add a note for a function delegating directly to itself.
17460       if (TCanonical != Canonical)
17461         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17462 
17463       CXXConstructorDecl *C = Target;
17464       while (C->getCanonicalDecl() != Canonical) {
17465         const FunctionDecl *FNTarget = nullptr;
17466         (void)C->getTargetConstructor()->hasBody(FNTarget);
17467         assert(FNTarget && "Ctor cycle through bodiless function");
17468 
17469         C = const_cast<CXXConstructorDecl*>(
17470           cast<CXXConstructorDecl>(FNTarget));
17471         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17472       }
17473     }
17474 
17475     Invalid.insert(Current.begin(), Current.end());
17476     Current.clear();
17477   } else {
17478     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17479   }
17480 }
17481 
17482 
CheckDelegatingCtorCycles()17483 void Sema::CheckDelegatingCtorCycles() {
17484   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17485 
17486   for (DelegatingCtorDeclsType::iterator
17487          I = DelegatingCtorDecls.begin(ExternalSource),
17488          E = DelegatingCtorDecls.end();
17489        I != E; ++I)
17490     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17491 
17492   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17493     (*CI)->setInvalidDecl();
17494 }
17495 
17496 namespace {
17497   /// AST visitor that finds references to the 'this' expression.
17498   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17499     Sema &S;
17500 
17501   public:
FindCXXThisExpr(Sema & S)17502     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17503 
VisitCXXThisExpr(CXXThisExpr * E)17504     bool VisitCXXThisExpr(CXXThisExpr *E) {
17505       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17506         << E->isImplicit();
17507       return false;
17508     }
17509   };
17510 }
17511 
checkThisInStaticMemberFunctionType(CXXMethodDecl * Method)17512 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17513   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17514   if (!TSInfo)
17515     return false;
17516 
17517   TypeLoc TL = TSInfo->getTypeLoc();
17518   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17519   if (!ProtoTL)
17520     return false;
17521 
17522   // C++11 [expr.prim.general]p3:
17523   //   [The expression this] shall not appear before the optional
17524   //   cv-qualifier-seq and it shall not appear within the declaration of a
17525   //   static member function (although its type and value category are defined
17526   //   within a static member function as they are within a non-static member
17527   //   function). [ Note: this is because declaration matching does not occur
17528   //  until the complete declarator is known. - end note ]
17529   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17530   FindCXXThisExpr Finder(*this);
17531 
17532   // If the return type came after the cv-qualifier-seq, check it now.
17533   if (Proto->hasTrailingReturn() &&
17534       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17535     return true;
17536 
17537   // Check the exception specification.
17538   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17539     return true;
17540 
17541   // Check the trailing requires clause
17542   if (Expr *E = Method->getTrailingRequiresClause())
17543     if (!Finder.TraverseStmt(E))
17544       return true;
17545 
17546   return checkThisInStaticMemberFunctionAttributes(Method);
17547 }
17548 
checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl * Method)17549 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17550   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17551   if (!TSInfo)
17552     return false;
17553 
17554   TypeLoc TL = TSInfo->getTypeLoc();
17555   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17556   if (!ProtoTL)
17557     return false;
17558 
17559   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17560   FindCXXThisExpr Finder(*this);
17561 
17562   switch (Proto->getExceptionSpecType()) {
17563   case EST_Unparsed:
17564   case EST_Uninstantiated:
17565   case EST_Unevaluated:
17566   case EST_BasicNoexcept:
17567   case EST_NoThrow:
17568   case EST_DynamicNone:
17569   case EST_MSAny:
17570   case EST_None:
17571     break;
17572 
17573   case EST_DependentNoexcept:
17574   case EST_NoexceptFalse:
17575   case EST_NoexceptTrue:
17576     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17577       return true;
17578     LLVM_FALLTHROUGH;
17579 
17580   case EST_Dynamic:
17581     for (const auto &E : Proto->exceptions()) {
17582       if (!Finder.TraverseType(E))
17583         return true;
17584     }
17585     break;
17586   }
17587 
17588   return false;
17589 }
17590 
checkThisInStaticMemberFunctionAttributes(CXXMethodDecl * Method)17591 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17592   FindCXXThisExpr Finder(*this);
17593 
17594   // Check attributes.
17595   for (const auto *A : Method->attrs()) {
17596     // FIXME: This should be emitted by tblgen.
17597     Expr *Arg = nullptr;
17598     ArrayRef<Expr *> Args;
17599     if (const auto *G = dyn_cast<GuardedByAttr>(A))
17600       Arg = G->getArg();
17601     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17602       Arg = G->getArg();
17603     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17604       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17605     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17606       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17607     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17608       Arg = ETLF->getSuccessValue();
17609       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17610     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17611       Arg = STLF->getSuccessValue();
17612       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17613     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17614       Arg = LR->getArg();
17615     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17616       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17617     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17618       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17619     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17620       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17621     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17622       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17623     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17624       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17625 
17626     if (Arg && !Finder.TraverseStmt(Arg))
17627       return true;
17628 
17629     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17630       if (!Finder.TraverseStmt(Args[I]))
17631         return true;
17632     }
17633   }
17634 
17635   return false;
17636 }
17637 
checkExceptionSpecification(bool IsTopLevel,ExceptionSpecificationType EST,ArrayRef<ParsedType> DynamicExceptions,ArrayRef<SourceRange> DynamicExceptionRanges,Expr * NoexceptExpr,SmallVectorImpl<QualType> & Exceptions,FunctionProtoType::ExceptionSpecInfo & ESI)17638 void Sema::checkExceptionSpecification(
17639     bool IsTopLevel, ExceptionSpecificationType EST,
17640     ArrayRef<ParsedType> DynamicExceptions,
17641     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17642     SmallVectorImpl<QualType> &Exceptions,
17643     FunctionProtoType::ExceptionSpecInfo &ESI) {
17644   Exceptions.clear();
17645   ESI.Type = EST;
17646   if (EST == EST_Dynamic) {
17647     Exceptions.reserve(DynamicExceptions.size());
17648     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17649       // FIXME: Preserve type source info.
17650       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17651 
17652       if (IsTopLevel) {
17653         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17654         collectUnexpandedParameterPacks(ET, Unexpanded);
17655         if (!Unexpanded.empty()) {
17656           DiagnoseUnexpandedParameterPacks(
17657               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17658               Unexpanded);
17659           continue;
17660         }
17661       }
17662 
17663       // Check that the type is valid for an exception spec, and
17664       // drop it if not.
17665       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17666         Exceptions.push_back(ET);
17667     }
17668     ESI.Exceptions = Exceptions;
17669     return;
17670   }
17671 
17672   if (isComputedNoexcept(EST)) {
17673     assert((NoexceptExpr->isTypeDependent() ||
17674             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
17675             Context.BoolTy) &&
17676            "Parser should have made sure that the expression is boolean");
17677     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17678       ESI.Type = EST_BasicNoexcept;
17679       return;
17680     }
17681 
17682     ESI.NoexceptExpr = NoexceptExpr;
17683     return;
17684   }
17685 }
17686 
actOnDelayedExceptionSpecification(Decl * MethodD,ExceptionSpecificationType EST,SourceRange SpecificationRange,ArrayRef<ParsedType> DynamicExceptions,ArrayRef<SourceRange> DynamicExceptionRanges,Expr * NoexceptExpr)17687 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17688              ExceptionSpecificationType EST,
17689              SourceRange SpecificationRange,
17690              ArrayRef<ParsedType> DynamicExceptions,
17691              ArrayRef<SourceRange> DynamicExceptionRanges,
17692              Expr *NoexceptExpr) {
17693   if (!MethodD)
17694     return;
17695 
17696   // Dig out the method we're referring to.
17697   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17698     MethodD = FunTmpl->getTemplatedDecl();
17699 
17700   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17701   if (!Method)
17702     return;
17703 
17704   // Check the exception specification.
17705   llvm::SmallVector<QualType, 4> Exceptions;
17706   FunctionProtoType::ExceptionSpecInfo ESI;
17707   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17708                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
17709                               ESI);
17710 
17711   // Update the exception specification on the function type.
17712   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17713 
17714   if (Method->isStatic())
17715     checkThisInStaticMemberFunctionExceptionSpec(Method);
17716 
17717   if (Method->isVirtual()) {
17718     // Check overrides, which we previously had to delay.
17719     for (const CXXMethodDecl *O : Method->overridden_methods())
17720       CheckOverridingFunctionExceptionSpec(Method, O);
17721   }
17722 }
17723 
17724 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17725 ///
HandleMSProperty(Scope * S,RecordDecl * Record,SourceLocation DeclStart,Declarator & D,Expr * BitWidth,InClassInitStyle InitStyle,AccessSpecifier AS,const ParsedAttr & MSPropertyAttr)17726 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17727                                        SourceLocation DeclStart, Declarator &D,
17728                                        Expr *BitWidth,
17729                                        InClassInitStyle InitStyle,
17730                                        AccessSpecifier AS,
17731                                        const ParsedAttr &MSPropertyAttr) {
17732   IdentifierInfo *II = D.getIdentifier();
17733   if (!II) {
17734     Diag(DeclStart, diag::err_anonymous_property);
17735     return nullptr;
17736   }
17737   SourceLocation Loc = D.getIdentifierLoc();
17738 
17739   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17740   QualType T = TInfo->getType();
17741   if (getLangOpts().CPlusPlus) {
17742     CheckExtraCXXDefaultArguments(D);
17743 
17744     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17745                                         UPPC_DataMemberType)) {
17746       D.setInvalidType();
17747       T = Context.IntTy;
17748       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17749     }
17750   }
17751 
17752   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17753 
17754   if (D.getDeclSpec().isInlineSpecified())
17755     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17756         << getLangOpts().CPlusPlus17;
17757   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17758     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17759          diag::err_invalid_thread)
17760       << DeclSpec::getSpecifierName(TSCS);
17761 
17762   // Check to see if this name was declared as a member previously
17763   NamedDecl *PrevDecl = nullptr;
17764   LookupResult Previous(*this, II, Loc, LookupMemberName,
17765                         ForVisibleRedeclaration);
17766   LookupName(Previous, S);
17767   switch (Previous.getResultKind()) {
17768   case LookupResult::Found:
17769   case LookupResult::FoundUnresolvedValue:
17770     PrevDecl = Previous.getAsSingle<NamedDecl>();
17771     break;
17772 
17773   case LookupResult::FoundOverloaded:
17774     PrevDecl = Previous.getRepresentativeDecl();
17775     break;
17776 
17777   case LookupResult::NotFound:
17778   case LookupResult::NotFoundInCurrentInstantiation:
17779   case LookupResult::Ambiguous:
17780     break;
17781   }
17782 
17783   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17784     // Maybe we will complain about the shadowed template parameter.
17785     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17786     // Just pretend that we didn't see the previous declaration.
17787     PrevDecl = nullptr;
17788   }
17789 
17790   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17791     PrevDecl = nullptr;
17792 
17793   SourceLocation TSSL = D.getBeginLoc();
17794   MSPropertyDecl *NewPD =
17795       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17796                              MSPropertyAttr.getPropertyDataGetter(),
17797                              MSPropertyAttr.getPropertyDataSetter());
17798   ProcessDeclAttributes(TUScope, NewPD, D);
17799   NewPD->setAccess(AS);
17800 
17801   if (NewPD->isInvalidDecl())
17802     Record->setInvalidDecl();
17803 
17804   if (D.getDeclSpec().isModulePrivateSpecified())
17805     NewPD->setModulePrivate();
17806 
17807   if (NewPD->isInvalidDecl() && PrevDecl) {
17808     // Don't introduce NewFD into scope; there's already something
17809     // with the same name in the same scope.
17810   } else if (II) {
17811     PushOnScopeChains(NewPD, S);
17812   } else
17813     Record->addDecl(NewPD);
17814 
17815   return NewPD;
17816 }
17817 
ActOnStartFunctionDeclarationDeclarator(Declarator & Declarator,unsigned TemplateParameterDepth)17818 void Sema::ActOnStartFunctionDeclarationDeclarator(
17819     Declarator &Declarator, unsigned TemplateParameterDepth) {
17820   auto &Info = InventedParameterInfos.emplace_back();
17821   TemplateParameterList *ExplicitParams = nullptr;
17822   ArrayRef<TemplateParameterList *> ExplicitLists =
17823       Declarator.getTemplateParameterLists();
17824   if (!ExplicitLists.empty()) {
17825     bool IsMemberSpecialization, IsInvalid;
17826     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17827         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17828         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17829         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17830         /*SuppressDiagnostic=*/true);
17831   }
17832   if (ExplicitParams) {
17833     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17834     for (NamedDecl *Param : *ExplicitParams)
17835       Info.TemplateParams.push_back(Param);
17836     Info.NumExplicitTemplateParams = ExplicitParams->size();
17837   } else {
17838     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17839     Info.NumExplicitTemplateParams = 0;
17840   }
17841 }
17842 
ActOnFinishFunctionDeclarationDeclarator(Declarator & Declarator)17843 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17844   auto &FSI = InventedParameterInfos.back();
17845   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17846     if (FSI.NumExplicitTemplateParams != 0) {
17847       TemplateParameterList *ExplicitParams =
17848           Declarator.getTemplateParameterLists().back();
17849       Declarator.setInventedTemplateParameterList(
17850           TemplateParameterList::Create(
17851               Context, ExplicitParams->getTemplateLoc(),
17852               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17853               ExplicitParams->getRAngleLoc(),
17854               ExplicitParams->getRequiresClause()));
17855     } else {
17856       Declarator.setInventedTemplateParameterList(
17857           TemplateParameterList::Create(
17858               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17859               SourceLocation(), /*RequiresClause=*/nullptr));
17860     }
17861   }
17862   InventedParameterInfos.pop_back();
17863 }
17864