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