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  SourceLocation Loc,
1232  const CXXRecordDecl *RD,
1233  CXXCastPath &BasePath) {
1234  auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1235  CXXBasePath &Path) {
1236  return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1237  };
1238 
1239  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 RD;
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 nullptr;
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 nullptr;
1277  }
1278 
1279  // ... public base class of E.
1280  if (BestPath->Access != AS_public) {
1281  S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1282  << RD << BaseType;
1283  for (auto &BS : *BestPath) {
1284  if (BS.Base->getAccessSpecifier() != AS_public) {
1285  S.Diag(BS.Base->getBeginLoc(), diag::note_access_constrained_by_path)
1286  << (BS.Base->getAccessSpecifier() == AS_protected)
1287  << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1288  break;
1289  }
1290  }
1291  return nullptr;
1292  }
1293 
1294  ClassWithFields = BaseType->getAsCXXRecordDecl();
1295  S.BuildBasePathArray(Paths, BasePath);
1296  }
1297 
1298  // The above search did not check whether the selected class itself has base
1299  // classes with fields, so check that now.
1300  CXXBasePaths Paths;
1301  if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1302  S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1303  << (ClassWithFields == RD) << RD << ClassWithFields
1304  << Paths.front().back().Base->getType();
1305  return nullptr;
1306  }
1307 
1308  return ClassWithFields;
1309 }
1310 
1312  ValueDecl *Src, QualType DecompType,
1313  const CXXRecordDecl *RD) {
1314  CXXCastPath BasePath;
1315  RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1316  if (!RD)
1317  return true;
1319  DecompType.getQualifiers());
1320 
1321  auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1322  unsigned NumFields =
1323  std::count_if(RD->field_begin(), RD->field_end(),
1324  [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1325  assert(Bindings.size() != NumFields);
1326  S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1327  << DecompType << (unsigned)Bindings.size() << NumFields
1328  << (NumFields < Bindings.size());
1329  return true;
1330  };
1331 
1332  // all of E's non-static data members shall be public [...] members,
1333  // E shall not have an anonymous union member, ...
1334  unsigned I = 0;
1335  for (auto *FD : RD->fields()) {
1336  if (FD->isUnnamedBitfield())
1337  continue;
1338 
1339  if (FD->isAnonymousStructOrUnion()) {
1340  S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1341  << DecompType << FD->getType()->isUnionType();
1342  S.Diag(FD->getLocation(), diag::note_declared_at);
1343  return true;
1344  }
1345 
1346  // We have a real field to bind.
1347  if (I >= Bindings.size())
1348  return DiagnoseBadNumberOfBindings();
1349  auto *B = Bindings[I++];
1350 
1351  SourceLocation Loc = B->getLocation();
1352  if (FD->getAccess() != AS_public) {
1353  S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1354 
1355  // Determine whether the access specifier was explicit.
1356  bool Implicit = true;
1357  for (const auto *D : RD->decls()) {
1358  if (declaresSameEntity(D, FD))
1359  break;
1360  if (isa<AccessSpecDecl>(D)) {
1361  Implicit = false;
1362  break;
1363  }
1364  }
1365 
1366  S.Diag(FD->getLocation(), diag::note_access_natural)
1367  << (FD->getAccess() == AS_protected) << Implicit;
1368  return true;
1369  }
1370 
1371  // Initialize the binding to Src.FD.
1372  ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1373  if (E.isInvalid())
1374  return true;
1375  E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1376  VK_LValue, &BasePath);
1377  if (E.isInvalid())
1378  return true;
1379  E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1380  CXXScopeSpec(), FD,
1381  DeclAccessPair::make(FD, FD->getAccess()),
1382  DeclarationNameInfo(FD->getDeclName(), Loc));
1383  if (E.isInvalid())
1384  return true;
1385 
1386  // If the type of the member is T, the referenced type is cv T, where cv is
1387  // the cv-qualification of the decomposition expression.
1388  //
1389  // FIXME: We resolve a defect here: if the field is mutable, we do not add
1390  // 'const' to the type of the field.
1391  Qualifiers Q = DecompType.getQualifiers();
1392  if (FD->isMutable())
1393  Q.removeConst();
1394  B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1395  }
1396 
1397  if (I != Bindings.size())
1398  return DiagnoseBadNumberOfBindings();
1399 
1400  return false;
1401 }
1402 
1404  QualType DecompType = DD->getType();
1405 
1406  // If the type of the decomposition is dependent, then so is the type of
1407  // each binding.
1408  if (DecompType->isDependentType()) {
1409  for (auto *B : DD->bindings())
1410  B->setType(Context.DependentTy);
1411  return;
1412  }
1413 
1414  DecompType = DecompType.getNonReferenceType();
1415  ArrayRef<BindingDecl*> Bindings = DD->bindings();
1416 
1417  // C++1z [dcl.decomp]/2:
1418  // If E is an array type [...]
1419  // As an extension, we also support decomposition of built-in complex and
1420  // vector types.
1421  if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1422  if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1423  DD->setInvalidDecl();
1424  return;
1425  }
1426  if (auto *VT = DecompType->getAs<VectorType>()) {
1427  if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1428  DD->setInvalidDecl();
1429  return;
1430  }
1431  if (auto *CT = DecompType->getAs<ComplexType>()) {
1432  if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1433  DD->setInvalidDecl();
1434  return;
1435  }
1436 
1437  // C++1z [dcl.decomp]/3:
1438  // if the expression std::tuple_size<E>::value is a well-formed integral
1439  // constant expression, [...]
1440  llvm::APSInt TupleSize(32);
1441  switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1442  case IsTupleLike::Error:
1443  DD->setInvalidDecl();
1444  return;
1445 
1446  case IsTupleLike::TupleLike:
1447  if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1448  DD->setInvalidDecl();
1449  return;
1450 
1451  case IsTupleLike::NotTupleLike:
1452  break;
1453  }
1454 
1455  // C++1z [dcl.dcl]/8:
1456  // [E shall be of array or non-union class type]
1457  CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1458  if (!RD || RD->isUnion()) {
1459  Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1460  << DD << !RD << DecompType;
1461  DD->setInvalidDecl();
1462  return;
1463  }
1464 
1465  // C++1z [dcl.decomp]/4:
1466  // all of E's non-static data members shall be [...] direct members of
1467  // E or of the same unambiguous public base class of E, ...
1468  if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1469  DD->setInvalidDecl();
1470 }
1471 
1472 /// Merge the exception specifications of two variable declarations.
1473 ///
1474 /// This is called when there's a redeclaration of a VarDecl. The function
1475 /// checks if the redeclaration might have an exception specification and
1476 /// validates compatibility and merges the specs if necessary.
1478  // Shortcut if exceptions are disabled.
1479  if (!getLangOpts().CXXExceptions)
1480  return;
1481 
1482  assert(Context.hasSameType(New->getType(), Old->getType()) &&
1483  "Should only be called if types are otherwise the same.");
1484 
1485  QualType NewType = New->getType();
1486  QualType OldType = Old->getType();
1487 
1488  // We're only interested in pointers and references to functions, as well
1489  // as pointers to member functions.
1490  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1491  NewType = R->getPointeeType();
1492  OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1493  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1494  NewType = P->getPointeeType();
1495  OldType = OldType->getAs<PointerType>()->getPointeeType();
1496  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1497  NewType = M->getPointeeType();
1498  OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1499  }
1500 
1501  if (!NewType->isFunctionProtoType())
1502  return;
1503 
1504  // There's lots of special cases for functions. For function pointers, system
1505  // libraries are hopefully not as broken so that we don't need these
1506  // workarounds.
1507  if (CheckEquivalentExceptionSpec(
1508  OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1509  NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1510  New->setInvalidDecl();
1511  }
1512 }
1513 
1514 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1515 /// function declaration are well-formed according to C++
1516 /// [dcl.fct.default].
1518  unsigned NumParams = FD->getNumParams();
1519  unsigned p;
1520 
1521  // Find first parameter with a default argument
1522  for (p = 0; p < NumParams; ++p) {
1523  ParmVarDecl *Param = FD->getParamDecl(p);
1524  if (Param->hasDefaultArg())
1525  break;
1526  }
1527 
1528  // C++11 [dcl.fct.default]p4:
1529  // In a given function declaration, each parameter subsequent to a parameter
1530  // with a default argument shall have a default argument supplied in this or
1531  // a previous declaration or shall be a function parameter pack. A default
1532  // argument shall not be redefined by a later declaration (not even to the
1533  // same value).
1534  unsigned LastMissingDefaultArg = 0;
1535  for (; p < NumParams; ++p) {
1536  ParmVarDecl *Param = FD->getParamDecl(p);
1537  if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1538  if (Param->isInvalidDecl())
1539  /* We already complained about this parameter. */;
1540  else if (Param->getIdentifier())
1541  Diag(Param->getLocation(),
1542  diag::err_param_default_argument_missing_name)
1543  << Param->getIdentifier();
1544  else
1545  Diag(Param->getLocation(),
1546  diag::err_param_default_argument_missing);
1547 
1548  LastMissingDefaultArg = p;
1549  }
1550  }
1551 
1552  if (LastMissingDefaultArg > 0) {
1553  // Some default arguments were missing. Clear out all of the
1554  // default arguments up to (and including) the last missing
1555  // default argument, so that we leave the function parameters
1556  // in a semantically valid state.
1557  for (p = 0; p <= LastMissingDefaultArg; ++p) {
1558  ParmVarDecl *Param = FD->getParamDecl(p);
1559  if (Param->hasDefaultArg()) {
1560  Param->setDefaultArg(nullptr);
1561  }
1562  }
1563  }
1564 }
1565 
1566 // CheckConstexprParameterTypes - Check whether a function's parameter types
1567 // are all literal types. If so, return true. If not, produce a suitable
1568 // diagnostic and return false.
1569 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1570  const FunctionDecl *FD) {
1571  unsigned ArgIndex = 0;
1572  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1574  e = FT->param_type_end();
1575  i != e; ++i, ++ArgIndex) {
1576  const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1577  SourceLocation ParamLoc = PD->getLocation();
1578  if (!(*i)->isDependentType() &&
1579  SemaRef.RequireLiteralType(ParamLoc, *i,
1580  diag::err_constexpr_non_literal_param,
1581  ArgIndex+1, PD->getSourceRange(),
1582  isa<CXXConstructorDecl>(FD)))
1583  return false;
1584  }
1585  return true;
1586 }
1587 
1588 /// Get diagnostic %select index for tag kind for
1589 /// record diagnostic message.
1590 /// WARNING: Indexes apply to particular diagnostics only!
1591 ///
1592 /// \returns diagnostic %select index.
1594  switch (Tag) {
1595  case TTK_Struct: return 0;
1596  case TTK_Interface: return 1;
1597  case TTK_Class: return 2;
1598  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1599  }
1600 }
1601 
1602 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1603 // the requirements of a constexpr function definition or a constexpr
1604 // constructor definition. If so, return true. If not, produce appropriate
1605 // diagnostics and return false.
1606 //
1607 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1609  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1610  if (MD && MD->isInstance()) {
1611  // C++11 [dcl.constexpr]p4:
1612  // The definition of a constexpr constructor shall satisfy the following
1613  // constraints:
1614  // - the class shall not have any virtual base classes;
1615  const CXXRecordDecl *RD = MD->getParent();
1616  if (RD->getNumVBases()) {
1617  Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1618  << isa<CXXConstructorDecl>(NewFD)
1620  for (const auto &I : RD->vbases())
1621  Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1622  << I.getSourceRange();
1623  return false;
1624  }
1625  }
1626 
1627  if (!isa<CXXConstructorDecl>(NewFD)) {
1628  // C++11 [dcl.constexpr]p3:
1629  // The definition of a constexpr function shall satisfy the following
1630  // constraints:
1631  // - it shall not be virtual;
1632  const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1633  if (Method && Method->isVirtual()) {
1634  Method = Method->getCanonicalDecl();
1635  Diag(Method->getLocation(), diag::err_constexpr_virtual);
1636 
1637  // If it's not obvious why this function is virtual, find an overridden
1638  // function which uses the 'virtual' keyword.
1639  const CXXMethodDecl *WrittenVirtual = Method;
1640  while (!WrittenVirtual->isVirtualAsWritten())
1641  WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1642  if (WrittenVirtual != Method)
1643  Diag(WrittenVirtual->getLocation(),
1644  diag::note_overridden_virtual_function);
1645  return false;
1646  }
1647 
1648  // - its return type shall be a literal type;
1649  QualType RT = NewFD->getReturnType();
1650  if (!RT->isDependentType() &&
1651  RequireLiteralType(NewFD->getLocation(), RT,
1652  diag::err_constexpr_non_literal_return))
1653  return false;
1654  }
1655 
1656  // - each of its parameter types shall be a literal type;
1657  if (!CheckConstexprParameterTypes(*this, NewFD))
1658  return false;
1659 
1660  return true;
1661 }
1662 
1663 /// Check the given declaration statement is legal within a constexpr function
1664 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1665 ///
1666 /// \return true if the body is OK (maybe only as an extension), false if we
1667 /// have diagnosed a problem.
1668 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1669  DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1670  // C++11 [dcl.constexpr]p3 and p4:
1671  // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1672  // contain only
1673  for (const auto *DclIt : DS->decls()) {
1674  switch (DclIt->getKind()) {
1675  case Decl::StaticAssert:
1676  case Decl::Using:
1677  case Decl::UsingShadow:
1678  case Decl::UsingDirective:
1679  case Decl::UnresolvedUsingTypename:
1680  case Decl::UnresolvedUsingValue:
1681  // - static_assert-declarations
1682  // - using-declarations,
1683  // - using-directives,
1684  continue;
1685 
1686  case Decl::Typedef:
1687  case Decl::TypeAlias: {
1688  // - typedef declarations and alias-declarations that do not define
1689  // classes or enumerations,
1690  const auto *TN = cast<TypedefNameDecl>(DclIt);
1691  if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1692  // Don't allow variably-modified types in constexpr functions.
1693  TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1694  SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1695  << TL.getSourceRange() << TL.getType()
1696  << isa<CXXConstructorDecl>(Dcl);
1697  return false;
1698  }
1699  continue;
1700  }
1701 
1702  case Decl::Enum:
1703  case Decl::CXXRecord:
1704  // C++1y allows types to be defined, not just declared.
1705  if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1706  SemaRef.Diag(DS->getBeginLoc(),
1707  SemaRef.getLangOpts().CPlusPlus14
1708  ? diag::warn_cxx11_compat_constexpr_type_definition
1709  : diag::ext_constexpr_type_definition)
1710  << isa<CXXConstructorDecl>(Dcl);
1711  continue;
1712 
1713  case Decl::EnumConstant:
1714  case Decl::IndirectField:
1715  case Decl::ParmVar:
1716  // These can only appear with other declarations which are banned in
1717  // C++11 and permitted in C++1y, so ignore them.
1718  continue;
1719 
1720  case Decl::Var:
1721  case Decl::Decomposition: {
1722  // C++1y [dcl.constexpr]p3 allows anything except:
1723  // a definition of a variable of non-literal type or of static or
1724  // thread storage duration or for which no initialization is performed.
1725  const auto *VD = cast<VarDecl>(DclIt);
1726  if (VD->isThisDeclarationADefinition()) {
1727  if (VD->isStaticLocal()) {
1728  SemaRef.Diag(VD->getLocation(),
1729  diag::err_constexpr_local_var_static)
1730  << isa<CXXConstructorDecl>(Dcl)
1731  << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1732  return false;
1733  }
1734  if (!VD->getType()->isDependentType() &&
1735  SemaRef.RequireLiteralType(
1736  VD->getLocation(), VD->getType(),
1737  diag::err_constexpr_local_var_non_literal_type,
1738  isa<CXXConstructorDecl>(Dcl)))
1739  return false;
1740  if (!VD->getType()->isDependentType() &&
1741  !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1742  SemaRef.Diag(VD->getLocation(),
1743  diag::err_constexpr_local_var_no_init)
1744  << isa<CXXConstructorDecl>(Dcl);
1745  return false;
1746  }
1747  }
1748  SemaRef.Diag(VD->getLocation(),
1749  SemaRef.getLangOpts().CPlusPlus14
1750  ? diag::warn_cxx11_compat_constexpr_local_var
1751  : diag::ext_constexpr_local_var)
1752  << isa<CXXConstructorDecl>(Dcl);
1753  continue;
1754  }
1755 
1756  case Decl::NamespaceAlias:
1757  case Decl::Function:
1758  // These are disallowed in C++11 and permitted in C++1y. Allow them
1759  // everywhere as an extension.
1760  if (!Cxx1yLoc.isValid())
1761  Cxx1yLoc = DS->getBeginLoc();
1762  continue;
1763 
1764  default:
1765  SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1766  << isa<CXXConstructorDecl>(Dcl);
1767  return false;
1768  }
1769  }
1770 
1771  return true;
1772 }
1773 
1774 /// Check that the given field is initialized within a constexpr constructor.
1775 ///
1776 /// \param Dcl The constexpr constructor being checked.
1777 /// \param Field The field being checked. This may be a member of an anonymous
1778 /// struct or union nested within the class being checked.
1779 /// \param Inits All declarations, including anonymous struct/union members and
1780 /// indirect members, for which any initialization was provided.
1781 /// \param Diagnosed Set to true if an error is produced.
1783  const FunctionDecl *Dcl,
1784  FieldDecl *Field,
1785  llvm::SmallSet<Decl*, 16> &Inits,
1786  bool &Diagnosed) {
1787  if (Field->isInvalidDecl())
1788  return;
1789 
1790  if (Field->isUnnamedBitfield())
1791  return;
1792 
1793  // Anonymous unions with no variant members and empty anonymous structs do not
1794  // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1795  // indirect fields don't need initializing.
1796  if (Field->isAnonymousStructOrUnion() &&
1797  (Field->getType()->isUnionType()
1798  ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1799  : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1800  return;
1801 
1802  if (!Inits.count(Field)) {
1803  if (!Diagnosed) {
1804  SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1805  Diagnosed = true;
1806  }
1807  SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1808  } else if (Field->isAnonymousStructOrUnion()) {
1809  const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1810  for (auto *I : RD->fields())
1811  // If an anonymous union contains an anonymous struct of which any member
1812  // is initialized, all members must be initialized.
1813  if (!RD->isUnion() || Inits.count(I))
1814  CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1815  }
1816 }
1817 
1818 /// Check the provided statement is allowed in a constexpr function
1819 /// definition.
1820 static bool
1822  SmallVectorImpl<SourceLocation> &ReturnStmts,
1823  SourceLocation &Cxx1yLoc) {
1824  // - its function-body shall be [...] a compound-statement that contains only
1825  switch (S->getStmtClass()) {
1826  case Stmt::NullStmtClass:
1827  // - null statements,
1828  return true;
1829 
1830  case Stmt::DeclStmtClass:
1831  // - static_assert-declarations
1832  // - using-declarations,
1833  // - using-directives,
1834  // - typedef declarations and alias-declarations that do not define
1835  // classes or enumerations,
1836  if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1837  return false;
1838  return true;
1839 
1840  case Stmt::ReturnStmtClass:
1841  // - and exactly one return statement;
1842  if (isa<CXXConstructorDecl>(Dcl)) {
1843  // C++1y allows return statements in constexpr constructors.
1844  if (!Cxx1yLoc.isValid())
1845  Cxx1yLoc = S->getBeginLoc();
1846  return true;
1847  }
1848 
1849  ReturnStmts.push_back(S->getBeginLoc());
1850  return true;
1851 
1852  case Stmt::CompoundStmtClass: {
1853  // C++1y allows compound-statements.
1854  if (!Cxx1yLoc.isValid())
1855  Cxx1yLoc = S->getBeginLoc();
1856 
1857  CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1858  for (auto *BodyIt : CompStmt->body()) {
1859  if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1860  Cxx1yLoc))
1861  return false;
1862  }
1863  return true;
1864  }
1865 
1866  case Stmt::AttributedStmtClass:
1867  if (!Cxx1yLoc.isValid())
1868  Cxx1yLoc = S->getBeginLoc();
1869  return true;
1870 
1871  case Stmt::IfStmtClass: {
1872  // C++1y allows if-statements.
1873  if (!Cxx1yLoc.isValid())
1874  Cxx1yLoc = S->getBeginLoc();
1875 
1876  IfStmt *If = cast<IfStmt>(S);
1877  if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1878  Cxx1yLoc))
1879  return false;
1880  if (If->getElse() &&
1881  !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1882  Cxx1yLoc))
1883  return false;
1884  return true;
1885  }
1886 
1887  case Stmt::WhileStmtClass:
1888  case Stmt::DoStmtClass:
1889  case Stmt::ForStmtClass:
1890  case Stmt::CXXForRangeStmtClass:
1891  case Stmt::ContinueStmtClass:
1892  // C++1y allows all of these. We don't allow them as extensions in C++11,
1893  // because they don't make sense without variable mutation.
1894  if (!SemaRef.getLangOpts().CPlusPlus14)
1895  break;
1896  if (!Cxx1yLoc.isValid())
1897  Cxx1yLoc = S->getBeginLoc();
1898  for (Stmt *SubStmt : S->children())
1899  if (SubStmt &&
1900  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1901  Cxx1yLoc))
1902  return false;
1903  return true;
1904 
1905  case Stmt::SwitchStmtClass:
1906  case Stmt::CaseStmtClass:
1907  case Stmt::DefaultStmtClass:
1908  case Stmt::BreakStmtClass:
1909  // C++1y allows switch-statements, and since they don't need variable
1910  // mutation, we can reasonably allow them in C++11 as an extension.
1911  if (!Cxx1yLoc.isValid())
1912  Cxx1yLoc = S->getBeginLoc();
1913  for (Stmt *SubStmt : S->children())
1914  if (SubStmt &&
1915  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1916  Cxx1yLoc))
1917  return false;
1918  return true;
1919 
1920  default:
1921  if (!isa<Expr>(S))
1922  break;
1923 
1924  // C++1y allows expression-statements.
1925  if (!Cxx1yLoc.isValid())
1926  Cxx1yLoc = S->getBeginLoc();
1927  return true;
1928  }
1929 
1930  SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1931  << isa<CXXConstructorDecl>(Dcl);
1932  return false;
1933 }
1934 
1935 /// Check the body for the given constexpr function declaration only contains
1936 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1937 ///
1938 /// \return true if the body is OK, false if we have diagnosed a problem.
1940  if (isa<CXXTryStmt>(Body)) {
1941  // C++11 [dcl.constexpr]p3:
1942  // The definition of a constexpr function shall satisfy the following
1943  // constraints: [...]
1944  // - its function-body shall be = delete, = default, or a
1945  // compound-statement
1946  //
1947  // C++11 [dcl.constexpr]p4:
1948  // In the definition of a constexpr constructor, [...]
1949  // - its function-body shall not be a function-try-block;
1950  Diag(Body->getBeginLoc(), diag::err_constexpr_function_try_block)
1951  << isa<CXXConstructorDecl>(Dcl);
1952  return false;
1953  }
1954 
1955  SmallVector<SourceLocation, 4> ReturnStmts;
1956 
1957  // - its function-body shall be [...] a compound-statement that contains only
1958  // [... list of cases ...]
1959  CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1960  SourceLocation Cxx1yLoc;
1961  for (auto *BodyIt : CompBody->body()) {
1962  if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1963  return false;
1964  }
1965 
1966  if (Cxx1yLoc.isValid())
1967  Diag(Cxx1yLoc,
1968  getLangOpts().CPlusPlus14
1969  ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1970  : diag::ext_constexpr_body_invalid_stmt)
1971  << isa<CXXConstructorDecl>(Dcl);
1972 
1973  if (const CXXConstructorDecl *Constructor
1974  = dyn_cast<CXXConstructorDecl>(Dcl)) {
1975  const CXXRecordDecl *RD = Constructor->getParent();
1976  // DR1359:
1977  // - every non-variant non-static data member and base class sub-object
1978  // shall be initialized;
1979  // DR1460:
1980  // - if the class is a union having variant members, exactly one of them
1981  // shall be initialized;
1982  if (RD->isUnion()) {
1983  if (Constructor->getNumCtorInitializers() == 0 &&
1984  RD->hasVariantMembers()) {
1985  Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1986  return false;
1987  }
1988  } else if (!Constructor->isDependentContext() &&
1989  !Constructor->isDelegatingConstructor()) {
1990  assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1991 
1992  // Skip detailed checking if we have enough initializers, and we would
1993  // allow at most one initializer per member.
1994  bool AnyAnonStructUnionMembers = false;
1995  unsigned Fields = 0;
1997  E = RD->field_end(); I != E; ++I, ++Fields) {
1998  if (I->isAnonymousStructOrUnion()) {
1999  AnyAnonStructUnionMembers = true;
2000  break;
2001  }
2002  }
2003  // DR1460:
2004  // - if the class is a union-like class, but is not a union, for each of
2005  // its anonymous union members having variant members, exactly one of
2006  // them shall be initialized;
2007  if (AnyAnonStructUnionMembers ||
2008  Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2009  // Check initialization of non-static data members. Base classes are
2010  // always initialized so do not need to be checked. Dependent bases
2011  // might not have initializers in the member initializer list.
2012  llvm::SmallSet<Decl*, 16> Inits;
2013  for (const auto *I: Constructor->inits()) {
2014  if (FieldDecl *FD = I->getMember())
2015  Inits.insert(FD);
2016  else if (IndirectFieldDecl *ID = I->getIndirectMember())
2017  Inits.insert(ID->chain_begin(), ID->chain_end());
2018  }
2019 
2020  bool Diagnosed = false;
2021  for (auto *I : RD->fields())
2022  CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2023  if (Diagnosed)
2024  return false;
2025  }
2026  }
2027  } else {
2028  if (ReturnStmts.empty()) {
2029  // C++1y doesn't require constexpr functions to contain a 'return'
2030  // statement. We still do, unless the return type might be void, because
2031  // otherwise if there's no return statement, the function cannot
2032  // be used in a core constant expression.
2033  bool OK = getLangOpts().CPlusPlus14 &&
2034  (Dcl->getReturnType()->isVoidType() ||
2035  Dcl->getReturnType()->isDependentType());
2036  Diag(Dcl->getLocation(),
2037  OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2038  : diag::err_constexpr_body_no_return);
2039  if (!OK)
2040  return false;
2041  } else if (ReturnStmts.size() > 1) {
2042  Diag(ReturnStmts.back(),
2043  getLangOpts().CPlusPlus14
2044  ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2045  : diag::ext_constexpr_body_multiple_return);
2046  for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2047  Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2048  }
2049  }
2050 
2051  // C++11 [dcl.constexpr]p5:
2052  // if no function argument values exist such that the function invocation
2053  // substitution would produce a constant expression, the program is
2054  // ill-formed; no diagnostic required.
2055  // C++11 [dcl.constexpr]p3:
2056  // - every constructor call and implicit conversion used in initializing the
2057  // return value shall be one of those allowed in a constant expression.
2058  // C++11 [dcl.constexpr]p4:
2059  // - every constructor involved in initializing non-static data members and
2060  // base class sub-objects shall be a constexpr constructor.
2062  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2063  Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2064  << isa<CXXConstructorDecl>(Dcl);
2065  for (size_t I = 0, N = Diags.size(); I != N; ++I)
2066  Diag(Diags[I].first, Diags[I].second);
2067  // Don't return false here: we allow this for compatibility in
2068  // system headers.
2069  }
2070 
2071  return true;
2072 }
2073 
2074 /// Get the class that is directly named by the current context. This is the
2075 /// class for which an unqualified-id in this scope could name a constructor
2076 /// or destructor.
2077 ///
2078 /// If the scope specifier denotes a class, this will be that class.
2079 /// If the scope specifier is empty, this will be the class whose
2080 /// member-specification we are currently within. Otherwise, there
2081 /// is no such class.
2083  assert(getLangOpts().CPlusPlus && "No class names in C!");
2084 
2085  if (SS && SS->isInvalid())
2086  return nullptr;
2087 
2088  if (SS && SS->isNotEmpty()) {
2089  DeclContext *DC = computeDeclContext(*SS, true);
2090  return dyn_cast_or_null<CXXRecordDecl>(DC);
2091  }
2092 
2093  return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2094 }
2095 
2096 /// isCurrentClassName - Determine whether the identifier II is the
2097 /// name of the class type currently being defined. In the case of
2098 /// nested classes, this will only return true if II is the name of
2099 /// the innermost class.
2101  const CXXScopeSpec *SS) {
2102  CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2103  return CurDecl && &II == CurDecl->getIdentifier();
2104 }
2105 
2106 /// Determine whether the identifier II is a typo for the name of
2107 /// the class type currently being defined. If so, update it to the identifier
2108 /// that should have been used.
2110  assert(getLangOpts().CPlusPlus && "No class names in C!");
2111 
2112  if (!getLangOpts().SpellChecking)
2113  return false;
2114 
2115  CXXRecordDecl *CurDecl;
2116  if (SS && SS->isSet() && !SS->isInvalid()) {
2117  DeclContext *DC = computeDeclContext(*SS, true);
2118  CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2119  } else
2120  CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2121 
2122  if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2123  3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2124  < II->getLength()) {
2125  II = CurDecl->getIdentifier();
2126  return true;
2127  }
2128 
2129  return false;
2130 }
2131 
2132 /// Determine whether the given class is a base class of the given
2133 /// class, including looking at dependent bases.
2134 static bool findCircularInheritance(const CXXRecordDecl *Class,
2135  const CXXRecordDecl *Current) {
2137 
2138  Class = Class->getCanonicalDecl();
2139  while (true) {
2140  for (const auto &I : Current->bases()) {
2141  CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2142  if (!Base)
2143  continue;
2144 
2145  Base = Base->getDefinition();
2146  if (!Base)
2147  continue;
2148 
2149  if (Base->getCanonicalDecl() == Class)
2150  return true;
2151 
2152  Queue.push_back(Base);
2153  }
2154 
2155  if (Queue.empty())
2156  return false;
2157 
2158  Current = Queue.pop_back_val();
2159  }
2160 
2161  return false;
2162 }
2163 
2164 /// Check the validity of a C++ base class specifier.
2165 ///
2166 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2167 /// and returns NULL otherwise.
2170  SourceRange SpecifierRange,
2171  bool Virtual, AccessSpecifier Access,
2172  TypeSourceInfo *TInfo,
2173  SourceLocation EllipsisLoc) {
2174  QualType BaseType = TInfo->getType();
2175 
2176  // C++ [class.union]p1:
2177  // A union shall not have base classes.
2178  if (Class->isUnion()) {
2179  Diag(Class->getLocation(), diag::err_base_clause_on_union)
2180  << SpecifierRange;
2181  return nullptr;
2182  }
2183 
2184  if (EllipsisLoc.isValid() &&
2186  Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2187  << TInfo->getTypeLoc().getSourceRange();
2188  EllipsisLoc = SourceLocation();
2189  }
2190 
2191  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2192 
2193  if (BaseType->isDependentType()) {
2194  // Make sure that we don't have circular inheritance among our dependent
2195  // bases. For non-dependent bases, the check for completeness below handles
2196  // this.
2197  if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2198  if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2199  ((BaseDecl = BaseDecl->getDefinition()) &&
2200  findCircularInheritance(Class, BaseDecl))) {
2201  Diag(BaseLoc, diag::err_circular_inheritance)
2202  << BaseType << Context.getTypeDeclType(Class);
2203 
2204  if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2205  Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2206  << BaseType;
2207 
2208  return nullptr;
2209  }
2210  }
2211 
2212  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2213  Class->getTagKind() == TTK_Class,
2214  Access, TInfo, EllipsisLoc);
2215  }
2216 
2217  // Base specifiers must be record types.
2218  if (!BaseType->isRecordType()) {
2219  Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2220  return nullptr;
2221  }
2222 
2223  // C++ [class.union]p1:
2224  // A union shall not be used as a base class.
2225  if (BaseType->isUnionType()) {
2226  Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2227  return nullptr;
2228  }
2229 
2230  // For the MS ABI, propagate DLL attributes to base class templates.
2231  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2232  if (Attr *ClassAttr = getDLLAttr(Class)) {
2233  if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2234  BaseType->getAsCXXRecordDecl())) {
2235  propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2236  BaseLoc);
2237  }
2238  }
2239  }
2240 
2241  // C++ [class.derived]p2:
2242  // The class-name in a base-specifier shall not be an incompletely
2243  // defined class.
2244  if (RequireCompleteType(BaseLoc, BaseType,
2245  diag::err_incomplete_base_class, SpecifierRange)) {
2246  Class->setInvalidDecl();
2247  return nullptr;
2248  }
2249 
2250  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2251  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2252  assert(BaseDecl && "Record type has no declaration");
2253  BaseDecl = BaseDecl->getDefinition();
2254  assert(BaseDecl && "Base type is not incomplete, but has no definition");
2255  CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2256  assert(CXXBaseDecl && "Base type is not a C++ type");
2257 
2258  // Microsoft docs say:
2259  // "If a base-class has a code_seg attribute, derived classes must have the
2260  // same attribute."
2261  const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2262  const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2263  if ((DerivedCSA || BaseCSA) &&
2264  (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2265  Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2266  Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2267  << CXXBaseDecl;
2268  return nullptr;
2269  }
2270 
2271  // A class which contains a flexible array member is not suitable for use as a
2272  // base class:
2273  // - If the layout determines that a base comes before another base,
2274  // the flexible array member would index into the subsequent base.
2275  // - If the layout determines that base comes before the derived class,
2276  // the flexible array member would index into the derived class.
2277  if (CXXBaseDecl->hasFlexibleArrayMember()) {
2278  Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2279  << CXXBaseDecl->getDeclName();
2280  return nullptr;
2281  }
2282 
2283  // C++ [class]p3:
2284  // If a class is marked final and it appears as a base-type-specifier in
2285  // base-clause, the program is ill-formed.
2286  if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2287  Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2288  << CXXBaseDecl->getDeclName()
2289  << FA->isSpelledAsSealed();
2290  Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2291  << CXXBaseDecl->getDeclName() << FA->getRange();
2292  return nullptr;
2293  }
2294 
2295  if (BaseDecl->isInvalidDecl())
2296  Class->setInvalidDecl();
2297 
2298  // Create the base specifier.
2299  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2300  Class->getTagKind() == TTK_Class,
2301  Access, TInfo, EllipsisLoc);
2302 }
2303 
2304 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2305 /// one entry in the base class list of a class specifier, for
2306 /// example:
2307 /// class foo : public bar, virtual private baz {
2308 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2309 BaseResult
2310 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2311  ParsedAttributes &Attributes,
2312  bool Virtual, AccessSpecifier Access,
2313  ParsedType basetype, SourceLocation BaseLoc,
2314  SourceLocation EllipsisLoc) {
2315  if (!classdecl)
2316  return true;
2317 
2318  AdjustDeclIfTemplate(classdecl);
2319  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2320  if (!Class)
2321  return true;
2322 
2323  // We haven't yet attached the base specifiers.
2324  Class->setIsParsingBaseSpecifiers();
2325 
2326  // We do not support any C++11 attributes on base-specifiers yet.
2327  // Diagnose any attributes we see.
2328  for (const ParsedAttr &AL : Attributes) {
2329  if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2330  continue;
2331  Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2332  ? diag::warn_unknown_attribute_ignored
2333  : diag::err_base_specifier_attribute)
2334  << AL.getName();
2335  }
2336 
2337  TypeSourceInfo *TInfo = nullptr;
2338  GetTypeFromParser(basetype, &TInfo);
2339 
2340  if (EllipsisLoc.isInvalid() &&
2341  DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2342  UPPC_BaseType))
2343  return true;
2344 
2345  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2346  Virtual, Access, TInfo,
2347  EllipsisLoc))
2348  return BaseSpec;
2349  else
2350  Class->setInvalidDecl();
2351 
2352  return true;
2353 }
2354 
2355 /// Use small set to collect indirect bases. As this is only used
2356 /// locally, there's no need to abstract the small size parameter.
2357 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2358 
2359 /// Recursively add the bases of Type. Don't add Type itself.
2360 static void
2361 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2362  const QualType &Type)
2363 {
2364  // Even though the incoming type is a base, it might not be
2365  // a class -- it could be a template parm, for instance.
2366  if (auto Rec = Type->getAs<RecordType>()) {
2367  auto Decl = Rec->getAsCXXRecordDecl();
2368 
2369  // Iterate over its bases.
2370  for (const auto &BaseSpec : Decl->bases()) {
2371  QualType Base = Context.getCanonicalType(BaseSpec.getType())
2372  .getUnqualifiedType();
2373  if (Set.insert(Base).second)
2374  // If we've not already seen it, recurse.
2375  NoteIndirectBases(Context, Set, Base);
2376  }
2377  }
2378 }
2379 
2380 /// Performs the actual work of attaching the given base class
2381 /// specifiers to a C++ class.
2384  if (Bases.empty())
2385  return false;
2386 
2387  // Used to keep track of which base types we have already seen, so
2388  // that we can properly diagnose redundant direct base types. Note
2389  // that the key is always the unqualified canonical type of the base
2390  // class.
2391  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2392 
2393  // Used to track indirect bases so we can see if a direct base is
2394  // ambiguous.
2395  IndirectBaseSet IndirectBaseTypes;
2396 
2397  // Copy non-redundant base specifiers into permanent storage.
2398  unsigned NumGoodBases = 0;
2399  bool Invalid = false;
2400  for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2401  QualType NewBaseType
2402  = Context.getCanonicalType(Bases[idx]->getType());
2403  NewBaseType = NewBaseType.getLocalUnqualifiedType();
2404 
2405  CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2406  if (KnownBase) {
2407  // C++ [class.mi]p3:
2408  // A class shall not be specified as a direct base class of a
2409  // derived class more than once.
2410  Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2411  << KnownBase->getType() << Bases[idx]->getSourceRange();
2412 
2413  // Delete the duplicate base class specifier; we're going to
2414  // overwrite its pointer later.
2415  Context.Deallocate(Bases[idx]);
2416 
2417  Invalid = true;
2418  } else {
2419  // Okay, add this new base class.
2420  KnownBase = Bases[idx];
2421  Bases[NumGoodBases++] = Bases[idx];
2422 
2423  // Note this base's direct & indirect bases, if there could be ambiguity.
2424  if (Bases.size() > 1)
2425  NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2426 
2427  if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2428  const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2429  if (Class->isInterface() &&
2430  (!RD->isInterfaceLike() ||
2431  KnownBase->getAccessSpecifier() != AS_public)) {
2432  // The Microsoft extension __interface does not permit bases that
2433  // are not themselves public interfaces.
2434  Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2435  << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2436  << RD->getSourceRange();
2437  Invalid = true;
2438  }
2439  if (RD->hasAttr<WeakAttr>())
2440  Class->addAttr(WeakAttr::CreateImplicit(Context));
2441  }
2442  }
2443  }
2444 
2445  // Attach the remaining base class specifiers to the derived class.
2446  Class->setBases(Bases.data(), NumGoodBases);
2447 
2448  // Check that the only base classes that are duplicate are virtual.
2449  for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2450  // Check whether this direct base is inaccessible due to ambiguity.
2451  QualType BaseType = Bases[idx]->getType();
2452 
2453  // Skip all dependent types in templates being used as base specifiers.
2454  // Checks below assume that the base specifier is a CXXRecord.
2455  if (BaseType->isDependentType())
2456  continue;
2457 
2458  CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2459  .getUnqualifiedType();
2460 
2461  if (IndirectBaseTypes.count(CanonicalBase)) {
2462  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2463  /*DetectVirtual=*/true);
2464  bool found
2465  = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2466  assert(found);
2467  (void)found;
2468 
2469  if (Paths.isAmbiguous(CanonicalBase))
2470  Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2471  << BaseType << getAmbiguousPathsDisplayString(Paths)
2472  << Bases[idx]->getSourceRange();
2473  else
2474  assert(Bases[idx]->isVirtual());
2475  }
2476 
2477  // Delete the base class specifier, since its data has been copied
2478  // into the CXXRecordDecl.
2479  Context.Deallocate(Bases[idx]);
2480  }
2481 
2482  return Invalid;
2483 }
2484 
2485 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2486 /// class, after checking whether there are any duplicate base
2487 /// classes.
2488 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2490  if (!ClassDecl || Bases.empty())
2491  return;
2492 
2493  AdjustDeclIfTemplate(ClassDecl);
2494  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2495 }
2496 
2497 /// Determine whether the type \p Derived is a C++ class that is
2498 /// derived from the type \p Base.
2500  if (!getLangOpts().CPlusPlus)
2501  return false;
2502 
2503  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2504  if (!DerivedRD)
2505  return false;
2506 
2507  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2508  if (!BaseRD)
2509  return false;
2510 
2511  // If either the base or the derived type is invalid, don't try to
2512  // check whether one is derived from the other.
2513  if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2514  return false;
2515 
2516  // FIXME: In a modules build, do we need the entire path to be visible for us
2517  // to be able to use the inheritance relationship?
2518  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2519  return false;
2520 
2521  return DerivedRD->isDerivedFrom(BaseRD);
2522 }
2523 
2524 /// Determine whether the type \p Derived is a C++ class that is
2525 /// derived from the type \p Base.
2527  CXXBasePaths &Paths) {
2528  if (!getLangOpts().CPlusPlus)
2529  return false;
2530 
2531  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2532  if (!DerivedRD)
2533  return false;
2534 
2535  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2536  if (!BaseRD)
2537  return false;
2538 
2539  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2540  return false;
2541 
2542  return DerivedRD->isDerivedFrom(BaseRD, Paths);
2543 }
2544 
2545 static void BuildBasePathArray(const CXXBasePath &Path,
2546  CXXCastPath &BasePathArray) {
2547  // We first go backward and check if we have a virtual base.
2548  // FIXME: It would be better if CXXBasePath had the base specifier for
2549  // the nearest virtual base.
2550  unsigned Start = 0;
2551  for (unsigned I = Path.size(); I != 0; --I) {
2552  if (Path[I - 1].Base->isVirtual()) {
2553  Start = I - 1;
2554  break;
2555  }
2556  }
2557 
2558  // Now add all bases.
2559  for (unsigned I = Start, E = Path.size(); I != E; ++I)
2560  BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2561 }
2562 
2563 
2565  CXXCastPath &BasePathArray) {
2566  assert(BasePathArray.empty() && "Base path array must be empty!");
2567  assert(Paths.isRecordingPaths() && "Must record paths!");
2568  return ::BuildBasePathArray(Paths.front(), BasePathArray);
2569 }
2570 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2571 /// conversion (where Derived and Base are class types) is
2572 /// well-formed, meaning that the conversion is unambiguous (and
2573 /// that all of the base classes are accessible). Returns true
2574 /// and emits a diagnostic if the code is ill-formed, returns false
2575 /// otherwise. Loc is the location where this routine should point to
2576 /// if there is an error, and Range is the source range to highlight
2577 /// if there is an error.
2578 ///
2579 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2580 /// diagnostic for the respective type of error will be suppressed, but the
2581 /// check for ill-formed code will still be performed.
2582 bool
2584  unsigned InaccessibleBaseID,
2585  unsigned AmbigiousBaseConvID,
2586  SourceLocation Loc, SourceRange Range,
2587  DeclarationName Name,
2588  CXXCastPath *BasePath,
2589  bool IgnoreAccess) {
2590  // First, determine whether the path from Derived to Base is
2591  // ambiguous. This is slightly more expensive than checking whether
2592  // the Derived to Base conversion exists, because here we need to
2593  // explore multiple paths to determine if there is an ambiguity.
2594  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2595  /*DetectVirtual=*/false);
2596  bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2597  if (!DerivationOkay)
2598  return true;
2599 
2600  const CXXBasePath *Path = nullptr;
2601  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2602  Path = &Paths.front();
2603 
2604  // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2605  // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2606  // user to access such bases.
2607  if (!Path && getLangOpts().MSVCCompat) {
2608  for (const CXXBasePath &PossiblePath : Paths) {
2609  if (PossiblePath.size() == 1) {
2610  Path = &PossiblePath;
2611  if (AmbigiousBaseConvID)
2612  Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2613  << Base << Derived << Range;
2614  break;
2615  }
2616  }
2617  }
2618 
2619  if (Path) {
2620  if (!IgnoreAccess) {
2621  // Check that the base class can be accessed.
2622  switch (
2623  CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2624  case AR_inaccessible:
2625  return true;
2626  case AR_accessible:
2627  case AR_dependent:
2628  case AR_delayed:
2629  break;
2630  }
2631  }
2632 
2633  // Build a base path if necessary.
2634  if (BasePath)
2635  ::BuildBasePathArray(*Path, *BasePath);
2636  return false;
2637  }
2638 
2639  if (AmbigiousBaseConvID) {
2640  // We know that the derived-to-base conversion is ambiguous, and
2641  // we're going to produce a diagnostic. Perform the derived-to-base
2642  // search just one more time to compute all of the possible paths so
2643  // that we can print them out. This is more expensive than any of
2644  // the previous derived-to-base checks we've done, but at this point
2645  // performance isn't as much of an issue.
2646  Paths.clear();
2647  Paths.setRecordingPaths(true);
2648  bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2649  assert(StillOkay && "Can only be used with a derived-to-base conversion");
2650  (void)StillOkay;
2651 
2652  // Build up a textual representation of the ambiguous paths, e.g.,
2653  // D -> B -> A, that will be used to illustrate the ambiguous
2654  // conversions in the diagnostic. We only print one of the paths
2655  // to each base class subobject.
2656  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2657 
2658  Diag(Loc, AmbigiousBaseConvID)
2659  << Derived << Base << PathDisplayStr << Range << Name;
2660  }
2661  return true;
2662 }
2663 
2664 bool
2666  SourceLocation Loc, SourceRange Range,
2667  CXXCastPath *BasePath,
2668  bool IgnoreAccess) {
2669  return CheckDerivedToBaseConversion(
2670  Derived, Base, diag::err_upcast_to_inaccessible_base,
2671  diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2672  BasePath, IgnoreAccess);
2673 }
2674 
2675 
2676 /// Builds a string representing ambiguous paths from a
2677 /// specific derived class to different subobjects of the same base
2678 /// class.
2679 ///
2680 /// This function builds a string that can be used in error messages
2681 /// to show the different paths that one can take through the
2682 /// inheritance hierarchy to go from the derived class to different
2683 /// subobjects of a base class. The result looks something like this:
2684 /// @code
2685 /// struct D -> struct B -> struct A
2686 /// struct D -> struct C -> struct A
2687 /// @endcode
2689  std::string PathDisplayStr;
2690  std::set<unsigned> DisplayedPaths;
2691  for (CXXBasePaths::paths_iterator Path = Paths.begin();
2692  Path != Paths.end(); ++Path) {
2693  if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2694  // We haven't displayed a path to this particular base
2695  // class subobject yet.
2696  PathDisplayStr += "\n ";
2697  PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2698  for (CXXBasePath::const_iterator Element = Path->begin();
2699  Element != Path->end(); ++Element)
2700  PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2701  }
2702  }
2703 
2704  return PathDisplayStr;
2705 }
2706 
2707 //===----------------------------------------------------------------------===//
2708 // C++ class member Handling
2709 //===----------------------------------------------------------------------===//
2710 
2711 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2714  const ParsedAttributesView &Attrs) {
2715  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2716  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2717  ASLoc, ColonLoc);
2718  CurContext->addHiddenDecl(ASDecl);
2719  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2720 }
2721 
2722 /// CheckOverrideControl - Check C++11 override control semantics.
2724  if (D->isInvalidDecl())
2725  return;
2726 
2727  // We only care about "override" and "final" declarations.
2728  if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2729  return;
2730 
2731  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2732 
2733  // We can't check dependent instance methods.
2734  if (MD && MD->isInstance() &&
2735  (MD->getParent()->hasAnyDependentBases() ||
2736  MD->getType()->isDependentType()))
2737  return;
2738 
2739  if (MD && !MD->isVirtual()) {
2740  // If we have a non-virtual method, check if if hides a virtual method.
2741  // (In that case, it's most likely the method has the wrong type.)
2742  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2743  FindHiddenVirtualMethods(MD, OverloadedMethods);
2744 
2745  if (!OverloadedMethods.empty()) {
2746  if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2747  Diag(OA->getLocation(),
2748  diag::override_keyword_hides_virtual_member_function)
2749  << "override" << (OverloadedMethods.size() > 1);
2750  } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2751  Diag(FA->getLocation(),
2752  diag::override_keyword_hides_virtual_member_function)
2753  << (FA->isSpelledAsSealed() ? "sealed" : "final")
2754  << (OverloadedMethods.size() > 1);
2755  }
2756  NoteHiddenVirtualMethods(MD, OverloadedMethods);
2757  MD->setInvalidDecl();
2758  return;
2759  }
2760  // Fall through into the general case diagnostic.
2761  // FIXME: We might want to attempt typo correction here.
2762  }
2763 
2764  if (!MD || !MD->isVirtual()) {
2765  if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2766  Diag(OA->getLocation(),
2767  diag::override_keyword_only_allowed_on_virtual_member_functions)
2768  << "override" << FixItHint::CreateRemoval(OA->getLocation());
2769  D->dropAttr<OverrideAttr>();
2770  }
2771  if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2772  Diag(FA->getLocation(),
2773  diag::override_keyword_only_allowed_on_virtual_member_functions)
2774  << (FA->isSpelledAsSealed() ? "sealed" : "final")
2775  << FixItHint::CreateRemoval(FA->getLocation());
2776  D->dropAttr<FinalAttr>();
2777  }
2778  return;
2779  }
2780 
2781  // C++11 [class.virtual]p5:
2782  // If a function is marked with the virt-specifier override and
2783  // does not override a member function of a base class, the program is
2784  // ill-formed.
2785  bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2786  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2787  Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2788  << MD->getDeclName();
2789 }
2790 
2792  if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2793  return;
2794  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2795  if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2796  return;
2797 
2798  SourceLocation Loc = MD->getLocation();
2799  SourceLocation SpellingLoc = Loc;
2800  if (getSourceManager().isMacroArgExpansion(Loc))
2801  SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2802  SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2803  if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2804  return;
2805 
2806  if (MD->size_overridden_methods() > 0) {
2807  unsigned DiagID = isa<CXXDestructorDecl>(MD)
2808  ? diag::warn_destructor_marked_not_override_overriding
2809  : diag::warn_function_marked_not_override_overriding;
2810  Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2811  const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2812  Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2813  }
2814 }
2815 
2816 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2817 /// function overrides a virtual member function marked 'final', according to
2818 /// C++11 [class.virtual]p4.
2820  const CXXMethodDecl *Old) {
2821  FinalAttr *FA = Old->getAttr<FinalAttr>();
2822  if (!FA)
2823  return false;
2824 
2825  Diag(New->getLocation(), diag::err_final_function_overridden)
2826  << New->getDeclName()
2827  << FA->isSpelledAsSealed();
2828  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2829  return true;
2830 }
2831 
2832 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2833  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2834  // FIXME: Destruction of ObjC lifetime types has side-effects.
2835  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2836  return !RD->isCompleteDefinition() ||
2837  !RD->hasTrivialDefaultConstructor() ||
2838  !RD->hasTrivialDestructor();
2839  return false;
2840 }
2841 
2844  llvm::find_if(list, [](const ParsedAttr &AL) {
2845  return AL.isDeclspecPropertyAttribute();
2846  });
2847  if (Itr != list.end())
2848  return &*Itr;
2849  return nullptr;
2850 }
2851 
2852 // Check if there is a field shadowing.
2853 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2854  DeclarationName FieldName,
2855  const CXXRecordDecl *RD) {
2856  if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2857  return;
2858 
2859  // To record a shadowed field in a base
2860  std::map<CXXRecordDecl*, NamedDecl*> Bases;
2861  auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2862  CXXBasePath &Path) {
2863  const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2864  // Record an ambiguous path directly
2865  if (Bases.find(Base) != Bases.end())
2866  return true;
2867  for (const auto Field : Base->lookup(FieldName)) {
2868  if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2869  Field->getAccess() != AS_private) {
2870  assert(Field->getAccess() != AS_none);
2871  assert(Bases.find(Base) == Bases.end());
2872  Bases[Base] = Field;
2873  return true;
2874  }
2875  }
2876  return false;
2877  };
2878 
2879  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2880  /*DetectVirtual=*/true);
2881  if (!RD->lookupInBases(FieldShadowed, Paths))
2882  return;
2883 
2884  for (const auto &P : Paths) {
2885  auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2886  auto It = Bases.find(Base);
2887  // Skip duplicated bases
2888  if (It == Bases.end())
2889  continue;
2890  auto BaseField = It->second;
2891  assert(BaseField->getAccess() != AS_private);
2892  if (AS_none !=
2893  CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2894  Diag(Loc, diag::warn_shadow_field)
2895  << FieldName << RD << Base;
2896  Diag(BaseField->getLocation(), diag::note_shadow_field);
2897  Bases.erase(It);
2898  }
2899  }
2900 }
2901 
2902 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2903 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2904 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2905 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2906 /// present (but parsing it has been deferred).
2907 NamedDecl *
2909  MultiTemplateParamsArg TemplateParameterLists,
2910  Expr *BW, const VirtSpecifiers &VS,
2911  InClassInitStyle InitStyle) {
2912  const DeclSpec &DS = D.getDeclSpec();
2913  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2914  DeclarationName Name = NameInfo.getName();
2915  SourceLocation Loc = NameInfo.getLoc();
2916 
2917  // For anonymous bitfields, the location should point to the type.
2918  if (Loc.isInvalid())
2919  Loc = D.getBeginLoc();
2920 
2921  Expr *BitWidth = static_cast<Expr*>(BW);
2922 
2923  assert(isa<CXXRecordDecl>(CurContext));
2924  assert(!DS.isFriendSpecified());
2925 
2926  bool isFunc = D.isDeclarationOfFunction();
2927  const ParsedAttr *MSPropertyAttr =
2929 
2930  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2931  // The Microsoft extension __interface only permits public member functions
2932  // and prohibits constructors, destructors, operators, non-public member
2933  // functions, static methods and data members.
2934  unsigned InvalidDecl;
2935  bool ShowDeclName = true;
2936  if (!isFunc &&
2937  (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2938  InvalidDecl = 0;
2939  else if (!isFunc)
2940  InvalidDecl = 1;
2941  else if (AS != AS_public)
2942  InvalidDecl = 2;
2943  else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2944  InvalidDecl = 3;
2945  else switch (Name.getNameKind()) {
2947  InvalidDecl = 4;
2948  ShowDeclName = false;
2949  break;
2950 
2952  InvalidDecl = 5;
2953  ShowDeclName = false;
2954  break;
2955 
2958  InvalidDecl = 6;
2959  break;
2960 
2961  default:
2962  InvalidDecl = 0;
2963  break;
2964  }
2965 
2966  if (InvalidDecl) {
2967  if (ShowDeclName)
2968  Diag(Loc, diag::err_invalid_member_in_interface)
2969  << (InvalidDecl-1) << Name;
2970  else
2971  Diag(Loc, diag::err_invalid_member_in_interface)
2972  << (InvalidDecl-1) << "";
2973  return nullptr;
2974  }
2975  }
2976 
2977  // C++ 9.2p6: A member shall not be declared to have automatic storage
2978  // duration (auto, register) or with the extern storage-class-specifier.
2979  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2980  // data members and cannot be applied to names declared const or static,
2981  // and cannot be applied to reference members.
2982  switch (DS.getStorageClassSpec()) {
2984  case DeclSpec::SCS_typedef:
2985  case DeclSpec::SCS_static:
2986  break;
2987  case DeclSpec::SCS_mutable:
2988  if (isFunc) {
2989  Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2990 
2991  // FIXME: It would be nicer if the keyword was ignored only for this
2992  // declarator. Otherwise we could get follow-up errors.
2994  }
2995  break;
2996  default:
2998  diag::err_storageclass_invalid_for_member);
3000  break;
3001  }
3002 
3003  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3005  !isFunc);
3006 
3007  if (DS.isConstexprSpecified() && isInstField) {
3009  Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3010  SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3011  if (InitStyle == ICIS_NoInit) {
3012  B << 0 << 0;
3014  B << FixItHint::CreateRemoval(ConstexprLoc);
3015  else {
3016  B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3018  const char *PrevSpec;
3019  unsigned DiagID;
3020  bool Failed = D.getMutableDeclSpec().SetTypeQual(
3021  DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3022  (void)Failed;
3023  assert(!Failed && "Making a constexpr member const shouldn't fail");
3024  }
3025  } else {
3026  B << 1;
3027  const char *PrevSpec;
3028  unsigned DiagID;
3030  *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3031  Context.getPrintingPolicy())) {
3032  assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3033  "This is the only DeclSpec that should fail to be applied");
3034  B << 1;
3035  } else {
3036  B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3037  isInstField = false;
3038  }
3039  }
3040  }
3041 
3042  NamedDecl *Member;
3043  if (isInstField) {
3044  CXXScopeSpec &SS = D.getCXXScopeSpec();
3045 
3046  // Data members must have identifiers for names.
3047  if (!Name.isIdentifier()) {
3048  Diag(Loc, diag::err_bad_variable_name)
3049  << Name;
3050  return nullptr;
3051  }
3052 
3053  IdentifierInfo *II = Name.getAsIdentifierInfo();
3054 
3055  // Member field could not be with "template" keyword.
3056  // So TemplateParameterLists should be empty in this case.
3057  if (TemplateParameterLists.size()) {
3058  TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3059  if (TemplateParams->size()) {
3060  // There is no such thing as a member field template.
3061  Diag(D.getIdentifierLoc(), diag::err_template_member)
3062  << II
3063  << SourceRange(TemplateParams->getTemplateLoc(),
3064  TemplateParams->getRAngleLoc());
3065  } else {
3066  // There is an extraneous 'template<>' for this member.
3067  Diag(TemplateParams->getTemplateLoc(),
3068  diag::err_template_member_noparams)
3069  << II
3070  << SourceRange(TemplateParams->getTemplateLoc(),
3071  TemplateParams->getRAngleLoc());
3072  }
3073  return nullptr;
3074  }
3075 
3076  if (SS.isSet() && !SS.isInvalid()) {
3077  // The user provided a superfluous scope specifier inside a class
3078  // definition:
3079  //
3080  // class X {
3081  // int X::member;
3082  // };
3083  if (DeclContext *DC = computeDeclContext(SS, false))
3084  diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3085  D.getName().getKind() ==
3087  else
3088  Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3089  << Name << SS.getRange();
3090 
3091  SS.clear();
3092  }
3093 
3094  if (MSPropertyAttr) {
3095  Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3096  BitWidth, InitStyle, AS, *MSPropertyAttr);
3097  if (!Member)
3098  return nullptr;
3099  isInstField = false;
3100  } else {
3101  Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3102  BitWidth, InitStyle, AS);
3103  if (!Member)
3104  return nullptr;
3105  }
3106 
3107  CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3108  } else {
3109  Member = HandleDeclarator(S, D, TemplateParameterLists);
3110  if (!Member)
3111  return nullptr;
3112 
3113  // Non-instance-fields can't have a bitfield.
3114  if (BitWidth) {
3115  if (Member->isInvalidDecl()) {
3116  // don't emit another diagnostic.
3117  } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3118  // C++ 9.6p3: A bit-field shall not be a static member.
3119  // "static member 'A' cannot be a bit-field"
3120  Diag(Loc, diag::err_static_not_bitfield)
3121  << Name << BitWidth->getSourceRange();
3122  } else if (isa<TypedefDecl>(Member)) {
3123  // "typedef member 'x' cannot be a bit-field"
3124  Diag(Loc, diag::err_typedef_not_bitfield)
3125  << Name << BitWidth->getSourceRange();
3126  } else {
3127  // A function typedef ("typedef int f(); f a;").
3128  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3129  Diag(Loc, diag::err_not_integral_type_bitfield)
3130  << Name << cast<ValueDecl>(Member)->getType()
3131  << BitWidth->getSourceRange();
3132  }
3133 
3134  BitWidth = nullptr;
3135  Member->setInvalidDecl();
3136  }
3137 
3138  NamedDecl *NonTemplateMember = Member;
3139  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3140  NonTemplateMember = FunTmpl->getTemplatedDecl();
3141  else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3142  NonTemplateMember = VarTmpl->getTemplatedDecl();
3143 
3144  Member->setAccess(AS);
3145 
3146  // If we have declared a member function template or static data member
3147  // template, set the access of the templated declaration as well.
3148  if (NonTemplateMember != Member)
3149  NonTemplateMember->setAccess(AS);
3150 
3151  // C++ [temp.deduct.guide]p3:
3152  // A deduction guide [...] for a member class template [shall be
3153  // declared] with the same access [as the template].
3154  if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3155  auto *TD = DG->getDeducedTemplate();
3156  if (AS != TD->getAccess()) {
3157  Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3158  Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3159  << TD->getAccess();
3160  const AccessSpecDecl *LastAccessSpec = nullptr;
3161  for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3162  if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3163  LastAccessSpec = AccessSpec;
3164  }
3165  assert(LastAccessSpec && "differing access with no access specifier");
3166  Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3167  << AS;
3168  }
3169  }
3170  }
3171 
3172  if (VS.isOverrideSpecified())
3173  Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3174  if (VS.isFinalSpecified())
3175  Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3176  VS.isFinalSpelledSealed()));
3177 
3178  if (VS.getLastLocation().isValid()) {
3179  // Update the end location of a method that has a virt-specifiers.
3180  if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3181  MD->setRangeEnd(VS.getLastLocation());
3182  }
3183 
3184  CheckOverrideControl(Member);
3185 
3186  assert((Name || isInstField) && "No identifier for non-field ?");
3187 
3188  if (isInstField) {
3189  FieldDecl *FD = cast<FieldDecl>(Member);
3190  FieldCollector->Add(FD);
3191 
3192  if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3193  // Remember all explicit private FieldDecls that have a name, no side
3194  // effects and are not part of a dependent type declaration.
3195  if (!FD->isImplicit() && FD->getDeclName() &&
3196  FD->getAccess() == AS_private &&
3197  !FD->hasAttr<UnusedAttr>() &&
3198  !FD->getParent()->isDependentContext() &&
3200  UnusedPrivateFields.insert(FD);
3201  }
3202  }
3203 
3204  return Member;
3205 }
3206 
3207 namespace {
3208  class UninitializedFieldVisitor
3209  : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3210  Sema &S;
3211  // List of Decls to generate a warning on. Also remove Decls that become
3212  // initialized.
3213  llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3214  // List of base classes of the record. Classes are removed after their
3215  // initializers.
3216  llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3217  // Vector of decls to be removed from the Decl set prior to visiting the
3218  // nodes. These Decls may have been initialized in the prior initializer.
3219  llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3220  // If non-null, add a note to the warning pointing back to the constructor.
3221  const CXXConstructorDecl *Constructor;
3222  // Variables to hold state when processing an initializer list. When
3223  // InitList is true, special case initialization of FieldDecls matching
3224  // InitListFieldDecl.
3225  bool InitList;
3226  FieldDecl *InitListFieldDecl;
3227  llvm::SmallVector<unsigned, 4> InitFieldIndex;
3228 
3229  public:
3231  UninitializedFieldVisitor(Sema &S,
3232  llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3233  llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3234  : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3235  Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3236 
3237  // Returns true if the use of ME is not an uninitialized use.
3238  bool IsInitListMemberExprInitialized(MemberExpr *ME,
3239  bool CheckReferenceOnly) {
3241  bool ReferenceField = false;
3242  while (ME) {
3243  FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3244  if (!FD)
3245  return false;
3246  Fields.push_back(FD);
3247  if (FD->getType()->isReferenceType())
3248  ReferenceField = true;
3249  ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3250  }
3251 
3252  // Binding a reference to an unintialized field is not an
3253  // uninitialized use.
3254  if (CheckReferenceOnly && !ReferenceField)
3255  return true;
3256 
3257  llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3258  // Discard the first field since it is the field decl that is being
3259  // initialized.
3260  for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3261  UsedFieldIndex.push_back((*I)->getFieldIndex());
3262  }
3263 
3264  for (auto UsedIter = UsedFieldIndex.begin(),
3265  UsedEnd = UsedFieldIndex.end(),
3266  OrigIter = InitFieldIndex.begin(),
3267  OrigEnd = InitFieldIndex.end();
3268  UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3269  if (*UsedIter < *OrigIter)
3270  return true;
3271  if (*UsedIter > *OrigIter)
3272  break;
3273  }
3274 
3275  return false;
3276  }
3277 
3278  void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3279  bool AddressOf) {
3280  if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3281  return;
3282 
3283  // FieldME is the inner-most MemberExpr that is not an anonymous struct
3284  // or union.
3285  MemberExpr *FieldME = ME;
3286 
3287  bool AllPODFields = FieldME->getType().isPODType(S.Context);
3288 
3289  Expr *Base = ME;
3290  while (MemberExpr *SubME =
3291  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3292 
3293  if (isa<VarDecl>(SubME->getMemberDecl()))
3294  return;
3295 
3296  if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3297  if (!FD->isAnonymousStructOrUnion())
3298  FieldME = SubME;
3299 
3300  if (!FieldME->getType().isPODType(S.Context))
3301  AllPODFields = false;
3302 
3303  Base = SubME->getBase();
3304  }
3305 
3306  if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3307  return;
3308 
3309  if (AddressOf && AllPODFields)
3310  return;
3311 
3312  ValueDecl* FoundVD = FieldME->getMemberDecl();
3313 
3314  if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3315  while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3316  BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3317  }
3318 
3319  if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3320  QualType T = BaseCast->getType();
3321  if (T->isPointerType() &&
3322  BaseClasses.count(T->getPointeeType())) {
3323  S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3324  << T->getPointeeType() << FoundVD;
3325  }
3326  }
3327  }
3328 
3329  if (!Decls.count(FoundVD))
3330  return;
3331 
3332  const bool IsReference = FoundVD->getType()->isReferenceType();
3333 
3334  if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3335  // Special checking for initializer lists.
3336  if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3337  return;
3338  }
3339  } else {
3340  // Prevent double warnings on use of unbounded references.
3341  if (CheckReferenceOnly && !IsReference)
3342  return;
3343  }
3344 
3345  unsigned diag = IsReference
3346  ? diag::warn_reference_field_is_uninit
3347  : diag::warn_field_is_uninit;
3348  S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3349  if (Constructor)
3350  S.Diag(Constructor->getLocation(),
3351  diag::note_uninit_in_this_constructor)
3352  << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3353 
3354  }
3355 
3356  void HandleValue(Expr *E, bool AddressOf) {
3357  E = E->IgnoreParens();
3358 
3359  if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3360  HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3361  AddressOf /*AddressOf*/);
3362  return;
3363  }
3364 
3365  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3366  Visit(CO->getCond());
3367  HandleValue(CO->getTrueExpr(), AddressOf);
3368  HandleValue(CO->getFalseExpr(), AddressOf);
3369  return;
3370  }
3371 
3372  if (BinaryConditionalOperator *BCO =
3373  dyn_cast<BinaryConditionalOperator>(E)) {
3374  Visit(BCO->getCond());
3375  HandleValue(BCO->getFalseExpr(), AddressOf);
3376  return;
3377  }
3378 
3379  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3380  HandleValue(OVE->getSourceExpr(), AddressOf);
3381  return;
3382  }
3383 
3384  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3385  switch (BO->getOpcode()) {
3386  default:
3387  break;
3388  case(BO_PtrMemD):
3389  case(BO_PtrMemI):
3390  HandleValue(BO->getLHS(), AddressOf);
3391  Visit(BO->getRHS());
3392  return;
3393  case(BO_Comma):
3394  Visit(BO->getLHS());
3395  HandleValue(BO->getRHS(), AddressOf);
3396  return;
3397  }
3398  }
3399 
3400  Visit(E);
3401  }
3402 
3403  void CheckInitListExpr(InitListExpr *ILE) {
3404  InitFieldIndex.push_back(0);
3405  for (auto Child : ILE->children()) {
3406  if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3407  CheckInitListExpr(SubList);
3408  } else {
3409  Visit(Child);
3410  }
3411  ++InitFieldIndex.back();
3412  }
3413  InitFieldIndex.pop_back();
3414  }
3415 
3416  void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3417  FieldDecl *Field, const Type *BaseClass) {
3418  // Remove Decls that may have been initialized in the previous
3419  // initializer.
3420  for (ValueDecl* VD : DeclsToRemove)
3421  Decls.erase(VD);
3422  DeclsToRemove.clear();
3423 
3424  Constructor = FieldConstructor;
3425  InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3426 
3427  if (ILE && Field) {
3428  InitList = true;
3429  InitListFieldDecl = Field;
3430  InitFieldIndex.clear();
3431  CheckInitListExpr(ILE);
3432  } else {
3433  InitList = false;
3434  Visit(E);
3435  }
3436 
3437  if (Field)
3438  Decls.erase(Field);
3439  if (BaseClass)
3440  BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3441  }
3442 
3443  void VisitMemberExpr(MemberExpr *ME) {
3444  // All uses of unbounded reference fields will warn.
3445  HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3446  }
3447 
3448  void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3449  if (E->getCastKind() == CK_LValueToRValue) {
3450  HandleValue(E->getSubExpr(), false /*AddressOf*/);
3451  return;
3452  }
3453 
3454  Inherited::VisitImplicitCastExpr(E);
3455  }
3456 
3457  void VisitCXXConstructExpr(CXXConstructExpr *E) {
3458  if (E->getConstructor()->isCopyConstructor()) {
3459  Expr *ArgExpr = E->getArg(0);
3460  if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3461  if (ILE->getNumInits() == 1)
3462  ArgExpr = ILE->getInit(0);
3463  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3464  if (ICE->getCastKind() == CK_NoOp)
3465  ArgExpr = ICE->getSubExpr();
3466  HandleValue(ArgExpr, false /*AddressOf*/);
3467  return;
3468  }
3469  Inherited::VisitCXXConstructExpr(E);
3470  }
3471 
3472  void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3473  Expr *Callee = E->getCallee();
3474  if (isa<MemberExpr>(Callee)) {
3475  HandleValue(Callee, false /*AddressOf*/);
3476  for (auto Arg : E->arguments())
3477  Visit(Arg);
3478  return;
3479  }
3480 
3481  Inherited::VisitCXXMemberCallExpr(E);
3482  }
3483 
3484  void VisitCallExpr(CallExpr *E) {
3485  // Treat std::move as a use.
3486  if (E->isCallToStdMove()) {
3487  HandleValue(E->getArg(0), /*AddressOf=*/false);
3488  return;
3489  }
3490 
3491  Inherited::VisitCallExpr(E);
3492  }
3493 
3494  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3495  Expr *Callee = E->getCallee();
3496 
3497  if (isa<UnresolvedLookupExpr>(Callee))
3498  return Inherited::VisitCXXOperatorCallExpr(E);
3499 
3500  Visit(Callee);
3501  for (auto Arg : E->arguments())
3502  HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3503  }
3504 
3505  void VisitBinaryOperator(BinaryOperator *E) {
3506  // If a field assignment is detected, remove the field from the
3507  // uninitiailized field set.
3508  if (E->getOpcode() == BO_Assign)
3509  if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3510  if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3511  if (!FD->getType()->isReferenceType())
3512  DeclsToRemove.push_back(FD);
3513 
3514  if (E->isCompoundAssignmentOp()) {
3515  HandleValue(E->getLHS(), false /*AddressOf*/);
3516  Visit(E->getRHS());
3517  return;
3518  }
3519 
3520  Inherited::VisitBinaryOperator(E);
3521  }
3522 
3523  void VisitUnaryOperator(UnaryOperator *E) {
3524  if (E->isIncrementDecrementOp()) {
3525  HandleValue(E->getSubExpr(), false /*AddressOf*/);
3526  return;
3527  }
3528  if (E->getOpcode() == UO_AddrOf) {
3529  if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3530  HandleValue(ME->getBase(), true /*AddressOf*/);
3531  return;
3532  }
3533  }
3534 
3535  Inherited::VisitUnaryOperator(E);
3536  }
3537  };
3538 
3539  // Diagnose value-uses of fields to initialize themselves, e.g.
3540  // foo(foo)
3541  // where foo is not also a parameter to the constructor.
3542  // Also diagnose across field uninitialized use such as
3543  // x(y), y(x)
3544  // TODO: implement -Wuninitialized and fold this into that framework.
3545  static void DiagnoseUninitializedFields(
3546  Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3547 
3548  if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3549  Constructor->getLocation())) {
3550  return;
3551  }
3552 
3553  if (Constructor->isInvalidDecl())
3554  return;
3555 
3556  const CXXRecordDecl *RD = Constructor->getParent();
3557 
3558  if (RD->getDescribedClassTemplate())
3559  return;
3560 
3561  // Holds fields that are uninitialized.
3562  llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3563 
3564  // At the beginning, all fields are uninitialized.
3565  for (auto *I : RD->decls()) {
3566  if (auto *FD = dyn_cast<FieldDecl>(I)) {
3567  UninitializedFields.insert(FD);
3568  } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3569  UninitializedFields.insert(IFD->getAnonField());
3570  }
3571  }
3572 
3573  llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3574  for (auto I : RD->bases())
3575  UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3576 
3577  if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3578  return;
3579 
3580  UninitializedFieldVisitor UninitializedChecker(SemaRef,
3581  UninitializedFields,
3582  UninitializedBaseClasses);
3583 
3584  for (const auto *FieldInit : Constructor->inits()) {
3585  if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3586  break;
3587 
3588  Expr *InitExpr = FieldInit->getInit();
3589  if (!InitExpr)
3590  continue;
3591 
3593  dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3594  InitExpr = Default->getExpr();
3595  if (!InitExpr)
3596  continue;
3597  // In class initializers will point to the constructor.
3598  UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3599  FieldInit->getAnyMember(),
3600  FieldInit->getBaseClass());
3601  } else {
3602  UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3603  FieldInit->getAnyMember(),
3604  FieldInit->getBaseClass());
3605  }
3606  }
3607  }
3608 } // namespace
3609 
3610 /// Enter a new C++ default initializer scope. After calling this, the
3611 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3612 /// parsing or instantiating the initializer failed.
3614  // Create a synthetic function scope to represent the call to the constructor
3615  // that notionally surrounds a use of this initializer.
3616  PushFunctionScope();
3617 }
3618 
3619 /// This is invoked after parsing an in-class initializer for a
3620 /// non-static C++ class member, and after instantiating an in-class initializer
3621 /// in a class template. Such actions are deferred until the class is complete.
3623  SourceLocation InitLoc,
3624  Expr *InitExpr) {
3625  // Pop the notional constructor scope we created earlier.
3626  PopFunctionScopeInfo(nullptr, D);
3627 
3628  FieldDecl *FD = dyn_cast<FieldDecl>(D);
3629  assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3630  "must set init style when field is created");
3631 
3632  if (!InitExpr) {
3633  D->setInvalidDecl();
3634  if (FD)
3636  return;
3637  }
3638 
3639  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3640  FD->setInvalidDecl();
3642  return;
3643  }
3644 
3645  ExprResult Init = InitExpr;
3646  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3647  InitializedEntity Entity =
3652  InitExpr->getBeginLoc(),
3653  InitExpr->getEndLoc())
3654  : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3655  InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3656  Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3657  if (Init.isInvalid()) {
3658  FD->setInvalidDecl();
3659  return;
3660  }
3661  }
3662 
3663  // C++11 [class.base.init]p7:
3664  // The initialization of each base and member constitutes a
3665  // full-expression.
3666  Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3667  if (Init.isInvalid()) {
3668  FD->setInvalidDecl();
3669  return;
3670  }
3671 
3672  InitExpr = Init.get();
3673 
3674  FD->setInClassInitializer(InitExpr);
3675 }
3676 
3677 /// Find the direct and/or virtual base specifiers that
3678 /// correspond to the given base type, for use in base initialization
3679 /// within a constructor.
3680 static bool FindBaseInitializer(Sema &SemaRef,
3681  CXXRecordDecl *ClassDecl,
3682  QualType BaseType,
3683  const CXXBaseSpecifier *&DirectBaseSpec,
3684  const CXXBaseSpecifier *&VirtualBaseSpec) {
3685  // First, check for a direct base class.
3686  DirectBaseSpec = nullptr;
3687  for (const auto &Base : ClassDecl->bases()) {
3688  if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3689  // We found a direct base of this type. That's what we're
3690  // initializing.
3691  DirectBaseSpec = &Base;
3692  break;
3693  }
3694  }
3695 
3696  // Check for a virtual base class.
3697  // FIXME: We might be able to short-circuit this if we know in advance that
3698  // there are no virtual bases.
3699  VirtualBaseSpec = nullptr;
3700  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3701  // We haven't found a base yet; search the class hierarchy for a
3702  // virtual base class.
3703  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3704  /*DetectVirtual=*/false);
3705  if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3706  SemaRef.Context.getTypeDeclType(ClassDecl),
3707  BaseType, Paths)) {
3708  for (CXXBasePaths::paths_iterator Path = Paths.begin();
3709  Path != Paths.end(); ++Path) {
3710  if (Path->back().Base->isVirtual()) {
3711  VirtualBaseSpec = Path->back().Base;
3712  break;
3713  }
3714  }
3715  }
3716  }
3717 
3718  return DirectBaseSpec || VirtualBaseSpec;
3719 }
3720 
3721 /// Handle a C++ member initializer using braced-init-list 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  Expr *InitList,
3731  SourceLocation EllipsisLoc) {
3732  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3733  DS, IdLoc, InitList,
3734  EllipsisLoc);
3735 }
3736 
3737 /// Handle a C++ member initializer using parentheses syntax.
3739 Sema::ActOnMemInitializer(Decl *ConstructorD,
3740  Scope *S,
3741  CXXScopeSpec &SS,
3742  IdentifierInfo *MemberOrBase,
3743  ParsedType TemplateTypeTy,
3744  const DeclSpec &DS,
3745  SourceLocation IdLoc,
3746  SourceLocation LParenLoc,
3747  ArrayRef<Expr *> Args,
3748  SourceLocation RParenLoc,
3749  SourceLocation EllipsisLoc) {
3750  Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3751  Args, RParenLoc);
3752  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3753  DS, IdLoc, List, EllipsisLoc);
3754 }
3755 
3756 namespace {
3757 
3758 // Callback to only accept typo corrections that can be a valid C++ member
3759 // intializer: either a non-static field member or a base class.
3760 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3761 public:
3762  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3763  : ClassDecl(ClassDecl) {}
3764 
3765  bool ValidateCandidate(const TypoCorrection &candidate) override {
3766  if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3767  if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3768  return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3769  return isa<TypeDecl>(ND);
3770  }
3771  return false;
3772  }
3773 
3774 private:
3775  CXXRecordDecl *ClassDecl;
3776 };
3777 
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  if (!SS.getScopeRep() && !TemplateTypeTy) {
3824  // Look for a member, first.
3825  DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3826  if (!Result.empty()) {
3827  ValueDecl *Member;
3828  if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3829  (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3830  if (EllipsisLoc.isValid())
3831  Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3832  << MemberOrBase
3833  << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3834 
3835  return BuildMemberInitializer(Member, Init, IdLoc);
3836  }
3837  }
3838  }
3839  // It didn't name a member, so see if it names a class.
3840  QualType BaseType;
3841  TypeSourceInfo *TInfo = nullptr;
3842 
3843  if (TemplateTypeTy) {
3844  BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3845  } else if (DS.getTypeSpecType() == TST_decltype) {
3846  BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3847  } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3848  Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3849  return true;
3850  } else {
3851  LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3852  LookupParsedName(R, S, &SS);
3853 
3854  TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3855  if (!TyD) {
3856  if (R.isAmbiguous()) return true;
3857 
3858  // We don't want access-control diagnostics here.
3859  R.suppressDiagnostics();
3860 
3861  if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3862  bool NotUnknownSpecialization = false;
3863  DeclContext *DC = computeDeclContext(SS, false);
3864  if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3865  NotUnknownSpecialization = !Record->hasAnyDependentBases();
3866 
3867  if (!NotUnknownSpecialization) {
3868  // When the scope specifier can refer to a member of an unknown
3869  // specialization, we take it as a type name.
3870  BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3871  SS.getWithLocInContext(Context),
3872  *MemberOrBase, IdLoc);
3873  if (BaseType.isNull())
3874  return true;
3875 
3876  TInfo = Context.CreateTypeSourceInfo(BaseType);
3879  if (!TL.isNull()) {
3880  TL.setNameLoc(IdLoc);
3882  TL.setQualifierLoc(SS.getWithLocInContext(Context));
3883  }
3884 
3885  R.clear();
3886  R.setLookupName(MemberOrBase);
3887  }
3888  }
3889 
3890  // If no results were found, try to correct typos.
3891  TypoCorrection Corr;
3892  if (R.empty() && BaseType.isNull() &&
3893  (Corr = CorrectTypo(
3894  R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3895  llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3896  CTK_ErrorRecovery, ClassDecl))) {
3897  if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3898  // We have found a non-static data member with a similar
3899  // name to what was typed; complain and initialize that
3900  // member.
3901  diagnoseTypo(Corr,
3902  PDiag(diag::err_mem_init_not_member_or_class_suggest)
3903  << MemberOrBase << true);
3904  return BuildMemberInitializer(Member, Init, IdLoc);
3905  } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3906  const CXXBaseSpecifier *DirectBaseSpec;
3907  const CXXBaseSpecifier *VirtualBaseSpec;
3908  if (FindBaseInitializer(*this, ClassDecl,
3909  Context.getTypeDeclType(Type),
3910  DirectBaseSpec, VirtualBaseSpec)) {
3911  // We have found a direct or virtual base class with a
3912  // similar name to what was typed; complain and initialize
3913  // that base class.
3914  diagnoseTypo(Corr,
3915  PDiag(diag::err_mem_init_not_member_or_class_suggest)
3916  << MemberOrBase << false,
3917  PDiag() /*Suppress note, we provide our own.*/);
3918 
3919  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3920  : VirtualBaseSpec;
3921  Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
3922  << BaseSpec->getType() << BaseSpec->getSourceRange();
3923 
3924  TyD = Type;
3925  }
3926  }
3927  }
3928 
3929  if (!TyD && BaseType.isNull()) {
3930  Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3931  << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3932  return true;
3933  }
3934  }
3935 
3936  if (BaseType.isNull()) {
3937  BaseType = Context.getTypeDeclType(TyD);
3938  MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3939  if (SS.isSet()) {
3940  BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3941  BaseType);
3942  TInfo = Context.CreateTypeSourceInfo(BaseType);
3944  TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3946  TL.setQualifierLoc(SS.getWithLocInContext(Context));
3947  }
3948  }
3949  }
3950 
3951  if (!TInfo)
3952  TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3953 
3954  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3955 }
3956 
3959  SourceLocation IdLoc) {
3960  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3961  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3962  assert((DirectMember || IndirectMember) &&
3963  "Member must be a FieldDecl or IndirectFieldDecl");
3964 
3965  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3966  return true;
3967 
3968  if (Member->isInvalidDecl())
3969  return true;
3970 
3971  MultiExprArg Args;
3972  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3973  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3974  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3975  Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3976  } else {
3977  // Template instantiation doesn't reconstruct ParenListExprs for us.
3978  Args = Init;
3979  }
3980 
3981  SourceRange InitRange = Init->getSourceRange();
3982 
3983  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3984  // Can't check initialization for a member of dependent type or when
3985  // any of the arguments are type-dependent expressions.
3986  DiscardCleanupsInEvaluationContext();
3987  } else {
3988  bool InitList = false;
3989  if (isa<InitListExpr>(Init)) {
3990  InitList = true;
3991  Args = Init;
3992  }
3993 
3994  // Initialize the member.
3995  InitializedEntity MemberEntity =
3996  DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3997  : InitializedEntity::InitializeMember(IndirectMember,
3998  nullptr);
4001  IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4002  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4003  InitRange.getEnd());
4004 
4005  InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4006  ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4007  nullptr);
4008  if (MemberInit.isInvalid())
4009  return true;
4010 
4011  // C++11 [class.base.init]p7:
4012  // The initialization of each base and member constitutes a
4013  // full-expression.
4014  MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
4015  if (MemberInit.isInvalid())
4016  return true;
4017 
4018  Init = MemberInit.get();
4019  }
4020 
4021  if (DirectMember) {
4022  return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4023  InitRange.getBegin(), Init,
4024  InitRange.getEnd());
4025  } else {
4026  return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4027  InitRange.getBegin(), Init,
4028  InitRange.getEnd());
4029  }
4030 }
4031 
4034  CXXRecordDecl *ClassDecl) {
4035  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4036  if (!LangOpts.CPlusPlus11)
4037  return Diag(NameLoc, diag::err_delegating_ctor)
4038  << TInfo->getTypeLoc().getLocalSourceRange();
4039  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4040 
4041  bool InitList = true;
4042  MultiExprArg Args = Init;
4043  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4044  InitList = false;
4045  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4046  }
4047 
4048  SourceRange InitRange = Init->getSourceRange();
4049  // Initialize the object.
4051  QualType(ClassDecl->getTypeForDecl(), 0));
4054  NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4055  : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4056  InitRange.getEnd());
4057  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4058  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4059  Args, nullptr);
4060  if (DelegationInit.isInvalid())
4061  return true;
4062 
4063  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4064  "Delegating constructor with no target?");
4065 
4066  // C++11 [class.base.init]p7:
4067  // The initialization of each base and member constitutes a
4068  // full-expression.
4069  DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4070  InitRange.getBegin());
4071  if (DelegationInit.isInvalid())
4072  return true;
4073 
4074  // If we are in a dependent context, template instantiation will
4075  // perform this type-checking again. Just save the arguments that we
4076  // received in a ParenListExpr.
4077  // FIXME: This isn't quite ideal, since our ASTs don't capture all
4078  // of the information that we have about the base
4079  // initializer. However, deconstructing the ASTs is a dicey process,
4080  // and this approach is far more likely to get the corner cases right.
4081  if (CurContext->isDependentContext())
4082  DelegationInit = Init;
4083 
4084  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4085  DelegationInit.getAs<Expr>(),
4086  InitRange.getEnd());
4087 }
4088 
4091  Expr *Init, CXXRecordDecl *ClassDecl,
4092  SourceLocation EllipsisLoc) {
4093  SourceLocation BaseLoc
4094  = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4095 
4096  if (!BaseType->isDependentType() && !BaseType->isRecordType())
4097  return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4098  << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4099 
4100  // C++ [class.base.init]p2:
4101  // [...] Unless the mem-initializer-id names a nonstatic data
4102  // member of the constructor's class or a direct or virtual base
4103  // of that class, the mem-initializer is ill-formed. A
4104  // mem-initializer-list can initialize a base class using any
4105  // name that denotes that base class type.
4106  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4107 
4108  SourceRange InitRange = Init->getSourceRange();
4109  if (EllipsisLoc.isValid()) {
4110  // This is a pack expansion.
4111  if (!BaseType->containsUnexpandedParameterPack()) {
4112  Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4113  << SourceRange(BaseLoc, InitRange.getEnd());
4114 
4115  EllipsisLoc = SourceLocation();
4116  }
4117  } else {
4118  // Check for any unexpanded parameter packs.
4119  if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4120  return true;
4121 
4122  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4123  return true;
4124  }
4125 
4126  // Check for direct and virtual base classes.
4127  const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4128  const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4129  if (!Dependent) {
4130  if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4131  BaseType))
4132  return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4133 
4134  FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4135  VirtualBaseSpec);
4136 
4137  // C++ [base.class.init]p2:
4138  // Unless the mem-initializer-id names a nonstatic data member of the
4139  // constructor's class or a direct or virtual base of that class, the
4140  // mem-initializer is ill-formed.
4141  if (!DirectBaseSpec && !VirtualBaseSpec) {
4142  // If the class has any dependent bases, then it's possible that
4143  // one of those types will resolve to the same type as
4144  // BaseType. Therefore, just treat this as a dependent base
4145  // class initialization. FIXME: Should we try to check the
4146  // initialization anyway? It seems odd.
4147  if (ClassDecl->hasAnyDependentBases())
4148  Dependent = true;
4149  else
4150  return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4151  << BaseType << Context.getTypeDeclType(ClassDecl)
4152  << BaseTInfo->getTypeLoc().getLocalSourceRange();
4153  }
4154  }
4155 
4156  if (Dependent) {
4157  DiscardCleanupsInEvaluationContext();
4158 
4159  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4160  /*IsVirtual=*/false,
4161  InitRange.getBegin(), Init,
4162  InitRange.getEnd(), EllipsisLoc);
4163  }
4164 
4165  // C++ [base.class.init]p2:
4166  // If a mem-initializer-id is ambiguous because it designates both
4167  // a direct non-virtual base class and an inherited virtual base
4168  // class, the mem-initializer is ill-formed.
4169  if (DirectBaseSpec && VirtualBaseSpec)
4170  return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4171  << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4172 
4173  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4174  if (!BaseSpec)
4175  BaseSpec = VirtualBaseSpec;
4176 
4177  // Initialize the base.
4178  bool InitList = true;
4179  MultiExprArg Args = Init;
4180  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4181  InitList = false;
4182  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4183  }
4184 
4185  InitializedEntity BaseEntity =
4186  InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4188  InitList ? InitializationKind::CreateDirectList(BaseLoc)
4189  : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4190  InitRange.getEnd());
4191  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4192  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4193  if (BaseInit.isInvalid())
4194  return true;
4195 
4196  // C++11 [class.base.init]p7:
4197  // The initialization of each base and member constitutes a
4198  // full-expression.
4199  BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4200  if (BaseInit.isInvalid())
4201  return true;
4202 
4203  // If we are in a dependent context, template instantiation will
4204  // perform this type-checking again. Just save the arguments that we
4205  // received in a ParenListExpr.
4206  // FIXME: This isn't quite ideal, since our ASTs don't capture all
4207  // of the information that we have about the base
4208  // initializer. However, deconstructing the ASTs is a dicey process,
4209  // and this approach is far more likely to get the corner cases right.
4210  if (CurContext->isDependentContext())
4211  BaseInit = Init;
4212 
4213  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4214  BaseSpec->isVirtual(),
4215  InitRange.getBegin(),
4216  BaseInit.getAs<Expr>(),
4217  InitRange.getEnd(), EllipsisLoc);
4218 }
4219 
4220 // Create a static_cast<T&&>(expr).
4221 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4222  if (T.isNull()) T = E->getType();
4223  QualType TargetType = SemaRef.BuildReferenceType(
4224  T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4225  SourceLocation ExprLoc = E->getBeginLoc();
4226  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4227  TargetType, ExprLoc);
4228 
4229  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4230  SourceRange(ExprLoc, ExprLoc),
4231  E->getSourceRange()).get();
4232 }
4233 
4234 /// ImplicitInitializerKind - How an implicit base or member initializer should
4235 /// initialize its base or member.
4241 };
4242 
4243 static bool
4245  ImplicitInitializerKind ImplicitInitKind,
4246  CXXBaseSpecifier *BaseSpec,
4247  bool IsInheritedVirtualBase,
4248  CXXCtorInitializer *&CXXBaseInit) {
4249  InitializedEntity InitEntity
4250  = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4251  IsInheritedVirtualBase);
4252 
4253  ExprResult BaseInit;
4254 
4255  switch (ImplicitInitKind) {
4256  case IIK_Inherit:
4257  case IIK_Default: {
4258  InitializationKind InitKind
4260  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4261  BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4262  break;
4263  }
4264 
4265  case IIK_Move:
4266  case IIK_Copy: {
4267  bool Moving = ImplicitInitKind == IIK_Move;
4268  ParmVarDecl *Param = Constructor->getParamDecl(0);
4269  QualType ParamType = Param->getType().getNonReferenceType();
4270 
4271  Expr *CopyCtorArg =
4273  SourceLocation(), Param, false,
4274  Constructor->getLocation(), ParamType,
4275  VK_LValue, nullptr);
4276 
4277  SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4278 
4279  // Cast to the base class to avoid ambiguities.
4280  QualType ArgTy =
4281  SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4282  ParamType.getQualifiers());
4283 
4284  if (Moving) {
4285  CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4286  }
4287 
4288  CXXCastPath BasePath;
4289  BasePath.push_back(BaseSpec);
4290  CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4291  CK_UncheckedDerivedToBase,
4292  Moving ? VK_XValue : VK_LValue,
4293  &BasePath).get();
4294 
4295  InitializationKind InitKind
4298  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4299  BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4300  break;
4301  }
4302  }
4303 
4304  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4305  if (BaseInit.isInvalid())
4306  return true;
4307 
4308  CXXBaseInit =
4309  new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4310  SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4311  SourceLocation()),
4312  BaseSpec->isVirtual(),
4313  SourceLocation(),
4314  BaseInit.getAs<Expr>(),
4315  SourceLocation(),
4316  SourceLocation());
4317 
4318  return false;
4319 }
4320 
4321 static bool RefersToRValueRef(Expr *MemRef) {
4322  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4323  return Referenced->getType()->isRValueReferenceType();
4324 }
4325 
4326 static bool
4328  ImplicitInitializerKind ImplicitInitKind,
4329  FieldDecl *Field, IndirectFieldDecl *Indirect,
4330  CXXCtorInitializer *&CXXMemberInit) {
4331  if (Field->isInvalidDecl())
4332  return true;
4333 
4334  SourceLocation Loc = Constructor->getLocation();
4335 
4336  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4337  bool Moving = ImplicitInitKind == IIK_Move;
4338  ParmVarDecl *Param = Constructor->getParamDecl(0);
4339  QualType ParamType = Param->getType().getNonReferenceType();
4340 
4341  // Suppress copying zero-width bitfields.
4342  if (Field->isZeroLengthBitField(SemaRef.Context))
4343  return false;
4344 
4345  Expr *MemberExprBase =
4347  SourceLocation(), Param, false,
4348  Loc, ParamType, VK_LValue, nullptr);
4349 
4350  SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4351 
4352  if (Moving) {
4353  MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4354  }
4355 
4356  // Build a reference to this field within the parameter.
4357  CXXScopeSpec SS;
4358  LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4360  MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4361  : cast<ValueDecl>(Field), AS_public);
4362  MemberLookup.resolveKind();
4363  ExprResult CtorArg
4364  = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4365  ParamType, Loc,
4366  /*IsArrow=*/false,
4367  SS,
4368  /*TemplateKWLoc=*/SourceLocation(),
4369  /*FirstQualifierInScope=*/nullptr,
4370  MemberLookup,
4371  /*TemplateArgs=*/nullptr,
4372  /*S*/nullptr);
4373  if (CtorArg.isInvalid())
4374  return true;
4375 
4376  // C++11 [class.copy]p15:
4377  // - if a member m has rvalue reference type T&&, it is direct-initialized
4378  // with static_cast<T&&>(x.m);
4379  if (RefersToRValueRef(CtorArg.get())) {
4380  CtorArg = CastForMoving(SemaRef, CtorArg.get());
4381  }
4382 
4383  InitializedEntity Entity =
4384  Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4385  /*Implicit*/ true)
4386  : InitializedEntity::InitializeMember(Field, nullptr,
4387  /*Implicit*/ true);
4388 
4389  // Direct-initialize to use the copy constructor.
4390  InitializationKind InitKind =
4392 
4393  Expr *CtorArgE = CtorArg.getAs<Expr>();
4394  InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4395  ExprResult MemberInit =
4396  InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4397  MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4398  if (MemberInit.isInvalid())
4399  return true;
4400 
4401  if (Indirect)
4402  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4403  SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4404  else
4405  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4406  SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4407  return false;
4408  }
4409 
4410  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4411  "Unhandled implicit init kind!");
4412 
4413  QualType FieldBaseElementType =
4414  SemaRef.Context.getBaseElementType(Field->getType());
4415 
4416  if (FieldBaseElementType->isRecordType()) {
4417  InitializedEntity InitEntity =
4418  Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4419  /*Implicit*/ true)
4420  : InitializedEntity::InitializeMember(Field, nullptr,
4421  /*Implicit*/ true);
4422  InitializationKind InitKind =
4424 
4425  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4426  ExprResult MemberInit =
4427  InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4428 
4429  MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4430  if (MemberInit.isInvalid())
4431  return true;
4432 
4433  if (Indirect)
4434  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4435  Indirect, Loc,
4436  Loc,
4437  MemberInit.get(),
4438  Loc);
4439  else
4440  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4441  Field, Loc, Loc,
4442  MemberInit.get(),
4443  Loc);
4444  return false;
4445  }
4446 
4447  if (!Field->getParent()->isUnion()) {
4448  if (FieldBaseElementType->isReferenceType()) {
4449  SemaRef.Diag(Constructor->getLocation(),
4450  diag::err_uninitialized_member_in_ctor)
4451  << (int)Constructor->isImplicit()
4452  << SemaRef.Context.getTagDeclType(Constructor->getParent())
4453  << 0 << Field->getDeclName();
4454  SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4455  return true;
4456  }
4457 
4458  if (FieldBaseElementType.isConstQualified()) {
4459  SemaRef.Diag(Constructor->getLocation(),
4460  diag::err_uninitialized_member_in_ctor)
4461  << (int)Constructor->isImplicit()
4462  << SemaRef.Context.getTagDeclType(Constructor->getParent())
4463  << 1 << Field->getDeclName();
4464  SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4465  return true;
4466  }
4467  }
4468 
4469  if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4470  // ARC and Weak:
4471  // Default-initialize Objective-C pointers to NULL.
4472  CXXMemberInit
4473  = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4474  Loc, Loc,
4475  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4476  Loc);
4477  return false;
4478  }
4479 
4480  // Nothing to initialize.
4481  CXXMemberInit = nullptr;
4482  return false;
4483 }
4484 
4485 namespace {
4486 struct BaseAndFieldInfo {
4487  Sema &S;
4488  CXXConstructorDecl *Ctor;
4489  bool AnyErrorsInInits;
4491  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4493  llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4494 
4495  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4496  : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4497  bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4498  if (Ctor->getInheritedConstructor())
4499  IIK = IIK_Inherit;
4500  else if (Generated && Ctor->isCopyConstructor())
4501  IIK = IIK_Copy;
4502  else if (Generated && Ctor->isMoveConstructor())
4503  IIK = IIK_Move;
4504  else
4505  IIK = IIK_Default;
4506  }
4507 
4508  bool isImplicitCopyOrMove() const {
4509  switch (IIK) {
4510  case IIK_Copy:
4511  case IIK_Move:
4512  return true;
4513 
4514  case IIK_Default:
4515  case IIK_Inherit:
4516  return false;
4517  }
4518 
4519  llvm_unreachable("Invalid ImplicitInitializerKind!");
4520  }
4521 
4522  bool addFieldInitializer(CXXCtorInitializer *Init) {
4523  AllToInit.push_back(Init);
4524 
4525  // Check whether this initializer makes the field "used".
4526  if (Init->getInit()->HasSideEffects(S.Context))
4527  S.UnusedPrivateFields.remove(Init->getAnyMember());
4528 
4529  return false;
4530  }
4531 
4532  bool isInactiveUnionMember(FieldDecl *Field) {
4533  RecordDecl *Record = Field->getParent();
4534  if (!Record->isUnion())
4535  return false;
4536 
4537  if (FieldDecl *Active =
4538  ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4539  return Active != Field->getCanonicalDecl();
4540 
4541  // In an implicit copy or move constructor, ignore any in-class initializer.
4542  if (isImplicitCopyOrMove())
4543  return true;
4544 
4545  // If there's no explicit initialization, the field is active only if it
4546  // has an in-class initializer...
4547  if (Field->hasInClassInitializer())
4548  return false;
4549  // ... or it's an anonymous struct or union whose class has an in-class
4550  // initializer.
4551  if (!Field->isAnonymousStructOrUnion())
4552  return true;
4553  CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4554  return !FieldRD->hasInClassInitializer();
4555  }
4556 
4557  /// Determine whether the given field is, or is within, a union member
4558  /// that is inactive (because there was an initializer given for a different
4559  /// member of the union, or because the union was not initialized at all).
4560  bool isWithinInactiveUnionMember(FieldDecl *Field,
4561  IndirectFieldDecl *Indirect) {
4562  if (!Indirect)
4563  return isInactiveUnionMember(Field);
4564 
4565  for (auto *C : Indirect->chain()) {
4566  FieldDecl *Field = dyn_cast<FieldDecl>(C);
4567  if (Field && isInactiveUnionMember(Field))
4568  return true;
4569  }
4570  return false;
4571  }
4572 };
4573 }
4574 
4575 /// Determine whether the given type is an incomplete or zero-lenfgth
4576 /// array type.
4578  if (T->isIncompleteArrayType())
4579  return true;
4580 
4581  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4582  if (!ArrayT->getSize())
4583  return true;
4584 
4585  T = ArrayT->getElementType();
4586  }
4587 
4588  return false;
4589 }
4590 
4591 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4592  FieldDecl *Field,
4593  IndirectFieldDecl *Indirect = nullptr) {
4594  if (Field->isInvalidDecl())
4595  return false;
4596 
4597  // Overwhelmingly common case: we have a direct initializer for this field.
4598  if (CXXCtorInitializer *Init =
4599  Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4600  return Info.addFieldInitializer(Init);
4601 
4602  // C++11 [class.base.init]p8:
4603  // if the entity is a non-static data member that has a
4604  // brace-or-equal-initializer and either
4605  // -- the constructor's class is a union and no other variant member of that
4606  // union is designated by a mem-initializer-id or
4607  // -- the constructor's class is not a union, and, if the entity is a member
4608  // of an anonymous union, no other member of that union is designated by
4609  // a mem-initializer-id,
4610  // the entity is initialized as specified in [dcl.init].
4611  //
4612  // We also apply the same rules to handle anonymous structs within anonymous
4613  // unions.
4614  if (Info.isWithinInactiveUnionMember(Field, Indirect))
4615  return false;
4616 
4617  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4618  ExprResult DIE =
4619  SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4620  if (DIE.isInvalid())
4621  return true;
4622 
4623  auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4624  SemaRef.checkInitializerLifetime(Entity, DIE.get());
4625 
4626  CXXCtorInitializer *Init;
4627  if (Indirect)
4628  Init = new (SemaRef.Context)
4629  CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4630  SourceLocation(), DIE.get(), SourceLocation());
4631  else
4632  Init = new (SemaRef.Context)
4633  CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4634  SourceLocation(), DIE.get(), SourceLocation());
4635  return Info.addFieldInitializer(Init);
4636  }
4637 
4638  // Don't initialize incomplete or zero-length arrays.
4639  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4640  return false;
4641 
4642  // Don't try to build an implicit initializer if there were semantic
4643  // errors in any of the initializers (and therefore we might be
4644  // missing some that the user actually wrote).
4645  if (Info.AnyErrorsInInits)
4646  return false;
4647 
4648  CXXCtorInitializer *Init = nullptr;
4649  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4650  Indirect, Init))
4651  return true;
4652 
4653  if (!Init)
4654  return false;
4655 
4656  return Info.addFieldInitializer(Init);
4657 }
4658 
4659 bool
4661  CXXCtorInitializer *Initializer) {
4662  assert(Initializer->isDelegatingInitializer());
4663  Constructor->setNumCtorInitializers(1);
4664  CXXCtorInitializer **initializer =
4665  new (Context) CXXCtorInitializer*[1];
4666  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4667  Constructor->setCtorInitializers(initializer);
4668 
4669  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4670  MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4671  DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4672  }
4673 
4674  DelegatingCtorDecls.push_back(Constructor);
4675 
4676  DiagnoseUninitializedFields(*this, Constructor);
4677 
4678  return false;
4679 }
4680 
4681 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4682  ArrayRef<CXXCtorInitializer *> Initializers) {
4683  if (Constructor->isDependentContext()) {
4684  // Just store the initializers as written, they will be checked during
4685  // instantiation.
4686  if (!Initializers.empty()) {
4687  Constructor->setNumCtorInitializers(Initializers.size());
4688  CXXCtorInitializer **baseOrMemberInitializers =
4689  new (Context) CXXCtorInitializer*[Initializers.size()];
4690  memcpy(baseOrMemberInitializers, Initializers.data(),
4691  Initializers.size() * sizeof(CXXCtorInitializer*));
4692  Constructor->setCtorInitializers(baseOrMemberInitializers);
4693  }
4694 
4695  // Let template instantiation know whether we had errors.
4696  if (AnyErrors)
4697  Constructor->setInvalidDecl();
4698 
4699  return false;
4700  }
4701 
4702  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4703 
4704  // We need to build the initializer AST according to order of construction
4705  // and not what user specified in the Initializers list.
4706  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4707  if (!ClassDecl)
4708  return true;
4709 
4710  bool HadError = false;
4711 
4712  for (unsigned i = 0; i < Initializers.size(); i++) {
4713  CXXCtorInitializer *Member = Initializers[i];
4714 
4715  if (Member->isBaseInitializer())
4716  Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4717  else {
4718  Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4719 
4720  if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4721  for (auto *C : F->chain()) {
4722  FieldDecl *FD = dyn_cast<FieldDecl>(C);
4723  if (FD && FD->getParent()->isUnion())
4724  Info.ActiveUnionMember.insert(std::make_pair(
4725  FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4726  }
4727  } else if (FieldDecl *FD = Member->getMember()) {
4728  if (FD->getParent()->isUnion())
4729  Info.ActiveUnionMember.insert(std::make_pair(
4730  FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4731  }
4732  }
4733  }
4734 
4735  // Keep track of the direct virtual bases.
4736  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4737  for (auto &I : ClassDecl->bases()) {
4738  if (I.isVirtual())
4739  DirectVBases.insert(&I);
4740  }
4741 
4742  // Push virtual bases before others.
4743  for (auto &VBase : ClassDecl->vbases()) {
4745  = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4746  // [class.base.init]p7, per DR257:
4747  // A mem-initializer where the mem-initializer-id names a virtual base
4748  // class is ignored during execution of a constructor of any class that
4749  // is not the most derived class.
4750  if (ClassDecl->isAbstract()) {
4751  // FIXME: Provide a fixit to remove the base specifier. This requires
4752  // tracking the location of the associated comma for a base specifier.
4753  Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4754  << VBase.getType() << ClassDecl;
4755  DiagnoseAbstractType(ClassDecl);
4756  }
4757 
4758  Info.AllToInit.push_back(Value);
4759  } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4760  // [class.base.init]p8, per DR257:
4761  // If a given [...] base class is not named by a mem-initializer-id
4762  // [...] and the entity is not a virtual base class of an abstract
4763  // class, then [...] the entity is default-initialized.
4764  bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4765  CXXCtorInitializer *CXXBaseInit;
4766  if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4767  &VBase, IsInheritedVirtualBase,
4768  CXXBaseInit)) {
4769  HadError = true;
4770  continue;
4771  }
4772 
4773  Info.AllToInit.push_back(CXXBaseInit);
4774  }
4775  }
4776 
4777  // Non-virtual bases.
4778  for (auto &Base : ClassDecl->bases()) {
4779  // Virtuals are in the virtual base list and already constructed.
4780  if (Base.isVirtual())
4781  continue;
4782 
4784  = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4785  Info.AllToInit.push_back(Value);
4786  } else if (!AnyErrors) {
4787  CXXCtorInitializer *CXXBaseInit;
4788  if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4789  &Base, /*IsInheritedVirtualBase=*/false,
4790  CXXBaseInit)) {
4791  HadError = true;
4792  continue;
4793  }
4794 
4795  Info.AllToInit.push_back(CXXBaseInit);
4796  }
4797  }
4798 
4799  // Fields.
4800  for (auto *Mem : ClassDecl->decls()) {
4801  if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4802  // C++ [class.bit]p2:
4803  // A declaration for a bit-field that omits the identifier declares an
4804  // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4805  // initialized.
4806  if (F->isUnnamedBitfield())
4807  continue;
4808 
4809  // If we're not generating the implicit copy/move constructor, then we'll
4810  // handle anonymous struct/union fields based on their individual
4811  // indirect fields.
4812  if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4813  continue;
4814 
4815  if (CollectFieldInitializer(*this, Info, F))
4816  HadError = true;
4817  continue;
4818  }
4819 
4820  // Beyond this point, we only consider default initialization.
4821  if (Info.isImplicitCopyOrMove())
4822  continue;
4823 
4824  if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4825  if (F->getType()->isIncompleteArrayType()) {
4826  assert(ClassDecl->hasFlexibleArrayMember() &&
4827  "Incomplete array type is not valid");
4828  continue;
4829  }
4830 
4831  // Initialize each field of an anonymous struct individually.
4832  if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4833  HadError = true;
4834 
4835  continue;
4836  }
4837  }
4838 
4839  unsigned NumInitializers = Info.AllToInit.size();
4840  if (NumInitializers > 0) {
4841  Constructor->setNumCtorInitializers(NumInitializers);
4842  CXXCtorInitializer **baseOrMemberInitializers =
4843  new (Context) CXXCtorInitializer*[NumInitializers];
4844  memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4845  NumInitializers * sizeof(CXXCtorInitializer*));
4846  Constructor->setCtorInitializers(baseOrMemberInitializers);
4847 
4848  // Constructors implicitly reference the base and member
4849  // destructors.
4850  MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4851  Constructor->getParent());
4852  }
4853 
4854  return HadError;
4855 }
4856 
4858  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4859  const RecordDecl *RD = RT->getDecl();
4860  if (RD->isAnonymousStructOrUnion()) {
4861  for (auto *Field : RD->fields())
4862  PopulateKeysForFields(Field, IdealInits);
4863  return;
4864  }
4865  }
4866  IdealInits.push_back(Field->getCanonicalDecl());
4867 }
4868 
4869 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4870  return Context.getCanonicalType(BaseType).getTypePtr();
4871 }
4872 
4873 static const void *GetKeyForMember(ASTContext &Context,
4874  CXXCtorInitializer *Member) {
4875  if (!Member->isAnyMemberInitializer())
4876  return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4877 
4878  return Member->getAnyMember()->getCanonicalDecl();
4879 }
4880 
4882  Sema &SemaRef, const CXXConstructorDecl *Constructor,
4884  if (Constructor->getDeclContext()->isDependentContext())
4885  return;
4886 
4887  // Don't check initializers order unless the warning is enabled at the
4888  // location of at least one initializer.
4889  bool ShouldCheckOrder = false;
4890  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4891  CXXCtorInitializer *Init = Inits[InitIndex];
4892  if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4893  Init->getSourceLocation())) {
4894  ShouldCheckOrder = true;
4895  break;
4896  }
4897  }
4898  if (!ShouldCheckOrder)
4899  return;
4900 
4901  // Build the list of bases and members in the order that they'll
4902  // actually be initialized. The explicit initializers should be in
4903  // this same order but may be missing things.
4904  SmallVector<const void*, 32> IdealInitKeys;
4905 
4906  const CXXRecordDecl *ClassDecl = Constructor->getParent();
4907 
4908  // 1. Virtual bases.
4909  for (const auto &VBase : ClassDecl->vbases())
4910  IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4911 
4912  // 2. Non-virtual bases.
4913  for (const auto &Base : ClassDecl->bases()) {
4914  if (Base.isVirtual())
4915  continue;
4916  IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4917  }
4918 
4919  // 3. Direct fields.
4920  for (auto *Field : ClassDecl->fields()) {
4921  if (Field->isUnnamedBitfield())
4922  continue;
4923 
4924  PopulateKeysForFields(Field, IdealInitKeys);
4925  }
4926 
4927  unsigned NumIdealInits = IdealInitKeys.size();
4928  unsigned IdealIndex = 0;
4929 
4930  CXXCtorInitializer *PrevInit = nullptr;
4931  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4932  CXXCtorInitializer *Init = Inits[InitIndex];
4933  const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4934 
4935  // Scan forward to try to find this initializer in the idealized
4936  // initializers list.
4937  for (; IdealIndex != NumIdealInits; ++IdealIndex)
4938  if (InitKey == IdealInitKeys[IdealIndex])
4939  break;
4940 
4941  // If we didn't find this initializer, it must be because we
4942  // scanned past it on a previous iteration. That can only
4943  // happen if we're out of order; emit a warning.
4944  if (IdealIndex == NumIdealInits && PrevInit) {
4946  SemaRef.Diag(PrevInit->getSourceLocation(),
4947  diag::warn_initializer_out_of_order);
4948 
4949  if (PrevInit->isAnyMemberInitializer())
4950  D << 0 << PrevInit->getAnyMember()->getDeclName();
4951  else
4952  D << 1 << PrevInit->getTypeSourceInfo()->getType();
4953 
4954  if (Init->isAnyMemberInitializer())
4955  D << 0 << Init->getAnyMember()->getDeclName();
4956  else
4957  D << 1 << Init->getTypeSourceInfo()->getType();
4958 
4959  // Move back to the initializer's location in the ideal list.
4960  for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4961  if (InitKey == IdealInitKeys[IdealIndex])
4962  break;
4963 
4964  assert(IdealIndex < NumIdealInits &&
4965  "initializer not found in initializer list");
4966  }
4967 
4968  PrevInit = Init;
4969  }
4970 }
4971 
4972 namespace {
4973 bool CheckRedundantInit(Sema &S,
4974  CXXCtorInitializer *Init,
4975  CXXCtorInitializer *&PrevInit) {
4976  if (!PrevInit) {
4977  PrevInit = Init;
4978  return false;
4979  }
4980 
4981  if (FieldDecl *Field = Init->getAnyMember())
4982  S.Diag(Init->getSourceLocation(),
4983  diag::err_multiple_mem_initialization)
4984  << Field->getDeclName()
4985  << Init->getSourceRange();
4986  else {
4987  const Type *BaseClass = Init->getBaseClass();
4988  assert(BaseClass && "neither field nor base");
4989  S.Diag(Init->getSourceLocation(),
4990  diag::err_multiple_base_initialization)
4991  << QualType(BaseClass, 0)
4992  << Init->getSourceRange();
4993  }
4994  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4995  << 0 << PrevInit->getSourceRange();
4996 
4997  return true;
4998 }
4999 
5000 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5001 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5002 
5003 bool CheckRedundantUnionInit(Sema &S,
5004  CXXCtorInitializer *Init,
5005  RedundantUnionMap &Unions) {
5006  FieldDecl *Field = Init->getAnyMember();
5007  RecordDecl *Parent = Field->getParent();
5008  NamedDecl *Child = Field;
5009 
5010  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5011  if (Parent->isUnion()) {
5012  UnionEntry &En = Unions[Parent];
5013  if (En.first && En.first != Child) {
5014  S.Diag(Init->getSourceLocation(),
5015  diag::err_multiple_mem_union_initialization)
5016  << Field->getDeclName()
5017  << Init->getSourceRange();
5018  S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5019  << 0 << En.second->getSourceRange();
5020  return true;
5021  }
5022  if (!En.first) {
5023  En.first = Child;
5024  En.second = Init;
5025  }
5026  if (!Parent->isAnonymousStructOrUnion())
5027  return false;
5028  }
5029 
5030  Child = Parent;
5031  Parent = cast<RecordDecl>(Parent->getDeclContext());
5032  }
5033 
5034  return false;
5035 }
5036 }
5037 
5038 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5039 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5042  bool AnyErrors) {
5043  if (!ConstructorDecl)
5044  return;
5045 
5046  AdjustDeclIfTemplate(ConstructorDecl);
5047 
5048  CXXConstructorDecl *Constructor
5049  = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5050 
5051  if (!Constructor) {
5052  Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5053  return;
5054  }
5055 
5056  // Mapping for the duplicate initializers check.
5057  // For member initializers, this is keyed with a FieldDecl*.
5058  // For base initializers, this is keyed with a Type*.
5059  llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5060 
5061  // Mapping for the inconsistent anonymous-union initializers check.
5062  RedundantUnionMap MemberUnions;
5063 
5064  bool HadError = false;
5065  for (unsigned i = 0; i < MemInits.size(); i++) {
5066  CXXCtorInitializer *Init = MemInits[i];
5067 
5068  // Set the source order index.
5069  Init->setSourceOrder(i);
5070 
5071  if (Init->isAnyMemberInitializer()) {
5072  const void *Key = GetKeyForMember(Context, Init);
5073  if (CheckRedundantInit(*this, Init, Members[Key]) ||
5074  CheckRedundantUnionInit(*this, Init, MemberUnions))
5075  HadError = true;
5076  } else if (Init->isBaseInitializer()) {
5077  const void *Key = GetKeyForMember(Context, Init);
5078  if (CheckRedundantInit(*this, Init, Members[Key]))
5079  HadError = true;
5080  } else {
5081  assert(Init->isDelegatingInitializer());
5082  // This must be the only initializer
5083  if (MemInits.size() != 1) {
5084  Diag(Init->getSourceLocation(),
5085  diag::err_delegating_initializer_alone)
5086  << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5087  // We will treat this as being the only initializer.
5088  }
5089  SetDelegatingInitializer(Constructor, MemInits[i]);
5090  // Return immediately as the initializer is set.
5091  return;
5092  }
5093  }
5094 
5095  if (HadError)
5096  return;
5097 
5098  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5099 
5100  SetCtorInitializers(Constructor, AnyErrors, MemInits);
5101 
5102  DiagnoseUninitializedFields(*this, Constructor);
5103 }
5104 
5105 void
5107  CXXRecordDecl *ClassDecl) {
5108  // Ignore dependent contexts. Also ignore unions, since their members never
5109  // have destructors implicitly called.
5110  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5111  return;
5112 
5113  // FIXME: all the access-control diagnostics are positioned on the
5114  // field/base declaration. That's probably good; that said, the
5115  // user might reasonably want to know why the destructor is being
5116  // emitted, and we currently don't say.
5117 
5118  // Non-static data members.
5119  for (auto *Field : ClassDecl->fields()) {
5120  if (Field->isInvalidDecl())
5121  continue;
5122 
5123  // Don't destroy incomplete or zero-length arrays.
5124  if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5125  continue;
5126 
5127  QualType FieldType = Context.getBaseElementType(Field->getType());
5128 
5129  const RecordType* RT = FieldType->getAs<RecordType>();
5130  if (!RT)
5131  continue;
5132 
5133  CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5134  if (FieldClassDecl->isInvalidDecl())
5135  continue;
5136  if (FieldClassDecl->hasIrrelevantDestructor())
5137  continue;
5138  // The destructor for an implicit anonymous union member is never invoked.
5139  if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5140  continue;
5141 
5142  CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5143  assert(Dtor && "No dtor found for FieldClassDecl!");
5144  CheckDestructorAccess(Field->getLocation(), Dtor,
5145  PDiag(diag::err_access_dtor_field)
5146  << Field->getDeclName()
5147  << FieldType);
5148 
5149  MarkFunctionReferenced(Location, Dtor);
5150  DiagnoseUseOfDecl(Dtor, Location);
5151  }
5152 
5153  // We only potentially invoke the destructors of potentially constructed
5154  // subobjects.
5155  bool VisitVirtualBases = !ClassDecl->isAbstract();
5156 
5157  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5158 
5159  // Bases.
5160  for (const auto &Base : ClassDecl->bases()) {
5161  // Bases are always records in a well-formed non-dependent class.
5162  const RecordType *RT = Base.getType()->getAs<RecordType>();
5163 
5164  // Remember direct virtual bases.
5165  if (Base.isVirtual()) {
5166  if (!VisitVirtualBases)
5167  continue;
5168  DirectVirtualBases.insert(RT);
5169  }
5170 
5171  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5172  // If our base class is invalid, we probably can't get its dtor anyway.
5173  if (BaseClassDecl->isInvalidDecl())
5174  continue;
5175  if (BaseClassDecl->hasIrrelevantDestructor())
5176  continue;
5177 
5178  CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5179  assert(Dtor && "No dtor found for BaseClassDecl!");
5180 
5181  // FIXME: caret should be on the start of the class name
5182  CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5183  PDiag(diag::err_access_dtor_base)
5184  << Base.getType() << Base.getSourceRange(),
5185  Context.getTypeDeclType(ClassDecl));
5186 
5187  MarkFunctionReferenced(Location, Dtor);
5188  DiagnoseUseOfDecl(Dtor, Location);
5189  }
5190 
5191  if (!VisitVirtualBases)
5192  return;
5193 
5194  // Virtual bases.
5195  for (const auto &VBase : ClassDecl->vbases()) {
5196  // Bases are always records in a well-formed non-dependent class.
5197  const RecordType *RT = VBase.getType()->castAs<RecordType>();
5198 
5199  // Ignore direct virtual bases.
5200  if (DirectVirtualBases.count(RT))
5201  continue;
5202 
5203  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5204  // If our base class is invalid, we probably can't get its dtor anyway.
5205  if (BaseClassDecl->isInvalidDecl())
5206  continue;
5207  if (BaseClassDecl->hasIrrelevantDestructor())
5208  continue;
5209 
5210  CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5211  assert(Dtor && "No dtor found for BaseClassDecl!");
5212  if (CheckDestructorAccess(
5213  ClassDecl->getLocation(), Dtor,
5214  PDiag(diag::err_access_dtor_vbase)
5215  << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5216  Context.getTypeDeclType(ClassDecl)) ==
5217  AR_accessible) {
5218  CheckDerivedToBaseConversion(
5219  Context.getTypeDeclType(ClassDecl), VBase.getType(),
5220  diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5221  SourceRange(), DeclarationName(), nullptr);
5222  }
5223 
5224  MarkFunctionReferenced(Location, Dtor);
5225  DiagnoseUseOfDecl(Dtor, Location);
5226  }
5227 }
5228 
5229 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5230  if (!CDtorDecl)
5231  return;
5232 
5233  if (CXXConstructorDecl *Constructor
5234  = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5235  SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5236  DiagnoseUninitializedFields(*this, Constructor);
5237  }
5238 }
5239 
5241  if (!getLangOpts().CPlusPlus)
5242  return false;
5243 
5244  const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5245  if (!RD)
5246  return false;
5247 
5248  // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5249  // class template specialization here, but doing so breaks a lot of code.
5250 
5251  // We can't answer whether something is abstract until it has a
5252  // definition. If it's currently being defined, we'll walk back
5253  // over all the declarations when we have a full definition.
5254  const CXXRecordDecl *Def = RD->getDefinition();
5255  if (!Def || Def->isBeingDefined())
5256  return false;
5257 
5258  return RD->isAbstract();
5259 }
5260 
5262  TypeDiagnoser &Diagnoser) {
5263  if (!isAbstractType(Loc, T))
5264  return false;
5265 
5266  T = Context.getBaseElementType(T);
5267  Diagnoser.diagnose(*this, Loc, T);
5268  DiagnoseAbstractType(T->getAsCXXRecordDecl());
5269  return true;
5270 }
5271 
5273  // Check if we've already emitted the list of pure virtual functions
5274  // for this class.
5275  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5276  return;
5277 
5278  // If the diagnostic is suppressed, don't emit the notes. We're only
5279  // going to emit them once, so try to attach them to a diagnostic we're
5280  // actually going to show.
5281  if (Diags.isLastDiagnosticIgnored())
5282  return;
5283 
5284  CXXFinalOverriderMap FinalOverriders;
5285  RD->getFinalOverriders(FinalOverriders);
5286 
5287  // Keep a set of seen pure methods so we won't diagnose the same method
5288  // more than once.
5289  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5290 
5291  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5292  MEnd = FinalOverriders.end();
5293  M != MEnd;
5294  ++M) {
5295  for (OverridingMethods::iterator SO = M->second.begin(),
5296  SOEnd = M->second.end();
5297  SO != SOEnd; ++SO) {
5298  // C++ [class.abstract]p4:
5299  // A class is abstract if it contains or inherits at least one
5300  // pure virtual function for which the final overrider is pure
5301  // virtual.
5302 
5303  //
5304  if (SO->second.size() != 1)
5305  continue;
5306 
5307  if (!SO->second.front().Method->isPure())
5308  continue;
5309 
5310  if (!SeenPureMethods.insert(SO->second.front().Method).second)
5311  continue;
5312 
5313  Diag(SO->second.front().Method->getLocation(),
5314  diag::note_pure_virtual_function)
5315  << SO->second.front().Method->getDeclName() << RD->getDeclName();
5316  }
5317  }
5318 
5319  if (!PureVirtualClassDiagSet)
5320  PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5321  PureVirtualClassDiagSet->insert(RD);
5322 }
5323 
5324 namespace {
5325 struct AbstractUsageInfo {
5326  Sema &S;
5327  CXXRecordDecl *Record;
5328  CanQualType AbstractType;
5329  bool Invalid;
5330 
5331  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5332  : S(S), Record(Record),
5333  AbstractType(S.Context.getCanonicalType(
5334  S.Context.getTypeDeclType(Record))),
5335  Invalid(false) {}
5336 
5337  void DiagnoseAbstractType() {
5338  if (Invalid) return;
5339  S.DiagnoseAbstractType(Record);
5340  Invalid = true;
5341  }
5342 
5343  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5344 };
5345 
5346 struct CheckAbstractUsage {
5347  AbstractUsageInfo &Info;
5348  const NamedDecl *Ctx;
5349 
5350  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5351  : Info(Info), Ctx(Ctx) {}
5352 
5353  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5354  switch (TL.getTypeLocClass()) {
5355 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5356 #define TYPELOC(CLASS, PARENT) \
5357  case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5358 #include "clang/AST/TypeLocNodes.def"
5359  }
5360  }
5361 
5362  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5364  for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5365  if (!TL.getParam(I))
5366  continue;
5367 
5368  TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5369  if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5370  }
5371  }
5372 
5373  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5375  }
5376 
5378  // Visit the type parameters from a permissive context.
5379  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5380  TemplateArgumentLoc TAL = TL.getArgLoc(I);
5382  if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5383  Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5384  // TODO: other template argument types?
5385  }
5386  }
5387 
5388  // Visit pointee types from a permissive context.
5389 #define CheckPolymorphic(Type) \
5390  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5391  Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5392  }
5398 
5399  /// Handle all the types we haven't given a more specific
5400  /// implementation for above.
5401  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5402  // Every other kind of type that we haven't called out already
5403  // that has an inner type is either (1) sugar or (2) contains that
5404  // inner type in some way as a subobject.
5405  if (TypeLoc Next = TL.getNextTypeLoc())
5406  return Visit(Next, Sel);
5407 
5408  // If there's no inner type and we're in a permissive context,
5409  // don't diagnose.
5410  if (Sel == Sema::AbstractNone) return;
5411 
5412  // Check whether the type matches the abstract type.
5413  QualType T = TL.getType();
5414  if (T->isArrayType()) {
5416  T = Info.S.Context.getBaseElementType(T);
5417  }
5419  if (CT != Info.AbstractType) return;
5420 
5421  // It matched; do some magic.
5422  if (Sel == Sema::AbstractArrayType) {
5423  Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5424  << T << TL.getSourceRange();
5425  } else {
5426  Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5427  << Sel << T << TL.getSourceRange();
5428  }
5429  Info.DiagnoseAbstractType();
5430  }
5431 };
5432 
5433 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5435  CheckAbstractUsage(*this, D).Visit(TL, Sel);
5436 }
5437 
5438 }
5439 
5440 /// Check for invalid uses of an abstract type in a method declaration.
5441 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5442  CXXMethodDecl *MD) {
5443  // No need to do the check on definitions, which require that
5444  // the return/param types be complete.
5445  if (MD->doesThisDeclarationHaveABody())
5446  return;
5447 
5448  // For safety's sake, just ignore it if we don't have type source
5449  // information. This should never happen for non-implicit methods,
5450  // but...
5451  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5452  Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5453 }
5454 
5455 /// Check for invalid uses of an abstract type within a class definition.
5456 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5457  CXXRecordDecl *RD) {
5458  for (auto *D : RD->decls()) {
5459  if (D->isImplicit()) continue;
5460 
5461  // Methods and method templates.
5462  if (isa<CXXMethodDecl>(D)) {
5463  CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5464  } else if (isa<FunctionTemplateDecl>(D)) {
5465  FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5466  CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5467 
5468  // Fields and static variables.
5469  } else if (isa<FieldDecl>(D)) {
5470  FieldDecl *FD = cast<FieldDecl>(D);
5471  if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5472  Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5473  } else if (isa<VarDecl>(D)) {
5474  VarDecl *VD = cast<VarDecl>(D);
5475  if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5476  Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5477 
5478  // Nested classes and class templates.
5479  } else if (isa<CXXRecordDecl>(D)) {
5480  CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5481  } else if (isa<ClassTemplateDecl>(D)) {
5483  cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5484  }
5485  }
5486 }
5487 
5489  Attr *ClassAttr = getDLLAttr(Class);
5490  if (!ClassAttr)
5491  return;
5492 
5493  assert(ClassAttr->getKind() == attr::DLLExport);
5494 
5496 
5498  // Don't go any further if this is just an explicit instantiation
5499  // declaration.
5500  return;
5501 
5502  for (Decl *Member : Class->decls()) {
5503  // Defined static variables that are members of an exported base
5504  // class must be marked export too.
5505  auto *VD = dyn_cast<VarDecl>(Member);
5506  if (VD && Member->getAttr<DLLExportAttr>() &&
5507  VD->getStorageClass() == SC_Static &&
5509  S.MarkVariableReferenced(VD->getLocation(), VD);
5510 
5511  auto *MD = dyn_cast<CXXMethodDecl>(Member);
5512  if (!MD)
5513  continue;
5514 
5515  if (Member->getAttr<DLLExportAttr>()) {
5516  if (MD->isUserProvided()) {
5517  // Instantiate non-default class member functions ...
5518 
5519  // .. except for certain kinds of template specializations.
5520  if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5521  continue;
5522 
5523  S.MarkFunctionReferenced(Class->getLocation(), MD);
5524 
5525  // The function will be passed to the consumer when its definition is
5526  // encountered.
5527  } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5528  MD->isCopyAssignmentOperator() ||
5529  MD->isMoveAssignmentOperator()) {
5530  // Synthesize and instantiate non-trivial implicit methods, explicitly
5531  // defaulted methods, and the copy and move assignment operators. The
5532  // latter are exported even if they are trivial, because the address of
5533  // an operator can be taken and should compare equal across libraries.
5534  DiagnosticErrorTrap Trap(S.Diags);
5535  S.MarkFunctionReferenced(Class->getLocation(), MD);
5536  if (Trap.hasErrorOccurred()) {
5537  S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5538  << Class << !S.getLangOpts().CPlusPlus11;
5539  break;
5540  }
5541 
5542  // There is no later point when we will see the definition of this
5543  // function, so pass it to the consumer now.
5545  }
5546  }
5547  }
5548 }
5549 
5551  CXXRecordDecl *Class) {
5552  // Only the MS ABI has default constructor closures, so we don't need to do
5553  // this semantic checking anywhere else.
5555  return;
5556 
5557  CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5558  for (Decl *Member : Class->decls()) {
5559  // Look for exported default constructors.
5560  auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5561  if (!CD || !CD->isDefaultConstructor())
5562  continue;
5563  auto *Attr = CD->getAttr<DLLExportAttr>();
5564  if (!Attr)
5565  continue;
5566 
5567  // If the class is non-dependent, mark the default arguments as ODR-used so
5568  // that we can properly codegen the constructor closure.
5569  if (!Class->isDependentContext()) {
5570  for (ParmVarDecl *PD : CD->parameters()) {
5571  (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5573  }
5574  }
5575 
5576  if (LastExportedDefaultCtor) {
5577  S.Diag(LastExportedDefaultCtor->getLocation(),
5578  diag::err_attribute_dll_ambiguous_default_ctor)
5579  << Class;
5580  S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5581  << CD->getDeclName();
5582  return;
5583  }
5584  LastExportedDefaultCtor = CD;
5585  }
5586 }
5587 
5589  // Mark any compiler-generated routines with the implicit code_seg attribute.
5590  for (auto *Method : Class->methods()) {
5591  if (Method->isUserProvided())
5592  continue;
5593  if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5594  Method->addAttr(A);
5595  }
5596 }
5597 
5598 /// Check class-level dllimport/dllexport attribute.
5600  Attr *ClassAttr = getDLLAttr(Class);
5601 
5602  // MSVC inherits DLL attributes to partial class template specializations.
5603  if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5604  if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5605  if (Attr *TemplateAttr =
5606  getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5607  auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5608  A->setInherited(true);
5609  ClassAttr = A;
5610  }
5611  }
5612  }
5613 
5614  if (!ClassAttr)
5615  return;
5616 
5617  if (!Class->isExternallyVisible()) {
5618  Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5619  << Class << ClassAttr;
5620  return;
5621  }
5622 
5623  if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5624  !ClassAttr->isInherited()) {
5625  // Diagnose dll attributes on members of class with dll attribute.
5626  for (Decl *Member : Class->decls()) {
5627  if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5628  continue;
5629  InheritableAttr *MemberAttr = getDLLAttr(Member);
5630  if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5631  continue;
5632 
5633  Diag(MemberAttr->getLocation(),
5634  diag::err_attribute_dll_member_of_dll_class)
5635  << MemberAttr << ClassAttr;
5636  Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5637  Member->setInvalidDecl();
5638  }
5639  }
5640 
5641  if (Class->getDescribedClassTemplate())
5642  // Don't inherit dll attribute until the template is instantiated.
5643  return;
5644 
5645  // The class is either imported or exported.
5646  const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5647 
5648  // Check if this was a dllimport attribute propagated from a derived class to
5649  // a base class template specialization. We don't apply these attributes to
5650  // static data members.
5651  const bool PropagatedImport =
5652  !ClassExported &&
5653  cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5654 
5656 
5657  // Ignore explicit dllexport on explicit class template instantiation declarations.
5658  if (ClassExported && !ClassAttr->isInherited() &&
5660  Class->dropAttr<DLLExportAttr>();
5661  return;
5662  }
5663 
5664  // Force declaration of implicit members so they can inherit the attribute.
5665  ForceDeclarationOfImplicitMembers(Class);
5666 
5667  // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5668  // seem to be true in practice?
5669 
5670  for (Decl *Member : Class->decls()) {
5671  VarDecl *VD = dyn_cast<VarDecl>(Member);
5672  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5673 
5674  // Only methods and static fields inherit the attributes.
5675  if (!VD && !MD)
5676  continue;
5677 
5678  if (MD) {
5679  // Don't process deleted methods.
5680  if (MD->isDeleted())
5681  continue;
5682 
5683  if (MD->isInlined()) {
5684  // MinGW does not import or export inline methods.
5685  if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5686  !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5687  continue;
5688 
5689  // MSVC versions before 2015 don't export the move assignment operators
5690  // and move constructor, so don't attempt to import/export them if
5691  // we have a definition.
5692  auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5693  if ((MD->isMoveAssignmentOperator() ||
5694  (Ctor && Ctor->isMoveConstructor())) &&
5695  !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5696  continue;
5697 
5698  // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5699  // operator is exported anyway.
5700  if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5701  (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5702  continue;
5703  }
5704  }
5705 
5706  // Don't apply dllimport attributes to static data members of class template
5707  // instantiations when the attribute is propagated from a derived class.
5708  if (VD && PropagatedImport)
5709  continue;
5710 
5711  if (!cast<NamedDecl>(Member)->isExternallyVisible())
5712  continue;
5713 
5714  if (!getD