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