clang  10.0.0svn
SemaDeclCXX.cpp
Go to the documentation of this file.
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"
18 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include <map>
44 #include <set>
45 
46 using namespace clang;
47 
48 //===----------------------------------------------------------------------===//
49 // CheckDefaultArgumentVisitor
50 //===----------------------------------------------------------------------===//
51 
52 namespace {
53  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54  /// the default argument of a parameter to determine whether it
55  /// contains any ill-formed subexpressions. For example, this will
56  /// diagnose the use of local variables or parameters within the
57  /// default argument expression.
58  class CheckDefaultArgumentVisitor
59  : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
60  Expr *DefaultArg;
61  Sema *S;
62 
63  public:
64  CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
65  : DefaultArg(defarg), S(s) {}
66 
67  bool VisitExpr(Expr *Node);
68  bool VisitDeclRefExpr(DeclRefExpr *DRE);
69  bool VisitCXXThisExpr(CXXThisExpr *ThisE);
70  bool VisitLambdaExpr(LambdaExpr *Lambda);
71  bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
72  };
73 
74  /// VisitExpr - Visit all of the children of this expression.
75  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76  bool IsInvalid = false;
77  for (Stmt *SubStmt : Node->children())
78  IsInvalid |= Visit(SubStmt);
79  return IsInvalid;
80  }
81 
82  /// VisitDeclRefExpr - Visit a reference to a declaration, to
83  /// determine whether this declaration can be used in the default
84  /// argument expression.
85  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
86  NamedDecl *Decl = DRE->getDecl();
87  if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88  // C++ [dcl.fct.default]p9
89  // Default arguments are evaluated each time the function is
90  // called. The order of evaluation of function arguments is
91  // unspecified. Consequently, parameters of a function shall not
92  // be used in default argument expressions, even if they are not
93  // evaluated. Parameters of a function declared before a default
94  // argument expression are in scope and can hide namespace and
95  // class member names.
96  return S->Diag(DRE->getBeginLoc(),
97  diag::err_param_default_argument_references_param)
98  << Param->getDeclName() << DefaultArg->getSourceRange();
99  } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
100  // C++ [dcl.fct.default]p7
101  // Local variables shall not be used in default argument
102  // expressions.
103  if (VDecl->isLocalVarDecl())
104  return S->Diag(DRE->getBeginLoc(),
105  diag::err_param_default_argument_references_local)
106  << VDecl->getDeclName() << DefaultArg->getSourceRange();
107  }
108 
109  return false;
110  }
111 
112  /// VisitCXXThisExpr - Visit a C++ "this" expression.
113  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114  // C++ [dcl.fct.default]p8:
115  // The keyword this shall not be used in a default argument of a
116  // member function.
117  return S->Diag(ThisE->getBeginLoc(),
118  diag::err_param_default_argument_references_this)
119  << ThisE->getSourceRange();
120  }
121 
122  bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123  bool Invalid = false;
125  i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126  Expr *E = *i;
127 
128  // Look through bindings.
129  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130  E = OVE->getSourceExpr();
131  assert(E && "pseudo-object binding without source expression?");
132  }
133 
134  Invalid |= Visit(E);
135  }
136  return Invalid;
137  }
138 
139  bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140  // C++11 [expr.lambda.prim]p13:
141  // A lambda-expression appearing in a default argument shall not
142  // implicitly or explicitly capture any entity.
143  if (Lambda->capture_begin() == Lambda->capture_end())
144  return false;
145 
146  return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
147  }
148 }
149 
150 void
152  const CXXMethodDecl *Method) {
153  // If we have an MSAny spec already, don't bother.
154  if (!Method || ComputedEST == EST_MSAny)
155  return;
156 
157  const FunctionProtoType *Proto
158  = Method->getType()->getAs<FunctionProtoType>();
159  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160  if (!Proto)
161  return;
162 
164 
165  // If we have a throw-all spec at this point, ignore the function.
166  if (ComputedEST == EST_None)
167  return;
168 
169  if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
170  EST = EST_BasicNoexcept;
171 
172  switch (EST) {
173  case EST_Unparsed:
174  case EST_Uninstantiated:
175  case EST_Unevaluated:
176  llvm_unreachable("should not see unresolved exception specs here");
177 
178  // If this function can throw any exceptions, make a note of that.
179  case EST_MSAny:
180  case EST_None:
181  // FIXME: Whichever we see last of MSAny and None determines our result.
182  // We should make a consistent, order-independent choice here.
183  ClearExceptions();
184  ComputedEST = EST;
185  return;
186  case EST_NoexceptFalse:
187  ClearExceptions();
188  ComputedEST = EST_None;
189  return;
190  // FIXME: If the call to this decl is using any of its default arguments, we
191  // need to search them for potentially-throwing calls.
192  // If this function has a basic noexcept, it doesn't affect the outcome.
193  case EST_BasicNoexcept:
194  case EST_NoexceptTrue:
195  case EST_NoThrow:
196  return;
197  // If we're still at noexcept(true) and there's a throw() callee,
198  // change to that specification.
199  case EST_DynamicNone:
200  if (ComputedEST == EST_BasicNoexcept)
201  ComputedEST = EST_DynamicNone;
202  return;
204  llvm_unreachable(
205  "should not generate implicit declarations for dependent cases");
206  case EST_Dynamic:
207  break;
208  }
209  assert(EST == EST_Dynamic && "EST case not considered earlier.");
210  assert(ComputedEST != EST_None &&
211  "Shouldn't collect exceptions when throw-all is guaranteed.");
212  ComputedEST = EST_Dynamic;
213  // Record the exceptions in this function's exception specification.
214  for (const auto &E : Proto->exceptions())
215  if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
216  Exceptions.push_back(E);
217 }
218 
220  if (!E || ComputedEST == EST_MSAny)
221  return;
222 
223  // FIXME:
224  //
225  // C++0x [except.spec]p14:
226  // [An] implicit exception-specification specifies the type-id T if and
227  // only if T is allowed by the exception-specification of a function directly
228  // invoked by f's implicit definition; f shall allow all exceptions if any
229  // function it directly invokes allows all exceptions, and f shall allow no
230  // exceptions if every function it directly invokes allows no exceptions.
231  //
232  // Note in particular that if an implicit exception-specification is generated
233  // for a function containing a throw-expression, that specification can still
234  // be noexcept(true).
235  //
236  // Note also that 'directly invoked' is not defined in the standard, and there
237  // is no indication that we should only consider potentially-evaluated calls.
238  //
239  // Ultimately we should implement the intent of the standard: the exception
240  // specification should be the set of exceptions which can be thrown by the
241  // implicit definition. For now, we assume that any non-nothrow expression can
242  // throw any exception.
243 
244  if (Self->canThrow(E))
245  ComputedEST = EST_None;
246 }
247 
248 bool
250  SourceLocation EqualLoc) {
251  if (RequireCompleteType(Param->getLocation(), Param->getType(),
252  diag::err_typecheck_decl_incomplete_type)) {
253  Param->setInvalidDecl();
254  return true;
255  }
256 
257  // C++ [dcl.fct.default]p5
258  // A default argument expression is implicitly converted (clause
259  // 4) to the parameter type. The default argument expression has
260  // the same semantic constraints as the initializer expression in
261  // a declaration of a variable of the parameter type, using the
262  // copy-initialization semantics (8.5).
264  Param);
266  EqualLoc);
267  InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269  if (Result.isInvalid())
270  return true;
271  Arg = Result.getAs<Expr>();
272 
273  CheckCompletedExpr(Arg, EqualLoc);
274  Arg = MaybeCreateExprWithCleanups(Arg);
275 
276  // Okay: add the default argument to the parameter
277  Param->setDefaultArg(Arg);
278 
279  // We have already instantiated this parameter; provide each of the
280  // instantiations with the uninstantiated default argument.
281  UnparsedDefaultArgInstantiationsMap::iterator InstPos
282  = UnparsedDefaultArgInstantiations.find(Param);
283  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284  for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285  InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286 
287  // We're done tracking this parameter's instantiations.
288  UnparsedDefaultArgInstantiations.erase(InstPos);
289  }
290 
291  return false;
292 }
293 
294 /// ActOnParamDefaultArgument - Check whether the default argument
295 /// provided for a function parameter is well-formed. If so, attach it
296 /// to the parameter declaration.
297 void
299  Expr *DefaultArg) {
300  if (!param || !DefaultArg)
301  return;
302 
303  ParmVarDecl *Param = cast<ParmVarDecl>(param);
304  UnparsedDefaultArgLocs.erase(Param);
305 
306  // Default arguments are only permitted in C++
307  if (!getLangOpts().CPlusPlus) {
308  Diag(EqualLoc, diag::err_param_default_argument)
309  << DefaultArg->getSourceRange();
310  Param->setInvalidDecl();
311  return;
312  }
313 
314  // Check for unexpanded parameter packs.
315  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316  Param->setInvalidDecl();
317  return;
318  }
319 
320  // C++11 [dcl.fct.default]p3
321  // A default argument expression [...] shall not be specified for a
322  // parameter pack.
323  if (Param->isParameterPack()) {
324  Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325  << DefaultArg->getSourceRange();
326  return;
327  }
328 
329  // Check that the default argument is well-formed
330  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331  if (DefaultArgChecker.Visit(DefaultArg)) {
332  Param->setInvalidDecl();
333  return;
334  }
335 
336  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
337 }
338 
339 /// ActOnParamUnparsedDefaultArgument - We've seen a default
340 /// argument for a function parameter, but we can't parse it yet
341 /// because we're inside a class definition. Note that this default
342 /// argument will be parsed later.
344  SourceLocation EqualLoc,
345  SourceLocation ArgLoc) {
346  if (!param)
347  return;
348 
349  ParmVarDecl *Param = cast<ParmVarDecl>(param);
350  Param->setUnparsedDefaultArg();
351  UnparsedDefaultArgLocs[Param] = ArgLoc;
352 }
353 
354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355 /// the default argument for the parameter param failed.
357  SourceLocation EqualLoc) {
358  if (!param)
359  return;
360 
361  ParmVarDecl *Param = cast<ParmVarDecl>(param);
362  Param->setInvalidDecl();
363  UnparsedDefaultArgLocs.erase(Param);
364  Param->setDefaultArg(new(Context)
365  OpaqueValueExpr(EqualLoc,
366  Param->getType().getNonReferenceType(),
367  VK_RValue));
368 }
369 
370 /// CheckExtraCXXDefaultArguments - Check for any extra default
371 /// arguments in the declarator, which is not a function declaration
372 /// or definition and therefore is not permitted to have default
373 /// arguments. This routine should be invoked for every declarator
374 /// that is not a function declaration or definition.
376  // C++ [dcl.fct.default]p3
377  // A default argument expression shall be specified only in the
378  // parameter-declaration-clause of a function declaration or in a
379  // template-parameter (14.1). It shall not be specified for a
380  // parameter pack. If it is specified in a
381  // parameter-declaration-clause, it shall not occur within a
382  // declarator or abstract-declarator of a parameter-declaration.
383  bool MightBeFunction = D.isFunctionDeclarationContext();
384  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
385  DeclaratorChunk &chunk = D.getTypeObject(i);
386  if (chunk.Kind == DeclaratorChunk::Function) {
387  if (MightBeFunction) {
388  // This is a function declaration. It can have default arguments, but
389  // keep looking in case its return type is a function type with default
390  // arguments.
391  MightBeFunction = false;
392  continue;
393  }
394  for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395  ++argIdx) {
396  ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
397  if (Param->hasUnparsedDefaultArg()) {
398  std::unique_ptr<CachedTokens> Toks =
399  std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
400  SourceRange SR;
401  if (Toks->size() > 1)
402  SR = SourceRange((*Toks)[1].getLocation(),
403  Toks->back().getLocation());
404  else
405  SR = UnparsedDefaultArgLocs[Param];
406  Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
407  << SR;
408  } else if (Param->getDefaultArg()) {
409  Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410  << Param->getDefaultArg()->getSourceRange();
411  Param->setDefaultArg(nullptr);
412  }
413  }
414  } else if (chunk.Kind != DeclaratorChunk::Paren) {
415  MightBeFunction = false;
416  }
417  }
418 }
419 
421  for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422  const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423  if (!PVD->hasDefaultArg())
424  return false;
425  if (!PVD->hasInheritedDefaultArg())
426  return true;
427  }
428  return false;
429 }
430 
431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
432 /// function, once we already know that they have the same
433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434 /// error, false otherwise.
436  Scope *S) {
437  bool Invalid = false;
438 
439  // The declaration context corresponding to the scope is the semantic
440  // parent, unless this is a local function declaration, in which case
441  // it is that surrounding function.
442  DeclContext *ScopeDC = New->isLocalExternDecl()
443  ? New->getLexicalDeclContext()
444  : New->getDeclContext();
445 
446  // Find the previous declaration for the purpose of default arguments.
447  FunctionDecl *PrevForDefaultArgs = Old;
448  for (/**/; PrevForDefaultArgs;
449  // Don't bother looking back past the latest decl if this is a local
450  // extern declaration; nothing else could work.
451  PrevForDefaultArgs = New->isLocalExternDecl()
452  ? nullptr
453  : PrevForDefaultArgs->getPreviousDecl()) {
454  // Ignore hidden declarations.
455  if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456  continue;
457 
458  if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459  !New->isCXXClassMember()) {
460  // Ignore default arguments of old decl if they are not in
461  // the same scope and this is not an out-of-line definition of
462  // a member function.
463  continue;
464  }
465 
466  if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467  // If only one of these is a local function declaration, then they are
468  // declared in different scopes, even though isDeclInScope may think
469  // they're in the same scope. (If both are local, the scope check is
470  // sufficient, and if neither is local, then they are in the same scope.)
471  continue;
472  }
473 
474  // We found the right previous declaration.
475  break;
476  }
477 
478  // C++ [dcl.fct.default]p4:
479  // For non-template functions, default arguments can be added in
480  // later declarations of a function in the same
481  // scope. Declarations in different scopes have completely
482  // distinct sets of default arguments. That is, declarations in
483  // inner scopes do not acquire default arguments from
484  // declarations in outer scopes, and vice versa. In a given
485  // function declaration, all parameters subsequent to a
486  // parameter with a default argument shall have default
487  // arguments supplied in this or previous declarations. A
488  // default argument shall not be redefined by a later
489  // declaration (not even to the same value).
490  //
491  // C++ [dcl.fct.default]p6:
492  // Except for member functions of class templates, the default arguments
493  // in a member function definition that appears outside of the class
494  // definition are added to the set of default arguments provided by the
495  // member function declaration in the class definition.
496  for (unsigned p = 0, NumParams = PrevForDefaultArgs
497  ? PrevForDefaultArgs->getNumParams()
498  : 0;
499  p < NumParams; ++p) {
500  ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
501  ParmVarDecl *NewParam = New->getParamDecl(p);
502 
503  bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
504  bool NewParamHasDfl = NewParam->hasDefaultArg();
505 
506  if (OldParamHasDfl && NewParamHasDfl) {
507  unsigned DiagDefaultParamID =
508  diag::err_param_default_argument_redefinition;
509 
510  // MSVC accepts that default parameters be redefined for member functions
511  // of template class. The new default parameter's value is ignored.
512  Invalid = true;
513  if (getLangOpts().MicrosoftExt) {
514  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
515  if (MD && MD->getParent()->getDescribedClassTemplate()) {
516  // Merge the old default argument into the new parameter.
517  NewParam->setHasInheritedDefaultArg();
518  if (OldParam->hasUninstantiatedDefaultArg())
519  NewParam->setUninstantiatedDefaultArg(
520  OldParam->getUninstantiatedDefaultArg());
521  else
522  NewParam->setDefaultArg(OldParam->getInit());
523  DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
524  Invalid = false;
525  }
526  }
527 
528  // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529  // hint here. Alternatively, we could walk the type-source information
530  // for NewParam to find the last source location in the type... but it
531  // isn't worth the effort right now. This is the kind of test case that
532  // is hard to get right:
533  // int f(int);
534  // void g(int (*fp)(int) = f);
535  // void g(int (*fp)(int) = &f);
536  Diag(NewParam->getLocation(), DiagDefaultParamID)
537  << NewParam->getDefaultArgRange();
538 
539  // Look for the function declaration where the default argument was
540  // actually written, which may be a declaration prior to Old.
541  for (auto Older = PrevForDefaultArgs;
542  OldParam->hasInheritedDefaultArg(); /**/) {
543  Older = Older->getPreviousDecl();
544  OldParam = Older->getParamDecl(p);
545  }
546 
547  Diag(OldParam->getLocation(), diag::note_previous_definition)
548  << OldParam->getDefaultArgRange();
549  } else if (OldParamHasDfl) {
550  // Merge the old default argument into the new parameter unless the new
551  // function is a friend declaration in a template class. In the latter
552  // case the default arguments will be inherited when the friend
553  // declaration will be instantiated.
554  if (New->getFriendObjectKind() == Decl::FOK_None ||
556  // It's important to use getInit() here; getDefaultArg()
557  // strips off any top-level ExprWithCleanups.
558  NewParam->setHasInheritedDefaultArg();
559  if (OldParam->hasUnparsedDefaultArg())
560  NewParam->setUnparsedDefaultArg();
561  else if (OldParam->hasUninstantiatedDefaultArg())
562  NewParam->setUninstantiatedDefaultArg(
563  OldParam->getUninstantiatedDefaultArg());
564  else
565  NewParam->setDefaultArg(OldParam->getInit());
566  }
567  } else if (NewParamHasDfl) {
568  if (New->getDescribedFunctionTemplate()) {
569  // Paragraph 4, quoted above, only applies to non-template functions.
570  Diag(NewParam->getLocation(),
571  diag::err_param_default_argument_template_redecl)
572  << NewParam->getDefaultArgRange();
573  Diag(PrevForDefaultArgs->getLocation(),
574  diag::note_template_prev_declaration)
575  << false;
576  } else if (New->getTemplateSpecializationKind()
579  // C++ [temp.expr.spec]p21:
580  // Default function arguments shall not be specified in a declaration
581  // or a definition for one of the following explicit specializations:
582  // - the explicit specialization of a function template;
583  // - the explicit specialization of a member function template;
584  // - the explicit specialization of a member function of a class
585  // template where the class template specialization to which the
586  // member function specialization belongs is implicitly
587  // instantiated.
588  Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
590  << New->getDeclName()
591  << NewParam->getDefaultArgRange();
592  } else if (New->getDeclContext()->isDependentContext()) {
593  // C++ [dcl.fct.default]p6 (DR217):
594  // Default arguments for a member function of a class template shall
595  // be specified on the initial declaration of the member function
596  // within the class template.
597  //
598  // Reading the tea leaves a bit in DR217 and its reference to DR205
599  // leads me to the conclusion that one cannot add default function
600  // arguments for an out-of-line definition of a member function of a
601  // dependent type.
602  int WhichKind = 2;
603  if (CXXRecordDecl *Record
604  = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
605  if (Record->getDescribedClassTemplate())
606  WhichKind = 0;
607  else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
608  WhichKind = 1;
609  else
610  WhichKind = 2;
611  }
612 
613  Diag(NewParam->getLocation(),
614  diag::err_param_default_argument_member_template_redecl)
615  << WhichKind
616  << NewParam->getDefaultArgRange();
617  }
618  }
619  }
620 
621  // DR1344: If a default argument is added outside a class definition and that
622  // default argument makes the function a special member function, the program
623  // is ill-formed. This can only happen for constructors.
624  if (isa<CXXConstructorDecl>(New) &&
626  CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
627  OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
628  if (NewSM != OldSM) {
629  ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
630  assert(NewParam->hasDefaultArg());
631  Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
632  << NewParam->getDefaultArgRange() << NewSM;
633  Diag(Old->getLocation(), diag::note_previous_declaration);
634  }
635  }
636 
637  const FunctionDecl *Def;
638  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
639  // template has a constexpr specifier then all its declarations shall
640  // contain the constexpr specifier.
641  if (New->getConstexprKind() != Old->getConstexprKind()) {
642  Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
643  << New << New->getConstexprKind() << Old->getConstexprKind();
644  Diag(Old->getLocation(), diag::note_previous_declaration);
645  Invalid = true;
646  } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
647  Old->isDefined(Def) &&
648  // If a friend function is inlined but does not have 'inline'
649  // specifier, it is a definition. Do not report attribute conflict
650  // in this case, redefinition will be diagnosed later.
651  (New->isInlineSpecified() ||
652  New->getFriendObjectKind() == Decl::FOK_None)) {
653  // C++11 [dcl.fcn.spec]p4:
654  // If the definition of a function appears in a translation unit before its
655  // first declaration as inline, the program is ill-formed.
656  Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
657  Diag(Def->getLocation(), diag::note_previous_definition);
658  Invalid = true;
659  }
660 
661  // C++17 [temp.deduct.guide]p3:
662  // Two deduction guide declarations in the same translation unit
663  // for the same class template shall not have equivalent
664  // parameter-declaration-clauses.
665  if (isa<CXXDeductionGuideDecl>(New) &&
667  Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
668  Diag(Old->getLocation(), diag::note_previous_declaration);
669  }
670 
671  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
672  // argument expression, that declaration shall be a definition and shall be
673  // the only declaration of the function or function template in the
674  // translation unit.
677  Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
678  Diag(Old->getLocation(), diag::note_previous_declaration);
679  Invalid = true;
680  }
681 
682  return Invalid;
683 }
684 
685 NamedDecl *
687  MultiTemplateParamsArg TemplateParamLists) {
688  assert(D.isDecompositionDeclarator());
690 
691  // The syntax only allows a decomposition declarator as a simple-declaration,
692  // a for-range-declaration, or a condition in Clang, but we parse it in more
693  // cases than that.
695  Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
696  << Decomp.getSourceRange();
697  return nullptr;
698  }
699 
700  if (!TemplateParamLists.empty()) {
701  // FIXME: There's no rule against this, but there are also no rules that
702  // would actually make it usable, so we reject it for now.
703  Diag(TemplateParamLists.front()->getTemplateLoc(),
704  diag::err_decomp_decl_template);
705  return nullptr;
706  }
707 
708  Diag(Decomp.getLSquareLoc(),
709  !getLangOpts().CPlusPlus17
710  ? diag::ext_decomp_decl
712  ? diag::ext_decomp_decl_cond
713  : diag::warn_cxx14_compat_decomp_decl)
714  << Decomp.getSourceRange();
715 
716  // The semantic context is always just the current context.
717  DeclContext *const DC = CurContext;
718 
719  // C++17 [dcl.dcl]/8:
720  // The decl-specifier-seq shall contain only the type-specifier auto
721  // and cv-qualifiers.
722  // C++2a [dcl.dcl]/8:
723  // If decl-specifier-seq contains any decl-specifier other than static,
724  // thread_local, auto, or cv-qualifiers, the program is ill-formed.
725  auto &DS = D.getDeclSpec();
726  {
727  SmallVector<StringRef, 8> BadSpecifiers;
728  SmallVector<SourceLocation, 8> BadSpecifierLocs;
729  SmallVector<StringRef, 8> CPlusPlus20Specifiers;
730  SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
731  if (auto SCS = DS.getStorageClassSpec()) {
732  if (SCS == DeclSpec::SCS_static) {
733  CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
734  CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
735  } else {
736  BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
737  BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
738  }
739  }
740  if (auto TSCS = DS.getThreadStorageClassSpec()) {
741  CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
742  CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
743  }
744  if (DS.hasConstexprSpecifier()) {
745  BadSpecifiers.push_back(
746  DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
747  BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
748  }
749  if (DS.isInlineSpecified()) {
750  BadSpecifiers.push_back("inline");
751  BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
752  }
753  if (!BadSpecifiers.empty()) {
754  auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
755  Err << (int)BadSpecifiers.size()
756  << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
757  // Don't add FixItHints to remove the specifiers; we do still respect
758  // them when building the underlying variable.
759  for (auto Loc : BadSpecifierLocs)
760  Err << SourceRange(Loc, Loc);
761  } else if (!CPlusPlus20Specifiers.empty()) {
762  auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
763  getLangOpts().CPlusPlus2a
764  ? diag::warn_cxx17_compat_decomp_decl_spec
765  : diag::ext_decomp_decl_spec);
766  Warn << (int)CPlusPlus20Specifiers.size()
767  << llvm::join(CPlusPlus20Specifiers.begin(),
768  CPlusPlus20Specifiers.end(), " ");
769  for (auto Loc : CPlusPlus20SpecifierLocs)
770  Warn << SourceRange(Loc, Loc);
771  }
772  // We can't recover from it being declared as a typedef.
773  if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
774  return nullptr;
775  }
776 
777  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
778  QualType R = TInfo->getType();
779 
780  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
781  UPPC_DeclarationType))
782  D.setInvalidType();
783 
784  // The syntax only allows a single ref-qualifier prior to the decomposition
785  // declarator. No other declarator chunks are permitted. Also check the type
786  // specifier here.
787  if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
788  D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
789  (D.getNumTypeObjects() == 1 &&
791  Diag(Decomp.getLSquareLoc(),
792  (D.hasGroupingParens() ||
793  (D.getNumTypeObjects() &&
795  ? diag::err_decomp_decl_parens
796  : diag::err_decomp_decl_type)
797  << R;
798 
799  // In most cases, there's no actual problem with an explicitly-specified
800  // type, but a function type won't work here, and ActOnVariableDeclarator
801  // shouldn't be called for such a type.
802  if (R->isFunctionType())
803  D.setInvalidType();
804  }
805 
806  // Build the BindingDecls.
808 
809  // Build the BindingDecls.
810  for (auto &B : D.getDecompositionDeclarator().bindings()) {
811  // Check for name conflicts.
812  DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
813  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
814  ForVisibleRedeclaration);
815  LookupName(Previous, S,
816  /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
817 
818  // It's not permitted to shadow a template parameter name.
819  if (Previous.isSingleResult() &&
820  Previous.getFoundDecl()->isTemplateParameter()) {
821  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
822  Previous.getFoundDecl());
823  Previous.clear();
824  }
825 
826  bool ConsiderLinkage = DC->isFunctionOrMethod() &&
827  DS.getStorageClassSpec() == DeclSpec::SCS_extern;
828  FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
829  /*AllowInlineNamespace*/false);
830  if (!Previous.empty()) {
831  auto *Old = Previous.getRepresentativeDecl();
832  Diag(B.NameLoc, diag::err_redefinition) << B.Name;
833  Diag(Old->getLocation(), diag::note_previous_definition);
834  }
835 
836  auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
837  PushOnScopeChains(BD, S, true);
838  Bindings.push_back(BD);
839  ParsingInitForAutoVars.insert(BD);
840  }
841 
842  // There are no prior lookup results for the variable itself, because it
843  // is unnamed.
844  DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
845  Decomp.getLSquareLoc());
846  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
847  ForVisibleRedeclaration);
848 
849  // Build the variable that holds the non-decomposed object.
850  bool AddToScope = true;
851  NamedDecl *New =
852  ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
853  MultiTemplateParamsArg(), AddToScope, Bindings);
854  if (AddToScope) {
855  S->AddDecl(New);
856  CurContext->addHiddenDecl(New);
857  }
858 
859  if (isInOpenMPDeclareTargetContext())
860  checkDeclIsAllowedInOpenMPTarget(nullptr, New);
861 
862  return New;
863 }
864 
866  Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
867  QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
868  llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
869  if ((int64_t)Bindings.size() != NumElems) {
870  S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
871  << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
872  << (NumElems < Bindings.size());
873  return true;
874  }
875 
876  unsigned I = 0;
877  for (auto *B : Bindings) {
878  SourceLocation Loc = B->getLocation();
879  ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
880  if (E.isInvalid())
881  return true;
882  E = GetInit(Loc, E.get(), I++);
883  if (E.isInvalid())
884  return true;
885  B->setBinding(ElemType, E.get());
886  }
887 
888  return false;
889 }
890 
892  ArrayRef<BindingDecl *> Bindings,
893  ValueDecl *Src, QualType DecompType,
894  const llvm::APSInt &NumElems,
895  QualType ElemType) {
897  S, Bindings, Src, DecompType, NumElems, ElemType,
898  [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
899  ExprResult E = S.ActOnIntegerConstant(Loc, I);
900  if (E.isInvalid())
901  return ExprError();
902  return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
903  });
904 }
905 
907  ValueDecl *Src, QualType DecompType,
908  const ConstantArrayType *CAT) {
909  return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
910  llvm::APSInt(CAT->getSize()),
911  CAT->getElementType());
912 }
913 
915  ValueDecl *Src, QualType DecompType,
916  const VectorType *VT) {
918  S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
920  DecompType.getQualifiers()));
921 }
922 
924  ArrayRef<BindingDecl *> Bindings,
925  ValueDecl *Src, QualType DecompType,
926  const ComplexType *CT) {
928  S, Bindings, Src, DecompType, llvm::APSInt::get(2),
930  DecompType.getQualifiers()),
931  [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
932  return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
933  });
934 }
935 
937  TemplateArgumentListInfo &Args) {
938  SmallString<128> SS;
939  llvm::raw_svector_ostream OS(SS);
940  bool First = true;
941  for (auto &Arg : Args.arguments()) {
942  if (!First)
943  OS << ", ";
944  Arg.getArgument().print(PrintingPolicy, OS);
945  First = false;
946  }
947  return OS.str();
948 }
949 
950 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
951  SourceLocation Loc, StringRef Trait,
953  unsigned DiagID) {
954  auto DiagnoseMissing = [&] {
955  if (DiagID)
956  S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
957  Args);
958  return true;
959  };
960 
961  // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
963  if (!Std)
964  return DiagnoseMissing();
965 
966  // Look up the trait itself, within namespace std. We can diagnose various
967  // problems with this lookup even if we've been asked to not diagnose a
968  // missing specialization, because this can only fail if the user has been
969  // declaring their own names in namespace std or we don't support the
970  // standard library implementation in use.
973  if (!S.LookupQualifiedName(Result, Std))
974  return DiagnoseMissing();
975  if (Result.isAmbiguous())
976  return true;
977 
978  ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
979  if (!TraitTD) {
980  Result.suppressDiagnostics();
981  NamedDecl *Found = *Result.begin();
982  S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
983  S.Diag(Found->getLocation(), diag::note_declared_at);
984  return true;
985  }
986 
987  // Build the template-id.
988  QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
989  if (TraitTy.isNull())
990  return true;
991  if (!S.isCompleteType(Loc, TraitTy)) {
992  if (DiagID)
994  Loc, TraitTy, DiagID,
996  return true;
997  }
998 
999  CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1000  assert(RD && "specialization of class template is not a class?");
1001 
1002  // Look up the member of the trait type.
1003  S.LookupQualifiedName(TraitMemberLookup, RD);
1004  return TraitMemberLookup.isAmbiguous();
1005 }
1006 
1007 static TemplateArgumentLoc
1009  uint64_t I) {
1010  TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1011  return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1012 }
1013 
1014 static TemplateArgumentLoc
1017 }
1018 
1019 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1020 
1022  llvm::APSInt &Size) {
1025 
1027  LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1028 
1029  // Form template argument list for tuple_size<T>.
1030  TemplateArgumentListInfo Args(Loc, Loc);
1032 
1033  // If there's no tuple_size specialization or the lookup of 'value' is empty,
1034  // it's not tuple-like.
1035  if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1036  R.empty())
1037  return IsTupleLike::NotTupleLike;
1038 
1039  // If we get this far, we've committed to the tuple interpretation, but
1040  // we can still fail if there actually isn't a usable ::value.
1041 
1042  struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1043  LookupResult &R;
1045  ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1046  : R(R), Args(Args) {}
1047  void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1048  S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1050  }
1051  } Diagnoser(R, Args);
1052 
1053  ExprResult E =
1054  S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1055  if (E.isInvalid())
1056  return IsTupleLike::Error;
1057 
1058  E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1059  if (E.isInvalid())
1060  return IsTupleLike::Error;
1061 
1062  return IsTupleLike::TupleLike;
1063 }
1064 
1065 /// \return std::tuple_element<I, T>::type.
1067  unsigned I, QualType T) {
1068  // Form template argument list for tuple_element<I, T>.
1069  TemplateArgumentListInfo Args(Loc, Loc);
1070  Args.addArgument(
1073 
1074  DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1075  LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1077  S, R, Loc, "tuple_element", Args,
1078  diag::err_decomp_decl_std_tuple_element_not_specialized))
1079  return QualType();
1080 
1081  auto *TD = R.getAsSingle<TypeDecl>();
1082  if (!TD) {
1083  R.suppressDiagnostics();
1084  S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1086  if (!R.empty())
1087  S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1088  return QualType();
1089  }
1090 
1091  return S.Context.getTypeDeclType(TD);
1092 }
1093 
1094 namespace {
1095 struct BindingDiagnosticTrap {
1096  Sema &S;
1097  DiagnosticErrorTrap Trap;
1098  BindingDecl *BD;
1099 
1100  BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1101  : S(S), Trap(S.Diags), BD(BD) {}
1102  ~BindingDiagnosticTrap() {
1103  if (Trap.hasErrorOccurred())
1104  S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1105  }
1106 };
1107 }
1108 
1110  ArrayRef<BindingDecl *> Bindings,
1111  VarDecl *Src, QualType DecompType,
1112  const llvm::APSInt &TupleSize) {
1113  if ((int64_t)Bindings.size() != TupleSize) {
1114  S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1115  << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1116  << (TupleSize < Bindings.size());
1117  return true;
1118  }
1119 
1120  if (Bindings.empty())
1121  return false;
1122 
1123  DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1124 
1125  // [dcl.decomp]p3:
1126  // The unqualified-id get is looked up in the scope of E by class member
1127  // access lookup ...
1128  LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1129  bool UseMemberGet = false;
1130  if (S.isCompleteType(Src->getLocation(), DecompType)) {
1131  if (auto *RD = DecompType->getAsCXXRecordDecl())
1132  S.LookupQualifiedName(MemberGet, RD);
1133  if (MemberGet.isAmbiguous())
1134  return true;
1135  // ... and if that finds at least one declaration that is a function
1136  // template whose first template parameter is a non-type parameter ...
1137  for (NamedDecl *D : MemberGet) {
1138  if (FunctionTemplateDecl *FTD =
1139  dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1140  TemplateParameterList *TPL = FTD->getTemplateParameters();
1141  if (TPL->size() != 0 &&
1142  isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1143  // ... the initializer is e.get<i>().
1144  UseMemberGet = true;
1145  break;
1146  }
1147  }
1148  }
1149  }
1150 
1151  unsigned I = 0;
1152  for (auto *B : Bindings) {
1153  BindingDiagnosticTrap Trap(S, B);
1154  SourceLocation Loc = B->getLocation();
1155 
1156  ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1157  if (E.isInvalid())
1158  return true;
1159 
1160  // e is an lvalue if the type of the entity is an lvalue reference and
1161  // an xvalue otherwise
1162  if (!Src->getType()->isLValueReferenceType())
1163  E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1164  E.get(), nullptr, VK_XValue);
1165 
1166  TemplateArgumentListInfo Args(Loc, Loc);
1167  Args.addArgument(
1169 
1170  if (UseMemberGet) {
1171  // if [lookup of member get] finds at least one declaration, the
1172  // initializer is e.get<i-1>().
1173  E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1174  CXXScopeSpec(), SourceLocation(), nullptr,
1175  MemberGet, &Args, nullptr);
1176  if (E.isInvalid())
1177  return true;
1178 
1179  E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1180  } else {
1181  // Otherwise, the initializer is get<i-1>(e), where get is looked up
1182  // in the associated namespaces.
1185  DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1187 
1188  Expr *Arg = E.get();
1189  E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1190  }
1191  if (E.isInvalid())
1192  return true;
1193  Expr *Init = E.get();
1194 
1195  // Given the type T designated by std::tuple_element<i - 1, E>::type,
1196  QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1197  if (T.isNull())
1198  return true;
1199 
1200  // each vi is a variable of type "reference to T" initialized with the
1201  // initializer, where the reference is an lvalue reference if the
1202  // initializer is an lvalue and an rvalue reference otherwise
1203  QualType RefType =
1204  S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1205  if (RefType.isNull())
1206  return true;
1207  auto *RefVD = VarDecl::Create(
1208  S.Context, Src->getDeclContext(), Loc, Loc,
1209  B->getDeclName().getAsIdentifierInfo(), RefType,
1212  RefVD->setTSCSpec(Src->getTSCSpec());
1213  RefVD->setImplicit();
1214  if (Src->isInlineSpecified())
1215  RefVD->setInlineSpecified();
1216  RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1217 
1220  InitializationSequence Seq(S, Entity, Kind, Init);
1221  E = Seq.Perform(S, Entity, Kind, Init);
1222  if (E.isInvalid())
1223  return true;
1224  E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1225  if (E.isInvalid())
1226  return true;
1227  RefVD->setInit(E.get());
1228  RefVD->checkInitIsICE();
1229 
1231  DeclarationNameInfo(B->getDeclName(), Loc),
1232  RefVD);
1233  if (E.isInvalid())
1234  return true;
1235 
1236  B->setBinding(T, E.get());
1237  I++;
1238  }
1239 
1240  return false;
1241 }
1242 
1243 /// Find the base class to decompose in a built-in decomposition of a class type.
1244 /// This base class search is, unfortunately, not quite like any other that we
1245 /// perform anywhere else in C++.
1247  const CXXRecordDecl *RD,
1248  CXXCastPath &BasePath) {
1249  auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1250  CXXBasePath &Path) {
1251  return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1252  };
1253 
1254  const CXXRecordDecl *ClassWithFields = nullptr;
1256  if (RD->hasDirectFields())
1257  // [dcl.decomp]p4:
1258  // Otherwise, all of E's non-static data members shall be public direct
1259  // members of E ...
1260  ClassWithFields = RD;
1261  else {
1262  // ... or of ...
1263  CXXBasePaths Paths;
1264  Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1265  if (!RD->lookupInBases(BaseHasFields, Paths)) {
1266  // If no classes have fields, just decompose RD itself. (This will work
1267  // if and only if zero bindings were provided.)
1268  return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1269  }
1270 
1271  CXXBasePath *BestPath = nullptr;
1272  for (auto &P : Paths) {
1273  if (!BestPath)
1274  BestPath = &P;
1275  else if (!S.Context.hasSameType(P.back().Base->getType(),
1276  BestPath->back().Base->getType())) {
1277  // ... the same ...
1278  S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1279  << false << RD << BestPath->back().Base->getType()
1280  << P.back().Base->getType();
1281  return DeclAccessPair();
1282  } else if (P.Access < BestPath->Access) {
1283  BestPath = &P;
1284  }
1285  }
1286 
1287  // ... unambiguous ...
1288  QualType BaseType = BestPath->back().Base->getType();
1289  if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1290  S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1291  << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1292  return DeclAccessPair();
1293  }
1294 
1295  // ... [accessible, implied by other rules] base class of E.
1296  S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1297  *BestPath, diag::err_decomp_decl_inaccessible_base);
1298  AS = BestPath->Access;
1299 
1300  ClassWithFields = BaseType->getAsCXXRecordDecl();
1301  S.BuildBasePathArray(Paths, BasePath);
1302  }
1303 
1304  // The above search did not check whether the selected class itself has base
1305  // classes with fields, so check that now.
1306  CXXBasePaths Paths;
1307  if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1308  S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1309  << (ClassWithFields == RD) << RD << ClassWithFields
1310  << Paths.front().back().Base->getType();
1311  return DeclAccessPair();
1312  }
1313 
1314  return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1315 }
1316 
1318  ValueDecl *Src, QualType DecompType,
1319  const CXXRecordDecl *OrigRD) {
1320  if (S.RequireCompleteType(Src->getLocation(), DecompType,
1321  diag::err_incomplete_type))
1322  return true;
1323 
1324  CXXCastPath BasePath;
1325  DeclAccessPair BasePair =
1326  findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1327  const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1328  if (!RD)
1329  return true;
1331  DecompType.getQualifiers());
1332 
1333  auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1334  unsigned NumFields =
1335  std::count_if(RD->field_begin(), RD->field_end(),
1336  [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1337  assert(Bindings.size() != NumFields);
1338  S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1339  << DecompType << (unsigned)Bindings.size() << NumFields
1340  << (NumFields < Bindings.size());
1341  return true;
1342  };
1343 
1344  // all of E's non-static data members shall be [...] well-formed
1345  // when named as e.name in the context of the structured binding,
1346  // E shall not have an anonymous union member, ...
1347  unsigned I = 0;
1348  for (auto *FD : RD->fields()) {
1349  if (FD->isUnnamedBitfield())
1350  continue;
1351 
1352  if (FD->isAnonymousStructOrUnion()) {
1353  S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1354  << DecompType << FD->getType()->isUnionType();
1355  S.Diag(FD->getLocation(), diag::note_declared_at);
1356  return true;
1357  }
1358 
1359  // We have a real field to bind.
1360  if (I >= Bindings.size())
1361  return DiagnoseBadNumberOfBindings();
1362  auto *B = Bindings[I++];
1363  SourceLocation Loc = B->getLocation();
1364 
1365  // The field must be accessible in the context of the structured binding.
1366  // We already checked that the base class is accessible.
1367  // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1368  // const_cast here.
1370  Loc, const_cast<CXXRecordDecl *>(OrigRD),
1372  BasePair.getAccess(), FD->getAccess())));
1373 
1374  // Initialize the binding to Src.FD.
1375  ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1376  if (E.isInvalid())
1377  return true;
1378  E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1379  VK_LValue, &BasePath);
1380  if (E.isInvalid())
1381  return true;
1382  E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1383  CXXScopeSpec(), FD,
1384  DeclAccessPair::make(FD, FD->getAccess()),
1385  DeclarationNameInfo(FD->getDeclName(), Loc));
1386  if (E.isInvalid())
1387  return true;
1388 
1389  // If the type of the member is T, the referenced type is cv T, where cv is
1390  // the cv-qualification of the decomposition expression.
1391  //
1392  // FIXME: We resolve a defect here: if the field is mutable, we do not add
1393  // 'const' to the type of the field.
1394  Qualifiers Q = DecompType.getQualifiers();
1395  if (FD->isMutable())
1396  Q.removeConst();
1397  B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1398  }
1399 
1400  if (I != Bindings.size())
1401  return DiagnoseBadNumberOfBindings();
1402 
1403  return false;
1404 }
1405 
1407  QualType DecompType = DD->getType();
1408 
1409  // If the type of the decomposition is dependent, then so is the type of
1410  // each binding.
1411  if (DecompType->isDependentType()) {
1412  for (auto *B : DD->bindings())
1413  B->setType(Context.DependentTy);
1414  return;
1415  }
1416 
1417  DecompType = DecompType.getNonReferenceType();
1418  ArrayRef<BindingDecl*> Bindings = DD->bindings();
1419 
1420  // C++1z [dcl.decomp]/2:
1421  // If E is an array type [...]
1422  // As an extension, we also support decomposition of built-in complex and
1423  // vector types.
1424  if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1425  if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1426  DD->setInvalidDecl();
1427  return;
1428  }
1429  if (auto *VT = DecompType->getAs<VectorType>()) {
1430  if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1431  DD->setInvalidDecl();
1432  return;
1433  }
1434  if (auto *CT = DecompType->getAs<ComplexType>()) {
1435  if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1436  DD->setInvalidDecl();
1437  return;
1438  }
1439 
1440  // C++1z [dcl.decomp]/3:
1441  // if the expression std::tuple_size<E>::value is a well-formed integral
1442  // constant expression, [...]
1443  llvm::APSInt TupleSize(32);
1444  switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1445  case IsTupleLike::Error:
1446  DD->setInvalidDecl();
1447  return;
1448 
1449  case IsTupleLike::TupleLike:
1450  if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1451  DD->setInvalidDecl();
1452  return;
1453 
1454  case IsTupleLike::NotTupleLike:
1455  break;
1456  }
1457 
1458  // C++1z [dcl.dcl]/8:
1459  // [E shall be of array or non-union class type]
1460  CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1461  if (!RD || RD->isUnion()) {
1462  Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1463  << DD << !RD << DecompType;
1464  DD->setInvalidDecl();
1465  return;
1466  }
1467 
1468  // C++1z [dcl.decomp]/4:
1469  // all of E's non-static data members shall be [...] direct members of
1470  // E or of the same unambiguous public base class of E, ...
1471  if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1472  DD->setInvalidDecl();
1473 }
1474 
1475 /// Merge the exception specifications of two variable declarations.
1476 ///
1477 /// This is called when there's a redeclaration of a VarDecl. The function
1478 /// checks if the redeclaration might have an exception specification and
1479 /// validates compatibility and merges the specs if necessary.
1481  // Shortcut if exceptions are disabled.
1482  if (!getLangOpts().CXXExceptions)
1483  return;
1484 
1485  assert(Context.hasSameType(New->getType(), Old->getType()) &&
1486  "Should only be called if types are otherwise the same.");
1487 
1488  QualType NewType = New->getType();
1489  QualType OldType = Old->getType();
1490 
1491  // We're only interested in pointers and references to functions, as well
1492  // as pointers to member functions.
1493  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1494  NewType = R->getPointeeType();
1495  OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1496  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1497  NewType = P->getPointeeType();
1498  OldType = OldType->getAs<PointerType>()->getPointeeType();
1499  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1500  NewType = M->getPointeeType();
1501  OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1502  }
1503 
1504  if (!NewType->isFunctionProtoType())
1505  return;
1506 
1507  // There's lots of special cases for functions. For function pointers, system
1508  // libraries are hopefully not as broken so that we don't need these
1509  // workarounds.
1510  if (CheckEquivalentExceptionSpec(
1511  OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1512  NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1513  New->setInvalidDecl();
1514  }
1515 }
1516 
1517 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1518 /// function declaration are well-formed according to C++
1519 /// [dcl.fct.default].
1521  unsigned NumParams = FD->getNumParams();
1522  unsigned p;
1523 
1524  // Find first parameter with a default argument
1525  for (p = 0; p < NumParams; ++p) {
1526  ParmVarDecl *Param = FD->getParamDecl(p);
1527  if (Param->hasDefaultArg())
1528  break;
1529  }
1530 
1531  // C++11 [dcl.fct.default]p4:
1532  // In a given function declaration, each parameter subsequent to a parameter
1533  // with a default argument shall have a default argument supplied in this or
1534  // a previous declaration or shall be a function parameter pack. A default
1535  // argument shall not be redefined by a later declaration (not even to the
1536  // same value).
1537  unsigned LastMissingDefaultArg = 0;
1538  for (; p < NumParams; ++p) {
1539  ParmVarDecl *Param = FD->getParamDecl(p);
1540  if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1541  if (Param->isInvalidDecl())
1542  /* We already complained about this parameter. */;
1543  else if (Param->getIdentifier())
1544  Diag(Param->getLocation(),
1545  diag::err_param_default_argument_missing_name)
1546  << Param->getIdentifier();
1547  else
1548  Diag(Param->getLocation(),
1549  diag::err_param_default_argument_missing);
1550 
1551  LastMissingDefaultArg = p;
1552  }
1553  }
1554 
1555  if (LastMissingDefaultArg > 0) {
1556  // Some default arguments were missing. Clear out all of the
1557  // default arguments up to (and including) the last missing
1558  // default argument, so that we leave the function parameters
1559  // in a semantically valid state.
1560  for (p = 0; p <= LastMissingDefaultArg; ++p) {
1561  ParmVarDecl *Param = FD->getParamDecl(p);
1562  if (Param->hasDefaultArg()) {
1563  Param->setDefaultArg(nullptr);
1564  }
1565  }
1566  }
1567 }
1568 
1569 /// Check that the given type is a literal type. Issue a diagnostic if not,
1570 /// if Kind is Diagnose.
1571 /// \return \c true if a problem has been found (and optionally diagnosed).
1572 template <typename... Ts>
1574  SourceLocation Loc, QualType T, unsigned DiagID,
1575  Ts &&...DiagArgs) {
1576  if (T->isDependentType())
1577  return false;
1578 
1579  switch (Kind) {
1581  return SemaRef.RequireLiteralType(Loc, T, DiagID,
1582  std::forward<Ts>(DiagArgs)...);
1583 
1585  return !T->isLiteralType(SemaRef.Context);
1586  }
1587 
1588  llvm_unreachable("unknown CheckConstexprKind");
1589 }
1590 
1591 // CheckConstexprParameterTypes - Check whether a function's parameter types
1592 // are all literal types. If so, return true. If not, produce a suitable
1593 // diagnostic and return false.
1594 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1595  const FunctionDecl *FD,
1597  unsigned ArgIndex = 0;
1598  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1600  e = FT->param_type_end();
1601  i != e; ++i, ++ArgIndex) {
1602  const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1603  SourceLocation ParamLoc = PD->getLocation();
1604  if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1605  diag::err_constexpr_non_literal_param, ArgIndex + 1,
1606  PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1607  FD->isConsteval()))
1608  return false;
1609  }
1610  return true;
1611 }
1612 
1613 /// Get diagnostic %select index for tag kind for
1614 /// record diagnostic message.
1615 /// WARNING: Indexes apply to particular diagnostics only!
1616 ///
1617 /// \returns diagnostic %select index.
1619  switch (Tag) {
1620  case TTK_Struct: return 0;
1621  case TTK_Interface: return 1;
1622  case TTK_Class: return 2;
1623  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1624  }
1625 }
1626 
1627 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1628  Stmt *Body,
1630 
1631 // Check whether a function declaration satisfies the requirements of a
1632 // constexpr function definition or a constexpr constructor definition. If so,
1633 // return true. If not, produce appropriate diagnostics (unless asked not to by
1634 // Kind) and return false.
1635 //
1636 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1638  CheckConstexprKind Kind) {
1639  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1640  if (MD && MD->isInstance()) {
1641  // C++11 [dcl.constexpr]p4:
1642  // The definition of a constexpr constructor shall satisfy the following
1643  // constraints:
1644  // - the class shall not have any virtual base classes;
1645  //
1646  // FIXME: This only applies to constructors, not arbitrary member
1647  // functions.
1648  const CXXRecordDecl *RD = MD->getParent();
1649  if (RD->getNumVBases()) {
1650  if (Kind == CheckConstexprKind::CheckValid)
1651  return false;
1652 
1653  Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1654  << isa<CXXConstructorDecl>(NewFD)
1656  for (const auto &I : RD->vbases())
1657  Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1658  << I.getSourceRange();
1659  return false;
1660  }
1661  }
1662 
1663  if (!isa<CXXConstructorDecl>(NewFD)) {
1664  // C++11 [dcl.constexpr]p3:
1665  // The definition of a constexpr function shall satisfy the following
1666  // constraints:
1667  // - it shall not be virtual; (removed in C++20)
1668  const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1669  if (Method && Method->isVirtual()) {
1670  if (getLangOpts().CPlusPlus2a) {
1671  if (Kind == CheckConstexprKind::Diagnose)
1672  Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1673  } else {
1674  if (Kind == CheckConstexprKind::CheckValid)
1675  return false;
1676 
1677  Method = Method->getCanonicalDecl();
1678  Diag(Method->getLocation(), diag::err_constexpr_virtual);
1679 
1680  // If it's not obvious why this function is virtual, find an overridden
1681  // function which uses the 'virtual' keyword.
1682  const CXXMethodDecl *WrittenVirtual = Method;
1683  while (!WrittenVirtual->isVirtualAsWritten())
1684  WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1685  if (WrittenVirtual != Method)
1686  Diag(WrittenVirtual->getLocation(),
1687  diag::note_overridden_virtual_function);
1688  return false;
1689  }
1690  }
1691 
1692  // - its return type shall be a literal type;
1693  QualType RT = NewFD->getReturnType();
1694  if (CheckLiteralType(*this, Kind, NewFD->getLocation(), RT,
1695  diag::err_constexpr_non_literal_return,
1696  NewFD->isConsteval()))
1697  return false;
1698  }
1699 
1700  // - each of its parameter types shall be a literal type;
1701  if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1702  return false;
1703 
1704  Stmt *Body = NewFD->getBody();
1705  assert(Body &&
1706  "CheckConstexprFunctionDefinition called on function with no body");
1707  return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1708 }
1709 
1710 /// Check the given declaration statement is legal within a constexpr function
1711 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1712 ///
1713 /// \return true if the body is OK (maybe only as an extension), false if we
1714 /// have diagnosed a problem.
1715 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1716  DeclStmt *DS, SourceLocation &Cxx1yLoc,
1717  Sema::CheckConstexprKind Kind) {
1718  // C++11 [dcl.constexpr]p3 and p4:
1719  // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1720  // contain only
1721  for (const auto *DclIt : DS->decls()) {
1722  switch (DclIt->getKind()) {
1723  case Decl::StaticAssert:
1724  case Decl::Using:
1725  case Decl::UsingShadow:
1726  case Decl::UsingDirective:
1727  case Decl::UnresolvedUsingTypename:
1728  case Decl::UnresolvedUsingValue:
1729  // - static_assert-declarations
1730  // - using-declarations,
1731  // - using-directives,
1732  continue;
1733 
1734  case Decl::Typedef:
1735  case Decl::TypeAlias: {
1736  // - typedef declarations and alias-declarations that do not define
1737  // classes or enumerations,
1738  const auto *TN = cast<TypedefNameDecl>(DclIt);
1739  if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1740  // Don't allow variably-modified types in constexpr functions.
1741  if (Kind == Sema::CheckConstexprKind::Diagnose) {
1742  TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1743  SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1744  << TL.getSourceRange() << TL.getType()
1745  << isa<CXXConstructorDecl>(Dcl);
1746  }
1747  return false;
1748  }
1749  continue;
1750  }
1751 
1752  case Decl::Enum:
1753  case Decl::CXXRecord:
1754  // C++1y allows types to be defined, not just declared.
1755  if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1756  if (Kind == Sema::CheckConstexprKind::Diagnose) {
1757  SemaRef.Diag(DS->getBeginLoc(),
1758  SemaRef.getLangOpts().CPlusPlus14
1759  ? diag::warn_cxx11_compat_constexpr_type_definition
1760  : diag::ext_constexpr_type_definition)
1761  << isa<CXXConstructorDecl>(Dcl);
1762  } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1763  return false;
1764  }
1765  }
1766  continue;
1767 
1768  case Decl::EnumConstant:
1769  case Decl::IndirectField:
1770  case Decl::ParmVar:
1771  // These can only appear with other declarations which are banned in
1772  // C++11 and permitted in C++1y, so ignore them.
1773  continue;
1774 
1775  case Decl::Var:
1776  case Decl::Decomposition: {
1777  // C++1y [dcl.constexpr]p3 allows anything except:
1778  // a definition of a variable of non-literal type or of static or
1779  // thread storage duration or for which no initialization is performed.
1780  const auto *VD = cast<VarDecl>(DclIt);
1781  if (VD->isThisDeclarationADefinition()) {
1782  if (VD->isStaticLocal()) {
1783  if (Kind == Sema::CheckConstexprKind::Diagnose) {
1784  SemaRef.Diag(VD->getLocation(),
1785  diag::err_constexpr_local_var_static)
1786  << isa<CXXConstructorDecl>(Dcl)
1787  << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1788  }
1789  return false;
1790  }
1791  if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1792  diag::err_constexpr_local_var_non_literal_type,
1793  isa<CXXConstructorDecl>(Dcl)))
1794  return false;
1795  if (!VD->getType()->isDependentType() &&
1796  !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1797  if (Kind == Sema::CheckConstexprKind::Diagnose) {
1798  SemaRef.Diag(VD->getLocation(),
1799  diag::err_constexpr_local_var_no_init)
1800  << isa<CXXConstructorDecl>(Dcl);
1801  }
1802  return false;
1803  }
1804  }
1805  if (Kind == Sema::CheckConstexprKind::Diagnose) {
1806  SemaRef.Diag(VD->getLocation(),
1807  SemaRef.getLangOpts().CPlusPlus14
1808  ? diag::warn_cxx11_compat_constexpr_local_var
1809  : diag::ext_constexpr_local_var)
1810  << isa<CXXConstructorDecl>(Dcl);
1811  } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1812  return false;
1813  }
1814  continue;
1815  }
1816 
1817  case Decl::NamespaceAlias:
1818  case Decl::Function:
1819  // These are disallowed in C++11 and permitted in C++1y. Allow them
1820  // everywhere as an extension.
1821  if (!Cxx1yLoc.isValid())
1822  Cxx1yLoc = DS->getBeginLoc();
1823  continue;
1824 
1825  default:
1826  if (Kind == Sema::CheckConstexprKind::Diagnose) {
1827  SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1828  << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1829  }
1830  return false;
1831  }
1832  }
1833 
1834  return true;
1835 }
1836 
1837 /// Check that the given field is initialized within a constexpr constructor.
1838 ///
1839 /// \param Dcl The constexpr constructor being checked.
1840 /// \param Field The field being checked. This may be a member of an anonymous
1841 /// struct or union nested within the class being checked.
1842 /// \param Inits All declarations, including anonymous struct/union members and
1843 /// indirect members, for which any initialization was provided.
1844 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1845 /// multiple notes for different members to the same error.
1846 /// \param Kind Whether we're diagnosing a constructor as written or determining
1847 /// whether the formal requirements are satisfied.
1848 /// \return \c false if we're checking for validity and the constructor does
1849 /// not satisfy the requirements on a constexpr constructor.
1851  const FunctionDecl *Dcl,
1852  FieldDecl *Field,
1853  llvm::SmallSet<Decl*, 16> &Inits,
1854  bool &Diagnosed,
1855  Sema::CheckConstexprKind Kind) {
1856  if (Field->isInvalidDecl())
1857  return true;
1858 
1859  if (Field->isUnnamedBitfield())
1860  return true;
1861 
1862  // Anonymous unions with no variant members and empty anonymous structs do not
1863  // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1864  // indirect fields don't need initializing.
1865  if (Field->isAnonymousStructOrUnion() &&
1866  (Field->getType()->isUnionType()
1867  ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1868  : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1869  return true;
1870 
1871  if (!Inits.count(Field)) {
1872  if (Kind == Sema::CheckConstexprKind::Diagnose) {
1873  if (!Diagnosed) {
1874  SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1875  Diagnosed = true;
1876  }
1877  SemaRef.Diag(Field->getLocation(),
1878  diag::note_constexpr_ctor_missing_init);
1879  } else {
1880  return false;
1881  }
1882  } else if (Field->isAnonymousStructOrUnion()) {
1883  const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1884  for (auto *I : RD->fields())
1885  // If an anonymous union contains an anonymous struct of which any member
1886  // is initialized, all members must be initialized.
1887  if (!RD->isUnion() || Inits.count(I))
1888  if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1889  Kind))
1890  return false;
1891  }
1892  return true;
1893 }
1894 
1895 /// Check the provided statement is allowed in a constexpr function
1896 /// definition.
1897 static bool
1899  SmallVectorImpl<SourceLocation> &ReturnStmts,
1900  SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
1901  Sema::CheckConstexprKind Kind) {
1902  // - its function-body shall be [...] a compound-statement that contains only
1903  switch (S->getStmtClass()) {
1904  case Stmt::NullStmtClass:
1905  // - null statements,
1906  return true;
1907 
1908  case Stmt::DeclStmtClass:
1909  // - static_assert-declarations
1910  // - using-declarations,
1911  // - using-directives,
1912  // - typedef declarations and alias-declarations that do not define
1913  // classes or enumerations,
1914  if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
1915  return false;
1916  return true;
1917 
1918  case Stmt::ReturnStmtClass:
1919  // - and exactly one return statement;
1920  if (isa<CXXConstructorDecl>(Dcl)) {
1921  // C++1y allows return statements in constexpr constructors.
1922  if (!Cxx1yLoc.isValid())
1923  Cxx1yLoc = S->getBeginLoc();
1924  return true;
1925  }
1926 
1927  ReturnStmts.push_back(S->getBeginLoc());
1928  return true;
1929 
1930  case Stmt::CompoundStmtClass: {
1931  // C++1y allows compound-statements.
1932  if (!Cxx1yLoc.isValid())
1933  Cxx1yLoc = S->getBeginLoc();
1934 
1935  CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1936  for (auto *BodyIt : CompStmt->body()) {
1937  if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1938  Cxx1yLoc, Cxx2aLoc, Kind))
1939  return false;
1940  }
1941  return true;
1942  }
1943 
1944  case Stmt::AttributedStmtClass:
1945  if (!Cxx1yLoc.isValid())
1946  Cxx1yLoc = S->getBeginLoc();
1947  return true;
1948 
1949  case Stmt::IfStmtClass: {
1950  // C++1y allows if-statements.
1951  if (!Cxx1yLoc.isValid())
1952  Cxx1yLoc = S->getBeginLoc();
1953 
1954  IfStmt *If = cast<IfStmt>(S);
1955  if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1956  Cxx1yLoc, Cxx2aLoc, Kind))
1957  return false;
1958  if (If->getElse() &&
1959  !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1960  Cxx1yLoc, Cxx2aLoc, Kind))
1961  return false;
1962  return true;
1963  }
1964 
1965  case Stmt::WhileStmtClass:
1966  case Stmt::DoStmtClass:
1967  case Stmt::ForStmtClass:
1968  case Stmt::CXXForRangeStmtClass:
1969  case Stmt::ContinueStmtClass:
1970  // C++1y allows all of these. We don't allow them as extensions in C++11,
1971  // because they don't make sense without variable mutation.
1972  if (!SemaRef.getLangOpts().CPlusPlus14)
1973  break;
1974  if (!Cxx1yLoc.isValid())
1975  Cxx1yLoc = S->getBeginLoc();
1976  for (Stmt *SubStmt : S->children())
1977  if (SubStmt &&
1978  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1979  Cxx1yLoc, Cxx2aLoc, Kind))
1980  return false;
1981  return true;
1982 
1983  case Stmt::SwitchStmtClass:
1984  case Stmt::CaseStmtClass:
1985  case Stmt::DefaultStmtClass:
1986  case Stmt::BreakStmtClass:
1987  // C++1y allows switch-statements, and since they don't need variable
1988  // mutation, we can reasonably allow them in C++11 as an extension.
1989  if (!Cxx1yLoc.isValid())
1990  Cxx1yLoc = S->getBeginLoc();
1991  for (Stmt *SubStmt : S->children())
1992  if (SubStmt &&
1993  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1994  Cxx1yLoc, Cxx2aLoc, Kind))
1995  return false;
1996  return true;
1997 
1998  case Stmt::GCCAsmStmtClass:
1999  case Stmt::MSAsmStmtClass:
2000  // C++2a allows inline assembly statements.
2001  case Stmt::CXXTryStmtClass:
2002  if (Cxx2aLoc.isInvalid())
2003  Cxx2aLoc = S->getBeginLoc();
2004  for (Stmt *SubStmt : S->children()) {
2005  if (SubStmt &&
2006  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2007  Cxx1yLoc, Cxx2aLoc, Kind))
2008  return false;
2009  }
2010  return true;
2011 
2012  case Stmt::CXXCatchStmtClass:
2013  // Do not bother checking the language mode (already covered by the
2014  // try block check).
2015  if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2016  cast<CXXCatchStmt>(S)->getHandlerBlock(),
2017  ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2018  return false;
2019  return true;
2020 
2021  default:
2022  if (!isa<Expr>(S))
2023  break;
2024 
2025  // C++1y allows expression-statements.
2026  if (!Cxx1yLoc.isValid())
2027  Cxx1yLoc = S->getBeginLoc();
2028  return true;
2029  }
2030 
2031  if (Kind == Sema::CheckConstexprKind::Diagnose) {
2032  SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2033  << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2034  }
2035  return false;
2036 }
2037 
2038 /// Check the body for the given constexpr function declaration only contains
2039 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2040 ///
2041 /// \return true if the body is OK, false if we have found or diagnosed a
2042 /// problem.
2043 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2044  Stmt *Body,
2045  Sema::CheckConstexprKind Kind) {
2046  SmallVector<SourceLocation, 4> ReturnStmts;
2047 
2048  if (isa<CXXTryStmt>(Body)) {
2049  // C++11 [dcl.constexpr]p3:
2050  // The definition of a constexpr function shall satisfy the following
2051  // constraints: [...]
2052  // - its function-body shall be = delete, = default, or a
2053  // compound-statement
2054  //
2055  // C++11 [dcl.constexpr]p4:
2056  // In the definition of a constexpr constructor, [...]
2057  // - its function-body shall not be a function-try-block;
2058  //
2059  // This restriction is lifted in C++2a, as long as inner statements also
2060  // apply the general constexpr rules.
2061  switch (Kind) {
2063  if (!SemaRef.getLangOpts().CPlusPlus2a)
2064  return false;
2065  break;
2066 
2068  SemaRef.Diag(Body->getBeginLoc(),
2069  !SemaRef.getLangOpts().CPlusPlus2a
2070  ? diag::ext_constexpr_function_try_block_cxx2a
2071  : diag::warn_cxx17_compat_constexpr_function_try_block)
2072  << isa<CXXConstructorDecl>(Dcl);
2073  break;
2074  }
2075  }
2076 
2077  // - its function-body shall be [...] a compound-statement that contains only
2078  // [... list of cases ...]
2079  //
2080  // Note that walking the children here is enough to properly check for
2081  // CompoundStmt and CXXTryStmt body.
2082  SourceLocation Cxx1yLoc, Cxx2aLoc;
2083  for (Stmt *SubStmt : Body->children()) {
2084  if (SubStmt &&
2085  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2086  Cxx1yLoc, Cxx2aLoc, Kind))
2087  return false;
2088  }
2089 
2091  // If this is only valid as an extension, report that we don't satisfy the
2092  // constraints of the current language.
2093  if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) ||
2094  (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2095  return false;
2096  } else if (Cxx2aLoc.isValid()) {
2097  SemaRef.Diag(Cxx2aLoc,
2098  SemaRef.getLangOpts().CPlusPlus2a
2099  ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2100  : diag::ext_constexpr_body_invalid_stmt_cxx2a)
2101  << isa<CXXConstructorDecl>(Dcl);
2102  } else if (Cxx1yLoc.isValid()) {
2103  SemaRef.Diag(Cxx1yLoc,
2104  SemaRef.getLangOpts().CPlusPlus14
2105  ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2106  : diag::ext_constexpr_body_invalid_stmt)
2107  << isa<CXXConstructorDecl>(Dcl);
2108  }
2109 
2110  if (const CXXConstructorDecl *Constructor
2111  = dyn_cast<CXXConstructorDecl>(Dcl)) {
2112  const CXXRecordDecl *RD = Constructor->getParent();
2113  // DR1359:
2114  // - every non-variant non-static data member and base class sub-object
2115  // shall be initialized;
2116  // DR1460:
2117  // - if the class is a union having variant members, exactly one of them
2118  // shall be initialized;
2119  if (RD->isUnion()) {
2120  if (Constructor->getNumCtorInitializers() == 0 &&
2121  RD->hasVariantMembers()) {
2123  SemaRef.Diag(Dcl->getLocation(),
2124  diag::err_constexpr_union_ctor_no_init);
2125  return false;
2126  }
2127  } else if (!Constructor->isDependentContext() &&
2128  !Constructor->isDelegatingConstructor()) {
2129  assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2130 
2131  // Skip detailed checking if we have enough initializers, and we would
2132  // allow at most one initializer per member.
2133  bool AnyAnonStructUnionMembers = false;
2134  unsigned Fields = 0;
2136  E = RD->field_end(); I != E; ++I, ++Fields) {
2137  if (I->isAnonymousStructOrUnion()) {
2138  AnyAnonStructUnionMembers = true;
2139  break;
2140  }
2141  }
2142  // DR1460:
2143  // - if the class is a union-like class, but is not a union, for each of
2144  // its anonymous union members having variant members, exactly one of
2145  // them shall be initialized;
2146  if (AnyAnonStructUnionMembers ||
2147  Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2148  // Check initialization of non-static data members. Base classes are
2149  // always initialized so do not need to be checked. Dependent bases
2150  // might not have initializers in the member initializer list.
2151  llvm::SmallSet<Decl*, 16> Inits;
2152  for (const auto *I: Constructor->inits()) {
2153  if (FieldDecl *FD = I->getMember())
2154  Inits.insert(FD);
2155  else if (IndirectFieldDecl *ID = I->getIndirectMember())
2156  Inits.insert(ID->chain_begin(), ID->chain_end());
2157  }
2158 
2159  bool Diagnosed = false;
2160  for (auto *I : RD->fields())
2161  if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2162  Kind))
2163  return false;
2164  }
2165  }
2166  } else {
2167  if (ReturnStmts.empty()) {
2168  // C++1y doesn't require constexpr functions to contain a 'return'
2169  // statement. We still do, unless the return type might be void, because
2170  // otherwise if there's no return statement, the function cannot
2171  // be used in a core constant expression.
2172  bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2173  (Dcl->getReturnType()->isVoidType() ||
2174  Dcl->getReturnType()->isDependentType());
2175  switch (Kind) {
2177  SemaRef.Diag(Dcl->getLocation(),
2178  OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2179  : diag::err_constexpr_body_no_return)
2180  << Dcl->isConsteval();
2181  if (!OK)
2182  return false;
2183  break;
2184 
2186  // The formal requirements don't include this rule in C++14, even
2187  // though the "must be able to produce a constant expression" rules
2188  // still imply it in some cases.
2189  if (!SemaRef.getLangOpts().CPlusPlus14)
2190  return false;
2191  break;
2192  }
2193  } else if (ReturnStmts.size() > 1) {
2194  switch (Kind) {
2196  SemaRef.Diag(
2197  ReturnStmts.back(),
2198  SemaRef.getLangOpts().CPlusPlus14
2199  ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2200  : diag::ext_constexpr_body_multiple_return);
2201  for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2202  SemaRef.Diag(ReturnStmts[I],
2203  diag::note_constexpr_body_previous_return);
2204  break;
2205 
2207  if (!SemaRef.getLangOpts().CPlusPlus14)
2208  return false;
2209  break;
2210  }
2211  }
2212  }
2213 
2214  // C++11 [dcl.constexpr]p5:
2215  // if no function argument values exist such that the function invocation
2216  // substitution would produce a constant expression, the program is
2217  // ill-formed; no diagnostic required.
2218  // C++11 [dcl.constexpr]p3:
2219  // - every constructor call and implicit conversion used in initializing the
2220  // return value shall be one of those allowed in a constant expression.
2221  // C++11 [dcl.constexpr]p4:
2222  // - every constructor involved in initializing non-static data members and
2223  // base class sub-objects shall be a constexpr constructor.
2224  //
2225  // Note that this rule is distinct from the "requirements for a constexpr
2226  // function", so is not checked in CheckValid mode.
2228  if (Kind == Sema::CheckConstexprKind::Diagnose &&
2229  !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2230  SemaRef.Diag(Dcl->getLocation(),
2231  diag::ext_constexpr_function_never_constant_expr)
2232  << isa<CXXConstructorDecl>(Dcl);
2233  for (size_t I = 0, N = Diags.size(); I != N; ++I)
2234  SemaRef.Diag(Diags[I].first, Diags[I].second);
2235  // Don't return false here: we allow this for compatibility in
2236  // system headers.
2237  }
2238 
2239  return true;
2240 }
2241 
2242 /// Get the class that is directly named by the current context. This is the
2243 /// class for which an unqualified-id in this scope could name a constructor
2244 /// or destructor.
2245 ///
2246 /// If the scope specifier denotes a class, this will be that class.
2247 /// If the scope specifier is empty, this will be the class whose
2248 /// member-specification we are currently within. Otherwise, there
2249 /// is no such class.
2251  assert(getLangOpts().CPlusPlus && "No class names in C!");
2252 
2253  if (SS && SS->isInvalid())
2254  return nullptr;
2255 
2256  if (SS && SS->isNotEmpty()) {
2257  DeclContext *DC = computeDeclContext(*SS, true);
2258  return dyn_cast_or_null<CXXRecordDecl>(DC);
2259  }
2260 
2261  return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2262 }
2263 
2264 /// isCurrentClassName - Determine whether the identifier II is the
2265 /// name of the class type currently being defined. In the case of
2266 /// nested classes, this will only return true if II is the name of
2267 /// the innermost class.
2269  const CXXScopeSpec *SS) {
2270  CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2271  return CurDecl && &II == CurDecl->getIdentifier();
2272 }
2273 
2274 /// Determine whether the identifier II is a typo for the name of
2275 /// the class type currently being defined. If so, update it to the identifier
2276 /// that should have been used.
2278  assert(getLangOpts().CPlusPlus && "No class names in C!");
2279 
2280  if (!getLangOpts().SpellChecking)
2281  return false;
2282 
2283  CXXRecordDecl *CurDecl;
2284  if (SS && SS->isSet() && !SS->isInvalid()) {
2285  DeclContext *DC = computeDeclContext(*SS, true);
2286  CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2287  } else
2288  CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2289 
2290  if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2291  3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2292  < II->getLength()) {
2293  II = CurDecl->getIdentifier();
2294  return true;
2295  }
2296 
2297  return false;
2298 }
2299 
2300 /// Determine whether the given class is a base class of the given
2301 /// class, including looking at dependent bases.
2302 static bool findCircularInheritance(const CXXRecordDecl *Class,
2303  const CXXRecordDecl *Current) {
2305 
2306  Class = Class->getCanonicalDecl();
2307  while (true) {
2308  for (const auto &I : Current->bases()) {
2309  CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2310  if (!Base)
2311  continue;
2312 
2313  Base = Base->getDefinition();
2314  if (!Base)
2315  continue;
2316 
2317  if (Base->getCanonicalDecl() == Class)
2318  return true;
2319 
2320  Queue.push_back(Base);
2321  }
2322 
2323  if (Queue.empty())
2324  return false;
2325 
2326  Current = Queue.pop_back_val();
2327  }
2328 
2329  return false;
2330 }
2331 
2332 /// Check the validity of a C++ base class specifier.
2333 ///
2334 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2335 /// and returns NULL otherwise.
2338  SourceRange SpecifierRange,
2339  bool Virtual, AccessSpecifier Access,
2340  TypeSourceInfo *TInfo,
2341  SourceLocation EllipsisLoc) {
2342  QualType BaseType = TInfo->getType();
2343 
2344  // C++ [class.union]p1:
2345  // A union shall not have base classes.
2346  if (Class->isUnion()) {
2347  Diag(Class->getLocation(), diag::err_base_clause_on_union)
2348  << SpecifierRange;
2349  return nullptr;
2350  }
2351 
2352  if (EllipsisLoc.isValid() &&
2354  Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2355  << TInfo->getTypeLoc().getSourceRange();
2356  EllipsisLoc = SourceLocation();
2357  }
2358 
2359  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2360 
2361  if (BaseType->isDependentType()) {
2362  // Make sure that we don't have circular inheritance among our dependent
2363  // bases. For non-dependent bases, the check for completeness below handles
2364  // this.
2365  if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2366  if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2367  ((BaseDecl = BaseDecl->getDefinition()) &&
2368  findCircularInheritance(Class, BaseDecl))) {
2369  Diag(BaseLoc, diag::err_circular_inheritance)
2370  << BaseType << Context.getTypeDeclType(Class);
2371 
2372  if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2373  Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2374  << BaseType;
2375 
2376  return nullptr;
2377  }
2378  }
2379 
2380  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2381  Class->getTagKind() == TTK_Class,
2382  Access, TInfo, EllipsisLoc);
2383  }
2384 
2385  // Base specifiers must be record types.
2386  if (!BaseType->isRecordType()) {
2387  Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2388  return nullptr;
2389  }
2390 
2391  // C++ [class.union]p1:
2392  // A union shall not be used as a base class.
2393  if (BaseType->isUnionType()) {
2394  Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2395  return nullptr;
2396  }
2397 
2398  // For the MS ABI, propagate DLL attributes to base class templates.
2399  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2400  if (Attr *ClassAttr = getDLLAttr(Class)) {
2401  if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2402  BaseType->getAsCXXRecordDecl())) {
2403  propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2404  BaseLoc);
2405  }
2406  }
2407  }
2408 
2409  // C++ [class.derived]p2:
2410  // The class-name in a base-specifier shall not be an incompletely
2411  // defined class.
2412  if (RequireCompleteType(BaseLoc, BaseType,
2413  diag::err_incomplete_base_class, SpecifierRange)) {
2414  Class->setInvalidDecl();
2415  return nullptr;
2416  }
2417 
2418  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2419  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2420  assert(BaseDecl && "Record type has no declaration");
2421  BaseDecl = BaseDecl->getDefinition();
2422  assert(BaseDecl && "Base type is not incomplete, but has no definition");
2423  CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2424  assert(CXXBaseDecl && "Base type is not a C++ type");
2425 
2426  // Microsoft docs say:
2427  // "If a base-class has a code_seg attribute, derived classes must have the
2428  // same attribute."
2429  const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2430  const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2431  if ((DerivedCSA || BaseCSA) &&
2432  (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2433  Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2434  Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2435  << CXXBaseDecl;
2436  return nullptr;
2437  }
2438 
2439  // A class which contains a flexible array member is not suitable for use as a
2440  // base class:
2441  // - If the layout determines that a base comes before another base,
2442  // the flexible array member would index into the subsequent base.
2443  // - If the layout determines that base comes before the derived class,
2444  // the flexible array member would index into the derived class.
2445  if (CXXBaseDecl->hasFlexibleArrayMember()) {
2446  Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2447  << CXXBaseDecl->getDeclName();
2448  return nullptr;
2449  }
2450 
2451  // C++ [class]p3:
2452  // If a class is marked final and it appears as a base-type-specifier in
2453  // base-clause, the program is ill-formed.
2454  if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2455  Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2456  << CXXBaseDecl->getDeclName()
2457  << FA->isSpelledAsSealed();
2458  Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2459  << CXXBaseDecl->getDeclName() << FA->getRange();
2460  return nullptr;
2461  }
2462 
2463  if (BaseDecl->isInvalidDecl())
2464  Class->setInvalidDecl();
2465 
2466  // Create the base specifier.
2467  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2468  Class->getTagKind() == TTK_Class,
2469  Access, TInfo, EllipsisLoc);
2470 }
2471 
2472 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2473 /// one entry in the base class list of a class specifier, for
2474 /// example:
2475 /// class foo : public bar, virtual private baz {
2476 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2477 BaseResult
2478 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2479  ParsedAttributes &Attributes,
2480  bool Virtual, AccessSpecifier Access,
2481  ParsedType basetype, SourceLocation BaseLoc,
2482  SourceLocation EllipsisLoc) {
2483  if (!classdecl)
2484  return true;
2485 
2486  AdjustDeclIfTemplate(classdecl);
2487  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2488  if (!Class)
2489  return true;
2490 
2491  // We haven't yet attached the base specifiers.
2492  Class->setIsParsingBaseSpecifiers();
2493 
2494  // We do not support any C++11 attributes on base-specifiers yet.
2495  // Diagnose any attributes we see.
2496  for (const ParsedAttr &AL : Attributes) {
2497  if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2498  continue;
2499  Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2500  ? (unsigned)diag::warn_unknown_attribute_ignored
2501  : (unsigned)diag::err_base_specifier_attribute)
2502  << AL.getName();
2503  }
2504 
2505  TypeSourceInfo *TInfo = nullptr;
2506  GetTypeFromParser(basetype, &TInfo);
2507 
2508  if (EllipsisLoc.isInvalid() &&
2509  DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2510  UPPC_BaseType))
2511  return true;
2512 
2513  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2514  Virtual, Access, TInfo,
2515  EllipsisLoc))
2516  return BaseSpec;
2517  else
2518  Class->setInvalidDecl();
2519 
2520  return true;
2521 }
2522 
2523 /// Use small set to collect indirect bases. As this is only used
2524 /// locally, there's no need to abstract the small size parameter.
2525 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2526 
2527 /// Recursively add the bases of Type. Don't add Type itself.
2528 static void
2529 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2530  const QualType &Type)
2531 {
2532  // Even though the incoming type is a base, it might not be
2533  // a class -- it could be a template parm, for instance.
2534  if (auto Rec = Type->getAs<RecordType>()) {
2535  auto Decl = Rec->getAsCXXRecordDecl();
2536 
2537  // Iterate over its bases.
2538  for (const auto &BaseSpec : Decl->bases()) {
2539  QualType Base = Context.getCanonicalType(BaseSpec.getType())
2540  .getUnqualifiedType();
2541  if (Set.insert(Base).second)
2542  // If we've not already seen it, recurse.
2543  NoteIndirectBases(Context, Set, Base);
2544  }
2545  }
2546 }
2547 
2548 /// Performs the actual work of attaching the given base class
2549 /// specifiers to a C++ class.
2552  if (Bases.empty())
2553  return false;
2554 
2555  // Used to keep track of which base types we have already seen, so
2556  // that we can properly diagnose redundant direct base types. Note
2557  // that the key is always the unqualified canonical type of the base
2558  // class.
2559  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2560 
2561  // Used to track indirect bases so we can see if a direct base is
2562  // ambiguous.
2563  IndirectBaseSet IndirectBaseTypes;
2564 
2565  // Copy non-redundant base specifiers into permanent storage.
2566  unsigned NumGoodBases = 0;
2567  bool Invalid = false;
2568  for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2569  QualType NewBaseType
2570  = Context.getCanonicalType(Bases[idx]->getType());
2571  NewBaseType = NewBaseType.getLocalUnqualifiedType();
2572 
2573  CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2574  if (KnownBase) {
2575  // C++ [class.mi]p3:
2576  // A class shall not be specified as a direct base class of a
2577  // derived class more than once.
2578  Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2579  << KnownBase->getType() << Bases[idx]->getSourceRange();
2580 
2581  // Delete the duplicate base class specifier; we're going to
2582  // overwrite its pointer later.
2583  Context.Deallocate(Bases[idx]);
2584 
2585  Invalid = true;
2586  } else {
2587  // Okay, add this new base class.
2588  KnownBase = Bases[idx];
2589  Bases[NumGoodBases++] = Bases[idx];
2590 
2591  // Note this base's direct & indirect bases, if there could be ambiguity.
2592  if (Bases.size() > 1)
2593  NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2594 
2595  if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2596  const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2597  if (Class->isInterface() &&
2598  (!RD->isInterfaceLike() ||
2599  KnownBase->getAccessSpecifier() != AS_public)) {
2600  // The Microsoft extension __interface does not permit bases that
2601  // are not themselves public interfaces.
2602  Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2603  << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2604  << RD->getSourceRange();
2605  Invalid = true;
2606  }
2607  if (RD->hasAttr<WeakAttr>())
2608  Class->addAttr(WeakAttr::CreateImplicit(Context));
2609  }
2610  }
2611  }
2612 
2613  // Attach the remaining base class specifiers to the derived class.
2614  Class->setBases(Bases.data(), NumGoodBases);
2615 
2616  // Check that the only base classes that are duplicate are virtual.
2617  for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2618  // Check whether this direct base is inaccessible due to ambiguity.
2619  QualType BaseType = Bases[idx]->getType();
2620 
2621  // Skip all dependent types in templates being used as base specifiers.
2622  // Checks below assume that the base specifier is a CXXRecord.
2623  if (BaseType->isDependentType())
2624  continue;
2625 
2626  CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2627  .getUnqualifiedType();
2628 
2629  if (IndirectBaseTypes.count(CanonicalBase)) {
2630  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2631  /*DetectVirtual=*/true);
2632  bool found
2633  = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2634  assert(found);
2635  (void)found;
2636 
2637  if (Paths.isAmbiguous(CanonicalBase))
2638  Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2639  << BaseType << getAmbiguousPathsDisplayString(Paths)
2640  << Bases[idx]->getSourceRange();
2641  else
2642  assert(Bases[idx]->isVirtual());
2643  }
2644 
2645  // Delete the base class specifier, since its data has been copied
2646  // into the CXXRecordDecl.
2647  Context.Deallocate(Bases[idx]);
2648  }
2649 
2650  return Invalid;
2651 }
2652 
2653 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2654 /// class, after checking whether there are any duplicate base
2655 /// classes.
2656 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2658  if (!ClassDecl || Bases.empty())
2659  return;
2660 
2661  AdjustDeclIfTemplate(ClassDecl);
2662  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2663 }
2664 
2665 /// Determine whether the type \p Derived is a C++ class that is
2666 /// derived from the type \p Base.
2668  if (!getLangOpts().CPlusPlus)
2669  return false;
2670 
2671  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2672  if (!DerivedRD)
2673  return false;
2674 
2675  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2676  if (!BaseRD)
2677  return false;
2678 
2679  // If either the base or the derived type is invalid, don't try to
2680  // check whether one is derived from the other.
2681  if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2682  return false;
2683 
2684  // FIXME: In a modules build, do we need the entire path to be visible for us
2685  // to be able to use the inheritance relationship?
2686  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2687  return false;
2688 
2689  return DerivedRD->isDerivedFrom(BaseRD);
2690 }
2691 
2692 /// Determine whether the type \p Derived is a C++ class that is
2693 /// derived from the type \p Base.
2695  CXXBasePaths &Paths) {
2696  if (!getLangOpts().CPlusPlus)
2697  return false;
2698 
2699  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2700  if (!DerivedRD)
2701  return false;
2702 
2703  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2704  if (!BaseRD)
2705  return false;
2706 
2707  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2708  return false;
2709 
2710  return DerivedRD->isDerivedFrom(BaseRD, Paths);
2711 }
2712 
2713 static void BuildBasePathArray(const CXXBasePath &Path,
2714  CXXCastPath &BasePathArray) {
2715  // We first go backward and check if we have a virtual base.
2716  // FIXME: It would be better if CXXBasePath had the base specifier for
2717  // the nearest virtual base.
2718  unsigned Start = 0;
2719  for (unsigned I = Path.size(); I != 0; --I) {
2720  if (Path[I - 1].Base->isVirtual()) {
2721  Start = I - 1;
2722  break;
2723  }
2724  }
2725 
2726  // Now add all bases.
2727  for (unsigned I = Start, E = Path.size(); I != E; ++I)
2728  BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2729 }
2730 
2731 
2733  CXXCastPath &BasePathArray) {
2734  assert(BasePathArray.empty() && "Base path array must be empty!");
2735  assert(Paths.isRecordingPaths() && "Must record paths!");
2736  return ::BuildBasePathArray(Paths.front(), BasePathArray);
2737 }
2738 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2739 /// conversion (where Derived and Base are class types) is
2740 /// well-formed, meaning that the conversion is unambiguous (and
2741 /// that all of the base classes are accessible). Returns true
2742 /// and emits a diagnostic if the code is ill-formed, returns false
2743 /// otherwise. Loc is the location where this routine should point to
2744 /// if there is an error, and Range is the source range to highlight
2745 /// if there is an error.
2746 ///
2747 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2748 /// diagnostic for the respective type of error will be suppressed, but the
2749 /// check for ill-formed code will still be performed.
2750 bool
2752  unsigned InaccessibleBaseID,
2753  unsigned AmbigiousBaseConvID,
2754  SourceLocation Loc, SourceRange Range,
2755  DeclarationName Name,
2756  CXXCastPath *BasePath,
2757  bool IgnoreAccess) {
2758  // First, determine whether the path from Derived to Base is
2759  // ambiguous. This is slightly more expensive than checking whether
2760  // the Derived to Base conversion exists, because here we need to
2761  // explore multiple paths to determine if there is an ambiguity.
2762  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2763  /*DetectVirtual=*/false);
2764  bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2765  if (!DerivationOkay)
2766  return true;
2767 
2768  const CXXBasePath *Path = nullptr;
2769  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2770  Path = &Paths.front();
2771 
2772  // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2773  // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2774  // user to access such bases.
2775  if (!Path && getLangOpts().MSVCCompat) {
2776  for (const CXXBasePath &PossiblePath : Paths) {
2777  if (PossiblePath.size() == 1) {
2778  Path = &PossiblePath;
2779  if (AmbigiousBaseConvID)
2780  Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2781  << Base << Derived << Range;
2782  break;
2783  }
2784  }
2785  }
2786 
2787  if (Path) {
2788  if (!IgnoreAccess) {
2789  // Check that the base class can be accessed.
2790  switch (
2791  CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2792  case AR_inaccessible:
2793  return true;
2794  case AR_accessible:
2795  case AR_dependent:
2796  case AR_delayed:
2797  break;
2798  }
2799  }
2800 
2801  // Build a base path if necessary.
2802  if (BasePath)
2803  ::BuildBasePathArray(*Path, *BasePath);
2804  return false;
2805  }
2806 
2807  if (AmbigiousBaseConvID) {
2808  // We know that the derived-to-base conversion is ambiguous, and
2809  // we're going to produce a diagnostic. Perform the derived-to-base
2810  // search just one more time to compute all of the possible paths so
2811  // that we can print them out. This is more expensive than any of
2812  // the previous derived-to-base checks we've done, but at this point
2813  // performance isn't as much of an issue.
2814  Paths.clear();
2815  Paths.setRecordingPaths(true);
2816  bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2817  assert(StillOkay && "Can only be used with a derived-to-base conversion");
2818  (void)StillOkay;
2819 
2820  // Build up a textual representation of the ambiguous paths, e.g.,
2821  // D -> B -> A, that will be used to illustrate the ambiguous
2822  // conversions in the diagnostic. We only print one of the paths
2823  // to each base class subobject.
2824  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2825 
2826  Diag(Loc, AmbigiousBaseConvID)
2827  << Derived << Base << PathDisplayStr << Range << Name;
2828  }
2829  return true;
2830 }
2831 
2832 bool
2834  SourceLocation Loc, SourceRange Range,
2835  CXXCastPath *BasePath,
2836  bool IgnoreAccess) {
2837  return CheckDerivedToBaseConversion(
2838  Derived, Base, diag::err_upcast_to_inaccessible_base,
2839  diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2840  BasePath, IgnoreAccess);
2841 }
2842 
2843 
2844 /// Builds a string representing ambiguous paths from a
2845 /// specific derived class to different subobjects of the same base
2846 /// class.
2847 ///
2848 /// This function builds a string that can be used in error messages
2849 /// to show the different paths that one can take through the
2850 /// inheritance hierarchy to go from the derived class to different
2851 /// subobjects of a base class. The result looks something like this:
2852 /// @code
2853 /// struct D -> struct B -> struct A
2854 /// struct D -> struct C -> struct A
2855 /// @endcode
2857  std::string PathDisplayStr;
2858  std::set<unsigned> DisplayedPaths;
2859  for (CXXBasePaths::paths_iterator Path = Paths.begin();
2860  Path != Paths.end(); ++Path) {
2861  if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2862  // We haven't displayed a path to this particular base
2863  // class subobject yet.
2864  PathDisplayStr += "\n ";
2865  PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2866  for (CXXBasePath::const_iterator Element = Path->begin();
2867  Element != Path->end(); ++Element)
2868  PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2869  }
2870  }
2871 
2872  return PathDisplayStr;
2873 }
2874 
2875 //===----------------------------------------------------------------------===//
2876 // C++ class member Handling
2877 //===----------------------------------------------------------------------===//
2878 
2879 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2882  const ParsedAttributesView &Attrs) {
2883  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2884  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2885  ASLoc, ColonLoc);
2886  CurContext->addHiddenDecl(ASDecl);
2887  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2888 }
2889 
2890 /// CheckOverrideControl - Check C++11 override control semantics.
2892  if (D->isInvalidDecl())
2893  return;
2894 
2895  // We only care about "override" and "final" declarations.
2896  if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2897  return;
2898 
2899  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2900 
2901  // We can't check dependent instance methods.
2902  if (MD && MD->isInstance() &&
2903  (MD->getParent()->hasAnyDependentBases() ||
2904  MD->getType()->isDependentType()))
2905  return;
2906 
2907  if (MD && !MD->isVirtual()) {
2908  // If we have a non-virtual method, check if if hides a virtual method.
2909  // (In that case, it's most likely the method has the wrong type.)
2910  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2911  FindHiddenVirtualMethods(MD, OverloadedMethods);
2912 
2913  if (!OverloadedMethods.empty()) {
2914  if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2915  Diag(OA->getLocation(),
2916  diag::override_keyword_hides_virtual_member_function)
2917  << "override" << (OverloadedMethods.size() > 1);
2918  } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2919  Diag(FA->getLocation(),
2920  diag::override_keyword_hides_virtual_member_function)
2921  << (FA->isSpelledAsSealed() ? "sealed" : "final")
2922  << (OverloadedMethods.size() > 1);
2923  }
2924  NoteHiddenVirtualMethods(MD, OverloadedMethods);
2925  MD->setInvalidDecl();
2926  return;
2927  }
2928  // Fall through into the general case diagnostic.
2929  // FIXME: We might want to attempt typo correction here.
2930  }
2931 
2932  if (!MD || !MD->isVirtual()) {
2933  if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2934  Diag(OA->getLocation(),
2935  diag::override_keyword_only_allowed_on_virtual_member_functions)
2936  << "override" << FixItHint::CreateRemoval(OA->getLocation());
2937  D->dropAttr<OverrideAttr>();
2938  }
2939  if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2940  Diag(FA->getLocation(),
2941  diag::override_keyword_only_allowed_on_virtual_member_functions)
2942  << (FA->isSpelledAsSealed() ? "sealed" : "final")
2943  << FixItHint::CreateRemoval(FA->getLocation());
2944  D->dropAttr<FinalAttr>();
2945  }
2946  return;
2947  }
2948 
2949  // C++11 [class.virtual]p5:
2950  // If a function is marked with the virt-specifier override and
2951  // does not override a member function of a base class, the program is
2952  // ill-formed.
2953  bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2954  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2955  Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2956  << MD->getDeclName();
2957 }
2958 
2960  if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2961  return;
2962  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2963  if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2964  return;
2965 
2966  SourceLocation Loc = MD->getLocation();
2967  SourceLocation SpellingLoc = Loc;
2968  if (getSourceManager().isMacroArgExpansion(Loc))
2969  SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2970  SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2971  if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2972  return;
2973 
2974  if (MD->size_overridden_methods() > 0) {
2975  unsigned DiagID = isa<CXXDestructorDecl>(MD)
2976  ? diag::warn_destructor_marked_not_override_overriding
2977  : diag::warn_function_marked_not_override_overriding;
2978  Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2979  const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2980  Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2981  }
2982 }
2983 
2984 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2985 /// function overrides a virtual member function marked 'final', according to
2986 /// C++11 [class.virtual]p4.
2988  const CXXMethodDecl *Old) {
2989  FinalAttr *FA = Old->getAttr<FinalAttr>();
2990  if (!FA)
2991  return false;
2992 
2993  Diag(New->getLocation(), diag::err_final_function_overridden)
2994  << New->getDeclName()
2995  << FA->isSpelledAsSealed();
2996  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2997  return true;
2998 }
2999 
3000 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3001  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3002  // FIXME: Destruction of ObjC lifetime types has side-effects.
3003  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3004  return !RD->isCompleteDefinition() ||
3005  !RD->hasTrivialDefaultConstructor() ||
3006  !RD->hasTrivialDestructor();
3007  return false;
3008 }
3009 
3012  llvm::find_if(list, [](const ParsedAttr &AL) {
3013  return AL.isDeclspecPropertyAttribute();
3014  });
3015  if (Itr != list.end())
3016  return &*Itr;
3017  return nullptr;
3018 }
3019 
3020 // Check if there is a field shadowing.
3021 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3022  DeclarationName FieldName,
3023  const CXXRecordDecl *RD,
3024  bool DeclIsField) {
3025  if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3026  return;
3027 
3028  // To record a shadowed field in a base
3029  std::map<CXXRecordDecl*, NamedDecl*> Bases;
3030  auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3031  CXXBasePath &Path) {
3032  const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3033  // Record an ambiguous path directly
3034  if (Bases.find(Base) != Bases.end())
3035  return true;
3036  for (const auto Field : Base->lookup(FieldName)) {
3037  if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3038  Field->getAccess() != AS_private) {
3039  assert(Field->getAccess() != AS_none);
3040  assert(Bases.find(Base) == Bases.end());
3041  Bases[Base] = Field;
3042  return true;
3043  }
3044  }
3045  return false;
3046  };
3047 
3048  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3049  /*DetectVirtual=*/true);
3050  if (!RD->lookupInBases(FieldShadowed, Paths))
3051  return;
3052 
3053  for (const auto &P : Paths) {
3054  auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3055  auto It = Bases.find(Base);
3056  // Skip duplicated bases
3057  if (It == Bases.end())
3058  continue;
3059  auto BaseField = It->second;
3060  assert(BaseField->getAccess() != AS_private);
3061  if (AS_none !=
3062  CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3063  Diag(Loc, diag::warn_shadow_field)
3064  << FieldName << RD << Base << DeclIsField;
3065  Diag(BaseField->getLocation(), diag::note_shadow_field);
3066  Bases.erase(It);
3067  }
3068  }
3069 }
3070 
3071 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3072 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3073 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3074 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3075 /// present (but parsing it has been deferred).
3076 NamedDecl *
3078  MultiTemplateParamsArg TemplateParameterLists,
3079  Expr *BW, const VirtSpecifiers &VS,
3080  InClassInitStyle InitStyle) {
3081  const DeclSpec &DS = D.getDeclSpec();
3082  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3083  DeclarationName Name = NameInfo.getName();
3084  SourceLocation Loc = NameInfo.getLoc();
3085 
3086  // For anonymous bitfields, the location should point to the type.
3087  if (Loc.isInvalid())
3088  Loc = D.getBeginLoc();
3089 
3090  Expr *BitWidth = static_cast<Expr*>(BW);
3091 
3092  assert(isa<CXXRecordDecl>(CurContext));
3093  assert(!DS.isFriendSpecified());
3094 
3095  bool isFunc = D.isDeclarationOfFunction();
3096  const ParsedAttr *MSPropertyAttr =
3098 
3099  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3100  // The Microsoft extension __interface only permits public member functions
3101  // and prohibits constructors, destructors, operators, non-public member
3102  // functions, static methods and data members.
3103  unsigned InvalidDecl;
3104  bool ShowDeclName = true;
3105  if (!isFunc &&
3106  (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3107  InvalidDecl = 0;
3108  else if (!isFunc)
3109  InvalidDecl = 1;
3110  else if (AS != AS_public)
3111  InvalidDecl = 2;
3112  else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3113  InvalidDecl = 3;
3114  else switch (Name.getNameKind()) {
3116  InvalidDecl = 4;
3117  ShowDeclName = false;
3118  break;
3119 
3121  InvalidDecl = 5;
3122  ShowDeclName = false;
3123  break;
3124 
3127  InvalidDecl = 6;
3128  break;
3129 
3130  default:
3131  InvalidDecl = 0;
3132  break;
3133  }
3134 
3135  if (InvalidDecl) {
3136  if (ShowDeclName)
3137  Diag(Loc, diag::err_invalid_member_in_interface)
3138  << (InvalidDecl-1) << Name;
3139  else
3140  Diag(Loc, diag::err_invalid_member_in_interface)
3141  << (InvalidDecl-1) << "";
3142  return nullptr;
3143  }
3144  }
3145 
3146  // C++ 9.2p6: A member shall not be declared to have automatic storage
3147  // duration (auto, register) or with the extern storage-class-specifier.
3148  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3149  // data members and cannot be applied to names declared const or static,
3150  // and cannot be applied to reference members.
3151  switch (DS.getStorageClassSpec()) {
3153  case DeclSpec::SCS_typedef:
3154  case DeclSpec::SCS_static:
3155  break;
3156  case DeclSpec::SCS_mutable:
3157  if (isFunc) {
3158  Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3159 
3160  // FIXME: It would be nicer if the keyword was ignored only for this
3161  // declarator. Otherwise we could get follow-up errors.
3163  }
3164  break;
3165  default:
3167  diag::err_storageclass_invalid_for_member);
3169  break;
3170  }
3171 
3172  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3174  !isFunc);
3175 
3176  if (DS.hasConstexprSpecifier() && isInstField) {
3178  Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3179  SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3180  if (InitStyle == ICIS_NoInit) {
3181  B << 0 << 0;
3183  B << FixItHint::CreateRemoval(ConstexprLoc);
3184  else {
3185  B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3187  const char *PrevSpec;
3188  unsigned DiagID;
3189  bool Failed = D.getMutableDeclSpec().SetTypeQual(
3190  DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3191  (void)Failed;
3192  assert(!Failed && "Making a constexpr member const shouldn't fail");
3193  }
3194  } else {
3195  B << 1;
3196  const char *PrevSpec;
3197  unsigned DiagID;
3199  *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3200  Context.getPrintingPolicy())) {
3201  assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3202  "This is the only DeclSpec that should fail to be applied");
3203  B << 1;
3204  } else {
3205  B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3206  isInstField = false;
3207  }
3208  }
3209  }
3210 
3211  NamedDecl *Member;
3212  if (isInstField) {
3213  CXXScopeSpec &SS = D.getCXXScopeSpec();
3214 
3215  // Data members must have identifiers for names.
3216  if (!Name.isIdentifier()) {
3217  Diag(Loc, diag::err_bad_variable_name)
3218  << Name;
3219  return nullptr;
3220  }
3221 
3222  IdentifierInfo *II = Name.getAsIdentifierInfo();
3223 
3224  // Member field could not be with "template" keyword.
3225  // So TemplateParameterLists should be empty in this case.
3226  if (TemplateParameterLists.size()) {
3227  TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3228  if (TemplateParams->size()) {
3229  // There is no such thing as a member field template.
3230  Diag(D.getIdentifierLoc(), diag::err_template_member)
3231  << II
3232  << SourceRange(TemplateParams->getTemplateLoc(),
3233  TemplateParams->getRAngleLoc());
3234  } else {
3235  // There is an extraneous 'template<>' for this member.
3236  Diag(TemplateParams->getTemplateLoc(),
3237  diag::err_template_member_noparams)
3238  << II
3239  << SourceRange(TemplateParams->getTemplateLoc(),
3240  TemplateParams->getRAngleLoc());
3241  }
3242  return nullptr;
3243  }
3244 
3245  if (SS.isSet() && !SS.isInvalid()) {
3246  // The user provided a superfluous scope specifier inside a class
3247  // definition:
3248  //
3249  // class X {
3250  // int X::member;
3251  // };
3252  if (DeclContext *DC = computeDeclContext(SS, false))
3253  diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3254  D.getName().getKind() ==
3256  else
3257  Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3258  << Name << SS.getRange();
3259 
3260  SS.clear();
3261  }
3262 
3263  if (MSPropertyAttr) {
3264  Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3265  BitWidth, InitStyle, AS, *MSPropertyAttr);
3266  if (!Member)
3267  return nullptr;
3268  isInstField = false;
3269  } else {
3270  Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3271  BitWidth, InitStyle, AS);
3272  if (!Member)
3273  return nullptr;
3274  }
3275 
3276  CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3277  } else {
3278  Member = HandleDeclarator(S, D, TemplateParameterLists);
3279  if (!Member)
3280  return nullptr;
3281 
3282  // Non-instance-fields can't have a bitfield.
3283  if (BitWidth) {
3284  if (Member->isInvalidDecl()) {
3285  // don't emit another diagnostic.
3286  } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3287  // C++ 9.6p3: A bit-field shall not be a static member.
3288  // "static member 'A' cannot be a bit-field"
3289  Diag(Loc, diag::err_static_not_bitfield)
3290  << Name << BitWidth->getSourceRange();
3291  } else if (isa<TypedefDecl>(Member)) {
3292  // "typedef member 'x' cannot be a bit-field"
3293  Diag(Loc, diag::err_typedef_not_bitfield)
3294  << Name << BitWidth->getSourceRange();
3295  } else {
3296  // A function typedef ("typedef int f(); f a;").
3297  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3298  Diag(Loc, diag::err_not_integral_type_bitfield)
3299  << Name << cast<ValueDecl>(Member)->getType()
3300  << BitWidth->getSourceRange();
3301  }
3302 
3303  BitWidth = nullptr;
3304  Member->setInvalidDecl();
3305  }
3306 
3307  NamedDecl *NonTemplateMember = Member;
3308  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3309  NonTemplateMember = FunTmpl->getTemplatedDecl();
3310  else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3311  NonTemplateMember = VarTmpl->getTemplatedDecl();
3312 
3313  Member->setAccess(AS);
3314 
3315  // If we have declared a member function template or static data member
3316  // template, set the access of the templated declaration as well.
3317  if (NonTemplateMember != Member)
3318  NonTemplateMember->setAccess(AS);
3319 
3320  // C++ [temp.deduct.guide]p3:
3321  // A deduction guide [...] for a member class template [shall be
3322  // declared] with the same access [as the template].
3323  if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3324  auto *TD = DG->getDeducedTemplate();
3325  // Access specifiers are only meaningful if both the template and the
3326  // deduction guide are from the same scope.
3327  if (AS != TD->getAccess() &&
3328  TD->getDeclContext()->getRedeclContext()->Equals(
3329  DG->getDeclContext()->getRedeclContext())) {
3330  Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3331  Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3332  << TD->getAccess();
3333  const AccessSpecDecl *LastAccessSpec = nullptr;
3334  for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3335  if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3336  LastAccessSpec = AccessSpec;
3337  }
3338  assert(LastAccessSpec && "differing access with no access specifier");
3339  Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3340  << AS;
3341  }
3342  }
3343  }
3344 
3345  if (VS.isOverrideSpecified())
3346  Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3347  if (VS.isFinalSpecified())
3348  Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3349  VS.isFinalSpelledSealed()));
3350 
3351  if (VS.getLastLocation().isValid()) {
3352  // Update the end location of a method that has a virt-specifiers.
3353  if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3354  MD->setRangeEnd(VS.getLastLocation());
3355  }
3356 
3357  CheckOverrideControl(Member);
3358 
3359  assert((Name || isInstField) && "No identifier for non-field ?");
3360 
3361  if (isInstField) {
3362  FieldDecl *FD = cast<FieldDecl>(Member);
3363  FieldCollector->Add(FD);
3364 
3365  if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3366  // Remember all explicit private FieldDecls that have a name, no side
3367  // effects and are not part of a dependent type declaration.
3368  if (!FD->isImplicit() && FD->getDeclName() &&
3369  FD->getAccess() == AS_private &&
3370  !FD->hasAttr<UnusedAttr>() &&
3371  !FD->getParent()->isDependentContext() &&
3373  UnusedPrivateFields.insert(FD);
3374  }
3375  }
3376 
3377  return Member;
3378 }
3379 
3380 namespace {
3381  class UninitializedFieldVisitor
3382  : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3383  Sema &S;
3384  // List of Decls to generate a warning on. Also remove Decls that become
3385  // initialized.
3386  llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3387  // List of base classes of the record. Classes are removed after their
3388  // initializers.
3389  llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3390  // Vector of decls to be removed from the Decl set prior to visiting the
3391  // nodes. These Decls may have been initialized in the prior initializer.
3392  llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3393  // If non-null, add a note to the warning pointing back to the constructor.
3394  const CXXConstructorDecl *Constructor;
3395  // Variables to hold state when processing an initializer list. When
3396  // InitList is true, special case initialization of FieldDecls matching
3397  // InitListFieldDecl.
3398  bool InitList;
3399  FieldDecl *InitListFieldDecl;
3400  llvm::SmallVector<unsigned, 4> InitFieldIndex;
3401 
3402  public:
3404  UninitializedFieldVisitor(Sema &S,
3405  llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3406  llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3407  : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3408  Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3409 
3410  // Returns true if the use of ME is not an uninitialized use.
3411  bool IsInitListMemberExprInitialized(MemberExpr *ME,
3412  bool CheckReferenceOnly) {
3414  bool ReferenceField = false;
3415  while (ME) {
3416  FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3417  if (!FD)
3418  return false;
3419  Fields.push_back(FD);
3420  if (FD->getType()->isReferenceType())
3421  ReferenceField = true;
3422  ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3423  }
3424 
3425  // Binding a reference to an uninitialized field is not an
3426  // uninitialized use.
3427  if (CheckReferenceOnly && !ReferenceField)
3428  return true;
3429 
3430  llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3431  // Discard the first field since it is the field decl that is being
3432  // initialized.
3433  for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3434  UsedFieldIndex.push_back((*I)->getFieldIndex());
3435  }
3436 
3437  for (auto UsedIter = UsedFieldIndex.begin(),
3438  UsedEnd = UsedFieldIndex.end(),
3439  OrigIter = InitFieldIndex.begin(),
3440  OrigEnd = InitFieldIndex.end();
3441  UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3442  if (*UsedIter < *OrigIter)
3443  return true;
3444  if (*UsedIter > *OrigIter)
3445  break;
3446  }
3447 
3448  return false;
3449  }
3450 
3451  void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3452  bool AddressOf) {
3453  if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3454  return;
3455 
3456  // FieldME is the inner-most MemberExpr that is not an anonymous struct
3457  // or union.
3458  MemberExpr *FieldME = ME;
3459 
3460  bool AllPODFields = FieldME->getType().isPODType(S.Context);
3461 
3462  Expr *Base = ME;
3463  while (MemberExpr *SubME =
3464  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3465 
3466  if (isa<VarDecl>(SubME->getMemberDecl()))
3467  return;
3468 
3469  if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3470  if (!FD->isAnonymousStructOrUnion())
3471  FieldME = SubME;
3472 
3473  if (!FieldME->getType().isPODType(S.Context))
3474  AllPODFields = false;
3475 
3476  Base = SubME->getBase();
3477  }
3478 
3479  if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3480  return;
3481 
3482  if (AddressOf && AllPODFields)
3483  return;
3484 
3485  ValueDecl* FoundVD = FieldME->getMemberDecl();
3486 
3487  if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3488  while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3489  BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3490  }
3491 
3492  if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3493  QualType T = BaseCast->getType();
3494  if (T->isPointerType() &&
3495  BaseClasses.count(T->getPointeeType())) {
3496  S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3497  << T->getPointeeType() << FoundVD;
3498  }
3499  }
3500  }
3501 
3502  if (!Decls.count(FoundVD))
3503  return;
3504 
3505  const bool IsReference = FoundVD->getType()->isReferenceType();
3506 
3507  if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3508  // Special checking for initializer lists.
3509  if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3510  return;
3511  }
3512  } else {
3513  // Prevent double warnings on use of unbounded references.
3514  if (CheckReferenceOnly && !IsReference)
3515  return;
3516  }
3517 
3518  unsigned diag = IsReference
3519  ? diag::warn_reference_field_is_uninit
3520  : diag::warn_field_is_uninit;
3521  S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3522  if (Constructor)
3523  S.Diag(Constructor->getLocation(),
3524  diag::note_uninit_in_this_constructor)
3525  << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3526 
3527  }
3528 
3529  void HandleValue(Expr *E, bool AddressOf) {
3530  E = E->IgnoreParens();
3531 
3532  if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3533  HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3534  AddressOf /*AddressOf*/);
3535  return;
3536  }
3537 
3538  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3539  Visit(CO->getCond());
3540  HandleValue(CO->getTrueExpr(), AddressOf);
3541  HandleValue(CO->getFalseExpr(), AddressOf);
3542  return;
3543  }
3544 
3545  if (BinaryConditionalOperator *BCO =
3546  dyn_cast<BinaryConditionalOperator>(E)) {
3547  Visit(BCO->getCond());
3548  HandleValue(BCO->getFalseExpr(), AddressOf);
3549  return;
3550  }
3551 
3552  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3553  HandleValue(OVE->getSourceExpr(), AddressOf);
3554  return;
3555  }
3556 
3557  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3558  switch (BO->getOpcode()) {
3559  default:
3560  break;
3561  case(BO_PtrMemD):
3562  case(BO_PtrMemI):
3563  HandleValue(BO->getLHS(), AddressOf);
3564  Visit(BO->getRHS());
3565  return;
3566  case(BO_Comma):
3567  Visit(BO->getLHS());
3568  HandleValue(BO->getRHS(), AddressOf);
3569  return;
3570  }
3571  }
3572 
3573  Visit(E);
3574  }
3575 
3576  void CheckInitListExpr(InitListExpr *ILE) {
3577  InitFieldIndex.push_back(0);
3578  for (auto Child : ILE->children()) {
3579  if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3580  CheckInitListExpr(SubList);
3581  } else {
3582  Visit(Child);
3583  }
3584  ++InitFieldIndex.back();
3585  }
3586  InitFieldIndex.pop_back();
3587  }
3588 
3589  void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3590  FieldDecl *Field, const Type *BaseClass) {
3591  // Remove Decls that may have been initialized in the previous
3592  // initializer.
3593  for (ValueDecl* VD : DeclsToRemove)
3594  Decls.erase(VD);
3595  DeclsToRemove.clear();
3596 
3597  Constructor = FieldConstructor;
3598  InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3599 
3600  if (ILE && Field) {
3601  InitList = true;
3602  InitListFieldDecl = Field;
3603  InitFieldIndex.clear();
3604  CheckInitListExpr(ILE);
3605  } else {
3606  InitList = false;
3607  Visit(E);
3608  }
3609 
3610  if (Field)
3611  Decls.erase(Field);
3612  if (BaseClass)
3613  BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3614  }
3615 
3616  void VisitMemberExpr(MemberExpr *ME) {
3617  // All uses of unbounded reference fields will warn.
3618  HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3619  }
3620 
3621  void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3622  if (E->getCastKind() == CK_LValueToRValue) {
3623  HandleValue(E->getSubExpr(), false /*AddressOf*/);
3624  return;
3625  }
3626 
3627  Inherited::VisitImplicitCastExpr(E);
3628  }
3629 
3630  void VisitCXXConstructExpr(CXXConstructExpr *E) {
3631  if (E->getConstructor()->isCopyConstructor()) {
3632  Expr *ArgExpr = E->getArg(0);
3633  if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3634  if (ILE->getNumInits() == 1)
3635  ArgExpr = ILE->getInit(0);
3636  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3637  if (ICE->getCastKind() == CK_NoOp)
3638  ArgExpr = ICE->getSubExpr();
3639  HandleValue(ArgExpr, false /*AddressOf*/);
3640  return;
3641  }
3642  Inherited::VisitCXXConstructExpr(E);
3643  }
3644 
3645  void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3646  Expr *Callee = E->getCallee();
3647  if (isa<MemberExpr>(Callee)) {
3648  HandleValue(Callee, false /*AddressOf*/);
3649  for (auto Arg : E->arguments())
3650  Visit(Arg);
3651  return;
3652  }
3653 
3654  Inherited::VisitCXXMemberCallExpr(E);
3655  }
3656 
3657  void VisitCallExpr(CallExpr *E) {
3658  // Treat std::move as a use.
3659  if (E->isCallToStdMove()) {
3660  HandleValue(E->getArg(0), /*AddressOf=*/false);
3661  return;
3662  }
3663 
3664  Inherited::VisitCallExpr(E);
3665  }
3666 
3667  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3668  Expr *Callee = E->getCallee();
3669 
3670  if (isa<UnresolvedLookupExpr>(Callee))
3671  return Inherited::VisitCXXOperatorCallExpr(E);
3672 
3673  Visit(Callee);
3674  for (auto Arg : E->arguments())
3675  HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3676  }
3677 
3678  void VisitBinaryOperator(BinaryOperator *E) {
3679  // If a field assignment is detected, remove the field from the
3680  // uninitiailized field set.
3681  if (E->getOpcode() == BO_Assign)
3682  if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3683  if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3684  if (!FD->getType()->isReferenceType())
3685  DeclsToRemove.push_back(FD);
3686 
3687  if (E->isCompoundAssignmentOp()) {
3688  HandleValue(E->getLHS(), false /*AddressOf*/);
3689  Visit(E->getRHS());
3690  return;
3691  }
3692 
3693  Inherited::VisitBinaryOperator(E);
3694  }
3695 
3696  void VisitUnaryOperator(UnaryOperator *E) {
3697  if (E->isIncrementDecrementOp()) {
3698  HandleValue(E->getSubExpr(), false /*AddressOf*/);
3699  return;
3700  }
3701  if (E->getOpcode() == UO_AddrOf) {
3702  if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3703  HandleValue(ME->getBase(), true /*AddressOf*/);
3704  return;
3705  }
3706  }
3707 
3708  Inherited::VisitUnaryOperator(E);
3709  }
3710  };
3711 
3712  // Diagnose value-uses of fields to initialize themselves, e.g.
3713  // foo(foo)
3714  // where foo is not also a parameter to the constructor.
3715  // Also diagnose across field uninitialized use such as
3716  // x(y), y(x)
3717  // TODO: implement -Wuninitialized and fold this into that framework.
3718  static void DiagnoseUninitializedFields(
3719  Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3720 
3721  if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3722  Constructor->getLocation())) {
3723  return;
3724  }
3725 
3726  if (Constructor->isInvalidDecl())
3727  return;
3728 
3729  const CXXRecordDecl *RD = Constructor->getParent();
3730 
3731  if (RD->getDescribedClassTemplate())
3732  return;
3733 
3734  // Holds fields that are uninitialized.
3735  llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3736 
3737  // At the beginning, all fields are uninitialized.
3738  for (auto *I : RD->decls()) {
3739  if (auto *FD = dyn_cast<FieldDecl>(I)) {
3740  UninitializedFields.insert(FD);
3741  } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3742  UninitializedFields.insert(IFD->getAnonField());
3743  }
3744  }
3745 
3746  llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3747  for (auto I : RD->bases())
3748  UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3749 
3750  if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3751  return;
3752 
3753  UninitializedFieldVisitor UninitializedChecker(SemaRef,
3754  UninitializedFields,
3755  UninitializedBaseClasses);
3756 
3757  for (const auto *FieldInit : Constructor->inits()) {
3758  if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3759  break;
3760 
3761  Expr *InitExpr = FieldInit->getInit();
3762  if (!InitExpr)
3763  continue;
3764 
3766  dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3767  InitExpr = Default->getExpr();
3768  if (!InitExpr)
3769  continue;
3770  // In class initializers will point to the constructor.
3771  UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3772  FieldInit->getAnyMember(),
3773  FieldInit->getBaseClass());
3774  } else {
3775  UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3776  FieldInit->getAnyMember(),
3777  FieldInit->getBaseClass());
3778  }
3779  }
3780  }
3781 } // namespace
3782 
3783 /// Enter a new C++ default initializer scope. After calling this, the
3784 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3785 /// parsing or instantiating the initializer failed.
3787  // Create a synthetic function scope to represent the call to the constructor
3788  // that notionally surrounds a use of this initializer.
3789  PushFunctionScope();
3790 }
3791 
3792 /// This is invoked after parsing an in-class initializer for a
3793 /// non-static C++ class member, and after instantiating an in-class initializer
3794 /// in a class template. Such actions are deferred until the class is complete.
3796  SourceLocation InitLoc,
3797  Expr *InitExpr) {
3798  // Pop the notional constructor scope we created earlier.
3799  PopFunctionScopeInfo(nullptr, D);
3800 
3801  FieldDecl *FD = dyn_cast<FieldDecl>(D);
3802  assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3803  "must set init style when field is created");
3804 
3805  if (!InitExpr) {
3806  D->setInvalidDecl();
3807  if (FD)
3809  return;
3810  }
3811 
3812  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3813  FD->setInvalidDecl();
3815  return;
3816  }
3817 
3818  ExprResult Init = InitExpr;
3819  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3820  InitializedEntity Entity =
3822  InitializationKind Kind =
3825  InitExpr->getBeginLoc(),
3826  InitExpr->getEndLoc())
3827  : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3828  InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3829  Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3830  if (Init.isInvalid()) {
3831  FD->setInvalidDecl();
3832  return;
3833  }
3834  }
3835 
3836  // C++11 [class.base.init]p7:
3837  // The initialization of each base and member constitutes a
3838  // full-expression.
3839  Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3840  if (Init.isInvalid()) {
3841  FD->setInvalidDecl();
3842  return;
3843  }
3844 
3845  InitExpr = Init.get();
3846 
3847  FD->setInClassInitializer(InitExpr);
3848 }
3849 
3850 /// Find the direct and/or virtual base specifiers that
3851 /// correspond to the given base type, for use in base initialization
3852 /// within a constructor.
3853 static bool FindBaseInitializer(Sema &SemaRef,
3854  CXXRecordDecl *ClassDecl,
3855  QualType BaseType,
3856  const CXXBaseSpecifier *&DirectBaseSpec,
3857  const CXXBaseSpecifier *&VirtualBaseSpec) {
3858  // First, check for a direct base class.
3859  DirectBaseSpec = nullptr;
3860  for (const auto &Base : ClassDecl->bases()) {
3861  if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3862  // We found a direct base of this type. That's what we're
3863  // initializing.
3864  DirectBaseSpec = &Base;
3865  break;
3866  }
3867  }
3868 
3869  // Check for a virtual base class.
3870  // FIXME: We might be able to short-circuit this if we know in advance that
3871  // there are no virtual bases.
3872  VirtualBaseSpec = nullptr;
3873  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3874  // We haven't found a base yet; search the class hierarchy for a
3875  // virtual base class.
3876  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3877  /*DetectVirtual=*/false);
3878  if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3879  SemaRef.Context.getTypeDeclType(ClassDecl),
3880  BaseType, Paths)) {
3881  for (CXXBasePaths::paths_iterator Path = Paths.begin();
3882  Path != Paths.end(); ++Path) {
3883  if (Path->back().Base->isVirtual()) {
3884  VirtualBaseSpec = Path->back().Base;
3885  break;
3886  }
3887  }
3888  }
3889  }
3890 
3891  return DirectBaseSpec || VirtualBaseSpec;
3892 }
3893 
3894 /// Handle a C++ member initializer using braced-init-list syntax.
3896 Sema::ActOnMemInitializer(Decl *ConstructorD,
3897  Scope *S,
3898  CXXScopeSpec &SS,
3899  IdentifierInfo *MemberOrBase,
3900  ParsedType TemplateTypeTy,
3901  const DeclSpec &DS,
3902  SourceLocation IdLoc,
3903  Expr *InitList,
3904  SourceLocation EllipsisLoc) {
3905  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3906  DS, IdLoc, InitList,
3907  EllipsisLoc);
3908 }
3909 
3910 /// Handle a C++ member initializer using parentheses syntax.
3912 Sema::ActOnMemInitializer(Decl *ConstructorD,
3913  Scope *S,
3914  CXXScopeSpec &SS,
3915  IdentifierInfo *MemberOrBase,
3916  ParsedType TemplateTypeTy,
3917  const DeclSpec &DS,
3918  SourceLocation IdLoc,
3919  SourceLocation LParenLoc,
3920  ArrayRef<Expr *> Args,
3921  SourceLocation RParenLoc,
3922  SourceLocation EllipsisLoc) {
3923  Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3924  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3925  DS, IdLoc, List, EllipsisLoc);
3926 }
3927 
3928 namespace {
3929 
3930 // Callback to only accept typo corrections that can be a valid C++ member
3931 // intializer: either a non-static field member or a base class.
3932 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
3933 public:
3934  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3935  : ClassDecl(ClassDecl) {}
3936 
3937  bool ValidateCandidate(const TypoCorrection &candidate) override {
3938  if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3939  if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3940  return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3941  return isa<TypeDecl>(ND);
3942  }
3943  return false;
3944  }
3945 
3946  std::unique_ptr<CorrectionCandidateCallback> clone() override {
3947  return std::make_unique<MemInitializerValidatorCCC>(*this);
3948  }
3949 
3950 private:
3951  CXXRecordDecl *ClassDecl;
3952 };
3953 
3954 }
3955 
3956 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3957  CXXScopeSpec &SS,
3958  ParsedType TemplateTypeTy,
3959  IdentifierInfo *MemberOrBase) {
3960  if (SS.getScopeRep() || TemplateTypeTy)
3961  return nullptr;
3962  DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3963  if (Result.empty())
3964  return nullptr;
3965  ValueDecl *Member;
3966  if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3967  (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3968  return Member;
3969  return nullptr;
3970 }
3971 
3972 /// Handle a C++ member initializer.
3974 Sema::BuildMemInitializer(Decl *ConstructorD,
3975  Scope *S,
3976  CXXScopeSpec &SS,
3977  IdentifierInfo *MemberOrBase,
3978  ParsedType TemplateTypeTy,
3979  const DeclSpec &DS,
3980  SourceLocation IdLoc,
3981  Expr *Init,
3982  SourceLocation EllipsisLoc) {
3983  ExprResult Res = CorrectDelayedTyposInExpr(Init);
3984  if (!Res.isUsable())
3985  return true;
3986  Init = Res.get();
3987 
3988  if (!ConstructorD)
3989  return true;
3990 
3991  AdjustDeclIfTemplate(ConstructorD);
3992 
3993  CXXConstructorDecl *Constructor
3994  = dyn_cast<CXXConstructorDecl>(ConstructorD);
3995  if (!Constructor) {
3996  // The user wrote a constructor initializer on a function that is
3997  // not a C++ constructor. Ignore the error for now, because we may
3998  // have more member initializers coming; we'll diagnose it just
3999  // once in ActOnMemInitializers.
4000  return true;
4001  }
4002 
4003  CXXRecordDecl *ClassDecl = Constructor->getParent();
4004 
4005  // C++ [class.base.init]p2:
4006  // Names in a mem-initializer-id are looked up in the scope of the
4007  // constructor's class and, if not found in that scope, are looked
4008  // up in the scope containing the constructor's definition.
4009  // [Note: if the constructor's class contains a member with the
4010  // same name as a direct or virtual base class of the class, a
4011  // mem-initializer-id naming the member or base class and composed
4012  // of a single identifier refers to the class member. A
4013  // mem-initializer-id for the hidden base class may be specified
4014  // using a qualified name. ]
4015 
4016  // Look for a member, first.
4017  if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4018  ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4019  if (EllipsisLoc.isValid())
4020  Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4021  << MemberOrBase
4022  << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4023 
4024  return BuildMemberInitializer(Member, Init, IdLoc);
4025  }
4026  // It didn't name a member, so see if it names a class.
4027  QualType BaseType;
4028  TypeSourceInfo *TInfo = nullptr;
4029 
4030  if (TemplateTypeTy) {
4031  BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4032  if (BaseType.isNull())
4033  return true;
4034  } else if (DS.getTypeSpecType() == TST_decltype) {
4035  BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4036  } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4037  Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4038  return true;
4039  } else {
4040  LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4041  LookupParsedName(R, S, &SS);
4042 
4043  TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4044  if (!TyD) {
4045  if (R.isAmbiguous()) return true;
4046 
4047  // We don't want access-control diagnostics here.
4048  R.suppressDiagnostics();
4049 
4050  if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4051  bool NotUnknownSpecialization = false;
4052  DeclContext *DC = computeDeclContext(SS, false);
4053  if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4054  NotUnknownSpecialization = !Record->hasAnyDependentBases();
4055 
4056  if (!NotUnknownSpecialization) {
4057  // When the scope specifier can refer to a member of an unknown
4058  // specialization, we take it as a type name.
4059  BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4060  SS.getWithLocInContext(Context),
4061  *MemberOrBase, IdLoc);
4062  if (BaseType.isNull())
4063  return true;
4064 
4065  TInfo = Context.CreateTypeSourceInfo(BaseType);
4068  if (!TL.isNull()) {
4069  TL.setNameLoc(IdLoc);
4071  TL.setQualifierLoc(SS.getWithLocInContext(Context));
4072  }
4073 
4074  R.clear();
4075  R.setLookupName(MemberOrBase);
4076  }
4077  }
4078 
4079  // If no results were found, try to correct typos.
4080  TypoCorrection Corr;
4081  MemInitializerValidatorCCC CCC(ClassDecl);
4082  if (R.empty() && BaseType.isNull() &&
4083  (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4084  CCC, CTK_ErrorRecovery, ClassDecl))) {
4085  if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4086  // We have found a non-static data member with a similar
4087  // name to what was typed; complain and initialize that
4088  // member.
4089  diagnoseTypo(Corr,
4090  PDiag(diag::err_mem_init_not_member_or_class_suggest)
4091  << MemberOrBase << true);
4092  return BuildMemberInitializer(Member, Init, IdLoc);
4093  } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4094  const CXXBaseSpecifier *DirectBaseSpec;
4095  const CXXBaseSpecifier *VirtualBaseSpec;
4096  if (FindBaseInitializer(*this, ClassDecl,
4097  Context.getTypeDeclType(Type),
4098  DirectBaseSpec, VirtualBaseSpec)) {
4099  // We have found a direct or virtual base class with a
4100  // similar name to what was typed; complain and initialize
4101  // that base class.
4102  diagnoseTypo(Corr,
4103  PDiag(diag::err_mem_init_not_member_or_class_suggest)
4104  << MemberOrBase << false,
4105  PDiag() /*Suppress note, we provide our own.*/);
4106 
4107  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4108  : VirtualBaseSpec;
4109  Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4110  << BaseSpec->getType() << BaseSpec->getSourceRange();
4111 
4112  TyD = Type;
4113  }
4114  }
4115  }
4116 
4117  if (!TyD && BaseType.isNull()) {
4118  Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4119  << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4120  return true;
4121  }
4122  }
4123 
4124  if (BaseType.isNull()) {
4125  BaseType = Context.getTypeDeclType(TyD);
4126  MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4127  if (SS.isSet()) {
4128  BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4129  BaseType);
4130  TInfo = Context.CreateTypeSourceInfo(BaseType);
4132  TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4134  TL.setQualifierLoc(SS.getWithLocInContext(Context));
4135  }
4136  }
4137  }
4138 
4139  if (!TInfo)
4140  TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4141 
4142  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4143 }
4144 
4147  SourceLocation IdLoc) {
4148  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4149  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4150  assert((DirectMember || IndirectMember) &&
4151  "Member must be a FieldDecl or IndirectFieldDecl");
4152 
4153  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4154  return true;
4155 
4156  if (Member->isInvalidDecl())
4157  return true;
4158 
4159  MultiExprArg Args;
4160  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4161  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4162  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4163  Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4164  } else {
4165  // Template instantiation doesn't reconstruct ParenListExprs for us.
4166  Args = Init;
4167  }
4168 
4169  SourceRange InitRange = Init->getSourceRange();
4170 
4171  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4172  // Can't check initialization for a member of dependent type or when
4173  // any of the arguments are type-dependent expressions.
4174  DiscardCleanupsInEvaluationContext();
4175  } else {
4176  bool InitList = false;
4177  if (isa<InitListExpr>(Init)) {
4178  InitList = true;
4179  Args = Init;
4180  }
4181 
4182  // Initialize the member.
4183  InitializedEntity MemberEntity =
4184  DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4185  : InitializedEntity::InitializeMember(IndirectMember,
4186  nullptr);
4187  InitializationKind Kind =
4189  IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4190  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4191  InitRange.getEnd());
4192 
4193  InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4194  ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4195  nullptr);
4196  if (MemberInit.isInvalid())
4197  return true;
4198 
4199  // C++11 [class.base.init]p7:
4200  // The initialization of each base and member constitutes a
4201  // full-expression.
4202  MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4203  /*DiscardedValue*/ false);
4204  if (MemberInit.isInvalid())
4205  return true;
4206 
4207  Init = MemberInit.get();
4208  }
4209 
4210  if (DirectMember) {
4211  return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4212  InitRange.getBegin(), Init,
4213  InitRange.getEnd());
4214  } else {
4215  return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4216  InitRange.getBegin(), Init,
4217  InitRange.getEnd());
4218  }
4219 }
4220 
4223  CXXRecordDecl *ClassDecl) {
4224  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4225  if (!LangOpts.CPlusPlus11)
4226  return Diag(NameLoc, diag::err_delegating_ctor)
4227  << TInfo->getTypeLoc().getLocalSourceRange();
4228  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4229 
4230  bool InitList = true;
4231  MultiExprArg Args = Init;
4232  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4233  InitList = false;
4234  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4235  }
4236 
4237  SourceRange InitRange = Init->getSourceRange();
4238  // Initialize the object.
4240  QualType(ClassDecl->getTypeForDecl(), 0));
4241  InitializationKind Kind =
4243  NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4244  : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4245  InitRange.getEnd());
4246  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4247  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4248  Args, nullptr);
4249  if (DelegationInit.isInvalid())
4250  return true;
4251 
4252  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4253  "Delegating constructor with no target?");
4254 
4255  // C++11 [class.base.init]p7:
4256  // The initialization of each base and member constitutes a
4257  // full-expression.
4258  DelegationInit = ActOnFinishFullExpr(
4259  DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4260  if (DelegationInit.isInvalid())
4261  return true;
4262 
4263  // If we are in a dependent context, template instantiation will
4264  // perform this type-checking again. Just save the arguments that we
4265  // received in a ParenListExpr.
4266  // FIXME: This isn't quite ideal, since our ASTs don't capture all
4267  // of the information that we have about the base
4268  // initializer. However, deconstructing the ASTs is a dicey process,
4269  // and this approach is far more likely to get the corner cases right.
4270  if (CurContext->isDependentContext())
4271  DelegationInit = Init;
4272 
4273  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4274  DelegationInit.getAs<Expr>(),
4275  InitRange.getEnd());
4276 }
4277 
4280  Expr *Init, CXXRecordDecl *ClassDecl,
4281  SourceLocation EllipsisLoc) {
4282  SourceLocation BaseLoc
4283  = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4284 
4285  if (!BaseType->isDependentType() && !BaseType->isRecordType())
4286  return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4287  << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4288 
4289  // C++ [class.base.init]p2:
4290  // [...] Unless the mem-initializer-id names a nonstatic data
4291  // member of the constructor's class or a direct or virtual base
4292  // of that class, the mem-initializer is ill-formed. A
4293  // mem-initializer-list can initialize a base class using any
4294  // name that denotes that base class type.
4295  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4296 
4297  SourceRange InitRange = Init->getSourceRange();
4298  if (EllipsisLoc.isValid()) {
4299  // This is a pack expansion.
4300  if (!BaseType->containsUnexpandedParameterPack()) {
4301  Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4302  << SourceRange(BaseLoc, InitRange.getEnd());
4303 
4304  EllipsisLoc = SourceLocation();
4305  }
4306  } else {
4307  // Check for any unexpanded parameter packs.
4308  if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4309  return true;
4310 
4311  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4312  return true;
4313  }
4314 
4315  // Check for direct and virtual base classes.
4316  const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4317  const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4318  if (!Dependent) {
4319  if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4320  BaseType))
4321  return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4322 
4323  FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4324  VirtualBaseSpec);
4325 
4326  // C++ [base.class.init]p2:
4327  // Unless the mem-initializer-id names a nonstatic data member of the
4328  // constructor's class or a direct or virtual base of that class, the
4329  // mem-initializer is ill-formed.
4330  if (!DirectBaseSpec && !VirtualBaseSpec) {
4331  // If the class has any dependent bases, then it's possible that
4332  // one of those types will resolve to the same type as
4333  // BaseType. Therefore, just treat this as a dependent base
4334  // class initialization. FIXME: Should we try to check the
4335  // initialization anyway? It seems odd.
4336  if (ClassDecl->hasAnyDependentBases())
4337  Dependent = true;
4338  else
4339  return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4340  << BaseType << Context.getTypeDeclType(ClassDecl)
4341  << BaseTInfo->getTypeLoc().getLocalSourceRange();
4342  }
4343  }
4344 
4345  if (Dependent) {
4346  DiscardCleanupsInEvaluationContext();
4347 
4348  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4349  /*IsVirtual=*/false,
4350  InitRange.getBegin(), Init,
4351  InitRange.getEnd(), EllipsisLoc);
4352  }
4353 
4354  // C++ [base.class.init]p2:
4355  // If a mem-initializer-id is ambiguous because it designates both
4356  // a direct non-virtual base class and an inherited virtual base
4357  // class, the mem-initializer is ill-formed.
4358  if (DirectBaseSpec && VirtualBaseSpec)
4359  return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4360  << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4361 
4362  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4363  if (!BaseSpec)
4364  BaseSpec = VirtualBaseSpec;
4365 
4366  // Initialize the base.
4367  bool InitList = true;
4368  MultiExprArg Args = Init;
4369  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4370  InitList = false;
4371  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4372  }
4373 
4374  InitializedEntity BaseEntity =
4375  InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4376  InitializationKind Kind =
4377  InitList ? InitializationKind::CreateDirectList(BaseLoc)
4378  : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4379  InitRange.getEnd());
4380  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4381  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4382  if (BaseInit.isInvalid())
4383  return true;
4384 
4385  // C++11 [class.base.init]p7:
4386  // The initialization of each base and member constitutes a
4387  // full-expression.
4388  BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4389  /*DiscardedValue*/ false);
4390  if (BaseInit.isInvalid())
4391  return true;
4392 
4393  // If we are in a dependent context, template instantiation will
4394  // perform this type-checking again. Just save the arguments that we
4395  // received in a ParenListExpr.
4396  // FIXME: This isn't quite ideal, since our ASTs don't capture all
4397  // of the information that we have about the base
4398  // initializer. However, deconstructing the ASTs is a dicey process,
4399  // and this approach is far more likely to get the corner cases right.
4400  if (CurContext->isDependentContext())
4401  BaseInit = Init;
4402 
4403  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4404  BaseSpec->isVirtual(),
4405  InitRange.getBegin(),
4406  BaseInit.getAs<Expr>(),
4407  InitRange.getEnd(), EllipsisLoc);
4408 }
4409 
4410 // Create a static_cast<T&&>(expr).
4411 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4412  if (T.isNull()) T = E->getType();
4413  QualType TargetType = SemaRef.BuildReferenceType(
4414  T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4415  SourceLocation ExprLoc = E->getBeginLoc();
4416  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4417  TargetType, ExprLoc);
4418 
4419  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4420  SourceRange(ExprLoc, ExprLoc),
4421  E->getSourceRange()).get();
4422 }
4423 
4424 /// ImplicitInitializerKind - How an implicit base or member initializer should
4425 /// initialize its base or member.
4431 };
4432 
4433 static bool
4435  ImplicitInitializerKind ImplicitInitKind,
4436  CXXBaseSpecifier *BaseSpec,
4437  bool IsInheritedVirtualBase,
4438  CXXCtorInitializer *&CXXBaseInit) {
4439  InitializedEntity InitEntity
4440  = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4441  IsInheritedVirtualBase);
4442 
4443  ExprResult BaseInit;
4444 
4445  switch (ImplicitInitKind) {
4446  case IIK_Inherit:
4447  case IIK_Default: {
4448  InitializationKind InitKind
4450  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4451  BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4452  break;
4453  }
4454 
4455  case IIK_Move:
4456  case IIK_Copy: {
4457  bool Moving = ImplicitInitKind == IIK_Move;
4458  ParmVarDecl *Param = Constructor->getParamDecl(0);
4459  QualType ParamType = Param->getType().getNonReferenceType();
4460 
4461  Expr *CopyCtorArg =
4463  SourceLocation(), Param, false,
4464  Constructor->getLocation(), ParamType,
4465  VK_LValue, nullptr);
4466 
4467  SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4468 
4469  // Cast to the base class to avoid ambiguities.
4470  QualType ArgTy =
4471  SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4472  ParamType.getQualifiers());
4473 
4474  if (Moving) {
4475  CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4476  }
4477 
4478  CXXCastPath BasePath;
4479  BasePath.push_back(BaseSpec);
4480  CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4481  CK_UncheckedDerivedToBase,
4482  Moving ? VK_XValue : VK_LValue,
4483  &BasePath).get();
4484 
4485  InitializationKind InitKind
4488  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4489  BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4490  break;
4491  }
4492  }
4493 
4494  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4495  if (BaseInit.isInvalid())
4496  return true;
4497 
4498  CXXBaseInit =
4499  new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4500  SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4501  SourceLocation()),
4502  BaseSpec->isVirtual(),
4503  SourceLocation(),
4504  BaseInit.getAs<Expr>(),
4505  SourceLocation(),
4506  SourceLocation());
4507 
4508  return false;
4509 }
4510 
4511 static bool RefersToRValueRef(Expr *MemRef) {
4512  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4513  return Referenced->getType()->isRValueReferenceType();
4514 }
4515 
4516 static bool
4518  ImplicitInitializerKind ImplicitInitKind,
4519  FieldDecl *Field, IndirectFieldDecl *Indirect,
4520  CXXCtorInitializer *&CXXMemberInit) {
4521  if (Field->isInvalidDecl())
4522  return true;
4523 
4524  SourceLocation Loc = Constructor->getLocation();
4525 
4526  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4527  bool Moving = ImplicitInitKind == IIK_Move;
4528  ParmVarDecl *Param = Constructor->getParamDecl(0);
4529  QualType ParamType = Param->getType().getNonReferenceType();
4530 
4531  // Suppress copying zero-width bitfields.
4532  if (Field->isZeroLengthBitField(SemaRef.Context))
4533  return false;
4534 
4535  Expr *MemberExprBase =
4537  SourceLocation(), Param, false,
4538  Loc, ParamType, VK_LValue, nullptr);
4539 
4540  SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4541 
4542  if (Moving) {
4543  MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4544  }
4545 
4546  // Build a reference to this field within the parameter.
4547  CXXScopeSpec SS;
4548  LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4550  MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4551  : cast<ValueDecl>(Field), AS_public);
4552  MemberLookup.resolveKind();
4553  ExprResult CtorArg
4554  = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4555  ParamType, Loc,
4556  /*IsArrow=*/false,
4557  SS,
4558  /*TemplateKWLoc=*/SourceLocation(),
4559  /*FirstQualifierInScope=*/nullptr,
4560  MemberLookup,
4561  /*TemplateArgs=*/nullptr,
4562  /*S*/nullptr);
4563  if (CtorArg.isInvalid())
4564  return true;
4565 
4566  // C++11 [class.copy]p15:
4567  // - if a member m has rvalue reference type T&&, it is direct-initialized
4568  // with static_cast<T&&>(x.m);
4569  if (RefersToRValueRef(CtorArg.get())) {
4570  CtorArg = CastForMoving(SemaRef, CtorArg.get());
4571  }
4572 
4573  InitializedEntity Entity =
4574  Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4575  /*Implicit*/ true)
4576  : InitializedEntity::InitializeMember(Field, nullptr,
4577  /*Implicit*/ true);
4578 
4579  // Direct-initialize to use the copy constructor.
4580  InitializationKind InitKind =
4582 
4583  Expr *CtorArgE = CtorArg.getAs<Expr>();
4584  InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4585  ExprResult MemberInit =
4586  InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4587  MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4588  if (MemberInit.isInvalid())
4589  return true;
4590 
4591  if (Indirect)
4592  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4593  SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4594  else
4595  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4596  SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4597  return false;
4598  }
4599 
4600  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4601  "Unhandled implicit init kind!");
4602 
4603  QualType FieldBaseElementType =
4604  SemaRef.Context.getBaseElementType(Field->getType());
4605 
4606  if (FieldBaseElementType->isRecordType()) {
4607  InitializedEntity InitEntity =
4608  Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4609  /*Implicit*/ true)
4610  : InitializedEntity::InitializeMember(Field, nullptr,
4611  /*Implicit*/ true);
4612  InitializationKind InitKind =
4614 
4615  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4616  ExprResult MemberInit =
4617  InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4618 
4619  MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4620  if (MemberInit.isInvalid())
4621  return true;
4622 
4623  if (Indirect)
4624  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4625  Indirect, Loc,
4626  Loc,
4627  MemberInit.get(),
4628  Loc);
4629  else
4630  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4631  Field, Loc, Loc,
4632  MemberInit.get(),
4633  Loc);
4634  return false;
4635  }
4636 
4637  if (!Field->getParent()->isUnion()) {
4638  if (FieldBaseElementType->isReferenceType()) {
4639  SemaRef.Diag(Constructor->getLocation(),
4640  diag::err_uninitialized_member_in_ctor)
4641  << (int)Constructor->isImplicit()
4642  << SemaRef.Context.getTagDeclType(Constructor->getParent())
4643  << 0 << Field->getDeclName();
4644  SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4645  return true;
4646  }
4647 
4648  if (FieldBaseElementType.isConstQualified()) {
4649  SemaRef.Diag(Constructor->getLocation(),
4650  diag::err_uninitialized_member_in_ctor)
4651  << (int)Constructor->isImplicit()
4652  << SemaRef.Context.getTagDeclType(Constructor->getParent())
4653  << 1 << Field->getDeclName();
4654  SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4655  return true;
4656  }
4657  }
4658 
4659  if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4660  // ARC and Weak:
4661  // Default-initialize Objective-C pointers to NULL.
4662  CXXMemberInit
4663  = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4664  Loc, Loc,
4665  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4666  Loc);
4667  return false;
4668  }
4669 
4670  // Nothing to initialize.
4671  CXXMemberInit = nullptr;
4672  return false;
4673 }
4674 
4675 namespace {
4676 struct BaseAndFieldInfo {
4677  Sema &S;
4678  CXXConstructorDecl *Ctor;
4679  bool AnyErrorsInInits;
4681  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4683  llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4684 
4685  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4686  : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4687  bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4688  if (Ctor->getInheritedConstructor())
4689  IIK = IIK_Inherit;
4690  else if (Generated && Ctor->isCopyConstructor())
4691  IIK = IIK_Copy;
4692  else if (Generated && Ctor->isMoveConstructor())
4693  IIK = IIK_Move;
4694  else
4695  IIK = IIK_Default;
4696  }
4697 
4698  bool isImplicitCopyOrMove() const {
4699  switch (IIK) {
4700  case IIK_Copy:
4701  case IIK_Move:
4702  return true;
4703 
4704  case IIK_Default:
4705  case IIK_Inherit:
4706  return false;
4707  }
4708 
4709  llvm_unreachable("Invalid ImplicitInitializerKind!");
4710  }
4711 
4712  bool addFieldInitializer(CXXCtorInitializer *Init) {
4713  AllToInit.push_back(Init);
4714 
4715  // Check whether this initializer makes the field "used".
4716  if (Init->getInit()->HasSideEffects(S.Context))
4717  S.UnusedPrivateFields.remove(Init->getAnyMember());
4718 
4719  return false;
4720  }
4721 
4722  bool isInactiveUnionMember(FieldDecl *Field) {
4723  RecordDecl *Record = Field->getParent();
4724  if (!Record->isUnion())
4725  return false;
4726 
4727  if (FieldDecl *Active =
4728  ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4729  return Active != Field->getCanonicalDecl();
4730 
4731  // In an implicit copy or move constructor, ignore any in-class initializer.
4732  if (isImplicitCopyOrMove())
4733  return true;
4734 
4735  // If there's no explicit initialization, the field is active only if it
4736  // has an in-class initializer...
4737  if (Field->hasInClassInitializer())
4738  return false;
4739  // ... or it's an anonymous struct or union whose class has an in-class
4740  // initializer.
4741  if (!Field->isAnonymousStructOrUnion())
4742  return true;
4743  CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4744  return !FieldRD->hasInClassInitializer();
4745  }
4746 
4747  /// Determine whether the given field is, or is within, a union member
4748  /// that is inactive (because there was an initializer given for a different
4749  /// member of the union, or because the union was not initialized at all).
4750  bool isWithinInactiveUnionMember(FieldDecl *Field,
4751  IndirectFieldDecl *Indirect) {
4752  if (!Indirect)
4753  return isInactiveUnionMember(Field);
4754 
4755  for (auto *C : Indirect->chain()) {
4756  FieldDecl *Field = dyn_cast<FieldDecl>(C);
4757  if (Field && isInactiveUnionMember(Field))
4758  return true;
4759  }
4760  return false;
4761  }
4762 };
4763 }
4764 
4765 /// Determine whether the given type is an incomplete or zero-lenfgth
4766 /// array type.
4768  if (T->isIncompleteArrayType())
4769  return true;
4770 
4771  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4772  if (!ArrayT->getSize())
4773  return true;
4774 
4775  T = ArrayT->getElementType();
4776  }
4777 
4778  return false;
4779 }
4780 
4781 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4782  FieldDecl *Field,
4783  IndirectFieldDecl *Indirect = nullptr) {
4784  if (Field->isInvalidDecl())
4785  return false;
4786 
4787  // Overwhelmingly common case: we have a direct initializer for this field.
4788  if (CXXCtorInitializer *Init =
4789  Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4790  return Info.addFieldInitializer(Init);
4791 
4792  // C++11 [class.base.init]p8:
4793  // if the entity is a non-static data member that has a
4794  // brace-or-equal-initializer and either
4795  // -- the constructor's class is a union and no other variant member of that
4796  // union is designated by a mem-initializer-id or
4797  // -- the constructor's class is not a union, and, if the entity is a member
4798  // of an anonymous union, no other member of that union is designated by
4799  // a mem-initializer-id,
4800  // the entity is initialized as specified in [dcl.init].
4801  //
4802  // We also apply the same rules to handle anonymous structs within anonymous
4803  // unions.
4804  if (Info.isWithinInactiveUnionMember(Field, Indirect))
4805  return false;
4806 
4807  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4808  ExprResult DIE =
4809  SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4810  if (DIE.isInvalid())
4811  return true;
4812 
4813  auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4814  SemaRef.checkInitializerLifetime(Entity, DIE.get());
4815 
4816  CXXCtorInitializer *Init;
4817  if (Indirect)
4818  Init = new (SemaRef.Context)
4819  CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4820  SourceLocation(), DIE.get(), SourceLocation());
4821  else
4822  Init = new (SemaRef.Context)
4823  CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4824  SourceLocation(), DIE.get(), SourceLocation());
4825  return Info.addFieldInitializer(Init);
4826  }
4827 
4828  // Don't initialize incomplete or zero-length arrays.
4829  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4830  return false;
4831 
4832  // Don't try to build an implicit initializer if there were semantic
4833  // errors in any of the initializers (and therefore we might be
4834  // missing some that the user actually wrote).
4835  if (Info.AnyErrorsInInits)
4836  return false;
4837 
4838  CXXCtorInitializer *Init = nullptr;
4839  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4840  Indirect, Init))
4841  return true;
4842 
4843  if (!Init)
4844  return false;
4845 
4846  return Info.addFieldInitializer(Init);
4847 }
4848 
4849 bool
4852  assert(Initializer->isDelegatingInitializer());
4853  Constructor->setNumCtorInitializers(1);
4854  CXXCtorInitializer **initializer =
4855  new (Context) CXXCtorInitializer*[1];
4856  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4857  Constructor->setCtorInitializers(initializer);
4858 
4859  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4860  MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4861  DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4862  }
4863 
4864  DelegatingCtorDecls.push_back(Constructor);
4865 
4866  DiagnoseUninitializedFields(*this, Constructor);
4867 
4868  return false;
4869 }
4870 
4871 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4872  ArrayRef<CXXCtorInitializer *> Initializers) {
4873  if (Constructor->isDependentContext()) {
4874  // Just store the initializers as written, they will be checked during
4875  // instantiation.
4876  if (!Initializers.empty()) {
4877  Constructor->setNumCtorInitializers(Initializers.size());
4878  CXXCtorInitializer **baseOrMemberInitializers =
4879  new (Context) CXXCtorInitializer*[Initializers.size()];
4880  memcpy(baseOrMemberInitializers, Initializers.data(),
4881  Initializers.size() * sizeof(CXXCtorInitializer*));
4882  Constructor->setCtorInitializers(baseOrMemberInitializers);
4883  }
4884 
4885  // Let template instantiation know whether we had errors.
4886  if (AnyErrors)
4887  Constructor->setInvalidDecl();
4888 
4889  return false;
4890  }
4891 
4892  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4893 
4894  // We need to build the initializer AST according to order of construction
4895  // and not what user specified in the Initializers list.
4896  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4897  if (!ClassDecl)
4898  return true;
4899 
4900  bool HadError = false;
4901 
4902  for (unsigned i = 0; i < Initializers.size(); i++) {
4903  CXXCtorInitializer *Member = Initializers[i];
4904 
4905  if (Member->isBaseInitializer())
4906  Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4907  else {
4908  Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4909 
4910  if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4911  for (auto *C : F->chain()) {
4912  FieldDecl *FD = dyn_cast<FieldDecl>(C);
4913  if (FD && FD->getParent()->isUnion())
4914  Info.ActiveUnionMember.insert(std::make_pair(
4915  FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4916  }
4917  } else if (FieldDecl *FD = Member->getMember()) {
4918  if (FD->getParent()->isUnion())
4919  Info.ActiveUnionMember.insert(std::make_pair(
4920  FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4921  }
4922  }
4923  }
4924 
4925  // Keep track of the direct virtual bases.
4926  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4927  for (auto &I : ClassDecl->bases()) {
4928  if (I.isVirtual())
4929  DirectVBases.insert(&I);
4930  }
4931 
4932  // Push virtual bases before others.
4933  for (auto &VBase : ClassDecl->vbases()) {
4935  = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4936  // [class.base.init]p7, per DR257:
4937  // A mem-initializer where the mem-initializer-id names a virtual base
4938  // class is ignored during execution of a constructor of any class that
4939  // is not the most derived class.
4940  if (ClassDecl->isAbstract()) {
4941  // FIXME: Provide a fixit to remove the base specifier. This requires
4942  // tracking the location of the associated comma for a base specifier.
4943  Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4944  << VBase.getType() << ClassDecl;
4945  DiagnoseAbstractType(ClassDecl);
4946  }
4947 
4948  Info.AllToInit.push_back(Value);
4949  } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4950  // [class.base.init]p8, per DR257:
4951  // If a given [...] base class is not named by a mem-initializer-id
4952  // [...] and the entity is not a virtual base class of an abstract
4953  // class, then [...] the entity is default-initialized.
4954  bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4955  CXXCtorInitializer *CXXBaseInit;
4956  if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4957  &VBase, IsInheritedVirtualBase,
4958  CXXBaseInit)) {
4959  HadError = true;
4960  continue;
4961  }
4962 
4963  Info.AllToInit.push_back(CXXBaseInit);
4964  }
4965  }
4966 
4967  // Non-virtual bases.
4968  for (auto &Base : ClassDecl->bases()) {
4969  // Virtuals are in the virtual base list and already constructed.
4970  if (Base.isVirtual())
4971  continue;
4972 
4974  = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4975  Info.AllToInit.push_back(Value);
4976  } else if (!AnyErrors) {
4977  CXXCtorInitializer *CXXBaseInit;
4978  if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4979  &Base, /*IsInheritedVirtualBase=*/false,
4980  CXXBaseInit)) {
4981  HadError = true;
4982  continue;
4983  }
4984 
4985  Info.AllToInit.push_back(CXXBaseInit);
4986  }
4987  }
4988 
4989  // Fields.
4990  for (auto *Mem : ClassDecl->decls()) {
4991  if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4992  // C++ [class.bit]p2:
4993  // A declaration for a bit-field that omits the identifier declares an
4994  // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4995  // initialized.
4996  if (F->isUnnamedBitfield())
4997  continue;
4998 
4999  // If we're not generating the implicit copy/move constructor, then we'll
5000  // handle anonymous struct/union fields based on their individual
5001  // indirect fields.
5002  if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5003  continue;
5004 
5005  if (CollectFieldInitializer(*this, Info, F))
5006  HadError = true;
5007  continue;
5008  }
5009 
5010  // Beyond this point, we only consider default initialization.
5011  if (Info.isImplicitCopyOrMove())
5012  continue;
5013 
5014  if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5015  if (F->getType()->isIncompleteArrayType()) {
5016  assert(ClassDecl->hasFlexibleArrayMember() &&
5017  "Incomplete array type is not valid");
5018  continue;
5019  }
5020 
5021  // Initialize each field of an anonymous struct individually.
5022  if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5023  HadError = true;
5024 
5025  continue;
5026  }
5027  }
5028 
5029  unsigned NumInitializers = Info.AllToInit.size();
5030  if (NumInitializers > 0) {
5031  Constructor->setNumCtorInitializers(NumInitializers);
5032  CXXCtorInitializer **baseOrMemberInitializers =
5033  new (Context) CXXCtorInitializer*[NumInitializers];
5034  memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5035  NumInitializers * sizeof(CXXCtorInitializer*));
5036  Constructor->setCtorInitializers(baseOrMemberInitializers);
5037 
5038  // Constructors implicitly reference the base and member
5039  // destructors.
5040  MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5041  Constructor->getParent());
5042  }
5043 
5044  return HadError;
5045 }
5046 
5048  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5049  const RecordDecl *RD = RT->getDecl();
5050  if (RD->isAnonymousStructOrUnion()) {
5051  for (auto *Field : RD->fields())
5052  PopulateKeysForFields(Field, IdealInits);
5053  return;
5054  }
5055  }
5056  IdealInits.push_back(Field->getCanonicalDecl());
5057 }
5058 
5059 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5060  return Context.getCanonicalType(BaseType).getTypePtr();
5061 }
5062 
5063 static const void *GetKeyForMember(ASTContext &Context,
5064  CXXCtorInitializer *Member) {
5065  if (!Member->isAnyMemberInitializer())
5066  return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5067 
5068  return Member->getAnyMember()->getCanonicalDecl();
5069 }
5070 
5072  Sema &SemaRef, const CXXConstructorDecl *Constructor,
5074  if (Constructor->getDeclContext()->isDependentContext())
5075  return;
5076 
5077  // Don't check initializers order unless the warning is enabled at the
5078  // location of at least one initializer.
5079  bool ShouldCheckOrder = false;
5080  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5081  CXXCtorInitializer *Init = Inits[InitIndex];
5082  if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5083  Init->getSourceLocation())) {
5084  ShouldCheckOrder = true;
5085  break;
5086  }
5087  }
5088  if (!ShouldCheckOrder)
5089  return;
5090 
5091  // Build the list of bases and members in the order that they'll
5092  // actually be initialized. The explicit initializers should be in
5093  // this same order but may be missing things.
5094  SmallVector<const void*, 32> IdealInitKeys;
5095 
5096  const CXXRecordDecl *ClassDecl = Constructor->getParent();
5097 
5098  // 1. Virtual bases.
5099  for (const auto &VBase : ClassDecl->vbases())
5100  IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5101 
5102  // 2. Non-virtual bases.
5103  for (const auto &Base : ClassDecl->bases()) {
5104  if (Base.isVirtual())
5105  continue;
5106  IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5107  }
5108 
5109  // 3. Direct fields.
5110  for (auto *Field : ClassDecl->fields()) {
5111  if (Field->isUnnamedBitfield())
5112  continue;
5113 
5114  PopulateKeysForFields(Field, IdealInitKeys);
5115  }
5116 
5117  unsigned NumIdealInits = IdealInitKeys.size();
5118  unsigned IdealIndex = 0;
5119 
5120  CXXCtorInitializer *PrevInit = nullptr;
5121  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5122  CXXCtorInitializer *Init = Inits[InitIndex];
5123  const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5124 
5125  // Scan forward to try to find this initializer in the idealized
5126  // initializers list.
5127  for (; IdealIndex != NumIdealInits; ++IdealIndex)
5128  if (InitKey == IdealInitKeys[IdealIndex])
5129  break;
5130 
5131  // If we didn't find this initializer, it must be because we
5132  // scanned past it on a previous iteration. That can only
5133  // happen if we're out of order; emit a warning.
5134  if (IdealIndex == NumIdealInits && PrevInit) {
5136  SemaRef.Diag(PrevInit->getSourceLocation(),
5137  diag::warn_initializer_out_of_order);
5138 
5139  if (PrevInit->isAnyMemberInitializer())
5140  D << 0 << PrevInit->getAnyMember()->getDeclName();
5141  else
5142  D << 1 << PrevInit->getTypeSourceInfo()->getType();
5143 
5144  if (Init->isAnyMemberInitializer())
5145  D << 0 << Init->getAnyMember()->getDeclName();
5146  else
5147  D << 1 << Init->getTypeSourceInfo()->getType();
5148 
5149  // Move back to the initializer's location in the ideal list.
5150  for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5151  if (InitKey == IdealInitKeys[IdealIndex])
5152  break;
5153 
5154  assert(IdealIndex < NumIdealInits &&
5155  "initializer not found in initializer list");
5156  }
5157 
5158  PrevInit = Init;
5159  }
5160 }
5161 
5162 namespace {
5163 bool CheckRedundantInit(Sema &S,
5164  CXXCtorInitializer *Init,
5165  CXXCtorInitializer *&PrevInit) {
5166  if (!PrevInit) {
5167  PrevInit = Init;
5168  return false;
5169  }
5170 
5171  if (FieldDecl *Field = Init->getAnyMember())
5172  S.Diag(Init->getSourceLocation(),
5173  diag::err_multiple_mem_initialization)
5174  << Field->getDeclName()
5175  << Init->getSourceRange();
5176  else {
5177  const Type *BaseClass = Init->getBaseClass();
5178  assert(BaseClass && "neither field nor base");
5179  S.Diag(Init->getSourceLocation(),
5180  diag::err_multiple_base_initialization)
5181  << QualType(BaseClass, 0)
5182  << Init->getSourceRange();
5183  }
5184  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5185  << 0 << PrevInit->getSourceRange();
5186 
5187  return true;
5188 }
5189 
5190 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5191 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5192 
5193 bool CheckRedundantUnionInit(Sema &S,
5194  CXXCtorInitializer *Init,
5195  RedundantUnionMap &Unions) {
5196  FieldDecl *Field = Init->getAnyMember();
5197  RecordDecl *Parent = Field->getParent();
5198  NamedDecl *Child = Field;
5199 
5200  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5201  if (Parent->isUnion()) {
5202  UnionEntry &En = Unions[Parent];
5203  if (En.first && En.first != Child) {
5204  S.Diag(Init->getSourceLocation(),
5205  diag::err_multiple_mem_union_initialization)
5206  << Field->getDeclName()
5207  << Init->getSourceRange();
5208  S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5209  << 0 << En.second->getSourceRange();
5210  return true;
5211  }
5212  if (!En.first) {
5213  En.first = Child;
5214  En.second = Init;
5215  }
5216  if (!Parent->isAnonymousStructOrUnion())
5217  return false;
5218  }
5219 
5220  Child = Parent;
5221  Parent = cast<RecordDecl>(Parent->getDeclContext());
5222  }
5223 
5224  return false;
5225 }
5226 }
5227 
5228 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5229 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5232  bool AnyErrors) {
5233  if (!ConstructorDecl)
5234  return;
5235 
5236  AdjustDeclIfTemplate(ConstructorDecl);
5237 
5238  CXXConstructorDecl *Constructor
5239  = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5240 
5241  if (!Constructor) {
5242  Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5243  return;
5244  }
5245 
5246  // Mapping for the duplicate initializers check.
5247  // For member initializers, this is keyed with a FieldDecl*.
5248  // For base initializers, this is keyed with a Type*.
5249  llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5250 
5251  // Mapping for the inconsistent anonymous-union initializers check.
5252  RedundantUnionMap MemberUnions;
5253 
5254  bool HadError = false;
5255  for (unsigned i = 0; i < MemInits.size(); i++) {
5256  CXXCtorInitializer *Init = MemInits[i];
5257 
5258  // Set the source order index.
5259  Init->setSourceOrder(i);
5260 
5261  if (Init->isAnyMemberInitializer()) {
5262  const void *Key = GetKeyForMember(Context, Init);
5263  if (CheckRedundantInit(*this, Init, Members[Key]) ||
5264  CheckRedundantUnionInit(*this, Init, MemberUnions))
5265  HadError = true;
5266  } else if (Init->isBaseInitializer()) {
5267  const void *Key = GetKeyForMember(Context, Init);
5268  if (CheckRedundantInit(*this, Init, Members[Key]))
5269  HadError = true;
5270  } else {
5271  assert(Init->isDelegatingInitializer());
5272  // This must be the only initializer
5273  if (MemInits.size() != 1) {
5274  Diag(Init->getSourceLocation(),
5275  diag::err_delegating_initializer_alone)
5276  << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5277  // We will treat this as being the only initializer.
5278  }
5279  SetDelegatingInitializer(Constructor, MemInits[i]);
5280  // Return immediately as the initializer is set.
5281  return;
5282  }
5283  }
5284 
5285  if (HadError)
5286  return;
5287 
5288  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5289 
5290  SetCtorInitializers(Constructor, AnyErrors, MemInits);
5291 
5292  DiagnoseUninitializedFields(*this, Constructor);
5293 }
5294 
5295 void
5297  CXXRecordDecl *ClassDecl) {
5298  // Ignore dependent contexts. Also ignore unions, since their members never
5299  // have destructors implicitly called.
5300  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5301  return;
5302 
5303  // FIXME: all the access-control diagnostics are positioned on the
5304  // field/base declaration. That's probably good; that said, the
5305  // user might reasonably want to know why the destructor is being
5306  // emitted, and we currently don't say.
5307 
5308  // Non-static data members.
5309  for (auto *Field : ClassDecl->fields()) {
5310  if (Field->isInvalidDecl())
5311  continue;
5312 
5313  // Don't destroy incomplete or zero-length arrays.
5314  if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5315  continue;
5316 
5317  QualType FieldType = Context.getBaseElementType(Field->getType());
5318 
5319  const RecordType* RT = FieldType->getAs<RecordType>();
5320  if (!RT)
5321  continue;
5322 
5323  CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5324  if (FieldClassDecl->isInvalidDecl())
5325  continue;
5326  if (FieldClassDecl->hasIrrelevantDestructor())
5327  continue;
5328  // The destructor for an implicit anonymous union member is never invoked.
5329  if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5330  continue;
5331 
5332  CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5333  assert(Dtor && "No dtor found for FieldClassDecl!");
5334  CheckDestructorAccess(Field->getLocation(), Dtor,
5335  PDiag(diag::err_access_dtor_field)
5336  << Field->getDeclName()
5337  << FieldType);
5338 
5339  MarkFunctionReferenced(Location, Dtor);
5340  DiagnoseUseOfDecl(Dtor, Location);
5341  }
5342 
5343  // We only potentially invoke the destructors of potentially constructed
5344  // subobjects.
5345  bool VisitVirtualBases = !ClassDecl->isAbstract();
5346 
5347  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5348 
5349  // Bases.
5350  for (const auto &Base : ClassDecl->bases()) {
5351  // Bases are always records in a well-formed non-dependent class.
5352  const RecordType *RT = Base.getType()->getAs<RecordType>();
5353 
5354  // Remember direct virtual bases.
5355  if (Base.isVirtual()) {
5356  if (!VisitVirtualBases)
5357  continue;
5358  DirectVirtualBases.insert(RT);
5359  }
5360 
5361  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5362  // If our base class is invalid, we probably can't get its dtor anyway.
5363  if (BaseClassDecl->isInvalidDecl())
5364  continue;
5365  if (BaseClassDecl->hasIrrelevantDestructor())
5366  continue;
5367 
5368  CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5369  assert(Dtor && "No dtor found for BaseClassDecl!");
5370 
5371  // FIXME: caret should be on the start of the class name
5372  CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5373  PDiag(diag::err_access_dtor_base)
5374  << Base.getType() << Base.getSourceRange(),
5375  Context.getTypeDeclType(ClassDecl));
5376 
5377  MarkFunctionReferenced(Location, Dtor);
5378  DiagnoseUseOfDecl(Dtor, Location);
5379  }
5380 
5381  if (!VisitVirtualBases)
5382  return;
5383 
5384  // Virtual bases.
5385  for (const auto &VBase : ClassDecl->vbases()) {
5386  // Bases are always records in a well-formed non-dependent class.
5387  const RecordType *RT = VBase.getType()->castAs<RecordType>();
5388 
5389  // Ignore direct virtual bases.
5390  if (DirectVirtualBases.count(RT))
5391  continue;
5392 
5393  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5394  // If our base class is invalid, we probably can't get its dtor anyway.
5395  if (BaseClassDecl->isInvalidDecl())
5396  continue;
5397  if (BaseClassDecl->hasIrrelevantDestructor())
5398  continue;
5399 
5400  CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5401  assert(Dtor && "No dtor found for BaseClassDecl!");
5402  if (CheckDestructorAccess(
5403  ClassDecl->getLocation(), Dtor,
5404  PDiag(diag::err_access_dtor_vbase)
5405  << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5406  Context.getTypeDeclType(ClassDecl)) ==
5407  AR_accessible) {
5408  CheckDerivedToBaseConversion(
5409  Context.getTypeDeclType(ClassDecl), VBase.getType(),
5410  diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5411  SourceRange(), DeclarationName(), nullptr);
5412  }
5413 
5414  MarkFunctionReferenced(Location, Dtor);
5415  DiagnoseUseOfDecl(Dtor, Location);
5416  }
5417 }
5418 
5419 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5420  if (!CDtorDecl)
5421  return;
5422 
5423  if (CXXConstructorDecl *Constructor
5424  = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5425  SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5426  DiagnoseUninitializedFields(*this, Constructor);
5427  }
5428 }
5429 
5431  if (!getLangOpts().CPlusPlus)
5432  return false;
5433 
5434  const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5435  if (!RD)
5436  return false;
5437 
5438  // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5439  // class template specialization here, but doing so breaks a lot of code.
5440 
5441  // We can't answer whether something is abstract until it has a
5442  // definition. If it's currently being defined, we'll walk back
5443  // over all the declarations when we have a full definition.
5444  const CXXRecordDecl *Def = RD->getDefinition();
5445  if (!Def || Def->isBeingDefined())
5446  return false;
5447 
5448  return RD->isAbstract();
5449 }
5450 
5452  TypeDiagnoser &Diagnoser) {
5453  if (!isAbstractType(Loc, T))
5454  return false;
5455 
5456  T = Context.getBaseElementType(T);
5457  Diagnoser.diagnose(*this, Loc, T);
5458  DiagnoseAbstractType(T->getAsCXXRecordDecl());
5459  return true;
5460 }
5461 
5463  // Check if we've already emitted the list of pure virtual functions
5464  // for this class.
5465  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5466  return;
5467 
5468  // If the diagnostic is suppressed, don't emit the notes. We're only
5469  // going to emit them once, so try to attach them to a diagnostic we're
5470  // actually going to show.
5471  if (Diags.isLastDiagnosticIgnored())
5472  return;
5473 
5474  CXXFinalOverriderMap FinalOverriders;
5475  RD->getFinalOverriders(FinalOverriders);
5476 
5477  // Keep a set of seen pure methods so we won't diagnose the same method
5478  // more than once.
5479  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5480 
5481  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5482  MEnd = FinalOverriders.end();
5483  M != MEnd;
5484  ++M) {
5485  for (OverridingMethods::iterator SO = M->second.begin(),
5486  SOEnd = M->second.end();
5487  SO != SOEnd; ++SO) {
5488  // C++ [class.abstract]p4:
5489  // A class is abstract if it contains or inherits at least one
5490  // pure virtual function for which the final overrider is pure
5491  // virtual.
5492 
5493  //
5494  if (SO->second.size() != 1)
5495  continue;
5496 
5497  if (!SO->second.front().Method->isPure())
5498  continue;
5499 
5500  if (!SeenPureMethods.insert(SO->second.front().Method).second)
5501  continue;
5502 
5503  Diag(SO->second.front().Method->getLocation(),
5504  diag::note_pure_virtual_function)
5505  << SO->second.front().Method->getDeclName() << RD->getDeclName();
5506  }
5507  }
5508 
5509  if (!PureVirtualClassDiagSet)
5510  PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5511  PureVirtualClassDiagSet->insert(RD);
5512 }
5513 
5514 namespace {
5515 struct AbstractUsageInfo {
5516  Sema &S;
5517  CXXRecordDecl *Record;
5518  CanQualType AbstractType;
5519  bool Invalid;
5520 
5521  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5522  : S(S), Record(Record),
5523  AbstractType(S.Context.getCanonicalType(
5524  S.Context.getTypeDeclType(Record))),
5525  Invalid(false) {}
5526 
5527  void DiagnoseAbstractType() {
5528  if (Invalid) return;
5529  S.DiagnoseAbstractType(Record);
5530  Invalid = true;
5531  }
5532 
5533  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5534 };
5535 
5536 struct CheckAbstractUsage {
5537  AbstractUsageInfo &Info;
5538  const NamedDecl *Ctx;
5539 
5540  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5541  : Info(Info), Ctx(Ctx) {}
5542 
5543  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5544  switch (TL.getTypeLocClass()) {
5545 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5546 #define TYPELOC(CLASS, PARENT) \
5547  case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5548 #include "clang/AST/TypeLocNodes.def"
5549  }
5550  }
5551 
5552  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5554  for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5555  if (!TL.getParam(I))
5556  continue;
5557 
5558  TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5559  if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5560  }
5561  }
5562 
5563  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5565  }
5566 
5568  // Visit the type parameters from a permissive context.
5569  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5570  TemplateArgumentLoc TAL = TL.getArgLoc(I);
5572  if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5573  Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5574  // TODO: other template argument types?
5575  }
5576  }
5577 
5578  // Visit pointee types from a permissive context.
5579 #define CheckPolymorphic(Type) \
5580  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5581  Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5582  }
5588 
5589  /// Handle all the types we haven't given a more specific
5590  /// implementation for above.
5591  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5592  // Every other kind of type that we haven't called out already
5593  // that has an inner type is either (1) sugar or (2) contains that
5594  // inner type in some way as a subobject.
5595  if (TypeLoc Next = TL.getNextTypeLoc())
5596  return Visit(Next, Sel);
5597 
5598  // If there's no inner type and we're in a permissive context,
5599  // don't diagnose.
5600  if (Sel == Sema::AbstractNone) return;
5601 
5602  // Check whether the type matches the abstract type.
5603  QualType T = TL.getType();
5604  if (T->isArrayType()) {
5606  T = Info.S.Context.getBaseElementType(T);
5607  }
5609  if (CT != Info.AbstractType) return;
5610 
5611  // It matched; do some magic.
5612  if (Sel == Sema::AbstractArrayType) {
5613  Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5614  << T << TL.getSourceRange();
5615  } else {
5616  Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5617  << Sel << T << TL.getSourceRange();
5618  }
5619  Info.DiagnoseAbstractType();
5620  }
5621 };
5622 
5623 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5625  CheckAbstractUsage(*this, D).Visit(TL, Sel);
5626 }
5627 
5628 }
5629 
5630 /// Check for invalid uses of an abstract type in a method declaration.
5631 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5632  CXXMethodDecl *MD) {
5633  // No need to do the check on definitions, which require that
5634  // the return/param types be complete.
5635  if (MD->doesThisDeclarationHaveABody())
5636  return;
5637 
5638  // For safety's sake, just ignore it if we don't have type source
5639  // information. This should never happen for non-implicit methods,
5640  // but...
5641  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5642  Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5643 }
5644 
5645 /// Check for invalid uses of an abstract type within a class definition.
5646 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5647  CXXRecordDecl *RD) {
5648  for (auto *D : RD->decls()) {
5649  if (D->isImplicit()) continue;
5650 
5651  // Methods and method templates.
5652  if (isa<CXXMethodDecl>(D)) {
5653  CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5654  } else if (isa<FunctionTemplateDecl>(D)) {
5655  FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5656  CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5657 
5658  // Fields and static variables.
5659  } else if (isa<FieldDecl>(D)) {
5660  FieldDecl *FD = cast<FieldDecl>(D);
5661  if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5662  Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5663  } else if (isa<VarDecl>(D)) {
5664  VarDecl *VD = cast<VarDecl>(D);
5665  if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5666  Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5667 
5668  // Nested classes and class templates.
5669  } else if (isa<CXXRecordDecl>(D)) {
5670  CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5671  } else if (isa<ClassTemplateDecl>(D)) {
5673  cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5674  }
5675  }
5676 }
5677 
5679  Attr *ClassAttr = getDLLAttr(Class);
5680  if (!ClassAttr)
5681  return;
5682 
5683  assert(ClassAttr->getKind() == attr::DLLExport);
5684 
5686 
5688  // Don't go any further if this is just an explicit instantiation
5689  // declaration.
5690  return;
5691 
5692  if (S.