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