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/Sema/SemaInternal.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #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 <map>
43 #include <set>
44
45 using namespace clang;
46
47 //===----------------------------------------------------------------------===//
48 // CheckDefaultArgumentVisitor
49 //===----------------------------------------------------------------------===//
50
51 namespace {
52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53 /// the default argument of a parameter to determine whether it
54 /// contains any ill-formed subexpressions. For example, this will
55 /// diagnose the use of local variables or parameters within the
56 /// default argument expression.
57 class CheckDefaultArgumentVisitor
58 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
59 Expr *DefaultArg;
60 Sema *S;
61
62 public:
CheckDefaultArgumentVisitor(Expr * defarg,Sema * s)63 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
64 : DefaultArg(defarg), S(s) {}
65
66 bool VisitExpr(Expr *Node);
67 bool VisitDeclRefExpr(DeclRefExpr *DRE);
68 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
69 bool VisitLambdaExpr(LambdaExpr *Lambda);
70 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
71 };
72
73 /// VisitExpr - Visit all of the children of this expression.
VisitExpr(Expr * Node)74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75 bool IsInvalid = false;
76 for (Stmt::child_range I = Node->children(); I; ++I)
77 IsInvalid |= Visit(*I);
78 return IsInvalid;
79 }
80
81 /// VisitDeclRefExpr - Visit a reference to a declaration, to
82 /// determine whether this declaration can be used in the default
83 /// argument expression.
VisitDeclRefExpr(DeclRefExpr * DRE)84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
85 NamedDecl *Decl = DRE->getDecl();
86 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87 // C++ [dcl.fct.default]p9
88 // Default arguments are evaluated each time the function is
89 // called. The order of evaluation of function arguments is
90 // unspecified. Consequently, parameters of a function shall not
91 // be used in default argument expressions, even if they are not
92 // evaluated. Parameters of a function declared before a default
93 // argument expression are in scope and can hide namespace and
94 // class member names.
95 return S->Diag(DRE->getLocStart(),
96 diag::err_param_default_argument_references_param)
97 << Param->getDeclName() << DefaultArg->getSourceRange();
98 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
99 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
101 // expressions.
102 if (VDecl->isLocalVarDecl())
103 return S->Diag(DRE->getLocStart(),
104 diag::err_param_default_argument_references_local)
105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
106 }
107
108 return false;
109 }
110
111 /// VisitCXXThisExpr - Visit a C++ "this" expression.
VisitCXXThisExpr(CXXThisExpr * ThisE)112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113 // C++ [dcl.fct.default]p8:
114 // The keyword this shall not be used in a default argument of a
115 // member function.
116 return S->Diag(ThisE->getLocStart(),
117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
119 }
120
VisitPseudoObjectExpr(PseudoObjectExpr * POE)121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122 bool Invalid = false;
123 for (PseudoObjectExpr::semantics_iterator
124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125 Expr *E = *i;
126
127 // Look through bindings.
128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129 E = OVE->getSourceExpr();
130 assert(E && "pseudo-object binding without source expression?");
131 }
132
133 Invalid |= Visit(E);
134 }
135 return Invalid;
136 }
137
VisitLambdaExpr(LambdaExpr * Lambda)138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139 // C++11 [expr.lambda.prim]p13:
140 // A lambda-expression appearing in a default argument shall not
141 // implicitly or explicitly capture any entity.
142 if (Lambda->capture_begin() == Lambda->capture_end())
143 return false;
144
145 return S->Diag(Lambda->getLocStart(),
146 diag::err_lambda_capture_default_arg);
147 }
148 }
149
150 void
CalledDecl(SourceLocation CallLoc,const CXXMethodDecl * Method)151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
162
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
165 // If this function can throw any exceptions, make a note of that.
166 if (EST == EST_MSAny || EST == EST_None) {
167 ClearExceptions();
168 ComputedEST = EST;
169 return;
170 }
171
172 // FIXME: If the call to this decl is using any of its default arguments, we
173 // need to search them for potentially-throwing calls.
174
175 // If this function has a basic noexcept, it doesn't affect the outcome.
176 if (EST == EST_BasicNoexcept)
177 return;
178
179 // If we have a throw-all spec at this point, ignore the function.
180 if (ComputedEST == EST_None)
181 return;
182
183 // If we're still at noexcept(true) and there's a nothrow() callee,
184 // change to that specification.
185 if (EST == EST_DynamicNone) {
186 if (ComputedEST == EST_BasicNoexcept)
187 ComputedEST = EST_DynamicNone;
188 return;
189 }
190
191 // Check out noexcept specs.
192 if (EST == EST_ComputedNoexcept) {
193 FunctionProtoType::NoexceptResult NR =
194 Proto->getNoexceptSpec(Self->Context);
195 assert(NR != FunctionProtoType::NR_NoNoexcept &&
196 "Must have noexcept result for EST_ComputedNoexcept.");
197 assert(NR != FunctionProtoType::NR_Dependent &&
198 "Should not generate implicit declarations for dependent cases, "
199 "and don't know how to handle them anyway.");
200
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
210 assert(EST == EST_Dynamic && "EST case not considered earlier.");
211 assert(ComputedEST != EST_None &&
212 "Shouldn't collect exceptions when throw-all is guaranteed.");
213 ComputedEST = EST_Dynamic;
214 // Record the exceptions in this function's exception specification.
215 for (const auto &E : Proto->exceptions())
216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
217 Exceptions.push_back(E);
218 }
219
CalledExpr(Expr * E)220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
221 if (!E || ComputedEST == EST_MSAny)
222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
245 if (Self->canThrow(E))
246 ComputedEST = EST_None;
247 }
248
249 bool
SetParamDefaultArgument(ParmVarDecl * Param,Expr * Arg,SourceLocation EqualLoc)250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
251 SourceLocation EqualLoc) {
252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
270 if (Result.isInvalid())
271 return true;
272 Arg = Result.getAs<Expr>();
273
274 CheckCompletedExpr(Arg, EqualLoc);
275 Arg = MaybeCreateExprWithCleanups(Arg);
276
277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
279
280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
292 return false;
293 }
294
295 /// ActOnParamDefaultArgument - Check whether the default argument
296 /// provided for a function parameter is well-formed. If so, attach it
297 /// to the parameter declaration.
298 void
ActOnParamDefaultArgument(Decl * param,SourceLocation EqualLoc,Expr * DefaultArg)299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
302 return;
303
304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
305 UnparsedDefaultArgLocs.erase(Param);
306
307 // Default arguments are only permitted in C++
308 if (!getLangOpts().CPlusPlus) {
309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
311 Param->setInvalidDecl();
312 return;
313 }
314
315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
321 // Check that the default argument is well-formed
322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
324 Param->setInvalidDecl();
325 return;
326 }
327
328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
329 }
330
331 /// ActOnParamUnparsedDefaultArgument - We've seen a default
332 /// argument for a function parameter, but we can't parse it yet
333 /// because we're inside a class definition. Note that this default
334 /// argument will be parsed later.
ActOnParamUnparsedDefaultArgument(Decl * param,SourceLocation EqualLoc,SourceLocation ArgLoc)335 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
338 if (!param)
339 return;
340
341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
342 Param->setUnparsedDefaultArg();
343 UnparsedDefaultArgLocs[Param] = ArgLoc;
344 }
345
346 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
347 /// the default argument for the parameter param failed.
ActOnParamDefaultArgumentError(Decl * param,SourceLocation EqualLoc)348 void Sema::ActOnParamDefaultArgumentError(Decl *param,
349 SourceLocation EqualLoc) {
350 if (!param)
351 return;
352
353 ParmVarDecl *Param = cast<ParmVarDecl>(param);
354 Param->setInvalidDecl();
355 UnparsedDefaultArgLocs.erase(Param);
356 Param->setDefaultArg(new(Context)
357 OpaqueValueExpr(EqualLoc,
358 Param->getType().getNonReferenceType(),
359 VK_RValue));
360 }
361
362 /// CheckExtraCXXDefaultArguments - Check for any extra default
363 /// arguments in the declarator, which is not a function declaration
364 /// or definition and therefore is not permitted to have default
365 /// arguments. This routine should be invoked for every declarator
366 /// that is not a function declaration or definition.
CheckExtraCXXDefaultArguments(Declarator & D)367 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
368 // C++ [dcl.fct.default]p3
369 // A default argument expression shall be specified only in the
370 // parameter-declaration-clause of a function declaration or in a
371 // template-parameter (14.1). It shall not be specified for a
372 // parameter pack. If it is specified in a
373 // parameter-declaration-clause, it shall not occur within a
374 // declarator or abstract-declarator of a parameter-declaration.
375 bool MightBeFunction = D.isFunctionDeclarationContext();
376 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
377 DeclaratorChunk &chunk = D.getTypeObject(i);
378 if (chunk.Kind == DeclaratorChunk::Function) {
379 if (MightBeFunction) {
380 // This is a function declaration. It can have default arguments, but
381 // keep looking in case its return type is a function type with default
382 // arguments.
383 MightBeFunction = false;
384 continue;
385 }
386 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
387 ++argIdx) {
388 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
389 if (Param->hasUnparsedDefaultArg()) {
390 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
391 SourceRange SR;
392 if (Toks->size() > 1)
393 SR = SourceRange((*Toks)[1].getLocation(),
394 Toks->back().getLocation());
395 else
396 SR = UnparsedDefaultArgLocs[Param];
397 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
398 << SR;
399 delete Toks;
400 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
401 } else if (Param->getDefaultArg()) {
402 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
403 << Param->getDefaultArg()->getSourceRange();
404 Param->setDefaultArg(nullptr);
405 }
406 }
407 } else if (chunk.Kind != DeclaratorChunk::Paren) {
408 MightBeFunction = false;
409 }
410 }
411 }
412
functionDeclHasDefaultArgument(const FunctionDecl * FD)413 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
414 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
415 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
416 if (!PVD->hasDefaultArg())
417 return false;
418 if (!PVD->hasInheritedDefaultArg())
419 return true;
420 }
421 return false;
422 }
423
424 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
425 /// function, once we already know that they have the same
426 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
427 /// error, false otherwise.
MergeCXXFunctionDecl(FunctionDecl * New,FunctionDecl * Old,Scope * S)428 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
429 Scope *S) {
430 bool Invalid = false;
431
432 // C++ [dcl.fct.default]p4:
433 // For non-template functions, default arguments can be added in
434 // later declarations of a function in the same
435 // scope. Declarations in different scopes have completely
436 // distinct sets of default arguments. That is, declarations in
437 // inner scopes do not acquire default arguments from
438 // declarations in outer scopes, and vice versa. In a given
439 // function declaration, all parameters subsequent to a
440 // parameter with a default argument shall have default
441 // arguments supplied in this or previous declarations. A
442 // default argument shall not be redefined by a later
443 // declaration (not even to the same value).
444 //
445 // C++ [dcl.fct.default]p6:
446 // Except for member functions of class templates, the default arguments
447 // in a member function definition that appears outside of the class
448 // definition are added to the set of default arguments provided by the
449 // member function declaration in the class definition.
450 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
451 ParmVarDecl *OldParam = Old->getParamDecl(p);
452 ParmVarDecl *NewParam = New->getParamDecl(p);
453
454 bool OldParamHasDfl = OldParam->hasDefaultArg();
455 bool NewParamHasDfl = NewParam->hasDefaultArg();
456
457 // The declaration context corresponding to the scope is the semantic
458 // parent, unless this is a local function declaration, in which case
459 // it is that surrounding function.
460 DeclContext *ScopeDC = New->isLocalExternDecl()
461 ? New->getLexicalDeclContext()
462 : New->getDeclContext();
463 if (S && !isDeclInScope(Old, ScopeDC, S) &&
464 !New->getDeclContext()->isRecord())
465 // Ignore default parameters of old decl if they are not in
466 // the same scope and this is not an out-of-line definition of
467 // a member function.
468 OldParamHasDfl = false;
469 if (New->isLocalExternDecl() != Old->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 // sufficent, and if neither is local, then they are in the same scope.)
474 OldParamHasDfl = false;
475
476 if (OldParamHasDfl && NewParamHasDfl) {
477
478 unsigned DiagDefaultParamID =
479 diag::err_param_default_argument_redefinition;
480
481 // MSVC accepts that default parameters be redefined for member functions
482 // of template class. The new default parameter's value is ignored.
483 Invalid = true;
484 if (getLangOpts().MicrosoftExt) {
485 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
486 if (MD && MD->getParent()->getDescribedClassTemplate()) {
487 // Merge the old default argument into the new parameter.
488 NewParam->setHasInheritedDefaultArg();
489 if (OldParam->hasUninstantiatedDefaultArg())
490 NewParam->setUninstantiatedDefaultArg(
491 OldParam->getUninstantiatedDefaultArg());
492 else
493 NewParam->setDefaultArg(OldParam->getInit());
494 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
495 Invalid = false;
496 }
497 }
498
499 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
500 // hint here. Alternatively, we could walk the type-source information
501 // for NewParam to find the last source location in the type... but it
502 // isn't worth the effort right now. This is the kind of test case that
503 // is hard to get right:
504 // int f(int);
505 // void g(int (*fp)(int) = f);
506 // void g(int (*fp)(int) = &f);
507 Diag(NewParam->getLocation(), DiagDefaultParamID)
508 << NewParam->getDefaultArgRange();
509
510 // Look for the function declaration where the default argument was
511 // actually written, which may be a declaration prior to Old.
512 for (FunctionDecl *Older = Old->getPreviousDecl();
513 Older; Older = Older->getPreviousDecl()) {
514 if (!Older->getParamDecl(p)->hasDefaultArg())
515 break;
516
517 OldParam = Older->getParamDecl(p);
518 }
519
520 Diag(OldParam->getLocation(), diag::note_previous_definition)
521 << OldParam->getDefaultArgRange();
522 } else if (OldParamHasDfl) {
523 // Merge the old default argument into the new parameter.
524 // It's important to use getInit() here; getDefaultArg()
525 // strips off any top-level ExprWithCleanups.
526 NewParam->setHasInheritedDefaultArg();
527 if (OldParam->hasUninstantiatedDefaultArg())
528 NewParam->setUninstantiatedDefaultArg(
529 OldParam->getUninstantiatedDefaultArg());
530 else
531 NewParam->setDefaultArg(OldParam->getInit());
532 } else if (NewParamHasDfl) {
533 if (New->getDescribedFunctionTemplate()) {
534 // Paragraph 4, quoted above, only applies to non-template functions.
535 Diag(NewParam->getLocation(),
536 diag::err_param_default_argument_template_redecl)
537 << NewParam->getDefaultArgRange();
538 Diag(Old->getLocation(), diag::note_template_prev_declaration)
539 << false;
540 } else if (New->getTemplateSpecializationKind()
541 != TSK_ImplicitInstantiation &&
542 New->getTemplateSpecializationKind() != TSK_Undeclared) {
543 // C++ [temp.expr.spec]p21:
544 // Default function arguments shall not be specified in a declaration
545 // or a definition for one of the following explicit specializations:
546 // - the explicit specialization of a function template;
547 // - the explicit specialization of a member function template;
548 // - the explicit specialization of a member function of a class
549 // template where the class template specialization to which the
550 // member function specialization belongs is implicitly
551 // instantiated.
552 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
553 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
554 << New->getDeclName()
555 << NewParam->getDefaultArgRange();
556 } else if (New->getDeclContext()->isDependentContext()) {
557 // C++ [dcl.fct.default]p6 (DR217):
558 // Default arguments for a member function of a class template shall
559 // be specified on the initial declaration of the member function
560 // within the class template.
561 //
562 // Reading the tea leaves a bit in DR217 and its reference to DR205
563 // leads me to the conclusion that one cannot add default function
564 // arguments for an out-of-line definition of a member function of a
565 // dependent type.
566 int WhichKind = 2;
567 if (CXXRecordDecl *Record
568 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
569 if (Record->getDescribedClassTemplate())
570 WhichKind = 0;
571 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
572 WhichKind = 1;
573 else
574 WhichKind = 2;
575 }
576
577 Diag(NewParam->getLocation(),
578 diag::err_param_default_argument_member_template_redecl)
579 << WhichKind
580 << NewParam->getDefaultArgRange();
581 }
582 }
583 }
584
585 // DR1344: If a default argument is added outside a class definition and that
586 // default argument makes the function a special member function, the program
587 // is ill-formed. This can only happen for constructors.
588 if (isa<CXXConstructorDecl>(New) &&
589 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
590 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
591 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
592 if (NewSM != OldSM) {
593 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
594 assert(NewParam->hasDefaultArg());
595 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
596 << NewParam->getDefaultArgRange() << NewSM;
597 Diag(Old->getLocation(), diag::note_previous_declaration);
598 }
599 }
600
601 const FunctionDecl *Def;
602 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
603 // template has a constexpr specifier then all its declarations shall
604 // contain the constexpr specifier.
605 if (New->isConstexpr() != Old->isConstexpr()) {
606 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
607 << New << New->isConstexpr();
608 Diag(Old->getLocation(), diag::note_previous_declaration);
609 Invalid = true;
610 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
611 // C++11 [dcl.fcn.spec]p4:
612 // If the definition of a function appears in a translation unit before its
613 // first declaration as inline, the program is ill-formed.
614 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
615 Diag(Def->getLocation(), diag::note_previous_definition);
616 Invalid = true;
617 }
618
619 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
620 // argument expression, that declaration shall be a definition and shall be
621 // the only declaration of the function or function template in the
622 // translation unit.
623 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
624 functionDeclHasDefaultArgument(Old)) {
625 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
626 Diag(Old->getLocation(), diag::note_previous_declaration);
627 Invalid = true;
628 }
629
630 if (CheckEquivalentExceptionSpec(Old, New))
631 Invalid = true;
632
633 return Invalid;
634 }
635
636 /// \brief Merge the exception specifications of two variable declarations.
637 ///
638 /// This is called when there's a redeclaration of a VarDecl. The function
639 /// checks if the redeclaration might have an exception specification and
640 /// validates compatibility and merges the specs if necessary.
MergeVarDeclExceptionSpecs(VarDecl * New,VarDecl * Old)641 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
642 // Shortcut if exceptions are disabled.
643 if (!getLangOpts().CXXExceptions)
644 return;
645
646 assert(Context.hasSameType(New->getType(), Old->getType()) &&
647 "Should only be called if types are otherwise the same.");
648
649 QualType NewType = New->getType();
650 QualType OldType = Old->getType();
651
652 // We're only interested in pointers and references to functions, as well
653 // as pointers to member functions.
654 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
655 NewType = R->getPointeeType();
656 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
657 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
658 NewType = P->getPointeeType();
659 OldType = OldType->getAs<PointerType>()->getPointeeType();
660 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
661 NewType = M->getPointeeType();
662 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
663 }
664
665 if (!NewType->isFunctionProtoType())
666 return;
667
668 // There's lots of special cases for functions. For function pointers, system
669 // libraries are hopefully not as broken so that we don't need these
670 // workarounds.
671 if (CheckEquivalentExceptionSpec(
672 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
673 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
674 New->setInvalidDecl();
675 }
676 }
677
678 /// CheckCXXDefaultArguments - Verify that the default arguments for a
679 /// function declaration are well-formed according to C++
680 /// [dcl.fct.default].
CheckCXXDefaultArguments(FunctionDecl * FD)681 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
682 unsigned NumParams = FD->getNumParams();
683 unsigned p;
684
685 // Find first parameter with a default argument
686 for (p = 0; p < NumParams; ++p) {
687 ParmVarDecl *Param = FD->getParamDecl(p);
688 if (Param->hasDefaultArg())
689 break;
690 }
691
692 // C++ [dcl.fct.default]p4:
693 // In a given function declaration, all parameters
694 // subsequent to a parameter with a default argument shall
695 // have default arguments supplied in this or previous
696 // declarations. A default argument shall not be redefined
697 // by a later declaration (not even to the same value).
698 unsigned LastMissingDefaultArg = 0;
699 for (; p < NumParams; ++p) {
700 ParmVarDecl *Param = FD->getParamDecl(p);
701 if (!Param->hasDefaultArg()) {
702 if (Param->isInvalidDecl())
703 /* We already complained about this parameter. */;
704 else if (Param->getIdentifier())
705 Diag(Param->getLocation(),
706 diag::err_param_default_argument_missing_name)
707 << Param->getIdentifier();
708 else
709 Diag(Param->getLocation(),
710 diag::err_param_default_argument_missing);
711
712 LastMissingDefaultArg = p;
713 }
714 }
715
716 if (LastMissingDefaultArg > 0) {
717 // Some default arguments were missing. Clear out all of the
718 // default arguments up to (and including) the last missing
719 // default argument, so that we leave the function parameters
720 // in a semantically valid state.
721 for (p = 0; p <= LastMissingDefaultArg; ++p) {
722 ParmVarDecl *Param = FD->getParamDecl(p);
723 if (Param->hasDefaultArg()) {
724 Param->setDefaultArg(nullptr);
725 }
726 }
727 }
728 }
729
730 // CheckConstexprParameterTypes - Check whether a function's parameter types
731 // are all literal types. If so, return true. If not, produce a suitable
732 // diagnostic and return false.
CheckConstexprParameterTypes(Sema & SemaRef,const FunctionDecl * FD)733 static bool CheckConstexprParameterTypes(Sema &SemaRef,
734 const FunctionDecl *FD) {
735 unsigned ArgIndex = 0;
736 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
737 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
738 e = FT->param_type_end();
739 i != e; ++i, ++ArgIndex) {
740 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
741 SourceLocation ParamLoc = PD->getLocation();
742 if (!(*i)->isDependentType() &&
743 SemaRef.RequireLiteralType(ParamLoc, *i,
744 diag::err_constexpr_non_literal_param,
745 ArgIndex+1, PD->getSourceRange(),
746 isa<CXXConstructorDecl>(FD)))
747 return false;
748 }
749 return true;
750 }
751
752 /// \brief Get diagnostic %select index for tag kind for
753 /// record diagnostic message.
754 /// WARNING: Indexes apply to particular diagnostics only!
755 ///
756 /// \returns diagnostic %select index.
getRecordDiagFromTagKind(TagTypeKind Tag)757 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
758 switch (Tag) {
759 case TTK_Struct: return 0;
760 case TTK_Interface: return 1;
761 case TTK_Class: return 2;
762 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
763 }
764 }
765
766 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
767 // the requirements of a constexpr function definition or a constexpr
768 // constructor definition. If so, return true. If not, produce appropriate
769 // diagnostics and return false.
770 //
771 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
CheckConstexprFunctionDecl(const FunctionDecl * NewFD)772 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
773 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
774 if (MD && MD->isInstance()) {
775 // C++11 [dcl.constexpr]p4:
776 // The definition of a constexpr constructor shall satisfy the following
777 // constraints:
778 // - the class shall not have any virtual base classes;
779 const CXXRecordDecl *RD = MD->getParent();
780 if (RD->getNumVBases()) {
781 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
782 << isa<CXXConstructorDecl>(NewFD)
783 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
784 for (const auto &I : RD->vbases())
785 Diag(I.getLocStart(),
786 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
787 return false;
788 }
789 }
790
791 if (!isa<CXXConstructorDecl>(NewFD)) {
792 // C++11 [dcl.constexpr]p3:
793 // The definition of a constexpr function shall satisfy the following
794 // constraints:
795 // - it shall not be virtual;
796 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
797 if (Method && Method->isVirtual()) {
798 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
799
800 // If it's not obvious why this function is virtual, find an overridden
801 // function which uses the 'virtual' keyword.
802 const CXXMethodDecl *WrittenVirtual = Method;
803 while (!WrittenVirtual->isVirtualAsWritten())
804 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
805 if (WrittenVirtual != Method)
806 Diag(WrittenVirtual->getLocation(),
807 diag::note_overridden_virtual_function);
808 return false;
809 }
810
811 // - its return type shall be a literal type;
812 QualType RT = NewFD->getReturnType();
813 if (!RT->isDependentType() &&
814 RequireLiteralType(NewFD->getLocation(), RT,
815 diag::err_constexpr_non_literal_return))
816 return false;
817 }
818
819 // - each of its parameter types shall be a literal type;
820 if (!CheckConstexprParameterTypes(*this, NewFD))
821 return false;
822
823 return true;
824 }
825
826 /// Check the given declaration statement is legal within a constexpr function
827 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
828 ///
829 /// \return true if the body is OK (maybe only as an extension), false if we
830 /// have diagnosed a problem.
CheckConstexprDeclStmt(Sema & SemaRef,const FunctionDecl * Dcl,DeclStmt * DS,SourceLocation & Cxx1yLoc)831 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
832 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
833 // C++11 [dcl.constexpr]p3 and p4:
834 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
835 // contain only
836 for (const auto *DclIt : DS->decls()) {
837 switch (DclIt->getKind()) {
838 case Decl::StaticAssert:
839 case Decl::Using:
840 case Decl::UsingShadow:
841 case Decl::UsingDirective:
842 case Decl::UnresolvedUsingTypename:
843 case Decl::UnresolvedUsingValue:
844 // - static_assert-declarations
845 // - using-declarations,
846 // - using-directives,
847 continue;
848
849 case Decl::Typedef:
850 case Decl::TypeAlias: {
851 // - typedef declarations and alias-declarations that do not define
852 // classes or enumerations,
853 const auto *TN = cast<TypedefNameDecl>(DclIt);
854 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
855 // Don't allow variably-modified types in constexpr functions.
856 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
857 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
858 << TL.getSourceRange() << TL.getType()
859 << isa<CXXConstructorDecl>(Dcl);
860 return false;
861 }
862 continue;
863 }
864
865 case Decl::Enum:
866 case Decl::CXXRecord:
867 // C++1y allows types to be defined, not just declared.
868 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
869 SemaRef.Diag(DS->getLocStart(),
870 SemaRef.getLangOpts().CPlusPlus14
871 ? diag::warn_cxx11_compat_constexpr_type_definition
872 : diag::ext_constexpr_type_definition)
873 << isa<CXXConstructorDecl>(Dcl);
874 continue;
875
876 case Decl::EnumConstant:
877 case Decl::IndirectField:
878 case Decl::ParmVar:
879 // These can only appear with other declarations which are banned in
880 // C++11 and permitted in C++1y, so ignore them.
881 continue;
882
883 case Decl::Var: {
884 // C++1y [dcl.constexpr]p3 allows anything except:
885 // a definition of a variable of non-literal type or of static or
886 // thread storage duration or for which no initialization is performed.
887 const auto *VD = cast<VarDecl>(DclIt);
888 if (VD->isThisDeclarationADefinition()) {
889 if (VD->isStaticLocal()) {
890 SemaRef.Diag(VD->getLocation(),
891 diag::err_constexpr_local_var_static)
892 << isa<CXXConstructorDecl>(Dcl)
893 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
894 return false;
895 }
896 if (!VD->getType()->isDependentType() &&
897 SemaRef.RequireLiteralType(
898 VD->getLocation(), VD->getType(),
899 diag::err_constexpr_local_var_non_literal_type,
900 isa<CXXConstructorDecl>(Dcl)))
901 return false;
902 if (!VD->getType()->isDependentType() &&
903 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
904 SemaRef.Diag(VD->getLocation(),
905 diag::err_constexpr_local_var_no_init)
906 << isa<CXXConstructorDecl>(Dcl);
907 return false;
908 }
909 }
910 SemaRef.Diag(VD->getLocation(),
911 SemaRef.getLangOpts().CPlusPlus14
912 ? diag::warn_cxx11_compat_constexpr_local_var
913 : diag::ext_constexpr_local_var)
914 << isa<CXXConstructorDecl>(Dcl);
915 continue;
916 }
917
918 case Decl::NamespaceAlias:
919 case Decl::Function:
920 // These are disallowed in C++11 and permitted in C++1y. Allow them
921 // everywhere as an extension.
922 if (!Cxx1yLoc.isValid())
923 Cxx1yLoc = DS->getLocStart();
924 continue;
925
926 default:
927 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
928 << isa<CXXConstructorDecl>(Dcl);
929 return false;
930 }
931 }
932
933 return true;
934 }
935
936 /// Check that the given field is initialized within a constexpr constructor.
937 ///
938 /// \param Dcl The constexpr constructor being checked.
939 /// \param Field The field being checked. This may be a member of an anonymous
940 /// struct or union nested within the class being checked.
941 /// \param Inits All declarations, including anonymous struct/union members and
942 /// indirect members, for which any initialization was provided.
943 /// \param Diagnosed Set to true if an error is produced.
CheckConstexprCtorInitializer(Sema & SemaRef,const FunctionDecl * Dcl,FieldDecl * Field,llvm::SmallSet<Decl *,16> & Inits,bool & Diagnosed)944 static void CheckConstexprCtorInitializer(Sema &SemaRef,
945 const FunctionDecl *Dcl,
946 FieldDecl *Field,
947 llvm::SmallSet<Decl*, 16> &Inits,
948 bool &Diagnosed) {
949 if (Field->isInvalidDecl())
950 return;
951
952 if (Field->isUnnamedBitfield())
953 return;
954
955 // Anonymous unions with no variant members and empty anonymous structs do not
956 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
957 // indirect fields don't need initializing.
958 if (Field->isAnonymousStructOrUnion() &&
959 (Field->getType()->isUnionType()
960 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
961 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
962 return;
963
964 if (!Inits.count(Field)) {
965 if (!Diagnosed) {
966 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
967 Diagnosed = true;
968 }
969 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
970 } else if (Field->isAnonymousStructOrUnion()) {
971 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
972 for (auto *I : RD->fields())
973 // If an anonymous union contains an anonymous struct of which any member
974 // is initialized, all members must be initialized.
975 if (!RD->isUnion() || Inits.count(I))
976 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
977 }
978 }
979
980 /// Check the provided statement is allowed in a constexpr function
981 /// definition.
982 static bool
CheckConstexprFunctionStmt(Sema & SemaRef,const FunctionDecl * Dcl,Stmt * S,SmallVectorImpl<SourceLocation> & ReturnStmts,SourceLocation & Cxx1yLoc)983 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
984 SmallVectorImpl<SourceLocation> &ReturnStmts,
985 SourceLocation &Cxx1yLoc) {
986 // - its function-body shall be [...] a compound-statement that contains only
987 switch (S->getStmtClass()) {
988 case Stmt::NullStmtClass:
989 // - null statements,
990 return true;
991
992 case Stmt::DeclStmtClass:
993 // - static_assert-declarations
994 // - using-declarations,
995 // - using-directives,
996 // - typedef declarations and alias-declarations that do not define
997 // classes or enumerations,
998 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
999 return false;
1000 return true;
1001
1002 case Stmt::ReturnStmtClass:
1003 // - and exactly one return statement;
1004 if (isa<CXXConstructorDecl>(Dcl)) {
1005 // C++1y allows return statements in constexpr constructors.
1006 if (!Cxx1yLoc.isValid())
1007 Cxx1yLoc = S->getLocStart();
1008 return true;
1009 }
1010
1011 ReturnStmts.push_back(S->getLocStart());
1012 return true;
1013
1014 case Stmt::CompoundStmtClass: {
1015 // C++1y allows compound-statements.
1016 if (!Cxx1yLoc.isValid())
1017 Cxx1yLoc = S->getLocStart();
1018
1019 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1020 for (auto *BodyIt : CompStmt->body()) {
1021 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1022 Cxx1yLoc))
1023 return false;
1024 }
1025 return true;
1026 }
1027
1028 case Stmt::AttributedStmtClass:
1029 if (!Cxx1yLoc.isValid())
1030 Cxx1yLoc = S->getLocStart();
1031 return true;
1032
1033 case Stmt::IfStmtClass: {
1034 // C++1y allows if-statements.
1035 if (!Cxx1yLoc.isValid())
1036 Cxx1yLoc = S->getLocStart();
1037
1038 IfStmt *If = cast<IfStmt>(S);
1039 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1040 Cxx1yLoc))
1041 return false;
1042 if (If->getElse() &&
1043 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1044 Cxx1yLoc))
1045 return false;
1046 return true;
1047 }
1048
1049 case Stmt::WhileStmtClass:
1050 case Stmt::DoStmtClass:
1051 case Stmt::ForStmtClass:
1052 case Stmt::CXXForRangeStmtClass:
1053 case Stmt::ContinueStmtClass:
1054 // C++1y allows all of these. We don't allow them as extensions in C++11,
1055 // because they don't make sense without variable mutation.
1056 if (!SemaRef.getLangOpts().CPlusPlus14)
1057 break;
1058 if (!Cxx1yLoc.isValid())
1059 Cxx1yLoc = S->getLocStart();
1060 for (Stmt::child_range Children = S->children(); Children; ++Children)
1061 if (*Children &&
1062 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1063 Cxx1yLoc))
1064 return false;
1065 return true;
1066
1067 case Stmt::SwitchStmtClass:
1068 case Stmt::CaseStmtClass:
1069 case Stmt::DefaultStmtClass:
1070 case Stmt::BreakStmtClass:
1071 // C++1y allows switch-statements, and since they don't need variable
1072 // mutation, we can reasonably allow them in C++11 as an extension.
1073 if (!Cxx1yLoc.isValid())
1074 Cxx1yLoc = S->getLocStart();
1075 for (Stmt::child_range Children = S->children(); Children; ++Children)
1076 if (*Children &&
1077 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1078 Cxx1yLoc))
1079 return false;
1080 return true;
1081
1082 default:
1083 if (!isa<Expr>(S))
1084 break;
1085
1086 // C++1y allows expression-statements.
1087 if (!Cxx1yLoc.isValid())
1088 Cxx1yLoc = S->getLocStart();
1089 return true;
1090 }
1091
1092 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1093 << isa<CXXConstructorDecl>(Dcl);
1094 return false;
1095 }
1096
1097 /// Check the body for the given constexpr function declaration only contains
1098 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1099 ///
1100 /// \return true if the body is OK, false if we have diagnosed a problem.
CheckConstexprFunctionBody(const FunctionDecl * Dcl,Stmt * Body)1101 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1102 if (isa<CXXTryStmt>(Body)) {
1103 // C++11 [dcl.constexpr]p3:
1104 // The definition of a constexpr function shall satisfy the following
1105 // constraints: [...]
1106 // - its function-body shall be = delete, = default, or a
1107 // compound-statement
1108 //
1109 // C++11 [dcl.constexpr]p4:
1110 // In the definition of a constexpr constructor, [...]
1111 // - its function-body shall not be a function-try-block;
1112 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1113 << isa<CXXConstructorDecl>(Dcl);
1114 return false;
1115 }
1116
1117 SmallVector<SourceLocation, 4> ReturnStmts;
1118
1119 // - its function-body shall be [...] a compound-statement that contains only
1120 // [... list of cases ...]
1121 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1122 SourceLocation Cxx1yLoc;
1123 for (auto *BodyIt : CompBody->body()) {
1124 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1125 return false;
1126 }
1127
1128 if (Cxx1yLoc.isValid())
1129 Diag(Cxx1yLoc,
1130 getLangOpts().CPlusPlus14
1131 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1132 : diag::ext_constexpr_body_invalid_stmt)
1133 << isa<CXXConstructorDecl>(Dcl);
1134
1135 if (const CXXConstructorDecl *Constructor
1136 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1137 const CXXRecordDecl *RD = Constructor->getParent();
1138 // DR1359:
1139 // - every non-variant non-static data member and base class sub-object
1140 // shall be initialized;
1141 // DR1460:
1142 // - if the class is a union having variant members, exactly one of them
1143 // shall be initialized;
1144 if (RD->isUnion()) {
1145 if (Constructor->getNumCtorInitializers() == 0 &&
1146 RD->hasVariantMembers()) {
1147 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1148 return false;
1149 }
1150 } else if (!Constructor->isDependentContext() &&
1151 !Constructor->isDelegatingConstructor()) {
1152 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1153
1154 // Skip detailed checking if we have enough initializers, and we would
1155 // allow at most one initializer per member.
1156 bool AnyAnonStructUnionMembers = false;
1157 unsigned Fields = 0;
1158 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1159 E = RD->field_end(); I != E; ++I, ++Fields) {
1160 if (I->isAnonymousStructOrUnion()) {
1161 AnyAnonStructUnionMembers = true;
1162 break;
1163 }
1164 }
1165 // DR1460:
1166 // - if the class is a union-like class, but is not a union, for each of
1167 // its anonymous union members having variant members, exactly one of
1168 // them shall be initialized;
1169 if (AnyAnonStructUnionMembers ||
1170 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1171 // Check initialization of non-static data members. Base classes are
1172 // always initialized so do not need to be checked. Dependent bases
1173 // might not have initializers in the member initializer list.
1174 llvm::SmallSet<Decl*, 16> Inits;
1175 for (const auto *I: Constructor->inits()) {
1176 if (FieldDecl *FD = I->getMember())
1177 Inits.insert(FD);
1178 else if (IndirectFieldDecl *ID = I->getIndirectMember())
1179 Inits.insert(ID->chain_begin(), ID->chain_end());
1180 }
1181
1182 bool Diagnosed = false;
1183 for (auto *I : RD->fields())
1184 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1185 if (Diagnosed)
1186 return false;
1187 }
1188 }
1189 } else {
1190 if (ReturnStmts.empty()) {
1191 // C++1y doesn't require constexpr functions to contain a 'return'
1192 // statement. We still do, unless the return type might be void, because
1193 // otherwise if there's no return statement, the function cannot
1194 // be used in a core constant expression.
1195 bool OK = getLangOpts().CPlusPlus14 &&
1196 (Dcl->getReturnType()->isVoidType() ||
1197 Dcl->getReturnType()->isDependentType());
1198 Diag(Dcl->getLocation(),
1199 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1200 : diag::err_constexpr_body_no_return);
1201 return OK;
1202 }
1203 if (ReturnStmts.size() > 1) {
1204 Diag(ReturnStmts.back(),
1205 getLangOpts().CPlusPlus14
1206 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1207 : diag::ext_constexpr_body_multiple_return);
1208 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1209 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1210 }
1211 }
1212
1213 // C++11 [dcl.constexpr]p5:
1214 // if no function argument values exist such that the function invocation
1215 // substitution would produce a constant expression, the program is
1216 // ill-formed; no diagnostic required.
1217 // C++11 [dcl.constexpr]p3:
1218 // - every constructor call and implicit conversion used in initializing the
1219 // return value shall be one of those allowed in a constant expression.
1220 // C++11 [dcl.constexpr]p4:
1221 // - every constructor involved in initializing non-static data members and
1222 // base class sub-objects shall be a constexpr constructor.
1223 SmallVector<PartialDiagnosticAt, 8> Diags;
1224 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1225 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1226 << isa<CXXConstructorDecl>(Dcl);
1227 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1228 Diag(Diags[I].first, Diags[I].second);
1229 // Don't return false here: we allow this for compatibility in
1230 // system headers.
1231 }
1232
1233 return true;
1234 }
1235
1236 /// isCurrentClassName - Determine whether the identifier II is the
1237 /// name of the class type currently being defined. In the case of
1238 /// nested classes, this will only return true if II is the name of
1239 /// the innermost class.
isCurrentClassName(const IdentifierInfo & II,Scope *,const CXXScopeSpec * SS)1240 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1241 const CXXScopeSpec *SS) {
1242 assert(getLangOpts().CPlusPlus && "No class names in C!");
1243
1244 CXXRecordDecl *CurDecl;
1245 if (SS && SS->isSet() && !SS->isInvalid()) {
1246 DeclContext *DC = computeDeclContext(*SS, true);
1247 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1248 } else
1249 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1250
1251 if (CurDecl && CurDecl->getIdentifier())
1252 return &II == CurDecl->getIdentifier();
1253 return false;
1254 }
1255
1256 /// \brief Determine whether the identifier II is a typo for the name of
1257 /// the class type currently being defined. If so, update it to the identifier
1258 /// that should have been used.
isCurrentClassNameTypo(IdentifierInfo * & II,const CXXScopeSpec * SS)1259 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1260 assert(getLangOpts().CPlusPlus && "No class names in C!");
1261
1262 if (!getLangOpts().SpellChecking)
1263 return false;
1264
1265 CXXRecordDecl *CurDecl;
1266 if (SS && SS->isSet() && !SS->isInvalid()) {
1267 DeclContext *DC = computeDeclContext(*SS, true);
1268 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1269 } else
1270 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1271
1272 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1273 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1274 < II->getLength()) {
1275 II = CurDecl->getIdentifier();
1276 return true;
1277 }
1278
1279 return false;
1280 }
1281
1282 /// \brief Determine whether the given class is a base class of the given
1283 /// class, including looking at dependent bases.
findCircularInheritance(const CXXRecordDecl * Class,const CXXRecordDecl * Current)1284 static bool findCircularInheritance(const CXXRecordDecl *Class,
1285 const CXXRecordDecl *Current) {
1286 SmallVector<const CXXRecordDecl*, 8> Queue;
1287
1288 Class = Class->getCanonicalDecl();
1289 while (true) {
1290 for (const auto &I : Current->bases()) {
1291 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1292 if (!Base)
1293 continue;
1294
1295 Base = Base->getDefinition();
1296 if (!Base)
1297 continue;
1298
1299 if (Base->getCanonicalDecl() == Class)
1300 return true;
1301
1302 Queue.push_back(Base);
1303 }
1304
1305 if (Queue.empty())
1306 return false;
1307
1308 Current = Queue.pop_back_val();
1309 }
1310
1311 return false;
1312 }
1313
1314 /// \brief Perform propagation of DLL attributes from a derived class to a
1315 /// templated base class for MS compatibility.
propagateDLLAttrToBaseClassTemplate(Sema & S,CXXRecordDecl * Class,Attr * ClassAttr,ClassTemplateSpecializationDecl * BaseTemplateSpec,SourceLocation BaseLoc)1316 static void propagateDLLAttrToBaseClassTemplate(
1317 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1318 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1319 if (getDLLAttr(
1320 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1321 // If the base class template has a DLL attribute, don't try to change it.
1322 return;
1323 }
1324
1325 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1326 // If the base class is not already specialized, we can do the propagation.
1327 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1328 NewAttr->setInherited(true);
1329 BaseTemplateSpec->addAttr(NewAttr);
1330 return;
1331 }
1332
1333 bool DifferentAttribute = false;
1334 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1335 if (!SpecializationAttr->isInherited()) {
1336 // The template has previously been specialized or instantiated with an
1337 // explicit attribute. We should not try to change it.
1338 return;
1339 }
1340 if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1341 // The specialization already has the right attribute.
1342 return;
1343 }
1344 DifferentAttribute = true;
1345 }
1346
1347 // The template was previously instantiated or explicitly specialized without
1348 // a dll attribute, or the template was previously instantiated with a
1349 // different inherited attribute. It's too late for us to change the
1350 // attribute, so warn that this is unsupported.
1351 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1352 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1353 S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1354 if (BaseTemplateSpec->isExplicitSpecialization()) {
1355 S.Diag(BaseTemplateSpec->getLocation(),
1356 diag::note_template_class_explicit_specialization_was_here)
1357 << BaseTemplateSpec;
1358 } else {
1359 S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1360 diag::note_template_class_instantiation_was_here)
1361 << BaseTemplateSpec;
1362 }
1363 }
1364
1365 /// \brief Check the validity of a C++ base class specifier.
1366 ///
1367 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1368 /// and returns NULL otherwise.
1369 CXXBaseSpecifier *
CheckBaseSpecifier(CXXRecordDecl * Class,SourceRange SpecifierRange,bool Virtual,AccessSpecifier Access,TypeSourceInfo * TInfo,SourceLocation EllipsisLoc)1370 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1371 SourceRange SpecifierRange,
1372 bool Virtual, AccessSpecifier Access,
1373 TypeSourceInfo *TInfo,
1374 SourceLocation EllipsisLoc) {
1375 QualType BaseType = TInfo->getType();
1376
1377 // C++ [class.union]p1:
1378 // A union shall not have base classes.
1379 if (Class->isUnion()) {
1380 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1381 << SpecifierRange;
1382 return nullptr;
1383 }
1384
1385 if (EllipsisLoc.isValid() &&
1386 !TInfo->getType()->containsUnexpandedParameterPack()) {
1387 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1388 << TInfo->getTypeLoc().getSourceRange();
1389 EllipsisLoc = SourceLocation();
1390 }
1391
1392 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1393
1394 if (BaseType->isDependentType()) {
1395 // Make sure that we don't have circular inheritance among our dependent
1396 // bases. For non-dependent bases, the check for completeness below handles
1397 // this.
1398 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1399 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1400 ((BaseDecl = BaseDecl->getDefinition()) &&
1401 findCircularInheritance(Class, BaseDecl))) {
1402 Diag(BaseLoc, diag::err_circular_inheritance)
1403 << BaseType << Context.getTypeDeclType(Class);
1404
1405 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1406 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1407 << BaseType;
1408
1409 return nullptr;
1410 }
1411 }
1412
1413 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1414 Class->getTagKind() == TTK_Class,
1415 Access, TInfo, EllipsisLoc);
1416 }
1417
1418 // Base specifiers must be record types.
1419 if (!BaseType->isRecordType()) {
1420 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1421 return nullptr;
1422 }
1423
1424 // C++ [class.union]p1:
1425 // A union shall not be used as a base class.
1426 if (BaseType->isUnionType()) {
1427 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1428 return nullptr;
1429 }
1430
1431 // For the MS ABI, propagate DLL attributes to base class templates.
1432 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1433 if (Attr *ClassAttr = getDLLAttr(Class)) {
1434 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1435 BaseType->getAsCXXRecordDecl())) {
1436 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1437 BaseTemplate, BaseLoc);
1438 }
1439 }
1440 }
1441
1442 // C++ [class.derived]p2:
1443 // The class-name in a base-specifier shall not be an incompletely
1444 // defined class.
1445 if (RequireCompleteType(BaseLoc, BaseType,
1446 diag::err_incomplete_base_class, SpecifierRange)) {
1447 Class->setInvalidDecl();
1448 return nullptr;
1449 }
1450
1451 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1452 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1453 assert(BaseDecl && "Record type has no declaration");
1454 BaseDecl = BaseDecl->getDefinition();
1455 assert(BaseDecl && "Base type is not incomplete, but has no definition");
1456 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1457 assert(CXXBaseDecl && "Base type is not a C++ type");
1458
1459 // A class which contains a flexible array member is not suitable for use as a
1460 // base class:
1461 // - If the layout determines that a base comes before another base,
1462 // the flexible array member would index into the subsequent base.
1463 // - If the layout determines that base comes before the derived class,
1464 // the flexible array member would index into the derived class.
1465 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1466 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1467 << CXXBaseDecl->getDeclName();
1468 return nullptr;
1469 }
1470
1471 // C++ [class]p3:
1472 // If a class is marked final and it appears as a base-type-specifier in
1473 // base-clause, the program is ill-formed.
1474 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1475 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1476 << CXXBaseDecl->getDeclName()
1477 << FA->isSpelledAsSealed();
1478 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1479 << CXXBaseDecl->getDeclName() << FA->getRange();
1480 return nullptr;
1481 }
1482
1483 if (BaseDecl->isInvalidDecl())
1484 Class->setInvalidDecl();
1485
1486 // Create the base specifier.
1487 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1488 Class->getTagKind() == TTK_Class,
1489 Access, TInfo, EllipsisLoc);
1490 }
1491
1492 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1493 /// one entry in the base class list of a class specifier, for
1494 /// example:
1495 /// class foo : public bar, virtual private baz {
1496 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1497 BaseResult
ActOnBaseSpecifier(Decl * classdecl,SourceRange SpecifierRange,ParsedAttributes & Attributes,bool Virtual,AccessSpecifier Access,ParsedType basetype,SourceLocation BaseLoc,SourceLocation EllipsisLoc)1498 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1499 ParsedAttributes &Attributes,
1500 bool Virtual, AccessSpecifier Access,
1501 ParsedType basetype, SourceLocation BaseLoc,
1502 SourceLocation EllipsisLoc) {
1503 if (!classdecl)
1504 return true;
1505
1506 AdjustDeclIfTemplate(classdecl);
1507 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1508 if (!Class)
1509 return true;
1510
1511 // We haven't yet attached the base specifiers.
1512 Class->setIsParsingBaseSpecifiers();
1513
1514 // We do not support any C++11 attributes on base-specifiers yet.
1515 // Diagnose any attributes we see.
1516 if (!Attributes.empty()) {
1517 for (AttributeList *Attr = Attributes.getList(); Attr;
1518 Attr = Attr->getNext()) {
1519 if (Attr->isInvalid() ||
1520 Attr->getKind() == AttributeList::IgnoredAttribute)
1521 continue;
1522 Diag(Attr->getLoc(),
1523 Attr->getKind() == AttributeList::UnknownAttribute
1524 ? diag::warn_unknown_attribute_ignored
1525 : diag::err_base_specifier_attribute)
1526 << Attr->getName();
1527 }
1528 }
1529
1530 TypeSourceInfo *TInfo = nullptr;
1531 GetTypeFromParser(basetype, &TInfo);
1532
1533 if (EllipsisLoc.isInvalid() &&
1534 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1535 UPPC_BaseType))
1536 return true;
1537
1538 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1539 Virtual, Access, TInfo,
1540 EllipsisLoc))
1541 return BaseSpec;
1542 else
1543 Class->setInvalidDecl();
1544
1545 return true;
1546 }
1547
1548 /// \brief Performs the actual work of attaching the given base class
1549 /// specifiers to a C++ class.
AttachBaseSpecifiers(CXXRecordDecl * Class,CXXBaseSpecifier ** Bases,unsigned NumBases)1550 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1551 unsigned NumBases) {
1552 if (NumBases == 0)
1553 return false;
1554
1555 // Used to keep track of which base types we have already seen, so
1556 // that we can properly diagnose redundant direct base types. Note
1557 // that the key is always the unqualified canonical type of the base
1558 // class.
1559 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1560
1561 // Copy non-redundant base specifiers into permanent storage.
1562 unsigned NumGoodBases = 0;
1563 bool Invalid = false;
1564 for (unsigned idx = 0; idx < NumBases; ++idx) {
1565 QualType NewBaseType
1566 = Context.getCanonicalType(Bases[idx]->getType());
1567 NewBaseType = NewBaseType.getLocalUnqualifiedType();
1568
1569 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1570 if (KnownBase) {
1571 // C++ [class.mi]p3:
1572 // A class shall not be specified as a direct base class of a
1573 // derived class more than once.
1574 Diag(Bases[idx]->getLocStart(),
1575 diag::err_duplicate_base_class)
1576 << KnownBase->getType()
1577 << Bases[idx]->getSourceRange();
1578
1579 // Delete the duplicate base class specifier; we're going to
1580 // overwrite its pointer later.
1581 Context.Deallocate(Bases[idx]);
1582
1583 Invalid = true;
1584 } else {
1585 // Okay, add this new base class.
1586 KnownBase = Bases[idx];
1587 Bases[NumGoodBases++] = Bases[idx];
1588 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1589 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1590 if (Class->isInterface() &&
1591 (!RD->isInterface() ||
1592 KnownBase->getAccessSpecifier() != AS_public)) {
1593 // The Microsoft extension __interface does not permit bases that
1594 // are not themselves public interfaces.
1595 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1596 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1597 << RD->getSourceRange();
1598 Invalid = true;
1599 }
1600 if (RD->hasAttr<WeakAttr>())
1601 Class->addAttr(WeakAttr::CreateImplicit(Context));
1602 }
1603 }
1604 }
1605
1606 // Attach the remaining base class specifiers to the derived class.
1607 Class->setBases(Bases, NumGoodBases);
1608
1609 // Delete the remaining (good) base class specifiers, since their
1610 // data has been copied into the CXXRecordDecl.
1611 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1612 Context.Deallocate(Bases[idx]);
1613
1614 return Invalid;
1615 }
1616
1617 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1618 /// class, after checking whether there are any duplicate base
1619 /// classes.
ActOnBaseSpecifiers(Decl * ClassDecl,CXXBaseSpecifier ** Bases,unsigned NumBases)1620 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1621 unsigned NumBases) {
1622 if (!ClassDecl || !Bases || !NumBases)
1623 return;
1624
1625 AdjustDeclIfTemplate(ClassDecl);
1626 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1627 }
1628
1629 /// \brief Determine whether the type \p Derived is a C++ class that is
1630 /// derived from the type \p Base.
IsDerivedFrom(QualType Derived,QualType Base)1631 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1632 if (!getLangOpts().CPlusPlus)
1633 return false;
1634
1635 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1636 if (!DerivedRD)
1637 return false;
1638
1639 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1640 if (!BaseRD)
1641 return false;
1642
1643 // If either the base or the derived type is invalid, don't try to
1644 // check whether one is derived from the other.
1645 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1646 return false;
1647
1648 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1649 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1650 }
1651
1652 /// \brief Determine whether the type \p Derived is a C++ class that is
1653 /// derived from the type \p Base.
IsDerivedFrom(QualType Derived,QualType Base,CXXBasePaths & Paths)1654 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1655 if (!getLangOpts().CPlusPlus)
1656 return false;
1657
1658 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1659 if (!DerivedRD)
1660 return false;
1661
1662 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1663 if (!BaseRD)
1664 return false;
1665
1666 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1667 }
1668
BuildBasePathArray(const CXXBasePaths & Paths,CXXCastPath & BasePathArray)1669 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1670 CXXCastPath &BasePathArray) {
1671 assert(BasePathArray.empty() && "Base path array must be empty!");
1672 assert(Paths.isRecordingPaths() && "Must record paths!");
1673
1674 const CXXBasePath &Path = Paths.front();
1675
1676 // We first go backward and check if we have a virtual base.
1677 // FIXME: It would be better if CXXBasePath had the base specifier for
1678 // the nearest virtual base.
1679 unsigned Start = 0;
1680 for (unsigned I = Path.size(); I != 0; --I) {
1681 if (Path[I - 1].Base->isVirtual()) {
1682 Start = I - 1;
1683 break;
1684 }
1685 }
1686
1687 // Now add all bases.
1688 for (unsigned I = Start, E = Path.size(); I != E; ++I)
1689 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1690 }
1691
1692 /// \brief Determine whether the given base path includes a virtual
1693 /// base class.
BasePathInvolvesVirtualBase(const CXXCastPath & BasePath)1694 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1695 for (CXXCastPath::const_iterator B = BasePath.begin(),
1696 BEnd = BasePath.end();
1697 B != BEnd; ++B)
1698 if ((*B)->isVirtual())
1699 return true;
1700
1701 return false;
1702 }
1703
1704 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1705 /// conversion (where Derived and Base are class types) is
1706 /// well-formed, meaning that the conversion is unambiguous (and
1707 /// that all of the base classes are accessible). Returns true
1708 /// and emits a diagnostic if the code is ill-formed, returns false
1709 /// otherwise. Loc is the location where this routine should point to
1710 /// if there is an error, and Range is the source range to highlight
1711 /// if there is an error.
1712 bool
CheckDerivedToBaseConversion(QualType Derived,QualType Base,unsigned InaccessibleBaseID,unsigned AmbigiousBaseConvID,SourceLocation Loc,SourceRange Range,DeclarationName Name,CXXCastPath * BasePath)1713 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1714 unsigned InaccessibleBaseID,
1715 unsigned AmbigiousBaseConvID,
1716 SourceLocation Loc, SourceRange Range,
1717 DeclarationName Name,
1718 CXXCastPath *BasePath) {
1719 // First, determine whether the path from Derived to Base is
1720 // ambiguous. This is slightly more expensive than checking whether
1721 // the Derived to Base conversion exists, because here we need to
1722 // explore multiple paths to determine if there is an ambiguity.
1723 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1724 /*DetectVirtual=*/false);
1725 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1726 assert(DerivationOkay &&
1727 "Can only be used with a derived-to-base conversion");
1728 (void)DerivationOkay;
1729
1730 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1731 if (InaccessibleBaseID) {
1732 // Check that the base class can be accessed.
1733 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1734 InaccessibleBaseID)) {
1735 case AR_inaccessible:
1736 return true;
1737 case AR_accessible:
1738 case AR_dependent:
1739 case AR_delayed:
1740 break;
1741 }
1742 }
1743
1744 // Build a base path if necessary.
1745 if (BasePath)
1746 BuildBasePathArray(Paths, *BasePath);
1747 return false;
1748 }
1749
1750 if (AmbigiousBaseConvID) {
1751 // We know that the derived-to-base conversion is ambiguous, and
1752 // we're going to produce a diagnostic. Perform the derived-to-base
1753 // search just one more time to compute all of the possible paths so
1754 // that we can print them out. This is more expensive than any of
1755 // the previous derived-to-base checks we've done, but at this point
1756 // performance isn't as much of an issue.
1757 Paths.clear();
1758 Paths.setRecordingPaths(true);
1759 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1760 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1761 (void)StillOkay;
1762
1763 // Build up a textual representation of the ambiguous paths, e.g.,
1764 // D -> B -> A, that will be used to illustrate the ambiguous
1765 // conversions in the diagnostic. We only print one of the paths
1766 // to each base class subobject.
1767 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1768
1769 Diag(Loc, AmbigiousBaseConvID)
1770 << Derived << Base << PathDisplayStr << Range << Name;
1771 }
1772 return true;
1773 }
1774
1775 bool
CheckDerivedToBaseConversion(QualType Derived,QualType Base,SourceLocation Loc,SourceRange Range,CXXCastPath * BasePath,bool IgnoreAccess)1776 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1777 SourceLocation Loc, SourceRange Range,
1778 CXXCastPath *BasePath,
1779 bool IgnoreAccess) {
1780 return CheckDerivedToBaseConversion(Derived, Base,
1781 IgnoreAccess ? 0
1782 : diag::err_upcast_to_inaccessible_base,
1783 diag::err_ambiguous_derived_to_base_conv,
1784 Loc, Range, DeclarationName(),
1785 BasePath);
1786 }
1787
1788
1789 /// @brief Builds a string representing ambiguous paths from a
1790 /// specific derived class to different subobjects of the same base
1791 /// class.
1792 ///
1793 /// This function builds a string that can be used in error messages
1794 /// to show the different paths that one can take through the
1795 /// inheritance hierarchy to go from the derived class to different
1796 /// subobjects of a base class. The result looks something like this:
1797 /// @code
1798 /// struct D -> struct B -> struct A
1799 /// struct D -> struct C -> struct A
1800 /// @endcode
getAmbiguousPathsDisplayString(CXXBasePaths & Paths)1801 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1802 std::string PathDisplayStr;
1803 std::set<unsigned> DisplayedPaths;
1804 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1805 Path != Paths.end(); ++Path) {
1806 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1807 // We haven't displayed a path to this particular base
1808 // class subobject yet.
1809 PathDisplayStr += "\n ";
1810 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1811 for (CXXBasePath::const_iterator Element = Path->begin();
1812 Element != Path->end(); ++Element)
1813 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1814 }
1815 }
1816
1817 return PathDisplayStr;
1818 }
1819
1820 //===----------------------------------------------------------------------===//
1821 // C++ class member Handling
1822 //===----------------------------------------------------------------------===//
1823
1824 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
ActOnAccessSpecifier(AccessSpecifier Access,SourceLocation ASLoc,SourceLocation ColonLoc,AttributeList * Attrs)1825 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1826 SourceLocation ASLoc,
1827 SourceLocation ColonLoc,
1828 AttributeList *Attrs) {
1829 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1830 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1831 ASLoc, ColonLoc);
1832 CurContext->addHiddenDecl(ASDecl);
1833 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1834 }
1835
1836 /// CheckOverrideControl - Check C++11 override control semantics.
CheckOverrideControl(NamedDecl * D)1837 void Sema::CheckOverrideControl(NamedDecl *D) {
1838 if (D->isInvalidDecl())
1839 return;
1840
1841 // We only care about "override" and "final" declarations.
1842 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1843 return;
1844
1845 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1846
1847 // We can't check dependent instance methods.
1848 if (MD && MD->isInstance() &&
1849 (MD->getParent()->hasAnyDependentBases() ||
1850 MD->getType()->isDependentType()))
1851 return;
1852
1853 if (MD && !MD->isVirtual()) {
1854 // If we have a non-virtual method, check if if hides a virtual method.
1855 // (In that case, it's most likely the method has the wrong type.)
1856 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1857 FindHiddenVirtualMethods(MD, OverloadedMethods);
1858
1859 if (!OverloadedMethods.empty()) {
1860 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1861 Diag(OA->getLocation(),
1862 diag::override_keyword_hides_virtual_member_function)
1863 << "override" << (OverloadedMethods.size() > 1);
1864 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1865 Diag(FA->getLocation(),
1866 diag::override_keyword_hides_virtual_member_function)
1867 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1868 << (OverloadedMethods.size() > 1);
1869 }
1870 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1871 MD->setInvalidDecl();
1872 return;
1873 }
1874 // Fall through into the general case diagnostic.
1875 // FIXME: We might want to attempt typo correction here.
1876 }
1877
1878 if (!MD || !MD->isVirtual()) {
1879 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1880 Diag(OA->getLocation(),
1881 diag::override_keyword_only_allowed_on_virtual_member_functions)
1882 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1883 D->dropAttr<OverrideAttr>();
1884 }
1885 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1886 Diag(FA->getLocation(),
1887 diag::override_keyword_only_allowed_on_virtual_member_functions)
1888 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1889 << FixItHint::CreateRemoval(FA->getLocation());
1890 D->dropAttr<FinalAttr>();
1891 }
1892 return;
1893 }
1894
1895 // C++11 [class.virtual]p5:
1896 // If a function is marked with the virt-specifier override and
1897 // does not override a member function of a base class, the program is
1898 // ill-formed.
1899 bool HasOverriddenMethods =
1900 MD->begin_overridden_methods() != MD->end_overridden_methods();
1901 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1902 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1903 << MD->getDeclName();
1904 }
1905
DiagnoseAbsenceOfOverrideControl(NamedDecl * D)1906 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1907 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1908 return;
1909 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1910 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1911 isa<CXXDestructorDecl>(MD))
1912 return;
1913
1914 SourceLocation Loc = MD->getLocation();
1915 SourceLocation SpellingLoc = Loc;
1916 if (getSourceManager().isMacroArgExpansion(Loc))
1917 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1918 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1919 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
1920 return;
1921
1922 if (MD->size_overridden_methods() > 0) {
1923 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1924 << MD->getDeclName();
1925 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1926 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1927 }
1928 }
1929
1930 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1931 /// function overrides a virtual member function marked 'final', according to
1932 /// C++11 [class.virtual]p4.
CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl * New,const CXXMethodDecl * Old)1933 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1934 const CXXMethodDecl *Old) {
1935 FinalAttr *FA = Old->getAttr<FinalAttr>();
1936 if (!FA)
1937 return false;
1938
1939 Diag(New->getLocation(), diag::err_final_function_overridden)
1940 << New->getDeclName()
1941 << FA->isSpelledAsSealed();
1942 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1943 return true;
1944 }
1945
InitializationHasSideEffects(const FieldDecl & FD)1946 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1947 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1948 // FIXME: Destruction of ObjC lifetime types has side-effects.
1949 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1950 return !RD->isCompleteDefinition() ||
1951 !RD->hasTrivialDefaultConstructor() ||
1952 !RD->hasTrivialDestructor();
1953 return false;
1954 }
1955
getMSPropertyAttr(AttributeList * list)1956 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1957 for (AttributeList *it = list; it != nullptr; it = it->getNext())
1958 if (it->isDeclspecPropertyAttribute())
1959 return it;
1960 return nullptr;
1961 }
1962
1963 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1964 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1965 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1966 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1967 /// present (but parsing it has been deferred).
1968 NamedDecl *
ActOnCXXMemberDeclarator(Scope * S,AccessSpecifier AS,Declarator & D,MultiTemplateParamsArg TemplateParameterLists,Expr * BW,const VirtSpecifiers & VS,InClassInitStyle InitStyle)1969 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1970 MultiTemplateParamsArg TemplateParameterLists,
1971 Expr *BW, const VirtSpecifiers &VS,
1972 InClassInitStyle InitStyle) {
1973 const DeclSpec &DS = D.getDeclSpec();
1974 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1975 DeclarationName Name = NameInfo.getName();
1976 SourceLocation Loc = NameInfo.getLoc();
1977
1978 // For anonymous bitfields, the location should point to the type.
1979 if (Loc.isInvalid())
1980 Loc = D.getLocStart();
1981
1982 Expr *BitWidth = static_cast<Expr*>(BW);
1983
1984 assert(isa<CXXRecordDecl>(CurContext));
1985 assert(!DS.isFriendSpecified());
1986
1987 bool isFunc = D.isDeclarationOfFunction();
1988
1989 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1990 // The Microsoft extension __interface only permits public member functions
1991 // and prohibits constructors, destructors, operators, non-public member
1992 // functions, static methods and data members.
1993 unsigned InvalidDecl;
1994 bool ShowDeclName = true;
1995 if (!isFunc)
1996 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1997 else if (AS != AS_public)
1998 InvalidDecl = 2;
1999 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2000 InvalidDecl = 3;
2001 else switch (Name.getNameKind()) {
2002 case DeclarationName::CXXConstructorName:
2003 InvalidDecl = 4;
2004 ShowDeclName = false;
2005 break;
2006
2007 case DeclarationName::CXXDestructorName:
2008 InvalidDecl = 5;
2009 ShowDeclName = false;
2010 break;
2011
2012 case DeclarationName::CXXOperatorName:
2013 case DeclarationName::CXXConversionFunctionName:
2014 InvalidDecl = 6;
2015 break;
2016
2017 default:
2018 InvalidDecl = 0;
2019 break;
2020 }
2021
2022 if (InvalidDecl) {
2023 if (ShowDeclName)
2024 Diag(Loc, diag::err_invalid_member_in_interface)
2025 << (InvalidDecl-1) << Name;
2026 else
2027 Diag(Loc, diag::err_invalid_member_in_interface)
2028 << (InvalidDecl-1) << "";
2029 return nullptr;
2030 }
2031 }
2032
2033 // C++ 9.2p6: A member shall not be declared to have automatic storage
2034 // duration (auto, register) or with the extern storage-class-specifier.
2035 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2036 // data members and cannot be applied to names declared const or static,
2037 // and cannot be applied to reference members.
2038 switch (DS.getStorageClassSpec()) {
2039 case DeclSpec::SCS_unspecified:
2040 case DeclSpec::SCS_typedef:
2041 case DeclSpec::SCS_static:
2042 break;
2043 case DeclSpec::SCS_mutable:
2044 if (isFunc) {
2045 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2046
2047 // FIXME: It would be nicer if the keyword was ignored only for this
2048 // declarator. Otherwise we could get follow-up errors.
2049 D.getMutableDeclSpec().ClearStorageClassSpecs();
2050 }
2051 break;
2052 default:
2053 Diag(DS.getStorageClassSpecLoc(),
2054 diag::err_storageclass_invalid_for_member);
2055 D.getMutableDeclSpec().ClearStorageClassSpecs();
2056 break;
2057 }
2058
2059 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2060 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2061 !isFunc);
2062
2063 if (DS.isConstexprSpecified() && isInstField) {
2064 SemaDiagnosticBuilder B =
2065 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2066 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2067 if (InitStyle == ICIS_NoInit) {
2068 B << 0 << 0;
2069 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2070 B << FixItHint::CreateRemoval(ConstexprLoc);
2071 else {
2072 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2073 D.getMutableDeclSpec().ClearConstexprSpec();
2074 const char *PrevSpec;
2075 unsigned DiagID;
2076 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2077 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2078 (void)Failed;
2079 assert(!Failed && "Making a constexpr member const shouldn't fail");
2080 }
2081 } else {
2082 B << 1;
2083 const char *PrevSpec;
2084 unsigned DiagID;
2085 if (D.getMutableDeclSpec().SetStorageClassSpec(
2086 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2087 Context.getPrintingPolicy())) {
2088 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2089 "This is the only DeclSpec that should fail to be applied");
2090 B << 1;
2091 } else {
2092 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2093 isInstField = false;
2094 }
2095 }
2096 }
2097
2098 NamedDecl *Member;
2099 if (isInstField) {
2100 CXXScopeSpec &SS = D.getCXXScopeSpec();
2101
2102 // Data members must have identifiers for names.
2103 if (!Name.isIdentifier()) {
2104 Diag(Loc, diag::err_bad_variable_name)
2105 << Name;
2106 return nullptr;
2107 }
2108
2109 IdentifierInfo *II = Name.getAsIdentifierInfo();
2110
2111 // Member field could not be with "template" keyword.
2112 // So TemplateParameterLists should be empty in this case.
2113 if (TemplateParameterLists.size()) {
2114 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2115 if (TemplateParams->size()) {
2116 // There is no such thing as a member field template.
2117 Diag(D.getIdentifierLoc(), diag::err_template_member)
2118 << II
2119 << SourceRange(TemplateParams->getTemplateLoc(),
2120 TemplateParams->getRAngleLoc());
2121 } else {
2122 // There is an extraneous 'template<>' for this member.
2123 Diag(TemplateParams->getTemplateLoc(),
2124 diag::err_template_member_noparams)
2125 << II
2126 << SourceRange(TemplateParams->getTemplateLoc(),
2127 TemplateParams->getRAngleLoc());
2128 }
2129 return nullptr;
2130 }
2131
2132 if (SS.isSet() && !SS.isInvalid()) {
2133 // The user provided a superfluous scope specifier inside a class
2134 // definition:
2135 //
2136 // class X {
2137 // int X::member;
2138 // };
2139 if (DeclContext *DC = computeDeclContext(SS, false))
2140 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2141 else
2142 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2143 << Name << SS.getRange();
2144
2145 SS.clear();
2146 }
2147
2148 AttributeList *MSPropertyAttr =
2149 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2150 if (MSPropertyAttr) {
2151 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2152 BitWidth, InitStyle, AS, MSPropertyAttr);
2153 if (!Member)
2154 return nullptr;
2155 isInstField = false;
2156 } else {
2157 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2158 BitWidth, InitStyle, AS);
2159 assert(Member && "HandleField never returns null");
2160 }
2161 } else {
2162 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2163
2164 Member = HandleDeclarator(S, D, TemplateParameterLists);
2165 if (!Member)
2166 return nullptr;
2167
2168 // Non-instance-fields can't have a bitfield.
2169 if (BitWidth) {
2170 if (Member->isInvalidDecl()) {
2171 // don't emit another diagnostic.
2172 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2173 // C++ 9.6p3: A bit-field shall not be a static member.
2174 // "static member 'A' cannot be a bit-field"
2175 Diag(Loc, diag::err_static_not_bitfield)
2176 << Name << BitWidth->getSourceRange();
2177 } else if (isa<TypedefDecl>(Member)) {
2178 // "typedef member 'x' cannot be a bit-field"
2179 Diag(Loc, diag::err_typedef_not_bitfield)
2180 << Name << BitWidth->getSourceRange();
2181 } else {
2182 // A function typedef ("typedef int f(); f a;").
2183 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2184 Diag(Loc, diag::err_not_integral_type_bitfield)
2185 << Name << cast<ValueDecl>(Member)->getType()
2186 << BitWidth->getSourceRange();
2187 }
2188
2189 BitWidth = nullptr;
2190 Member->setInvalidDecl();
2191 }
2192
2193 Member->setAccess(AS);
2194
2195 // If we have declared a member function template or static data member
2196 // template, set the access of the templated declaration as well.
2197 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2198 FunTmpl->getTemplatedDecl()->setAccess(AS);
2199 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2200 VarTmpl->getTemplatedDecl()->setAccess(AS);
2201 }
2202
2203 if (VS.isOverrideSpecified())
2204 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2205 if (VS.isFinalSpecified())
2206 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2207 VS.isFinalSpelledSealed()));
2208
2209 if (VS.getLastLocation().isValid()) {
2210 // Update the end location of a method that has a virt-specifiers.
2211 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2212 MD->setRangeEnd(VS.getLastLocation());
2213 }
2214
2215 CheckOverrideControl(Member);
2216
2217 assert((Name || isInstField) && "No identifier for non-field ?");
2218
2219 if (isInstField) {
2220 FieldDecl *FD = cast<FieldDecl>(Member);
2221 FieldCollector->Add(FD);
2222
2223 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2224 // Remember all explicit private FieldDecls that have a name, no side
2225 // effects and are not part of a dependent type declaration.
2226 if (!FD->isImplicit() && FD->getDeclName() &&
2227 FD->getAccess() == AS_private &&
2228 !FD->hasAttr<UnusedAttr>() &&
2229 !FD->getParent()->isDependentContext() &&
2230 !InitializationHasSideEffects(*FD))
2231 UnusedPrivateFields.insert(FD);
2232 }
2233 }
2234
2235 return Member;
2236 }
2237
2238 namespace {
2239 class UninitializedFieldVisitor
2240 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2241 Sema &S;
2242 // List of Decls to generate a warning on. Also remove Decls that become
2243 // initialized.
2244 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2245 // List of base classes of the record. Classes are removed after their
2246 // initializers.
2247 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
2248 // Vector of decls to be removed from the Decl set prior to visiting the
2249 // nodes. These Decls may have been initialized in the prior initializer.
2250 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
2251 // If non-null, add a note to the warning pointing back to the constructor.
2252 const CXXConstructorDecl *Constructor;
2253 // Variables to hold state when processing an initializer list. When
2254 // InitList is true, special case initialization of FieldDecls matching
2255 // InitListFieldDecl.
2256 bool InitList;
2257 FieldDecl *InitListFieldDecl;
2258 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2259
2260 public:
2261 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
UninitializedFieldVisitor(Sema & S,llvm::SmallPtrSetImpl<ValueDecl * > & Decls,llvm::SmallPtrSetImpl<QualType> & BaseClasses)2262 UninitializedFieldVisitor(Sema &S,
2263 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2264 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2265 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2266 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
2267
2268 // Returns true if the use of ME is not an uninitialized use.
IsInitListMemberExprInitialized(MemberExpr * ME,bool CheckReferenceOnly)2269 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2270 bool CheckReferenceOnly) {
2271 llvm::SmallVector<FieldDecl*, 4> Fields;
2272 bool ReferenceField = false;
2273 while (ME) {
2274 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2275 if (!FD)
2276 return false;
2277 Fields.push_back(FD);
2278 if (FD->getType()->isReferenceType())
2279 ReferenceField = true;
2280 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2281 }
2282
2283 // Binding a reference to an unintialized field is not an
2284 // uninitialized use.
2285 if (CheckReferenceOnly && !ReferenceField)
2286 return true;
2287
2288 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2289 // Discard the first field since it is the field decl that is being
2290 // initialized.
2291 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2292 UsedFieldIndex.push_back((*I)->getFieldIndex());
2293 }
2294
2295 for (auto UsedIter = UsedFieldIndex.begin(),
2296 UsedEnd = UsedFieldIndex.end(),
2297 OrigIter = InitFieldIndex.begin(),
2298 OrigEnd = InitFieldIndex.end();
2299 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2300 if (*UsedIter < *OrigIter)
2301 return true;
2302 if (*UsedIter > *OrigIter)
2303 break;
2304 }
2305
2306 return false;
2307 }
2308
HandleMemberExpr(MemberExpr * ME,bool CheckReferenceOnly,bool AddressOf)2309 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2310 bool AddressOf) {
2311 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2312 return;
2313
2314 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2315 // or union.
2316 MemberExpr *FieldME = ME;
2317
2318 bool AllPODFields = FieldME->getType().isPODType(S.Context);
2319
2320 Expr *Base = ME;
2321 while (MemberExpr *SubME =
2322 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
2323
2324 if (isa<VarDecl>(SubME->getMemberDecl()))
2325 return;
2326
2327 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
2328 if (!FD->isAnonymousStructOrUnion())
2329 FieldME = SubME;
2330
2331 if (!FieldME->getType().isPODType(S.Context))
2332 AllPODFields = false;
2333
2334 Base = SubME->getBase();
2335 }
2336
2337 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
2338 return;
2339
2340 if (AddressOf && AllPODFields)
2341 return;
2342
2343 ValueDecl* FoundVD = FieldME->getMemberDecl();
2344
2345 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2346 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2347 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2348 }
2349
2350 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2351 QualType T = BaseCast->getType();
2352 if (T->isPointerType() &&
2353 BaseClasses.count(T->getPointeeType())) {
2354 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2355 << T->getPointeeType() << FoundVD;
2356 }
2357 }
2358 }
2359
2360 if (!Decls.count(FoundVD))
2361 return;
2362
2363 const bool IsReference = FoundVD->getType()->isReferenceType();
2364
2365 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2366 // Special checking for initializer lists.
2367 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2368 return;
2369 }
2370 } else {
2371 // Prevent double warnings on use of unbounded references.
2372 if (CheckReferenceOnly && !IsReference)
2373 return;
2374 }
2375
2376 unsigned diag = IsReference
2377 ? diag::warn_reference_field_is_uninit
2378 : diag::warn_field_is_uninit;
2379 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2380 if (Constructor)
2381 S.Diag(Constructor->getLocation(),
2382 diag::note_uninit_in_this_constructor)
2383 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2384
2385 }
2386
HandleValue(Expr * E,bool AddressOf)2387 void HandleValue(Expr *E, bool AddressOf) {
2388 E = E->IgnoreParens();
2389
2390 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2391 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2392 AddressOf /*AddressOf*/);
2393 return;
2394 }
2395
2396 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2397 Visit(CO->getCond());
2398 HandleValue(CO->getTrueExpr(), AddressOf);
2399 HandleValue(CO->getFalseExpr(), AddressOf);
2400 return;
2401 }
2402
2403 if (BinaryConditionalOperator *BCO =
2404 dyn_cast<BinaryConditionalOperator>(E)) {
2405 Visit(BCO->getCond());
2406 HandleValue(BCO->getFalseExpr(), AddressOf);
2407 return;
2408 }
2409
2410 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2411 HandleValue(OVE->getSourceExpr(), AddressOf);
2412 return;
2413 }
2414
2415 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2416 switch (BO->getOpcode()) {
2417 default:
2418 break;
2419 case(BO_PtrMemD):
2420 case(BO_PtrMemI):
2421 HandleValue(BO->getLHS(), AddressOf);
2422 Visit(BO->getRHS());
2423 return;
2424 case(BO_Comma):
2425 Visit(BO->getLHS());
2426 HandleValue(BO->getRHS(), AddressOf);
2427 return;
2428 }
2429 }
2430
2431 Visit(E);
2432 }
2433
CheckInitListExpr(InitListExpr * ILE)2434 void CheckInitListExpr(InitListExpr *ILE) {
2435 InitFieldIndex.push_back(0);
2436 for (auto Child : ILE->children()) {
2437 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2438 CheckInitListExpr(SubList);
2439 } else {
2440 Visit(Child);
2441 }
2442 ++InitFieldIndex.back();
2443 }
2444 InitFieldIndex.pop_back();
2445 }
2446
CheckInitializer(Expr * E,const CXXConstructorDecl * FieldConstructor,FieldDecl * Field,const Type * BaseClass)2447 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2448 FieldDecl *Field, const Type *BaseClass) {
2449 // Remove Decls that may have been initialized in the previous
2450 // initializer.
2451 for (ValueDecl* VD : DeclsToRemove)
2452 Decls.erase(VD);
2453 DeclsToRemove.clear();
2454
2455 Constructor = FieldConstructor;
2456 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2457
2458 if (ILE && Field) {
2459 InitList = true;
2460 InitListFieldDecl = Field;
2461 InitFieldIndex.clear();
2462 CheckInitListExpr(ILE);
2463 } else {
2464 InitList = false;
2465 Visit(E);
2466 }
2467
2468 if (Field)
2469 Decls.erase(Field);
2470 if (BaseClass)
2471 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
2472 }
2473
VisitMemberExpr(MemberExpr * ME)2474 void VisitMemberExpr(MemberExpr *ME) {
2475 // All uses of unbounded reference fields will warn.
2476 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
2477 }
2478
VisitImplicitCastExpr(ImplicitCastExpr * E)2479 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2480 if (E->getCastKind() == CK_LValueToRValue) {
2481 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2482 return;
2483 }
2484
2485 Inherited::VisitImplicitCastExpr(E);
2486 }
2487
VisitCXXConstructExpr(CXXConstructExpr * E)2488 void VisitCXXConstructExpr(CXXConstructExpr *E) {
2489 if (E->getConstructor()->isCopyConstructor()) {
2490 Expr *ArgExpr = E->getArg(0);
2491 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2492 if (ILE->getNumInits() == 1)
2493 ArgExpr = ILE->getInit(0);
2494 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2495 if (ICE->getCastKind() == CK_NoOp)
2496 ArgExpr = ICE->getSubExpr();
2497 HandleValue(ArgExpr, false /*AddressOf*/);
2498 return;
2499 }
2500 Inherited::VisitCXXConstructExpr(E);
2501 }
2502
VisitCXXMemberCallExpr(CXXMemberCallExpr * E)2503 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2504 Expr *Callee = E->getCallee();
2505 if (isa<MemberExpr>(Callee)) {
2506 HandleValue(Callee, false /*AddressOf*/);
2507 for (auto Arg : E->arguments())
2508 Visit(Arg);
2509 return;
2510 }
2511
2512 Inherited::VisitCXXMemberCallExpr(E);
2513 }
2514
VisitCallExpr(CallExpr * E)2515 void VisitCallExpr(CallExpr *E) {
2516 // Treat std::move as a use.
2517 if (E->getNumArgs() == 1) {
2518 if (FunctionDecl *FD = E->getDirectCallee()) {
2519 if (FD->isInStdNamespace() && FD->getIdentifier() &&
2520 FD->getIdentifier()->isStr("move")) {
2521 HandleValue(E->getArg(0), false /*AddressOf*/);
2522 return;
2523 }
2524 }
2525 }
2526
2527 Inherited::VisitCallExpr(E);
2528 }
2529
VisitCXXOperatorCallExpr(CXXOperatorCallExpr * E)2530 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2531 Expr *Callee = E->getCallee();
2532
2533 if (isa<UnresolvedLookupExpr>(Callee))
2534 return Inherited::VisitCXXOperatorCallExpr(E);
2535
2536 Visit(Callee);
2537 for (auto Arg : E->arguments())
2538 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2539 }
2540
VisitBinaryOperator(BinaryOperator * E)2541 void VisitBinaryOperator(BinaryOperator *E) {
2542 // If a field assignment is detected, remove the field from the
2543 // uninitiailized field set.
2544 if (E->getOpcode() == BO_Assign)
2545 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2546 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2547 if (!FD->getType()->isReferenceType())
2548 DeclsToRemove.push_back(FD);
2549
2550 if (E->isCompoundAssignmentOp()) {
2551 HandleValue(E->getLHS(), false /*AddressOf*/);
2552 Visit(E->getRHS());
2553 return;
2554 }
2555
2556 Inherited::VisitBinaryOperator(E);
2557 }
2558
VisitUnaryOperator(UnaryOperator * E)2559 void VisitUnaryOperator(UnaryOperator *E) {
2560 if (E->isIncrementDecrementOp()) {
2561 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2562 return;
2563 }
2564 if (E->getOpcode() == UO_AddrOf) {
2565 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2566 HandleValue(ME->getBase(), true /*AddressOf*/);
2567 return;
2568 }
2569 }
2570
2571 Inherited::VisitUnaryOperator(E);
2572 }
2573 };
2574
2575 // Diagnose value-uses of fields to initialize themselves, e.g.
2576 // foo(foo)
2577 // where foo is not also a parameter to the constructor.
2578 // Also diagnose across field uninitialized use such as
2579 // x(y), y(x)
2580 // TODO: implement -Wuninitialized and fold this into that framework.
DiagnoseUninitializedFields(Sema & SemaRef,const CXXConstructorDecl * Constructor)2581 static void DiagnoseUninitializedFields(
2582 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2583
2584 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2585 Constructor->getLocation())) {
2586 return;
2587 }
2588
2589 if (Constructor->isInvalidDecl())
2590 return;
2591
2592 const CXXRecordDecl *RD = Constructor->getParent();
2593
2594 if (RD->getDescribedClassTemplate())
2595 return;
2596
2597 // Holds fields that are uninitialized.
2598 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2599
2600 // At the beginning, all fields are uninitialized.
2601 for (auto *I : RD->decls()) {
2602 if (auto *FD = dyn_cast<FieldDecl>(I)) {
2603 UninitializedFields.insert(FD);
2604 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2605 UninitializedFields.insert(IFD->getAnonField());
2606 }
2607 }
2608
2609 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2610 for (auto I : RD->bases())
2611 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2612
2613 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2614 return;
2615
2616 UninitializedFieldVisitor UninitializedChecker(SemaRef,
2617 UninitializedFields,
2618 UninitializedBaseClasses);
2619
2620 for (const auto *FieldInit : Constructor->inits()) {
2621 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2622 break;
2623
2624 Expr *InitExpr = FieldInit->getInit();
2625 if (!InitExpr)
2626 continue;
2627
2628 if (CXXDefaultInitExpr *Default =
2629 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2630 InitExpr = Default->getExpr();
2631 if (!InitExpr)
2632 continue;
2633 // In class initializers will point to the constructor.
2634 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2635 FieldInit->getAnyMember(),
2636 FieldInit->getBaseClass());
2637 } else {
2638 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2639 FieldInit->getAnyMember(),
2640 FieldInit->getBaseClass());
2641 }
2642 }
2643 }
2644 } // namespace
2645
2646 /// \brief Enter a new C++ default initializer scope. After calling this, the
2647 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2648 /// parsing or instantiating the initializer failed.
ActOnStartCXXInClassMemberInitializer()2649 void Sema::ActOnStartCXXInClassMemberInitializer() {
2650 // Create a synthetic function scope to represent the call to the constructor
2651 // that notionally surrounds a use of this initializer.
2652 PushFunctionScope();
2653 }
2654
2655 /// \brief This is invoked after parsing an in-class initializer for a
2656 /// non-static C++ class member, and after instantiating an in-class initializer
2657 /// in a class template. Such actions are deferred until the class is complete.
ActOnFinishCXXInClassMemberInitializer(Decl * D,SourceLocation InitLoc,Expr * InitExpr)2658 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2659 SourceLocation InitLoc,
2660 Expr *InitExpr) {
2661 // Pop the notional constructor scope we created earlier.
2662 PopFunctionScopeInfo(nullptr, D);
2663
2664 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2665 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
2666 "must set init style when field is created");
2667
2668 if (!InitExpr) {
2669 D->setInvalidDecl();
2670 if (FD)
2671 FD->removeInClassInitializer();
2672 return;
2673 }
2674
2675 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2676 FD->setInvalidDecl();
2677 FD->removeInClassInitializer();
2678 return;
2679 }
2680
2681 ExprResult Init = InitExpr;
2682 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2683 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2684 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2685 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2686 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2687 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2688 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2689 if (Init.isInvalid()) {
2690 FD->setInvalidDecl();
2691 return;
2692 }
2693 }
2694
2695 // C++11 [class.base.init]p7:
2696 // The initialization of each base and member constitutes a
2697 // full-expression.
2698 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2699 if (Init.isInvalid()) {
2700 FD->setInvalidDecl();
2701 return;
2702 }
2703
2704 InitExpr = Init.get();
2705
2706 FD->setInClassInitializer(InitExpr);
2707 }
2708
2709 /// \brief Find the direct and/or virtual base specifiers that
2710 /// correspond to the given base type, for use in base initialization
2711 /// within a constructor.
FindBaseInitializer(Sema & SemaRef,CXXRecordDecl * ClassDecl,QualType BaseType,const CXXBaseSpecifier * & DirectBaseSpec,const CXXBaseSpecifier * & VirtualBaseSpec)2712 static bool FindBaseInitializer(Sema &SemaRef,
2713 CXXRecordDecl *ClassDecl,
2714 QualType BaseType,
2715 const CXXBaseSpecifier *&DirectBaseSpec,
2716 const CXXBaseSpecifier *&VirtualBaseSpec) {
2717 // First, check for a direct base class.
2718 DirectBaseSpec = nullptr;
2719 for (const auto &Base : ClassDecl->bases()) {
2720 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2721 // We found a direct base of this type. That's what we're
2722 // initializing.
2723 DirectBaseSpec = &Base;
2724 break;
2725 }
2726 }
2727
2728 // Check for a virtual base class.
2729 // FIXME: We might be able to short-circuit this if we know in advance that
2730 // there are no virtual bases.
2731 VirtualBaseSpec = nullptr;
2732 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2733 // We haven't found a base yet; search the class hierarchy for a
2734 // virtual base class.
2735 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2736 /*DetectVirtual=*/false);
2737 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2738 BaseType, Paths)) {
2739 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2740 Path != Paths.end(); ++Path) {
2741 if (Path->back().Base->isVirtual()) {
2742 VirtualBaseSpec = Path->back().Base;
2743 break;
2744 }
2745 }
2746 }
2747 }
2748
2749 return DirectBaseSpec || VirtualBaseSpec;
2750 }
2751
2752 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2753 MemInitResult
ActOnMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,Expr * InitList,SourceLocation EllipsisLoc)2754 Sema::ActOnMemInitializer(Decl *ConstructorD,
2755 Scope *S,
2756 CXXScopeSpec &SS,
2757 IdentifierInfo *MemberOrBase,
2758 ParsedType TemplateTypeTy,
2759 const DeclSpec &DS,
2760 SourceLocation IdLoc,
2761 Expr *InitList,
2762 SourceLocation EllipsisLoc) {
2763 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2764 DS, IdLoc, InitList,
2765 EllipsisLoc);
2766 }
2767
2768 /// \brief Handle a C++ member initializer using parentheses syntax.
2769 MemInitResult
ActOnMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,SourceLocation LParenLoc,ArrayRef<Expr * > Args,SourceLocation RParenLoc,SourceLocation EllipsisLoc)2770 Sema::ActOnMemInitializer(Decl *ConstructorD,
2771 Scope *S,
2772 CXXScopeSpec &SS,
2773 IdentifierInfo *MemberOrBase,
2774 ParsedType TemplateTypeTy,
2775 const DeclSpec &DS,
2776 SourceLocation IdLoc,
2777 SourceLocation LParenLoc,
2778 ArrayRef<Expr *> Args,
2779 SourceLocation RParenLoc,
2780 SourceLocation EllipsisLoc) {
2781 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2782 Args, RParenLoc);
2783 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2784 DS, IdLoc, List, EllipsisLoc);
2785 }
2786
2787 namespace {
2788
2789 // Callback to only accept typo corrections that can be a valid C++ member
2790 // intializer: either a non-static field member or a base class.
2791 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2792 public:
MemInitializerValidatorCCC(CXXRecordDecl * ClassDecl)2793 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2794 : ClassDecl(ClassDecl) {}
2795
ValidateCandidate(const TypoCorrection & candidate)2796 bool ValidateCandidate(const TypoCorrection &candidate) override {
2797 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2798 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2799 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2800 return isa<TypeDecl>(ND);
2801 }
2802 return false;
2803 }
2804
2805 private:
2806 CXXRecordDecl *ClassDecl;
2807 };
2808
2809 }
2810
2811 /// \brief Handle a C++ member initializer.
2812 MemInitResult
BuildMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,Expr * Init,SourceLocation EllipsisLoc)2813 Sema::BuildMemInitializer(Decl *ConstructorD,
2814 Scope *S,
2815 CXXScopeSpec &SS,
2816 IdentifierInfo *MemberOrBase,
2817 ParsedType TemplateTypeTy,
2818 const DeclSpec &DS,
2819 SourceLocation IdLoc,
2820 Expr *Init,
2821 SourceLocation EllipsisLoc) {
2822 ExprResult Res = CorrectDelayedTyposInExpr(Init);
2823 if (!Res.isUsable())
2824 return true;
2825 Init = Res.get();
2826
2827 if (!ConstructorD)
2828 return true;
2829
2830 AdjustDeclIfTemplate(ConstructorD);
2831
2832 CXXConstructorDecl *Constructor
2833 = dyn_cast<CXXConstructorDecl>(ConstructorD);
2834 if (!Constructor) {
2835 // The user wrote a constructor initializer on a function that is
2836 // not a C++ constructor. Ignore the error for now, because we may
2837 // have more member initializers coming; we'll diagnose it just
2838 // once in ActOnMemInitializers.
2839 return true;
2840 }
2841
2842 CXXRecordDecl *ClassDecl = Constructor->getParent();
2843
2844 // C++ [class.base.init]p2:
2845 // Names in a mem-initializer-id are looked up in the scope of the
2846 // constructor's class and, if not found in that scope, are looked
2847 // up in the scope containing the constructor's definition.
2848 // [Note: if the constructor's class contains a member with the
2849 // same name as a direct or virtual base class of the class, a
2850 // mem-initializer-id naming the member or base class and composed
2851 // of a single identifier refers to the class member. A
2852 // mem-initializer-id for the hidden base class may be specified
2853 // using a qualified name. ]
2854 if (!SS.getScopeRep() && !TemplateTypeTy) {
2855 // Look for a member, first.
2856 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
2857 if (!Result.empty()) {
2858 ValueDecl *Member;
2859 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2860 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2861 if (EllipsisLoc.isValid())
2862 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2863 << MemberOrBase
2864 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2865
2866 return BuildMemberInitializer(Member, Init, IdLoc);
2867 }
2868 }
2869 }
2870 // It didn't name a member, so see if it names a class.
2871 QualType BaseType;
2872 TypeSourceInfo *TInfo = nullptr;
2873
2874 if (TemplateTypeTy) {
2875 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2876 } else if (DS.getTypeSpecType() == TST_decltype) {
2877 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2878 } else {
2879 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2880 LookupParsedName(R, S, &SS);
2881
2882 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2883 if (!TyD) {
2884 if (R.isAmbiguous()) return true;
2885
2886 // We don't want access-control diagnostics here.
2887 R.suppressDiagnostics();
2888
2889 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2890 bool NotUnknownSpecialization = false;
2891 DeclContext *DC = computeDeclContext(SS, false);
2892 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2893 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2894
2895 if (!NotUnknownSpecialization) {
2896 // When the scope specifier can refer to a member of an unknown
2897 // specialization, we take it as a type name.
2898 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2899 SS.getWithLocInContext(Context),
2900 *MemberOrBase, IdLoc);
2901 if (BaseType.isNull())
2902 return true;
2903
2904 R.clear();
2905 R.setLookupName(MemberOrBase);
2906 }
2907 }
2908
2909 // If no results were found, try to correct typos.
2910 TypoCorrection Corr;
2911 if (R.empty() && BaseType.isNull() &&
2912 (Corr = CorrectTypo(
2913 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2914 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2915 CTK_ErrorRecovery, ClassDecl))) {
2916 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2917 // We have found a non-static data member with a similar
2918 // name to what was typed; complain and initialize that
2919 // member.
2920 diagnoseTypo(Corr,
2921 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2922 << MemberOrBase << true);
2923 return BuildMemberInitializer(Member, Init, IdLoc);
2924 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2925 const CXXBaseSpecifier *DirectBaseSpec;
2926 const CXXBaseSpecifier *VirtualBaseSpec;
2927 if (FindBaseInitializer(*this, ClassDecl,
2928 Context.getTypeDeclType(Type),
2929 DirectBaseSpec, VirtualBaseSpec)) {
2930 // We have found a direct or virtual base class with a
2931 // similar name to what was typed; complain and initialize
2932 // that base class.
2933 diagnoseTypo(Corr,
2934 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2935 << MemberOrBase << false,
2936 PDiag() /*Suppress note, we provide our own.*/);
2937
2938 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2939 : VirtualBaseSpec;
2940 Diag(BaseSpec->getLocStart(),
2941 diag::note_base_class_specified_here)
2942 << BaseSpec->getType()
2943 << BaseSpec->getSourceRange();
2944
2945 TyD = Type;
2946 }
2947 }
2948 }
2949
2950 if (!TyD && BaseType.isNull()) {
2951 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2952 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2953 return true;
2954 }
2955 }
2956
2957 if (BaseType.isNull()) {
2958 BaseType = Context.getTypeDeclType(TyD);
2959 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
2960 if (SS.isSet())
2961 // FIXME: preserve source range information
2962 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2963 BaseType);
2964 }
2965 }
2966
2967 if (!TInfo)
2968 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2969
2970 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2971 }
2972
2973 /// Checks a member initializer expression for cases where reference (or
2974 /// pointer) members are bound to by-value parameters (or their addresses).
CheckForDanglingReferenceOrPointer(Sema & S,ValueDecl * Member,Expr * Init,SourceLocation IdLoc)2975 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2976 Expr *Init,
2977 SourceLocation IdLoc) {
2978 QualType MemberTy = Member->getType();
2979
2980 // We only handle pointers and references currently.
2981 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2982 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2983 return;
2984
2985 const bool IsPointer = MemberTy->isPointerType();
2986 if (IsPointer) {
2987 if (const UnaryOperator *Op
2988 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2989 // The only case we're worried about with pointers requires taking the
2990 // address.
2991 if (Op->getOpcode() != UO_AddrOf)
2992 return;
2993
2994 Init = Op->getSubExpr();
2995 } else {
2996 // We only handle address-of expression initializers for pointers.
2997 return;
2998 }
2999 }
3000
3001 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3002 // We only warn when referring to a non-reference parameter declaration.
3003 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3004 if (!Parameter || Parameter->getType()->isReferenceType())
3005 return;
3006
3007 S.Diag(Init->getExprLoc(),
3008 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3009 : diag::warn_bind_ref_member_to_parameter)
3010 << Member << Parameter << Init->getSourceRange();
3011 } else {
3012 // Other initializers are fine.
3013 return;
3014 }
3015
3016 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3017 << (unsigned)IsPointer;
3018 }
3019
3020 MemInitResult
BuildMemberInitializer(ValueDecl * Member,Expr * Init,SourceLocation IdLoc)3021 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3022 SourceLocation IdLoc) {
3023 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3024 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3025 assert((DirectMember || IndirectMember) &&
3026 "Member must be a FieldDecl or IndirectFieldDecl");
3027
3028 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3029 return true;
3030
3031 if (Member->isInvalidDecl())
3032 return true;
3033
3034 MultiExprArg Args;
3035 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3036 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3037 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3038 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3039 } else {
3040 // Template instantiation doesn't reconstruct ParenListExprs for us.
3041 Args = Init;
3042 }
3043
3044 SourceRange InitRange = Init->getSourceRange();
3045
3046 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3047 // Can't check initialization for a member of dependent type or when
3048 // any of the arguments are type-dependent expressions.
3049 DiscardCleanupsInEvaluationContext();
3050 } else {
3051 bool InitList = false;
3052 if (isa<InitListExpr>(Init)) {
3053 InitList = true;
3054 Args = Init;
3055 }
3056
3057 // Initialize the member.
3058 InitializedEntity MemberEntity =
3059 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3060 : InitializedEntity::InitializeMember(IndirectMember,
3061 nullptr);
3062 InitializationKind Kind =
3063 InitList ? InitializationKind::CreateDirectList(IdLoc)
3064 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3065 InitRange.getEnd());
3066
3067 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3068 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3069 nullptr);
3070 if (MemberInit.isInvalid())
3071 return true;
3072
3073 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3074
3075 // C++11 [class.base.init]p7:
3076 // The initialization of each base and member constitutes a
3077 // full-expression.
3078 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3079 if (MemberInit.isInvalid())
3080 return true;
3081
3082 Init = MemberInit.get();
3083 }
3084
3085 if (DirectMember) {
3086 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3087 InitRange.getBegin(), Init,
3088 InitRange.getEnd());
3089 } else {
3090 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3091 InitRange.getBegin(), Init,
3092 InitRange.getEnd());
3093 }
3094 }
3095
3096 MemInitResult
BuildDelegatingInitializer(TypeSourceInfo * TInfo,Expr * Init,CXXRecordDecl * ClassDecl)3097 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3098 CXXRecordDecl *ClassDecl) {
3099 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3100 if (!LangOpts.CPlusPlus11)
3101 return Diag(NameLoc, diag::err_delegating_ctor)
3102 << TInfo->getTypeLoc().getLocalSourceRange();
3103 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3104
3105 bool InitList = true;
3106 MultiExprArg Args = Init;
3107 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3108 InitList = false;
3109 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3110 }
3111
3112 SourceRange InitRange = Init->getSourceRange();
3113 // Initialize the object.
3114 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3115 QualType(ClassDecl->getTypeForDecl(), 0));
3116 InitializationKind Kind =
3117 InitList ? InitializationKind::CreateDirectList(NameLoc)
3118 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3119 InitRange.getEnd());
3120 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3121 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3122 Args, nullptr);
3123 if (DelegationInit.isInvalid())
3124 return true;
3125
3126 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3127 "Delegating constructor with no target?");
3128
3129 // C++11 [class.base.init]p7:
3130 // The initialization of each base and member constitutes a
3131 // full-expression.
3132 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3133 InitRange.getBegin());
3134 if (DelegationInit.isInvalid())
3135 return true;
3136
3137 // If we are in a dependent context, template instantiation will
3138 // perform this type-checking again. Just save the arguments that we
3139 // received in a ParenListExpr.
3140 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3141 // of the information that we have about the base
3142 // initializer. However, deconstructing the ASTs is a dicey process,
3143 // and this approach is far more likely to get the corner cases right.
3144 if (CurContext->isDependentContext())
3145 DelegationInit = Init;
3146
3147 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3148 DelegationInit.getAs<Expr>(),
3149 InitRange.getEnd());
3150 }
3151
3152 MemInitResult
BuildBaseInitializer(QualType BaseType,TypeSourceInfo * BaseTInfo,Expr * Init,CXXRecordDecl * ClassDecl,SourceLocation EllipsisLoc)3153 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3154 Expr *Init, CXXRecordDecl *ClassDecl,
3155 SourceLocation EllipsisLoc) {
3156 SourceLocation BaseLoc
3157 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3158
3159 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3160 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3161 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3162
3163 // C++ [class.base.init]p2:
3164 // [...] Unless the mem-initializer-id names a nonstatic data
3165 // member of the constructor's class or a direct or virtual base
3166 // of that class, the mem-initializer is ill-formed. A
3167 // mem-initializer-list can initialize a base class using any
3168 // name that denotes that base class type.
3169 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3170
3171 SourceRange InitRange = Init->getSourceRange();
3172 if (EllipsisLoc.isValid()) {
3173 // This is a pack expansion.
3174 if (!BaseType->containsUnexpandedParameterPack()) {
3175 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3176 << SourceRange(BaseLoc, InitRange.getEnd());
3177
3178 EllipsisLoc = SourceLocation();
3179 }
3180 } else {
3181 // Check for any unexpanded parameter packs.
3182 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3183 return true;
3184
3185 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3186 return true;
3187 }
3188
3189 // Check for direct and virtual base classes.
3190 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3191 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3192 if (!Dependent) {
3193 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3194 BaseType))
3195 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3196
3197 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3198 VirtualBaseSpec);
3199
3200 // C++ [base.class.init]p2:
3201 // Unless the mem-initializer-id names a nonstatic data member of the
3202 // constructor's class or a direct or virtual base of that class, the
3203 // mem-initializer is ill-formed.
3204 if (!DirectBaseSpec && !VirtualBaseSpec) {
3205 // If the class has any dependent bases, then it's possible that
3206 // one of those types will resolve to the same type as
3207 // BaseType. Therefore, just treat this as a dependent base
3208 // class initialization. FIXME: Should we try to check the
3209 // initialization anyway? It seems odd.
3210 if (ClassDecl->hasAnyDependentBases())
3211 Dependent = true;
3212 else
3213 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3214 << BaseType << Context.getTypeDeclType(ClassDecl)
3215 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3216 }
3217 }
3218
3219 if (Dependent) {
3220 DiscardCleanupsInEvaluationContext();
3221
3222 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3223 /*IsVirtual=*/false,
3224 InitRange.getBegin(), Init,
3225 InitRange.getEnd(), EllipsisLoc);
3226 }
3227
3228 // C++ [base.class.init]p2:
3229 // If a mem-initializer-id is ambiguous because it designates both
3230 // a direct non-virtual base class and an inherited virtual base
3231 // class, the mem-initializer is ill-formed.
3232 if (DirectBaseSpec && VirtualBaseSpec)
3233 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3234 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3235
3236 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3237 if (!BaseSpec)
3238 BaseSpec = VirtualBaseSpec;
3239
3240 // Initialize the base.
3241 bool InitList = true;
3242 MultiExprArg Args = Init;
3243 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3244 InitList = false;
3245 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3246 }
3247
3248 InitializedEntity BaseEntity =
3249 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3250 InitializationKind Kind =
3251 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3252 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3253 InitRange.getEnd());
3254 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3255 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3256 if (BaseInit.isInvalid())
3257 return true;
3258
3259 // C++11 [class.base.init]p7:
3260 // The initialization of each base and member constitutes a
3261 // full-expression.
3262 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3263 if (BaseInit.isInvalid())
3264 return true;
3265
3266 // If we are in a dependent context, template instantiation will
3267 // perform this type-checking again. Just save the arguments that we
3268 // received in a ParenListExpr.
3269 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3270 // of the information that we have about the base
3271 // initializer. However, deconstructing the ASTs is a dicey process,
3272 // and this approach is far more likely to get the corner cases right.
3273 if (CurContext->isDependentContext())
3274 BaseInit = Init;
3275
3276 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3277 BaseSpec->isVirtual(),
3278 InitRange.getBegin(),
3279 BaseInit.getAs<Expr>(),
3280 InitRange.getEnd(), EllipsisLoc);
3281 }
3282
3283 // Create a static_cast\<T&&>(expr).
CastForMoving(Sema & SemaRef,Expr * E,QualType T=QualType ())3284 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3285 if (T.isNull()) T = E->getType();
3286 QualType TargetType = SemaRef.BuildReferenceType(
3287 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3288 SourceLocation ExprLoc = E->getLocStart();
3289 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3290 TargetType, ExprLoc);
3291
3292 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3293 SourceRange(ExprLoc, ExprLoc),
3294 E->getSourceRange()).get();
3295 }
3296
3297 /// ImplicitInitializerKind - How an implicit base or member initializer should
3298 /// initialize its base or member.
3299 enum ImplicitInitializerKind {
3300 IIK_Default,
3301 IIK_Copy,
3302 IIK_Move,
3303 IIK_Inherit
3304 };
3305
3306 static bool
BuildImplicitBaseInitializer(Sema & SemaRef,CXXConstructorDecl * Constructor,ImplicitInitializerKind ImplicitInitKind,CXXBaseSpecifier * BaseSpec,bool IsInheritedVirtualBase,CXXCtorInitializer * & CXXBaseInit)3307 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3308 ImplicitInitializerKind ImplicitInitKind,
3309 CXXBaseSpecifier *BaseSpec,
3310 bool IsInheritedVirtualBase,
3311 CXXCtorInitializer *&CXXBaseInit) {
3312 InitializedEntity InitEntity
3313 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3314 IsInheritedVirtualBase);
3315
3316 ExprResult BaseInit;
3317
3318 switch (ImplicitInitKind) {
3319 case IIK_Inherit: {
3320 const CXXRecordDecl *Inherited =
3321 Constructor->getInheritedConstructor()->getParent();
3322 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3323 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3324 // C++11 [class.inhctor]p8:
3325 // Each expression in the expression-list is of the form
3326 // static_cast<T&&>(p), where p is the name of the corresponding
3327 // constructor parameter and T is the declared type of p.
3328 SmallVector<Expr*, 16> Args;
3329 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3330 ParmVarDecl *PD = Constructor->getParamDecl(I);
3331 ExprResult ArgExpr =
3332 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3333 VK_LValue, SourceLocation());
3334 if (ArgExpr.isInvalid())
3335 return true;
3336 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3337 }
3338
3339 InitializationKind InitKind = InitializationKind::CreateDirect(
3340 Constructor->getLocation(), SourceLocation(), SourceLocation());
3341 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3342 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3343 break;
3344 }
3345 }
3346 // Fall through.
3347 case IIK_Default: {
3348 InitializationKind InitKind
3349 = InitializationKind::CreateDefault(Constructor->getLocation());
3350 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3351 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3352 break;
3353 }
3354
3355 case IIK_Move:
3356 case IIK_Copy: {
3357 bool Moving = ImplicitInitKind == IIK_Move;
3358 ParmVarDecl *Param = Constructor->getParamDecl(0);
3359 QualType ParamType = Param->getType().getNonReferenceType();
3360
3361 Expr *CopyCtorArg =
3362 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3363 SourceLocation(), Param, false,
3364 Constructor->getLocation(), ParamType,
3365 VK_LValue, nullptr);
3366
3367 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3368
3369 // Cast to the base class to avoid ambiguities.
3370 QualType ArgTy =
3371 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3372 ParamType.getQualifiers());
3373
3374 if (Moving) {
3375 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3376 }
3377
3378 CXXCastPath BasePath;
3379 BasePath.push_back(BaseSpec);
3380 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3381 CK_UncheckedDerivedToBase,
3382 Moving ? VK_XValue : VK_LValue,
3383 &BasePath).get();
3384
3385 InitializationKind InitKind
3386 = InitializationKind::CreateDirect(Constructor->getLocation(),
3387 SourceLocation(), SourceLocation());
3388 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3389 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3390 break;
3391 }
3392 }
3393
3394 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3395 if (BaseInit.isInvalid())
3396 return true;
3397
3398 CXXBaseInit =
3399 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3400 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3401 SourceLocation()),
3402 BaseSpec->isVirtual(),
3403 SourceLocation(),
3404 BaseInit.getAs<Expr>(),
3405 SourceLocation(),
3406 SourceLocation());
3407
3408 return false;
3409 }
3410
RefersToRValueRef(Expr * MemRef)3411 static bool RefersToRValueRef(Expr *MemRef) {
3412 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3413 return Referenced->getType()->isRValueReferenceType();
3414 }
3415
3416 static bool
BuildImplicitMemberInitializer(Sema & SemaRef,CXXConstructorDecl * Constructor,ImplicitInitializerKind ImplicitInitKind,FieldDecl * Field,IndirectFieldDecl * Indirect,CXXCtorInitializer * & CXXMemberInit)3417 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3418 ImplicitInitializerKind ImplicitInitKind,
3419 FieldDecl *Field, IndirectFieldDecl *Indirect,
3420 CXXCtorInitializer *&CXXMemberInit) {
3421 if (Field->isInvalidDecl())
3422 return true;
3423
3424 SourceLocation Loc = Constructor->getLocation();
3425
3426 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3427 bool Moving = ImplicitInitKind == IIK_Move;
3428 ParmVarDecl *Param = Constructor->getParamDecl(0);
3429 QualType ParamType = Param->getType().getNonReferenceType();
3430
3431 // Suppress copying zero-width bitfields.
3432 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3433 return false;
3434
3435 Expr *MemberExprBase =
3436 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3437 SourceLocation(), Param, false,
3438 Loc, ParamType, VK_LValue, nullptr);
3439
3440 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3441
3442 if (Moving) {
3443 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3444 }
3445
3446 // Build a reference to this field within the parameter.
3447 CXXScopeSpec SS;
3448 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3449 Sema::LookupMemberName);
3450 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3451 : cast<ValueDecl>(Field), AS_public);
3452 MemberLookup.resolveKind();
3453 ExprResult CtorArg
3454 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3455 ParamType, Loc,
3456 /*IsArrow=*/false,
3457 SS,
3458 /*TemplateKWLoc=*/SourceLocation(),
3459 /*FirstQualifierInScope=*/nullptr,
3460 MemberLookup,
3461 /*TemplateArgs=*/nullptr);
3462 if (CtorArg.isInvalid())
3463 return true;
3464
3465 // C++11 [class.copy]p15:
3466 // - if a member m has rvalue reference type T&&, it is direct-initialized
3467 // with static_cast<T&&>(x.m);
3468 if (RefersToRValueRef(CtorArg.get())) {
3469 CtorArg = CastForMoving(SemaRef, CtorArg.get());
3470 }
3471
3472 // When the field we are copying is an array, create index variables for
3473 // each dimension of the array. We use these index variables to subscript
3474 // the source array, and other clients (e.g., CodeGen) will perform the
3475 // necessary iteration with these index variables.
3476 SmallVector<VarDecl *, 4> IndexVariables;
3477 QualType BaseType = Field->getType();
3478 QualType SizeType = SemaRef.Context.getSizeType();
3479 bool InitializingArray = false;
3480 while (const ConstantArrayType *Array
3481 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3482 InitializingArray = true;
3483 // Create the iteration variable for this array index.
3484 IdentifierInfo *IterationVarName = nullptr;
3485 {
3486 SmallString<8> Str;
3487 llvm::raw_svector_ostream OS(Str);
3488 OS << "__i" << IndexVariables.size();
3489 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3490 }
3491 VarDecl *IterationVar
3492 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3493 IterationVarName, SizeType,
3494 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3495 SC_None);
3496 IndexVariables.push_back(IterationVar);
3497
3498 // Create a reference to the iteration variable.
3499 ExprResult IterationVarRef
3500 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3501 assert(!IterationVarRef.isInvalid() &&
3502 "Reference to invented variable cannot fail!");
3503 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3504 assert(!IterationVarRef.isInvalid() &&
3505 "Conversion of invented variable cannot fail!");
3506
3507 // Subscript the array with this iteration variable.
3508 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3509 IterationVarRef.get(),
3510 Loc);
3511 if (CtorArg.isInvalid())
3512 return true;
3513
3514 BaseType = Array->getElementType();
3515 }
3516
3517 // The array subscript expression is an lvalue, which is wrong for moving.
3518 if (Moving && InitializingArray)
3519 CtorArg = CastForMoving(SemaRef, CtorArg.get());
3520
3521 // Construct the entity that we will be initializing. For an array, this
3522 // will be first element in the array, which may require several levels
3523 // of array-subscript entities.
3524 SmallVector<InitializedEntity, 4> Entities;
3525 Entities.reserve(1 + IndexVariables.size());
3526 if (Indirect)
3527 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3528 else
3529 Entities.push_back(InitializedEntity::InitializeMember(Field));
3530 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3531 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3532 0,
3533 Entities.back()));
3534
3535 // Direct-initialize to use the copy constructor.
3536 InitializationKind InitKind =
3537 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3538
3539 Expr *CtorArgE = CtorArg.getAs<Expr>();
3540 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3541
3542 ExprResult MemberInit
3543 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3544 MultiExprArg(&CtorArgE, 1));
3545 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3546 if (MemberInit.isInvalid())
3547 return true;
3548
3549 if (Indirect) {
3550 assert(IndexVariables.size() == 0 &&
3551 "Indirect field improperly initialized");
3552 CXXMemberInit
3553 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3554 Loc, Loc,
3555 MemberInit.getAs<Expr>(),
3556 Loc);
3557 } else
3558 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3559 Loc, MemberInit.getAs<Expr>(),
3560 Loc,
3561 IndexVariables.data(),
3562 IndexVariables.size());
3563 return false;
3564 }
3565
3566 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3567 "Unhandled implicit init kind!");
3568
3569 QualType FieldBaseElementType =
3570 SemaRef.Context.getBaseElementType(Field->getType());
3571
3572 if (FieldBaseElementType->isRecordType()) {
3573 InitializedEntity InitEntity
3574 = Indirect? InitializedEntity::InitializeMember(Indirect)
3575 : InitializedEntity::InitializeMember(Field);
3576 InitializationKind InitKind =
3577 InitializationKind::CreateDefault(Loc);
3578
3579 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3580 ExprResult MemberInit =
3581 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3582
3583 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3584 if (MemberInit.isInvalid())
3585 return true;
3586
3587 if (Indirect)
3588 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3589 Indirect, Loc,
3590 Loc,
3591 MemberInit.get(),
3592 Loc);
3593 else
3594 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3595 Field, Loc, Loc,
3596 MemberInit.get(),
3597 Loc);
3598 return false;
3599 }
3600
3601 if (!Field->getParent()->isUnion()) {
3602 if (FieldBaseElementType->isReferenceType()) {
3603 SemaRef.Diag(Constructor->getLocation(),
3604 diag::err_uninitialized_member_in_ctor)
3605 << (int)Constructor->isImplicit()
3606 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3607 << 0 << Field->getDeclName();
3608 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3609 return true;
3610 }
3611
3612 if (FieldBaseElementType.isConstQualified()) {
3613 SemaRef.Diag(Constructor->getLocation(),
3614 diag::err_uninitialized_member_in_ctor)
3615 << (int)Constructor->isImplicit()
3616 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3617 << 1 << Field->getDeclName();
3618 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3619 return true;
3620 }
3621 }
3622
3623 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3624 FieldBaseElementType->isObjCRetainableType() &&
3625 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3626 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3627 // ARC:
3628 // Default-initialize Objective-C pointers to NULL.
3629 CXXMemberInit
3630 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3631 Loc, Loc,
3632 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3633 Loc);
3634 return false;
3635 }
3636
3637 // Nothing to initialize.
3638 CXXMemberInit = nullptr;
3639 return false;
3640 }
3641
3642 namespace {
3643 struct BaseAndFieldInfo {
3644 Sema &S;
3645 CXXConstructorDecl *Ctor;
3646 bool AnyErrorsInInits;
3647 ImplicitInitializerKind IIK;
3648 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3649 SmallVector<CXXCtorInitializer*, 8> AllToInit;
3650 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3651
BaseAndFieldInfo__anon515e6f930411::BaseAndFieldInfo3652 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3653 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3654 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3655 if (Generated && Ctor->isCopyConstructor())
3656 IIK = IIK_Copy;
3657 else if (Generated && Ctor->isMoveConstructor())
3658 IIK = IIK_Move;
3659 else if (Ctor->getInheritedConstructor())
3660 IIK = IIK_Inherit;
3661 else
3662 IIK = IIK_Default;
3663 }
3664
isImplicitCopyOrMove__anon515e6f930411::BaseAndFieldInfo3665 bool isImplicitCopyOrMove() const {
3666 switch (IIK) {
3667 case IIK_Copy:
3668 case IIK_Move:
3669 return true;
3670
3671 case IIK_Default:
3672 case IIK_Inherit:
3673 return false;
3674 }
3675
3676 llvm_unreachable("Invalid ImplicitInitializerKind!");
3677 }
3678
addFieldInitializer__anon515e6f930411::BaseAndFieldInfo3679 bool addFieldInitializer(CXXCtorInitializer *Init) {
3680 AllToInit.push_back(Init);
3681
3682 // Check whether this initializer makes the field "used".
3683 if (Init->getInit()->HasSideEffects(S.Context))
3684 S.UnusedPrivateFields.remove(Init->getAnyMember());
3685
3686 return false;
3687 }
3688
isInactiveUnionMember__anon515e6f930411::BaseAndFieldInfo3689 bool isInactiveUnionMember(FieldDecl *Field) {
3690 RecordDecl *Record = Field->getParent();
3691 if (!Record->isUnion())
3692 return false;
3693
3694 if (FieldDecl *Active =
3695 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3696 return Active != Field->getCanonicalDecl();
3697
3698 // In an implicit copy or move constructor, ignore any in-class initializer.
3699 if (isImplicitCopyOrMove())
3700 return true;
3701
3702 // If there's no explicit initialization, the field is active only if it
3703 // has an in-class initializer...
3704 if (Field->hasInClassInitializer())
3705 return false;
3706 // ... or it's an anonymous struct or union whose class has an in-class
3707 // initializer.
3708 if (!Field->isAnonymousStructOrUnion())
3709 return true;
3710 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3711 return !FieldRD->hasInClassInitializer();
3712 }
3713
3714 /// \brief Determine whether the given field is, or is within, a union member
3715 /// that is inactive (because there was an initializer given for a different
3716 /// member of the union, or because the union was not initialized at all).
isWithinInactiveUnionMember__anon515e6f930411::BaseAndFieldInfo3717 bool isWithinInactiveUnionMember(FieldDecl *Field,
3718 IndirectFieldDecl *Indirect) {
3719 if (!Indirect)
3720 return isInactiveUnionMember(Field);
3721
3722 for (auto *C : Indirect->chain()) {
3723 FieldDecl *Field = dyn_cast<FieldDecl>(C);
3724 if (Field && isInactiveUnionMember(Field))
3725 return true;
3726 }
3727 return false;
3728 }
3729 };
3730 }
3731
3732 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3733 /// array type.
isIncompleteOrZeroLengthArrayType(ASTContext & Context,QualType T)3734 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3735 if (T->isIncompleteArrayType())
3736 return true;
3737
3738 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3739 if (!ArrayT->getSize())
3740 return true;
3741
3742 T = ArrayT->getElementType();
3743 }
3744
3745 return false;
3746 }
3747
CollectFieldInitializer(Sema & SemaRef,BaseAndFieldInfo & Info,FieldDecl * Field,IndirectFieldDecl * Indirect=nullptr)3748 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3749 FieldDecl *Field,
3750 IndirectFieldDecl *Indirect = nullptr) {
3751 if (Field->isInvalidDecl())
3752 return false;
3753
3754 // Overwhelmingly common case: we have a direct initializer for this field.
3755 if (CXXCtorInitializer *Init =
3756 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3757 return Info.addFieldInitializer(Init);
3758
3759 // C++11 [class.base.init]p8:
3760 // if the entity is a non-static data member that has a
3761 // brace-or-equal-initializer and either
3762 // -- the constructor's class is a union and no other variant member of that
3763 // union is designated by a mem-initializer-id or
3764 // -- the constructor's class is not a union, and, if the entity is a member
3765 // of an anonymous union, no other member of that union is designated by
3766 // a mem-initializer-id,
3767 // the entity is initialized as specified in [dcl.init].
3768 //
3769 // We also apply the same rules to handle anonymous structs within anonymous
3770 // unions.
3771 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3772 return false;
3773
3774 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3775 ExprResult DIE =
3776 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3777 if (DIE.isInvalid())
3778 return true;
3779 CXXCtorInitializer *Init;
3780 if (Indirect)
3781 Init = new (SemaRef.Context)
3782 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3783 SourceLocation(), DIE.get(), SourceLocation());
3784 else
3785 Init = new (SemaRef.Context)
3786 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3787 SourceLocation(), DIE.get(), SourceLocation());
3788 return Info.addFieldInitializer(Init);
3789 }
3790
3791 // Don't initialize incomplete or zero-length arrays.
3792 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3793 return false;
3794
3795 // Don't try to build an implicit initializer if there were semantic
3796 // errors in any of the initializers (and therefore we might be
3797 // missing some that the user actually wrote).
3798 if (Info.AnyErrorsInInits)
3799 return false;
3800
3801 CXXCtorInitializer *Init = nullptr;
3802 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3803 Indirect, Init))
3804 return true;
3805
3806 if (!Init)
3807 return false;
3808
3809 return Info.addFieldInitializer(Init);
3810 }
3811
3812 bool
SetDelegatingInitializer(CXXConstructorDecl * Constructor,CXXCtorInitializer * Initializer)3813 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3814 CXXCtorInitializer *Initializer) {
3815 assert(Initializer->isDelegatingInitializer());
3816 Constructor->setNumCtorInitializers(1);
3817 CXXCtorInitializer **initializer =
3818 new (Context) CXXCtorInitializer*[1];
3819 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3820 Constructor->setCtorInitializers(initializer);
3821
3822 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3823 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3824 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3825 }
3826
3827 DelegatingCtorDecls.push_back(Constructor);
3828
3829 DiagnoseUninitializedFields(*this, Constructor);
3830
3831 return false;
3832 }
3833
SetCtorInitializers(CXXConstructorDecl * Constructor,bool AnyErrors,ArrayRef<CXXCtorInitializer * > Initializers)3834 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3835 ArrayRef<CXXCtorInitializer *> Initializers) {
3836 if (Constructor->isDependentContext()) {
3837 // Just store the initializers as written, they will be checked during
3838 // instantiation.
3839 if (!Initializers.empty()) {
3840 Constructor->setNumCtorInitializers(Initializers.size());
3841 CXXCtorInitializer **baseOrMemberInitializers =
3842 new (Context) CXXCtorInitializer*[Initializers.size()];
3843 memcpy(baseOrMemberInitializers, Initializers.data(),
3844 Initializers.size() * sizeof(CXXCtorInitializer*));
3845 Constructor->setCtorInitializers(baseOrMemberInitializers);
3846 }
3847
3848 // Let template instantiation know whether we had errors.
3849 if (AnyErrors)
3850 Constructor->setInvalidDecl();
3851
3852 return false;
3853 }
3854
3855 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3856
3857 // We need to build the initializer AST according to order of construction
3858 // and not what user specified in the Initializers list.
3859 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3860 if (!ClassDecl)
3861 return true;
3862
3863 bool HadError = false;
3864
3865 for (unsigned i = 0; i < Initializers.size(); i++) {
3866 CXXCtorInitializer *Member = Initializers[i];
3867
3868 if (Member->isBaseInitializer())
3869 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3870 else {
3871 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3872
3873 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3874 for (auto *C : F->chain()) {
3875 FieldDecl *FD = dyn_cast<FieldDecl>(C);
3876 if (FD && FD->getParent()->isUnion())
3877 Info.ActiveUnionMember.insert(std::make_pair(
3878 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3879 }
3880 } else if (FieldDecl *FD = Member->getMember()) {
3881 if (FD->getParent()->isUnion())
3882 Info.ActiveUnionMember.insert(std::make_pair(
3883 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3884 }
3885 }
3886 }
3887
3888 // Keep track of the direct virtual bases.
3889 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3890 for (auto &I : ClassDecl->bases()) {
3891 if (I.isVirtual())
3892 DirectVBases.insert(&I);
3893 }
3894
3895 // Push virtual bases before others.
3896 for (auto &VBase : ClassDecl->vbases()) {
3897 if (CXXCtorInitializer *Value
3898 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3899 // [class.base.init]p7, per DR257:
3900 // A mem-initializer where the mem-initializer-id names a virtual base
3901 // class is ignored during execution of a constructor of any class that
3902 // is not the most derived class.
3903 if (ClassDecl->isAbstract()) {
3904 // FIXME: Provide a fixit to remove the base specifier. This requires
3905 // tracking the location of the associated comma for a base specifier.
3906 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3907 << VBase.getType() << ClassDecl;
3908 DiagnoseAbstractType(ClassDecl);
3909 }
3910
3911 Info.AllToInit.push_back(Value);
3912 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3913 // [class.base.init]p8, per DR257:
3914 // If a given [...] base class is not named by a mem-initializer-id
3915 // [...] and the entity is not a virtual base class of an abstract
3916 // class, then [...] the entity is default-initialized.
3917 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3918 CXXCtorInitializer *CXXBaseInit;
3919 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3920 &VBase, IsInheritedVirtualBase,
3921 CXXBaseInit)) {
3922 HadError = true;
3923 continue;
3924 }
3925
3926 Info.AllToInit.push_back(CXXBaseInit);
3927 }
3928 }
3929
3930 // Non-virtual bases.
3931 for (auto &Base : ClassDecl->bases()) {
3932 // Virtuals are in the virtual base list and already constructed.
3933 if (Base.isVirtual())
3934 continue;
3935
3936 if (CXXCtorInitializer *Value
3937 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3938 Info.AllToInit.push_back(Value);
3939 } else if (!AnyErrors) {
3940 CXXCtorInitializer *CXXBaseInit;
3941 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3942 &Base, /*IsInheritedVirtualBase=*/false,
3943 CXXBaseInit)) {
3944 HadError = true;
3945 continue;
3946 }
3947
3948 Info.AllToInit.push_back(CXXBaseInit);
3949 }
3950 }
3951
3952 // Fields.
3953 for (auto *Mem : ClassDecl->decls()) {
3954 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3955 // C++ [class.bit]p2:
3956 // A declaration for a bit-field that omits the identifier declares an
3957 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3958 // initialized.
3959 if (F->isUnnamedBitfield())
3960 continue;
3961
3962 // If we're not generating the implicit copy/move constructor, then we'll
3963 // handle anonymous struct/union fields based on their individual
3964 // indirect fields.
3965 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3966 continue;
3967
3968 if (CollectFieldInitializer(*this, Info, F))
3969 HadError = true;
3970 continue;
3971 }
3972
3973 // Beyond this point, we only consider default initialization.
3974 if (Info.isImplicitCopyOrMove())
3975 continue;
3976
3977 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
3978 if (F->getType()->isIncompleteArrayType()) {
3979 assert(ClassDecl->hasFlexibleArrayMember() &&
3980 "Incomplete array type is not valid");
3981 continue;
3982 }
3983
3984 // Initialize each field of an anonymous struct individually.
3985 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3986 HadError = true;
3987
3988 continue;
3989 }
3990 }
3991
3992 unsigned NumInitializers = Info.AllToInit.size();
3993 if (NumInitializers > 0) {
3994 Constructor->setNumCtorInitializers(NumInitializers);
3995 CXXCtorInitializer **baseOrMemberInitializers =
3996 new (Context) CXXCtorInitializer*[NumInitializers];
3997 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3998 NumInitializers * sizeof(CXXCtorInitializer*));
3999 Constructor->setCtorInitializers(baseOrMemberInitializers);
4000
4001 // Constructors implicitly reference the base and member
4002 // destructors.
4003 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4004 Constructor->getParent());
4005 }
4006
4007 return HadError;
4008 }
4009
PopulateKeysForFields(FieldDecl * Field,SmallVectorImpl<const void * > & IdealInits)4010 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4011 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4012 const RecordDecl *RD = RT->getDecl();
4013 if (RD->isAnonymousStructOrUnion()) {
4014 for (auto *Field : RD->fields())
4015 PopulateKeysForFields(Field, IdealInits);
4016 return;
4017 }
4018 }
4019 IdealInits.push_back(Field->getCanonicalDecl());
4020 }
4021
GetKeyForBase(ASTContext & Context,QualType BaseType)4022 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4023 return Context.getCanonicalType(BaseType).getTypePtr();
4024 }
4025
GetKeyForMember(ASTContext & Context,CXXCtorInitializer * Member)4026 static const void *GetKeyForMember(ASTContext &Context,
4027 CXXCtorInitializer *Member) {
4028 if (!Member->isAnyMemberInitializer())
4029 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4030
4031 return Member->getAnyMember()->getCanonicalDecl();
4032 }
4033
DiagnoseBaseOrMemInitializerOrder(Sema & SemaRef,const CXXConstructorDecl * Constructor,ArrayRef<CXXCtorInitializer * > Inits)4034 static void DiagnoseBaseOrMemInitializerOrder(
4035 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4036 ArrayRef<CXXCtorInitializer *> Inits) {
4037 if (Constructor->getDeclContext()->isDependentContext())
4038 return;
4039
4040 // Don't check initializers order unless the warning is enabled at the
4041 // location of at least one initializer.
4042 bool ShouldCheckOrder = false;
4043 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4044 CXXCtorInitializer *Init = Inits[InitIndex];
4045 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4046 Init->getSourceLocation())) {
4047 ShouldCheckOrder = true;
4048 break;
4049 }
4050 }
4051 if (!ShouldCheckOrder)
4052 return;
4053
4054 // Build the list of bases and members in the order that they'll
4055 // actually be initialized. The explicit initializers should be in
4056 // this same order but may be missing things.
4057 SmallVector<const void*, 32> IdealInitKeys;
4058
4059 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4060
4061 // 1. Virtual bases.
4062 for (const auto &VBase : ClassDecl->vbases())
4063 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4064
4065 // 2. Non-virtual bases.
4066 for (const auto &Base : ClassDecl->bases()) {
4067 if (Base.isVirtual())
4068 continue;
4069 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4070 }
4071
4072 // 3. Direct fields.
4073 for (auto *Field : ClassDecl->fields()) {
4074 if (Field->isUnnamedBitfield())
4075 continue;
4076
4077 PopulateKeysForFields(Field, IdealInitKeys);
4078 }
4079
4080 unsigned NumIdealInits = IdealInitKeys.size();
4081 unsigned IdealIndex = 0;
4082
4083 CXXCtorInitializer *PrevInit = nullptr;
4084 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4085 CXXCtorInitializer *Init = Inits[InitIndex];
4086 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4087
4088 // Scan forward to try to find this initializer in the idealized
4089 // initializers list.
4090 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4091 if (InitKey == IdealInitKeys[IdealIndex])
4092 break;
4093
4094 // If we didn't find this initializer, it must be because we
4095 // scanned past it on a previous iteration. That can only
4096 // happen if we're out of order; emit a warning.
4097 if (IdealIndex == NumIdealInits && PrevInit) {
4098 Sema::SemaDiagnosticBuilder D =
4099 SemaRef.Diag(PrevInit->getSourceLocation(),
4100 diag::warn_initializer_out_of_order);
4101
4102 if (PrevInit->isAnyMemberInitializer())
4103 D << 0 << PrevInit->getAnyMember()->getDeclName();
4104 else
4105 D << 1 << PrevInit->getTypeSourceInfo()->getType();
4106
4107 if (Init->isAnyMemberInitializer())
4108 D << 0 << Init->getAnyMember()->getDeclName();
4109 else
4110 D << 1 << Init->getTypeSourceInfo()->getType();
4111
4112 // Move back to the initializer's location in the ideal list.
4113 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4114 if (InitKey == IdealInitKeys[IdealIndex])
4115 break;
4116
4117 assert(IdealIndex != NumIdealInits &&
4118 "initializer not found in initializer list");
4119 }
4120
4121 PrevInit = Init;
4122 }
4123 }
4124
4125 namespace {
CheckRedundantInit(Sema & S,CXXCtorInitializer * Init,CXXCtorInitializer * & PrevInit)4126 bool CheckRedundantInit(Sema &S,
4127 CXXCtorInitializer *Init,
4128 CXXCtorInitializer *&PrevInit) {
4129 if (!PrevInit) {
4130 PrevInit = Init;
4131 return false;
4132 }
4133
4134 if (FieldDecl *Field = Init->getAnyMember())
4135 S.Diag(Init->getSourceLocation(),
4136 diag::err_multiple_mem_initialization)
4137 << Field->getDeclName()
4138 << Init->getSourceRange();
4139 else {
4140 const Type *BaseClass = Init->getBaseClass();
4141 assert(BaseClass && "neither field nor base");
4142 S.Diag(Init->getSourceLocation(),
4143 diag::err_multiple_base_initialization)
4144 << QualType(BaseClass, 0)
4145 << Init->getSourceRange();
4146 }
4147 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4148 << 0 << PrevInit->getSourceRange();
4149
4150 return true;
4151 }
4152
4153 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4154 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4155
CheckRedundantUnionInit(Sema & S,CXXCtorInitializer * Init,RedundantUnionMap & Unions)4156 bool CheckRedundantUnionInit(Sema &S,
4157 CXXCtorInitializer *Init,
4158 RedundantUnionMap &Unions) {
4159 FieldDecl *Field = Init->getAnyMember();
4160 RecordDecl *Parent = Field->getParent();
4161 NamedDecl *Child = Field;
4162
4163 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4164 if (Parent->isUnion()) {
4165 UnionEntry &En = Unions[Parent];
4166 if (En.first && En.first != Child) {
4167 S.Diag(Init->getSourceLocation(),
4168 diag::err_multiple_mem_union_initialization)
4169 << Field->getDeclName()
4170 << Init->getSourceRange();
4171 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4172 << 0 << En.second->getSourceRange();
4173 return true;
4174 }
4175 if (!En.first) {
4176 En.first = Child;
4177 En.second = Init;
4178 }
4179 if (!Parent->isAnonymousStructOrUnion())
4180 return false;
4181 }
4182
4183 Child = Parent;
4184 Parent = cast<RecordDecl>(Parent->getDeclContext());
4185 }
4186
4187 return false;
4188 }
4189 }
4190
4191 /// ActOnMemInitializers - Handle the member initializers for a constructor.
ActOnMemInitializers(Decl * ConstructorDecl,SourceLocation ColonLoc,ArrayRef<CXXCtorInitializer * > MemInits,bool AnyErrors)4192 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4193 SourceLocation ColonLoc,
4194 ArrayRef<CXXCtorInitializer*> MemInits,
4195 bool AnyErrors) {
4196 if (!ConstructorDecl)
4197 return;
4198
4199 AdjustDeclIfTemplate(ConstructorDecl);
4200
4201 CXXConstructorDecl *Constructor
4202 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4203
4204 if (!Constructor) {
4205 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4206 return;
4207 }
4208
4209 // Mapping for the duplicate initializers check.
4210 // For member initializers, this is keyed with a FieldDecl*.
4211 // For base initializers, this is keyed with a Type*.
4212 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4213
4214 // Mapping for the inconsistent anonymous-union initializers check.
4215 RedundantUnionMap MemberUnions;
4216
4217 bool HadError = false;
4218 for (unsigned i = 0; i < MemInits.size(); i++) {
4219 CXXCtorInitializer *Init = MemInits[i];
4220
4221 // Set the source order index.
4222 Init->setSourceOrder(i);
4223
4224 if (Init->isAnyMemberInitializer()) {
4225 const void *Key = GetKeyForMember(Context, Init);
4226 if (CheckRedundantInit(*this, Init, Members[Key]) ||
4227 CheckRedundantUnionInit(*this, Init, MemberUnions))
4228 HadError = true;
4229 } else if (Init->isBaseInitializer()) {
4230 const void *Key = GetKeyForMember(Context, Init);
4231 if (CheckRedundantInit(*this, Init, Members[Key]))
4232 HadError = true;
4233 } else {
4234 assert(Init->isDelegatingInitializer());
4235 // This must be the only initializer
4236 if (MemInits.size() != 1) {
4237 Diag(Init->getSourceLocation(),
4238 diag::err_delegating_initializer_alone)
4239 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4240 // We will treat this as being the only initializer.
4241 }
4242 SetDelegatingInitializer(Constructor, MemInits[i]);
4243 // Return immediately as the initializer is set.
4244 return;
4245 }
4246 }
4247
4248 if (HadError)
4249 return;
4250
4251 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4252
4253 SetCtorInitializers(Constructor, AnyErrors, MemInits);
4254
4255 DiagnoseUninitializedFields(*this, Constructor);
4256 }
4257
4258 void
MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,CXXRecordDecl * ClassDecl)4259 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4260 CXXRecordDecl *ClassDecl) {
4261 // Ignore dependent contexts. Also ignore unions, since their members never
4262 // have destructors implicitly called.
4263 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4264 return;
4265
4266 // FIXME: all the access-control diagnostics are positioned on the
4267 // field/base declaration. That's probably good; that said, the
4268 // user might reasonably want to know why the destructor is being
4269 // emitted, and we currently don't say.
4270
4271 // Non-static data members.
4272 for (auto *Field : ClassDecl->fields()) {
4273 if (Field->isInvalidDecl())
4274 continue;
4275
4276 // Don't destroy incomplete or zero-length arrays.
4277 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4278 continue;
4279
4280 QualType FieldType = Context.getBaseElementType(Field->getType());
4281
4282 const RecordType* RT = FieldType->getAs<RecordType>();
4283 if (!RT)
4284 continue;
4285
4286 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4287 if (FieldClassDecl->isInvalidDecl())
4288 continue;
4289 if (FieldClassDecl->hasIrrelevantDestructor())
4290 continue;
4291 // The destructor for an implicit anonymous union member is never invoked.
4292 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4293 continue;
4294
4295 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4296 assert(Dtor && "No dtor found for FieldClassDecl!");
4297 CheckDestructorAccess(Field->getLocation(), Dtor,
4298 PDiag(diag::err_access_dtor_field)
4299 << Field->getDeclName()
4300 << FieldType);
4301
4302 MarkFunctionReferenced(Location, Dtor);
4303 DiagnoseUseOfDecl(Dtor, Location);
4304 }
4305
4306 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4307
4308 // Bases.
4309 for (const auto &Base : ClassDecl->bases()) {
4310 // Bases are always records in a well-formed non-dependent class.
4311 const RecordType *RT = Base.getType()->getAs<RecordType>();
4312
4313 // Remember direct virtual bases.
4314 if (Base.isVirtual())
4315 DirectVirtualBases.insert(RT);
4316
4317 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4318 // If our base class is invalid, we probably can't get its dtor anyway.
4319 if (BaseClassDecl->isInvalidDecl())
4320 continue;
4321 if (BaseClassDecl->hasIrrelevantDestructor())
4322 continue;
4323
4324 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4325 assert(Dtor && "No dtor found for BaseClassDecl!");
4326
4327 // FIXME: caret should be on the start of the class name
4328 CheckDestructorAccess(Base.getLocStart(), Dtor,
4329 PDiag(diag::err_access_dtor_base)
4330 << Base.getType()
4331 << Base.getSourceRange(),
4332 Context.getTypeDeclType(ClassDecl));
4333
4334 MarkFunctionReferenced(Location, Dtor);
4335 DiagnoseUseOfDecl(Dtor, Location);
4336 }
4337
4338 // Virtual bases.
4339 for (const auto &VBase : ClassDecl->vbases()) {
4340 // Bases are always records in a well-formed non-dependent class.
4341 const RecordType *RT = VBase.getType()->castAs<RecordType>();
4342
4343 // Ignore direct virtual bases.
4344 if (DirectVirtualBases.count(RT))
4345 continue;
4346
4347 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4348 // If our base class is invalid, we probably can't get its dtor anyway.
4349 if (BaseClassDecl->isInvalidDecl())
4350 continue;
4351 if (BaseClassDecl->hasIrrelevantDestructor())
4352 continue;
4353
4354 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4355 assert(Dtor && "No dtor found for BaseClassDecl!");
4356 if (CheckDestructorAccess(
4357 ClassDecl->getLocation(), Dtor,
4358 PDiag(diag::err_access_dtor_vbase)
4359 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4360 Context.getTypeDeclType(ClassDecl)) ==
4361 AR_accessible) {
4362 CheckDerivedToBaseConversion(
4363 Context.getTypeDeclType(ClassDecl), VBase.getType(),
4364 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4365 SourceRange(), DeclarationName(), nullptr);
4366 }
4367
4368 MarkFunctionReferenced(Location, Dtor);
4369 DiagnoseUseOfDecl(Dtor, Location);
4370 }
4371 }
4372
ActOnDefaultCtorInitializers(Decl * CDtorDecl)4373 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4374 if (!CDtorDecl)
4375 return;
4376
4377 if (CXXConstructorDecl *Constructor
4378 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4379 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4380 DiagnoseUninitializedFields(*this, Constructor);
4381 }
4382 }
4383
RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,AbstractDiagSelID SelID)4384 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4385 unsigned DiagID, AbstractDiagSelID SelID) {
4386 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4387 unsigned DiagID;
4388 AbstractDiagSelID SelID;
4389
4390 public:
4391 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4392 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4393
4394 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4395 if (Suppressed) return;
4396 if (SelID == -1)
4397 S.Diag(Loc, DiagID) << T;
4398 else
4399 S.Diag(Loc, DiagID) << SelID << T;
4400 }
4401 } Diagnoser(DiagID, SelID);
4402
4403 return RequireNonAbstractType(Loc, T, Diagnoser);
4404 }
4405
RequireNonAbstractType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)4406 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4407 TypeDiagnoser &Diagnoser) {
4408 if (!getLangOpts().CPlusPlus)
4409 return false;
4410
4411 if (const ArrayType *AT = Context.getAsArrayType(T))
4412 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4413
4414 if (const PointerType *PT = T->getAs<PointerType>()) {
4415 // Find the innermost pointer type.
4416 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4417 PT = T;
4418
4419 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4420 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4421 }
4422
4423 const RecordType *RT = T->getAs<RecordType>();
4424 if (!RT)
4425 return false;
4426
4427 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4428
4429 // We can't answer whether something is abstract until it has a
4430 // definition. If it's currently being defined, we'll walk back
4431 // over all the declarations when we have a full definition.
4432 const CXXRecordDecl *Def = RD->getDefinition();
4433 if (!Def || Def->isBeingDefined())
4434 return false;
4435
4436 if (!RD->isAbstract())
4437 return false;
4438
4439 Diagnoser.diagnose(*this, Loc, T);
4440 DiagnoseAbstractType(RD);
4441
4442 return true;
4443 }
4444
DiagnoseAbstractType(const CXXRecordDecl * RD)4445 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4446 // Check if we've already emitted the list of pure virtual functions
4447 // for this class.
4448 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4449 return;
4450
4451 // If the diagnostic is suppressed, don't emit the notes. We're only
4452 // going to emit them once, so try to attach them to a diagnostic we're
4453 // actually going to show.
4454 if (Diags.isLastDiagnosticIgnored())
4455 return;
4456
4457 CXXFinalOverriderMap FinalOverriders;
4458 RD->getFinalOverriders(FinalOverriders);
4459
4460 // Keep a set of seen pure methods so we won't diagnose the same method
4461 // more than once.
4462 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4463
4464 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4465 MEnd = FinalOverriders.end();
4466 M != MEnd;
4467 ++M) {
4468 for (OverridingMethods::iterator SO = M->second.begin(),
4469 SOEnd = M->second.end();
4470 SO != SOEnd; ++SO) {
4471 // C++ [class.abstract]p4:
4472 // A class is abstract if it contains or inherits at least one
4473 // pure virtual function for which the final overrider is pure
4474 // virtual.
4475
4476 //
4477 if (SO->second.size() != 1)
4478 continue;
4479
4480 if (!SO->second.front().Method->isPure())
4481 continue;
4482
4483 if (!SeenPureMethods.insert(SO->second.front().Method).second)
4484 continue;
4485
4486 Diag(SO->second.front().Method->getLocation(),
4487 diag::note_pure_virtual_function)
4488 << SO->second.front().Method->getDeclName() << RD->getDeclName();
4489 }
4490 }
4491
4492 if (!PureVirtualClassDiagSet)
4493 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4494 PureVirtualClassDiagSet->insert(RD);
4495 }
4496
4497 namespace {
4498 struct AbstractUsageInfo {
4499 Sema &S;
4500 CXXRecordDecl *Record;
4501 CanQualType AbstractType;
4502 bool Invalid;
4503
AbstractUsageInfo__anon515e6f930611::AbstractUsageInfo4504 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4505 : S(S), Record(Record),
4506 AbstractType(S.Context.getCanonicalType(
4507 S.Context.getTypeDeclType(Record))),
4508 Invalid(false) {}
4509
DiagnoseAbstractType__anon515e6f930611::AbstractUsageInfo4510 void DiagnoseAbstractType() {
4511 if (Invalid) return;
4512 S.DiagnoseAbstractType(Record);
4513 Invalid = true;
4514 }
4515
4516 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4517 };
4518
4519 struct CheckAbstractUsage {
4520 AbstractUsageInfo &Info;
4521 const NamedDecl *Ctx;
4522
CheckAbstractUsage__anon515e6f930611::CheckAbstractUsage4523 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4524 : Info(Info), Ctx(Ctx) {}
4525
Visit__anon515e6f930611::CheckAbstractUsage4526 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4527 switch (TL.getTypeLocClass()) {
4528 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4529 #define TYPELOC(CLASS, PARENT) \
4530 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4531 #include "clang/AST/TypeLocNodes.def"
4532 }
4533 }
4534
Check__anon515e6f930611::CheckAbstractUsage4535 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4536 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4537 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4538 if (!TL.getParam(I))
4539 continue;
4540
4541 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4542 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4543 }
4544 }
4545
Check__anon515e6f930611::CheckAbstractUsage4546 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4547 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4548 }
4549
Check__anon515e6f930611::CheckAbstractUsage4550 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4551 // Visit the type parameters from a permissive context.
4552 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4553 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4554 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4555 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4556 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4557 // TODO: other template argument types?
4558 }
4559 }
4560
4561 // Visit pointee types from a permissive context.
4562 #define CheckPolymorphic(Type) \
4563 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4564 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4565 }
4566 CheckPolymorphic(PointerTypeLoc)
CheckPolymorphic__anon515e6f930611::CheckAbstractUsage4567 CheckPolymorphic(ReferenceTypeLoc)
4568 CheckPolymorphic(MemberPointerTypeLoc)
4569 CheckPolymorphic(BlockPointerTypeLoc)
4570 CheckPolymorphic(AtomicTypeLoc)
4571
4572 /// Handle all the types we haven't given a more specific
4573 /// implementation for above.
4574 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4575 // Every other kind of type that we haven't called out already
4576 // that has an inner type is either (1) sugar or (2) contains that
4577 // inner type in some way as a subobject.
4578 if (TypeLoc Next = TL.getNextTypeLoc())
4579 return Visit(Next, Sel);
4580
4581 // If there's no inner type and we're in a permissive context,
4582 // don't diagnose.
4583 if (Sel == Sema::AbstractNone) return;
4584
4585 // Check whether the type matches the abstract type.
4586 QualType T = TL.getType();
4587 if (T->isArrayType()) {
4588 Sel = Sema::AbstractArrayType;
4589 T = Info.S.Context.getBaseElementType(T);
4590 }
4591 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4592 if (CT != Info.AbstractType) return;
4593
4594 // It matched; do some magic.
4595 if (Sel == Sema::AbstractArrayType) {
4596 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4597 << T << TL.getSourceRange();
4598 } else {
4599 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4600 << Sel << T << TL.getSourceRange();
4601 }
4602 Info.DiagnoseAbstractType();
4603 }
4604 };
4605
CheckType(const NamedDecl * D,TypeLoc TL,Sema::AbstractDiagSelID Sel)4606 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4607 Sema::AbstractDiagSelID Sel) {
4608 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4609 }
4610
4611 }
4612
4613 /// Check for invalid uses of an abstract type in a method declaration.
CheckAbstractClassUsage(AbstractUsageInfo & Info,CXXMethodDecl * MD)4614 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4615 CXXMethodDecl *MD) {
4616 // No need to do the check on definitions, which require that
4617 // the return/param types be complete.
4618 if (MD->doesThisDeclarationHaveABody())
4619 return;
4620
4621 // For safety's sake, just ignore it if we don't have type source
4622 // information. This should never happen for non-implicit methods,
4623 // but...
4624 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4625 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4626 }
4627
4628 /// Check for invalid uses of an abstract type within a class definition.
CheckAbstractClassUsage(AbstractUsageInfo & Info,CXXRecordDecl * RD)4629 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4630 CXXRecordDecl *RD) {
4631 for (auto *D : RD->decls()) {
4632 if (D->isImplicit()) continue;
4633
4634 // Methods and method templates.
4635 if (isa<CXXMethodDecl>(D)) {
4636 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4637 } else if (isa<FunctionTemplateDecl>(D)) {
4638 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4639 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4640
4641 // Fields and static variables.
4642 } else if (isa<FieldDecl>(D)) {
4643 FieldDecl *FD = cast<FieldDecl>(D);
4644 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4645 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4646 } else if (isa<VarDecl>(D)) {
4647 VarDecl *VD = cast<VarDecl>(D);
4648 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4649 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4650
4651 // Nested classes and class templates.
4652 } else if (isa<CXXRecordDecl>(D)) {
4653 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4654 } else if (isa<ClassTemplateDecl>(D)) {
4655 CheckAbstractClassUsage(Info,
4656 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4657 }
4658 }
4659 }
4660
4661 /// \brief Check class-level dllimport/dllexport attribute.
checkDLLAttribute(Sema & S,CXXRecordDecl * Class)4662 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4663 Attr *ClassAttr = getDLLAttr(Class);
4664
4665 // MSVC inherits DLL attributes to partial class template specializations.
4666 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4667 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4668 if (Attr *TemplateAttr =
4669 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4670 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4671 A->setInherited(true);
4672 ClassAttr = A;
4673 }
4674 }
4675 }
4676
4677 if (!ClassAttr)
4678 return;
4679
4680 if (!Class->isExternallyVisible()) {
4681 S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4682 << Class << ClassAttr;
4683 return;
4684 }
4685
4686 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4687 !ClassAttr->isInherited()) {
4688 // Diagnose dll attributes on members of class with dll attribute.
4689 for (Decl *Member : Class->decls()) {
4690 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4691 continue;
4692 InheritableAttr *MemberAttr = getDLLAttr(Member);
4693 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4694 continue;
4695
4696 S.Diag(MemberAttr->getLocation(),
4697 diag::err_attribute_dll_member_of_dll_class)
4698 << MemberAttr << ClassAttr;
4699 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4700 Member->setInvalidDecl();
4701 }
4702 }
4703
4704 if (Class->getDescribedClassTemplate())
4705 // Don't inherit dll attribute until the template is instantiated.
4706 return;
4707
4708 // The class is either imported or exported.
4709 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4710 const bool ClassImported = !ClassExported;
4711
4712 // Force declaration of implicit members so they can inherit the attribute.
4713 S.ForceDeclarationOfImplicitMembers(Class);
4714
4715 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4716 // seem to be true in practice?
4717
4718 TemplateSpecializationKind TSK =
4719 Class->getTemplateSpecializationKind();
4720
4721 for (Decl *Member : Class->decls()) {
4722 VarDecl *VD = dyn_cast<VarDecl>(Member);
4723 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4724
4725 // Only methods and static fields inherit the attributes.
4726 if (!VD && !MD)
4727 continue;
4728
4729 if (MD) {
4730 // Don't process deleted methods.
4731 if (MD->isDeleted())
4732 continue;
4733
4734 if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) {
4735 // Current MSVC versions don't export the move assignment operators, so
4736 // don't attempt to import them if we have a definition.
4737 continue;
4738 }
4739
4740 if (MD->isInlined() && ClassImported &&
4741 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4742 // MinGW does not import inline functions.
4743 continue;
4744 }
4745 }
4746
4747 if (!getDLLAttr(Member)) {
4748 auto *NewAttr =
4749 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4750 NewAttr->setInherited(true);
4751 Member->addAttr(NewAttr);
4752 }
4753
4754 if (MD && ClassExported) {
4755 if (MD->isUserProvided()) {
4756 // Instantiate non-default class member functions ...
4757
4758 // .. except for certain kinds of template specializations.
4759 if (TSK == TSK_ExplicitInstantiationDeclaration)
4760 continue;
4761 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4762 continue;
4763
4764 S.MarkFunctionReferenced(Class->getLocation(), MD);
4765
4766 // The function will be passed to the consumer when its definition is
4767 // encountered.
4768 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4769 MD->isCopyAssignmentOperator() ||
4770 MD->isMoveAssignmentOperator()) {
4771 // Synthesize and instantiate non-trivial implicit methods, explicitly
4772 // defaulted methods, and the copy and move assignment operators. The
4773 // latter are exported even if they are trivial, because the address of
4774 // an operator can be taken and should compare equal accross libraries.
4775 S.MarkFunctionReferenced(Class->getLocation(), MD);
4776
4777 // There is no later point when we will see the definition of this
4778 // function, so pass it to the consumer now.
4779 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
4780 }
4781 }
4782 }
4783 }
4784
4785 /// \brief Perform semantic checks on a class definition that has been
4786 /// completing, introducing implicitly-declared members, checking for
4787 /// abstract types, etc.
CheckCompletedCXXClass(CXXRecordDecl * Record)4788 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4789 if (!Record)
4790 return;
4791
4792 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4793 AbstractUsageInfo Info(*this, Record);
4794 CheckAbstractClassUsage(Info, Record);
4795 }
4796
4797 // If this is not an aggregate type and has no user-declared constructor,
4798 // complain about any non-static data members of reference or const scalar
4799 // type, since they will never get initializers.
4800 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4801 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4802 !Record->isLambda()) {
4803 bool Complained = false;
4804 for (const auto *F : Record->fields()) {
4805 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4806 continue;
4807
4808 if (F->getType()->isReferenceType() ||
4809 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4810 if (!Complained) {
4811 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4812 << Record->getTagKind() << Record;
4813 Complained = true;
4814 }
4815
4816 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4817 << F->getType()->isReferenceType()
4818 << F->getDeclName();
4819 }
4820 }
4821 }
4822
4823 if (Record->isDynamicClass() && !Record->isDependentType())
4824 DynamicClasses.push_back(Record);
4825
4826 if (Record->getIdentifier()) {
4827 // C++ [class.mem]p13:
4828 // If T is the name of a class, then each of the following shall have a
4829 // name different from T:
4830 // - every member of every anonymous union that is a member of class T.
4831 //
4832 // C++ [class.mem]p14:
4833 // In addition, if class T has a user-declared constructor (12.1), every
4834 // non-static data member of class T shall have a name different from T.
4835 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4836 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4837 ++I) {
4838 NamedDecl *D = *I;
4839 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4840 isa<IndirectFieldDecl>(D)) {
4841 Diag(D->getLocation(), diag::err_member_name_of_class)
4842 << D->getDeclName();
4843 break;
4844 }
4845 }
4846 }
4847
4848 // Warn if the class has virtual methods but non-virtual public destructor.
4849 if (Record->isPolymorphic() && !Record->isDependentType()) {
4850 CXXDestructorDecl *dtor = Record->getDestructor();
4851 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4852 !Record->hasAttr<FinalAttr>())
4853 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4854 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4855 }
4856
4857 if (Record->isAbstract()) {
4858 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4859 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4860 << FA->isSpelledAsSealed();
4861 DiagnoseAbstractType(Record);
4862 }
4863 }
4864
4865 bool HasMethodWithOverrideControl = false,
4866 HasOverridingMethodWithoutOverrideControl = false;
4867 if (!Record->isDependentType()) {
4868 for (auto *M : Record->methods()) {
4869 // See if a method overloads virtual methods in a base
4870 // class without overriding any.
4871 if (!M->isStatic())
4872 DiagnoseHiddenVirtualMethods(M);
4873 if (M->hasAttr<OverrideAttr>())
4874 HasMethodWithOverrideControl = true;
4875 else if (M->size_overridden_methods() > 0)
4876 HasOverridingMethodWithoutOverrideControl = true;
4877 // Check whether the explicitly-defaulted special members are valid.
4878 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4879 CheckExplicitlyDefaultedSpecialMember(M);
4880
4881 // For an explicitly defaulted or deleted special member, we defer
4882 // determining triviality until the class is complete. That time is now!
4883 if (!M->isImplicit() && !M->isUserProvided()) {
4884 CXXSpecialMember CSM = getSpecialMember(M);
4885 if (CSM != CXXInvalid) {
4886 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4887
4888 // Inform the class that we've finished declaring this member.
4889 Record->finishedDefaultedOrDeletedMember(M);
4890 }
4891 }
4892 }
4893 }
4894
4895 if (HasMethodWithOverrideControl &&
4896 HasOverridingMethodWithoutOverrideControl) {
4897 // At least one method has the 'override' control declared.
4898 // Diagnose all other overridden methods which do not have 'override' specified on them.
4899 for (auto *M : Record->methods())
4900 DiagnoseAbsenceOfOverrideControl(M);
4901 }
4902
4903 // ms_struct is a request to use the same ABI rules as MSVC. Check
4904 // whether this class uses any C++ features that are implemented
4905 // completely differently in MSVC, and if so, emit a diagnostic.
4906 // That diagnostic defaults to an error, but we allow projects to
4907 // map it down to a warning (or ignore it). It's a fairly common
4908 // practice among users of the ms_struct pragma to mass-annotate
4909 // headers, sweeping up a bunch of types that the project doesn't
4910 // really rely on MSVC-compatible layout for. We must therefore
4911 // support "ms_struct except for C++ stuff" as a secondary ABI.
4912 if (Record->isMsStruct(Context) &&
4913 (Record->isPolymorphic() || Record->getNumBases())) {
4914 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
4915 }
4916
4917 // Declare inheriting constructors. We do this eagerly here because:
4918 // - The standard requires an eager diagnostic for conflicting inheriting
4919 // constructors from different classes.
4920 // - The lazy declaration of the other implicit constructors is so as to not
4921 // waste space and performance on classes that are not meant to be
4922 // instantiated (e.g. meta-functions). This doesn't apply to classes that
4923 // have inheriting constructors.
4924 DeclareInheritingConstructors(Record);
4925
4926 checkDLLAttribute(*this, Record);
4927 }
4928
4929 /// Look up the special member function that would be called by a special
4930 /// member function for a subobject of class type.
4931 ///
4932 /// \param Class The class type of the subobject.
4933 /// \param CSM The kind of special member function.
4934 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4935 /// \param ConstRHS True if this is a copy operation with a const object
4936 /// on its RHS, that is, if the argument to the outer special member
4937 /// function is 'const' and this is not a field marked 'mutable'.
lookupCallFromSpecialMember(Sema & S,CXXRecordDecl * Class,Sema::CXXSpecialMember CSM,unsigned FieldQuals,bool ConstRHS)4938 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4939 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4940 unsigned FieldQuals, bool ConstRHS) {
4941 unsigned LHSQuals = 0;
4942 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4943 LHSQuals = FieldQuals;
4944
4945 unsigned RHSQuals = FieldQuals;
4946 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4947 RHSQuals = 0;
4948 else if (ConstRHS)
4949 RHSQuals |= Qualifiers::Const;
4950
4951 return S.LookupSpecialMember(Class, CSM,
4952 RHSQuals & Qualifiers::Const,
4953 RHSQuals & Qualifiers::Volatile,
4954 false,
4955 LHSQuals & Qualifiers::Const,
4956 LHSQuals & Qualifiers::Volatile);
4957 }
4958
4959 /// Is the special member function which would be selected to perform the
4960 /// specified operation on the specified class type a constexpr constructor?
specialMemberIsConstexpr(Sema & S,CXXRecordDecl * ClassDecl,Sema::CXXSpecialMember CSM,unsigned Quals,bool ConstRHS)4961 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4962 Sema::CXXSpecialMember CSM,
4963 unsigned Quals, bool ConstRHS) {
4964 Sema::SpecialMemberOverloadResult *SMOR =
4965 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
4966 if (!SMOR || !SMOR->getMethod())
4967 // A constructor we wouldn't select can't be "involved in initializing"
4968 // anything.
4969 return true;
4970 return SMOR->getMethod()->isConstexpr();
4971 }
4972
4973 /// Determine whether the specified special member function would be constexpr
4974 /// if it were implicitly defined.
defaultedSpecialMemberIsConstexpr(Sema & S,CXXRecordDecl * ClassDecl,Sema::CXXSpecialMember CSM,bool ConstArg)4975 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4976 Sema::CXXSpecialMember CSM,
4977 bool ConstArg) {
4978 if (!S.getLangOpts().CPlusPlus11)
4979 return false;
4980
4981 // C++11 [dcl.constexpr]p4:
4982 // In the definition of a constexpr constructor [...]
4983 bool Ctor = true;
4984 switch (CSM) {
4985 case Sema::CXXDefaultConstructor:
4986 // Since default constructor lookup is essentially trivial (and cannot
4987 // involve, for instance, template instantiation), we compute whether a
4988 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4989 //
4990 // This is important for performance; we need to know whether the default
4991 // constructor is constexpr to determine whether the type is a literal type.
4992 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4993
4994 case Sema::CXXCopyConstructor:
4995 case Sema::CXXMoveConstructor:
4996 // For copy or move constructors, we need to perform overload resolution.
4997 break;
4998
4999 case Sema::CXXCopyAssignment:
5000 case Sema::CXXMoveAssignment:
5001 if (!S.getLangOpts().CPlusPlus14)
5002 return false;
5003 // In C++1y, we need to perform overload resolution.
5004 Ctor = false;
5005 break;
5006
5007 case Sema::CXXDestructor:
5008 case Sema::CXXInvalid:
5009 return false;
5010 }
5011
5012 // -- if the class is a non-empty union, or for each non-empty anonymous
5013 // union member of a non-union class, exactly one non-static data member
5014 // shall be initialized; [DR1359]
5015 //
5016 // If we squint, this is guaranteed, since exactly one non-static data member
5017 // will be initialized (if the constructor isn't deleted), we just don't know
5018 // which one.
5019 if (Ctor && ClassDecl->isUnion())
5020 return true;
5021
5022 // -- the class shall not have any virtual base classes;
5023 if (Ctor && ClassDecl->getNumVBases())
5024 return false;
5025
5026 // C++1y [class.copy]p26:
5027 // -- [the class] is a literal type, and
5028 if (!Ctor && !ClassDecl->isLiteral())
5029 return false;
5030
5031 // -- every constructor involved in initializing [...] base class
5032 // sub-objects shall be a constexpr constructor;
5033 // -- the assignment operator selected to copy/move each direct base
5034 // class is a constexpr function, and
5035 for (const auto &B : ClassDecl->bases()) {
5036 const RecordType *BaseType = B.getType()->getAs<RecordType>();
5037 if (!BaseType) continue;
5038
5039 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5040 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
5041 return false;
5042 }
5043
5044 // -- every constructor involved in initializing non-static data members
5045 // [...] shall be a constexpr constructor;
5046 // -- every non-static data member and base class sub-object shall be
5047 // initialized
5048 // -- for each non-static data member of X that is of class type (or array
5049 // thereof), the assignment operator selected to copy/move that member is
5050 // a constexpr function
5051 for (const auto *F : ClassDecl->fields()) {
5052 if (F->isInvalidDecl())
5053 continue;
5054 QualType BaseType = S.Context.getBaseElementType(F->getType());
5055 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
5056 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5057 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5058 BaseType.getCVRQualifiers(),
5059 ConstArg && !F->isMutable()))
5060 return false;
5061 }
5062 }
5063
5064 // All OK, it's constexpr!
5065 return true;
5066 }
5067
5068 static Sema::ImplicitExceptionSpecification
computeImplicitExceptionSpec(Sema & S,SourceLocation Loc,CXXMethodDecl * MD)5069 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5070 switch (S.getSpecialMember(MD)) {
5071 case Sema::CXXDefaultConstructor:
5072 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5073 case Sema::CXXCopyConstructor:
5074 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5075 case Sema::CXXCopyAssignment:
5076 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5077 case Sema::CXXMoveConstructor:
5078 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5079 case Sema::CXXMoveAssignment:
5080 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5081 case Sema::CXXDestructor:
5082 return S.ComputeDefaultedDtorExceptionSpec(MD);
5083 case Sema::CXXInvalid:
5084 break;
5085 }
5086 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5087 "only special members have implicit exception specs");
5088 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
5089 }
5090
getImplicitMethodEPI(Sema & S,CXXMethodDecl * MD)5091 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5092 CXXMethodDecl *MD) {
5093 FunctionProtoType::ExtProtoInfo EPI;
5094
5095 // Build an exception specification pointing back at this member.
5096 EPI.ExceptionSpec.Type = EST_Unevaluated;
5097 EPI.ExceptionSpec.SourceDecl = MD;
5098
5099 // Set the calling convention to the default for C++ instance methods.
5100 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5101 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5102 /*IsCXXMethod=*/true));
5103 return EPI;
5104 }
5105
EvaluateImplicitExceptionSpec(SourceLocation Loc,CXXMethodDecl * MD)5106 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5107 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5108 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5109 return;
5110
5111 // Evaluate the exception specification.
5112 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
5113
5114 // Update the type of the special member to use it.
5115 UpdateExceptionSpec(MD, ESI);
5116
5117 // A user-provided destructor can be defined outside the class. When that
5118 // happens, be sure to update the exception specification on both
5119 // declarations.
5120 const FunctionProtoType *CanonicalFPT =
5121 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5122 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
5123 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
5124 }
5125
CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl * MD)5126 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5127 CXXRecordDecl *RD = MD->getParent();
5128 CXXSpecialMember CSM = getSpecialMember(MD);
5129
5130 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5131 "not an explicitly-defaulted special member");
5132
5133 // Whether this was the first-declared instance of the constructor.
5134 // This affects whether we implicitly add an exception spec and constexpr.
5135 bool First = MD == MD->getCanonicalDecl();
5136
5137 bool HadError = false;
5138
5139 // C++11 [dcl.fct.def.default]p1:
5140 // A function that is explicitly defaulted shall
5141 // -- be a special member function (checked elsewhere),
5142 // -- have the same type (except for ref-qualifiers, and except that a
5143 // copy operation can take a non-const reference) as an implicit
5144 // declaration, and
5145 // -- not have default arguments.
5146 unsigned ExpectedParams = 1;
5147 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5148 ExpectedParams = 0;
5149 if (MD->getNumParams() != ExpectedParams) {
5150 // This also checks for default arguments: a copy or move constructor with a
5151 // default argument is classified as a default constructor, and assignment
5152 // operations and destructors can't have default arguments.
5153 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5154 << CSM << MD->getSourceRange();
5155 HadError = true;
5156 } else if (MD->isVariadic()) {
5157 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5158 << CSM << MD->getSourceRange();
5159 HadError = true;
5160 }
5161
5162 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
5163
5164 bool CanHaveConstParam = false;
5165 if (CSM == CXXCopyConstructor)
5166 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
5167 else if (CSM == CXXCopyAssignment)
5168 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
5169
5170 QualType ReturnType = Context.VoidTy;
5171 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5172 // Check for return type matching.
5173 ReturnType = Type->getReturnType();
5174 QualType ExpectedReturnType =
5175 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5176 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5177 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5178 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5179 HadError = true;
5180 }
5181
5182 // A defaulted special member cannot have cv-qualifiers.
5183 if (Type->getTypeQuals()) {
5184 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
5185 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
5186 HadError = true;
5187 }
5188 }
5189
5190 // Check for parameter type matching.
5191 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
5192 bool HasConstParam = false;
5193 if (ExpectedParams && ArgType->isReferenceType()) {
5194 // Argument must be reference to possibly-const T.
5195 QualType ReferentType = ArgType->getPointeeType();
5196 HasConstParam = ReferentType.isConstQualified();
5197
5198 if (ReferentType.isVolatileQualified()) {
5199 Diag(MD->getLocation(),
5200 diag::err_defaulted_special_member_volatile_param) << CSM;
5201 HadError = true;
5202 }
5203
5204 if (HasConstParam && !CanHaveConstParam) {
5205 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5206 Diag(MD->getLocation(),
5207 diag::err_defaulted_special_member_copy_const_param)
5208 << (CSM == CXXCopyAssignment);
5209 // FIXME: Explain why this special member can't be const.
5210 } else {
5211 Diag(MD->getLocation(),
5212 diag::err_defaulted_special_member_move_const_param)
5213 << (CSM == CXXMoveAssignment);
5214 }
5215 HadError = true;
5216 }
5217 } else if (ExpectedParams) {
5218 // A copy assignment operator can take its argument by value, but a
5219 // defaulted one cannot.
5220 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5221 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5222 HadError = true;
5223 }
5224
5225 // C++11 [dcl.fct.def.default]p2:
5226 // An explicitly-defaulted function may be declared constexpr only if it
5227 // would have been implicitly declared as constexpr,
5228 // Do not apply this rule to members of class templates, since core issue 1358
5229 // makes such functions always instantiate to constexpr functions. For
5230 // functions which cannot be constexpr (for non-constructors in C++11 and for
5231 // destructors in C++1y), this is checked elsewhere.
5232 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5233 HasConstParam);
5234 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5235 : isa<CXXConstructorDecl>(MD)) &&
5236 MD->isConstexpr() && !Constexpr &&
5237 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5238 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5239 // FIXME: Explain why the special member can't be constexpr.
5240 HadError = true;
5241 }
5242
5243 // and may have an explicit exception-specification only if it is compatible
5244 // with the exception-specification on the implicit declaration.
5245 if (Type->hasExceptionSpec()) {
5246 // Delay the check if this is the first declaration of the special member,
5247 // since we may not have parsed some necessary in-class initializers yet.
5248 if (First) {
5249 // If the exception specification needs to be instantiated, do so now,
5250 // before we clobber it with an EST_Unevaluated specification below.
5251 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5252 InstantiateExceptionSpec(MD->getLocStart(), MD);
5253 Type = MD->getType()->getAs<FunctionProtoType>();
5254 }
5255 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5256 } else
5257 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5258 }
5259
5260 // If a function is explicitly defaulted on its first declaration,
5261 if (First) {
5262 // -- it is implicitly considered to be constexpr if the implicit
5263 // definition would be,
5264 MD->setConstexpr(Constexpr);
5265
5266 // -- it is implicitly considered to have the same exception-specification
5267 // as if it had been implicitly declared,
5268 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5269 EPI.ExceptionSpec.Type = EST_Unevaluated;
5270 EPI.ExceptionSpec.SourceDecl = MD;
5271 MD->setType(Context.getFunctionType(ReturnType,
5272 llvm::makeArrayRef(&ArgType,
5273 ExpectedParams),
5274 EPI));
5275 }
5276
5277 if (ShouldDeleteSpecialMember(MD, CSM)) {
5278 if (First) {
5279 SetDeclDeleted(MD, MD->getLocation());
5280 } else {
5281 // C++11 [dcl.fct.def.default]p4:
5282 // [For a] user-provided explicitly-defaulted function [...] if such a
5283 // function is implicitly defined as deleted, the program is ill-formed.
5284 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5285 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5286 HadError = true;
5287 }
5288 }
5289
5290 if (HadError)
5291 MD->setInvalidDecl();
5292 }
5293
5294 /// Check whether the exception specification provided for an
5295 /// explicitly-defaulted special member matches the exception specification
5296 /// that would have been generated for an implicit special member, per
5297 /// C++11 [dcl.fct.def.default]p2.
CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl * MD,const FunctionProtoType * SpecifiedType)5298 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5299 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5300 // If the exception specification was explicitly specified but hadn't been
5301 // parsed when the method was defaulted, grab it now.
5302 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5303 SpecifiedType =
5304 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5305
5306 // Compute the implicit exception specification.
5307 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5308 /*IsCXXMethod=*/true);
5309 FunctionProtoType::ExtProtoInfo EPI(CC);
5310 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5311 .getExceptionSpec();
5312 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5313 Context.getFunctionType(Context.VoidTy, None, EPI));
5314
5315 // Ensure that it matches.
5316 CheckEquivalentExceptionSpec(
5317 PDiag(diag::err_incorrect_defaulted_exception_spec)
5318 << getSpecialMember(MD), PDiag(),
5319 ImplicitType, SourceLocation(),
5320 SpecifiedType, MD->getLocation());
5321 }
5322
CheckDelayedMemberExceptionSpecs()5323 void Sema::CheckDelayedMemberExceptionSpecs() {
5324 decltype(DelayedExceptionSpecChecks) Checks;
5325 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
5326
5327 std::swap(Checks, DelayedExceptionSpecChecks);
5328 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5329
5330 // Perform any deferred checking of exception specifications for virtual
5331 // destructors.
5332 for (auto &Check : Checks)
5333 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
5334
5335 // Check that any explicitly-defaulted methods have exception specifications
5336 // compatible with their implicit exception specifications.
5337 for (auto &Spec : Specs)
5338 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
5339 }
5340
5341 namespace {
5342 struct SpecialMemberDeletionInfo {
5343 Sema &S;
5344 CXXMethodDecl *MD;
5345 Sema::CXXSpecialMember CSM;
5346 bool Diagnose;
5347
5348 // Properties of the special member, computed for convenience.
5349 bool IsConstructor, IsAssignment, IsMove, ConstArg;
5350 SourceLocation Loc;
5351
5352 bool AllFieldsAreConst;
5353
SpecialMemberDeletionInfo__anon515e6f930711::SpecialMemberDeletionInfo5354 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5355 Sema::CXXSpecialMember CSM, bool Diagnose)
5356 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5357 IsConstructor(false), IsAssignment(false), IsMove(false),
5358 ConstArg(false), Loc(MD->getLocation()),
5359 AllFieldsAreConst(true) {
5360 switch (CSM) {
5361 case Sema::CXXDefaultConstructor:
5362 case Sema::CXXCopyConstructor:
5363 IsConstructor = true;
5364 break;
5365 case Sema::CXXMoveConstructor:
5366 IsConstructor = true;
5367 IsMove = true;
5368 break;
5369 case Sema::CXXCopyAssignment:
5370 IsAssignment = true;
5371 break;
5372 case Sema::CXXMoveAssignment:
5373 IsAssignment = true;
5374 IsMove = true;
5375 break;
5376 case Sema::CXXDestructor:
5377 break;
5378 case Sema::CXXInvalid:
5379 llvm_unreachable("invalid special member kind");
5380 }
5381
5382 if (MD->getNumParams()) {
5383 if (const ReferenceType *RT =
5384 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5385 ConstArg = RT->getPointeeType().isConstQualified();
5386 }
5387 }
5388
inUnion__anon515e6f930711::SpecialMemberDeletionInfo5389 bool inUnion() const { return MD->getParent()->isUnion(); }
5390
5391 /// Look up the corresponding special member in the given class.
lookupIn__anon515e6f930711::SpecialMemberDeletionInfo5392 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5393 unsigned Quals, bool IsMutable) {
5394 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5395 ConstArg && !IsMutable);
5396 }
5397
5398 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5399
5400 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5401 bool shouldDeleteForField(FieldDecl *FD);
5402 bool shouldDeleteForAllConstMembers();
5403
5404 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5405 unsigned Quals);
5406 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5407 Sema::SpecialMemberOverloadResult *SMOR,
5408 bool IsDtorCallInCtor);
5409
5410 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5411 };
5412 }
5413
5414 /// Is the given special member inaccessible when used on the given
5415 /// sub-object.
isAccessible(Subobject Subobj,CXXMethodDecl * target)5416 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5417 CXXMethodDecl *target) {
5418 /// If we're operating on a base class, the object type is the
5419 /// type of this special member.
5420 QualType objectTy;
5421 AccessSpecifier access = target->getAccess();
5422 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5423 objectTy = S.Context.getTypeDeclType(MD->getParent());
5424 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5425
5426 // If we're operating on a field, the object type is the type of the field.
5427 } else {
5428 objectTy = S.Context.getTypeDeclType(target->getParent());
5429 }
5430
5431 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5432 }
5433
5434 /// Check whether we should delete a special member due to the implicit
5435 /// definition containing a call to a special member of a subobject.
shouldDeleteForSubobjectCall(Subobject Subobj,Sema::SpecialMemberOverloadResult * SMOR,bool IsDtorCallInCtor)5436 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5437 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5438 bool IsDtorCallInCtor) {
5439 CXXMethodDecl *Decl = SMOR->getMethod();
5440 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5441
5442 int DiagKind = -1;
5443
5444 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5445 DiagKind = !Decl ? 0 : 1;
5446 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5447 DiagKind = 2;
5448 else if (!isAccessible(Subobj, Decl))
5449 DiagKind = 3;
5450 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5451 !Decl->isTrivial()) {
5452 // A member of a union must have a trivial corresponding special member.
5453 // As a weird special case, a destructor call from a union's constructor
5454 // must be accessible and non-deleted, but need not be trivial. Such a
5455 // destructor is never actually called, but is semantically checked as
5456 // if it were.
5457 DiagKind = 4;
5458 }
5459
5460 if (DiagKind == -1)
5461 return false;
5462
5463 if (Diagnose) {
5464 if (Field) {
5465 S.Diag(Field->getLocation(),
5466 diag::note_deleted_special_member_class_subobject)
5467 << CSM << MD->getParent() << /*IsField*/true
5468 << Field << DiagKind << IsDtorCallInCtor;
5469 } else {
5470 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5471 S.Diag(Base->getLocStart(),
5472 diag::note_deleted_special_member_class_subobject)
5473 << CSM << MD->getParent() << /*IsField*/false
5474 << Base->getType() << DiagKind << IsDtorCallInCtor;
5475 }
5476
5477 if (DiagKind == 1)
5478 S.NoteDeletedFunction(Decl);
5479 // FIXME: Explain inaccessibility if DiagKind == 3.
5480 }
5481
5482 return true;
5483 }
5484
5485 /// Check whether we should delete a special member function due to having a
5486 /// direct or virtual base class or non-static data member of class type M.
shouldDeleteForClassSubobject(CXXRecordDecl * Class,Subobject Subobj,unsigned Quals)5487 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5488 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5489 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5490 bool IsMutable = Field && Field->isMutable();
5491
5492 // C++11 [class.ctor]p5:
5493 // -- any direct or virtual base class, or non-static data member with no
5494 // brace-or-equal-initializer, has class type M (or array thereof) and
5495 // either M has no default constructor or overload resolution as applied
5496 // to M's default constructor results in an ambiguity or in a function
5497 // that is deleted or inaccessible
5498 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5499 // -- a direct or virtual base class B that cannot be copied/moved because
5500 // overload resolution, as applied to B's corresponding special member,
5501 // results in an ambiguity or a function that is deleted or inaccessible
5502 // from the defaulted special member
5503 // C++11 [class.dtor]p5:
5504 // -- any direct or virtual base class [...] has a type with a destructor
5505 // that is deleted or inaccessible
5506 if (!(CSM == Sema::CXXDefaultConstructor &&
5507 Field && Field->hasInClassInitializer()) &&
5508 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5509 false))
5510 return true;
5511
5512 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5513 // -- any direct or virtual base class or non-static data member has a
5514 // type with a destructor that is deleted or inaccessible
5515 if (IsConstructor) {
5516 Sema::SpecialMemberOverloadResult *SMOR =
5517 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5518 false, false, false, false, false);
5519 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5520 return true;
5521 }
5522
5523 return false;
5524 }
5525
5526 /// Check whether we should delete a special member function due to the class
5527 /// having a particular direct or virtual base class.
shouldDeleteForBase(CXXBaseSpecifier * Base)5528 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5529 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5530 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5531 }
5532
5533 /// Check whether we should delete a special member function due to the class
5534 /// having a particular non-static data member.
shouldDeleteForField(FieldDecl * FD)5535 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5536 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5537 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5538
5539 if (CSM == Sema::CXXDefaultConstructor) {
5540 // For a default constructor, all references must be initialized in-class
5541 // and, if a union, it must have a non-const member.
5542 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5543 if (Diagnose)
5544 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5545 << MD->getParent() << FD << FieldType << /*Reference*/0;
5546 return true;
5547 }
5548 // C++11 [class.ctor]p5: any non-variant non-static data member of
5549 // const-qualified type (or array thereof) with no
5550 // brace-or-equal-initializer does not have a user-provided default
5551 // constructor.
5552 if (!inUnion() && FieldType.isConstQualified() &&
5553 !FD->hasInClassInitializer() &&
5554 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5555 if (Diagnose)
5556 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5557 << MD->getParent() << FD << FD->getType() << /*Const*/1;
5558 return true;
5559 }
5560
5561 if (inUnion() && !FieldType.isConstQualified())
5562 AllFieldsAreConst = false;
5563 } else if (CSM == Sema::CXXCopyConstructor) {
5564 // For a copy constructor, data members must not be of rvalue reference
5565 // type.
5566 if (FieldType->isRValueReferenceType()) {
5567 if (Diagnose)
5568 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5569 << MD->getParent() << FD << FieldType;
5570 return true;
5571 }
5572 } else if (IsAssignment) {
5573 // For an assignment operator, data members must not be of reference type.
5574 if (FieldType->isReferenceType()) {
5575 if (Diagnose)
5576 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5577 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5578 return true;
5579 }
5580 if (!FieldRecord && FieldType.isConstQualified()) {
5581 // C++11 [class.copy]p23:
5582 // -- a non-static data member of const non-class type (or array thereof)
5583 if (Diagnose)
5584 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5585 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5586 return true;
5587 }
5588 }
5589
5590 if (FieldRecord) {
5591 // Some additional restrictions exist on the variant members.
5592 if (!inUnion() && FieldRecord->isUnion() &&
5593 FieldRecord->isAnonymousStructOrUnion()) {
5594 bool AllVariantFieldsAreConst = true;
5595
5596 // FIXME: Handle anonymous unions declared within anonymous unions.
5597 for (auto *UI : FieldRecord->fields()) {
5598 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5599
5600 if (!UnionFieldType.isConstQualified())
5601 AllVariantFieldsAreConst = false;
5602
5603 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5604 if (UnionFieldRecord &&
5605 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5606 UnionFieldType.getCVRQualifiers()))
5607 return true;
5608 }
5609
5610 // At least one member in each anonymous union must be non-const
5611 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5612 !FieldRecord->field_empty()) {
5613 if (Diagnose)
5614 S.Diag(FieldRecord->getLocation(),
5615 diag::note_deleted_default_ctor_all_const)
5616 << MD->getParent() << /*anonymous union*/1;
5617 return true;
5618 }
5619
5620 // Don't check the implicit member of the anonymous union type.
5621 // This is technically non-conformant, but sanity demands it.
5622 return false;
5623 }
5624
5625 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5626 FieldType.getCVRQualifiers()))
5627 return true;
5628 }
5629
5630 return false;
5631 }
5632
5633 /// C++11 [class.ctor] p5:
5634 /// A defaulted default constructor for a class X is defined as deleted if
5635 /// X is a union and all of its variant members are of const-qualified type.
shouldDeleteForAllConstMembers()5636 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5637 // This is a silly definition, because it gives an empty union a deleted
5638 // default constructor. Don't do that.
5639 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5640 !MD->getParent()->field_empty()) {
5641 if (Diagnose)
5642 S.Diag(MD->getParent()->getLocation(),
5643 diag::note_deleted_default_ctor_all_const)
5644 << MD->getParent() << /*not anonymous union*/0;
5645 return true;
5646 }
5647 return false;
5648 }
5649
5650 /// Determine whether a defaulted special member function should be defined as
5651 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5652 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
ShouldDeleteSpecialMember(CXXMethodDecl * MD,CXXSpecialMember CSM,bool Diagnose)5653 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5654 bool Diagnose) {
5655 if (MD->isInvalidDecl())
5656 return false;
5657 CXXRecordDecl *RD = MD->getParent();
5658 assert(!RD->isDependentType() && "do deletion after instantiation");
5659 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5660 return false;
5661
5662 // C++11 [expr.lambda.prim]p19:
5663 // The closure type associated with a lambda-expression has a
5664 // deleted (8.4.3) default constructor and a deleted copy
5665 // assignment operator.
5666 if (RD->isLambda() &&
5667 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5668 if (Diagnose)
5669 Diag(RD->getLocation(), diag::note_lambda_decl);
5670 return true;
5671 }
5672
5673 // For an anonymous struct or union, the copy and assignment special members
5674 // will never be used, so skip the check. For an anonymous union declared at
5675 // namespace scope, the constructor and destructor are used.
5676 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5677 RD->isAnonymousStructOrUnion())
5678 return false;
5679
5680 // C++11 [class.copy]p7, p18:
5681 // If the class definition declares a move constructor or move assignment
5682 // operator, an implicitly declared copy constructor or copy assignment
5683 // operator is defined as deleted.
5684 if (MD->isImplicit() &&
5685 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5686 CXXMethodDecl *UserDeclaredMove = nullptr;
5687
5688 // In Microsoft mode, a user-declared move only causes the deletion of the
5689 // corresponding copy operation, not both copy operations.
5690 if (RD->hasUserDeclaredMoveConstructor() &&
5691 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5692 if (!Diagnose) return true;
5693
5694 // Find any user-declared move constructor.
5695 for (auto *I : RD->ctors()) {
5696 if (I->isMoveConstructor()) {
5697 UserDeclaredMove = I;
5698 break;
5699 }
5700 }
5701 assert(UserDeclaredMove);
5702 } else if (RD->hasUserDeclaredMoveAssignment() &&
5703 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5704 if (!Diagnose) return true;
5705
5706 // Find any user-declared move assignment operator.
5707 for (auto *I : RD->methods()) {
5708 if (I->isMoveAssignmentOperator()) {
5709 UserDeclaredMove = I;
5710 break;
5711 }
5712 }
5713 assert(UserDeclaredMove);
5714 }
5715
5716 if (UserDeclaredMove) {
5717 Diag(UserDeclaredMove->getLocation(),
5718 diag::note_deleted_copy_user_declared_move)
5719 << (CSM == CXXCopyAssignment) << RD
5720 << UserDeclaredMove->isMoveAssignmentOperator();
5721 return true;
5722 }
5723 }
5724
5725 // Do access control from the special member function
5726 ContextRAII MethodContext(*this, MD);
5727
5728 // C++11 [class.dtor]p5:
5729 // -- for a virtual destructor, lookup of the non-array deallocation function
5730 // results in an ambiguity or in a function that is deleted or inaccessible
5731 if (CSM == CXXDestructor && MD->isVirtual()) {
5732 FunctionDecl *OperatorDelete = nullptr;
5733 DeclarationName Name =
5734 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5735 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5736 OperatorDelete, false)) {
5737 if (Diagnose)
5738 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5739 return true;
5740 }
5741 }
5742
5743 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5744
5745 for (auto &BI : RD->bases())
5746 if (!BI.isVirtual() &&
5747 SMI.shouldDeleteForBase(&BI))
5748 return true;
5749
5750 // Per DR1611, do not consider virtual bases of constructors of abstract
5751 // classes, since we are not going to construct them.
5752 if (!RD->isAbstract() || !SMI.IsConstructor) {
5753 for (auto &BI : RD->vbases())
5754 if (SMI.shouldDeleteForBase(&BI))
5755 return true;
5756 }
5757
5758 for (auto *FI : RD->fields())
5759 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5760 SMI.shouldDeleteForField(FI))
5761 return true;
5762
5763 if (SMI.shouldDeleteForAllConstMembers())
5764 return true;
5765
5766 if (getLangOpts().CUDA) {
5767 // We should delete the special member in CUDA mode if target inference
5768 // failed.
5769 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5770 Diagnose);
5771 }
5772
5773 return false;
5774 }
5775
5776 /// Perform lookup for a special member of the specified kind, and determine
5777 /// whether it is trivial. If the triviality can be determined without the
5778 /// lookup, skip it. This is intended for use when determining whether a
5779 /// special member of a containing object is trivial, and thus does not ever
5780 /// perform overload resolution for default constructors.
5781 ///
5782 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5783 /// member that was most likely to be intended to be trivial, if any.
findTrivialSpecialMember(Sema & S,CXXRecordDecl * RD,Sema::CXXSpecialMember CSM,unsigned Quals,bool ConstRHS,CXXMethodDecl ** Selected)5784 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5785 Sema::CXXSpecialMember CSM, unsigned Quals,
5786 bool ConstRHS, CXXMethodDecl **Selected) {
5787 if (Selected)
5788 *Selected = nullptr;
5789
5790 switch (CSM) {
5791 case Sema::CXXInvalid:
5792 llvm_unreachable("not a special member");
5793
5794 case Sema::CXXDefaultConstructor:
5795 // C++11 [class.ctor]p5:
5796 // A default constructor is trivial if:
5797 // - all the [direct subobjects] have trivial default constructors
5798 //
5799 // Note, no overload resolution is performed in this case.
5800 if (RD->hasTrivialDefaultConstructor())
5801 return true;
5802
5803 if (Selected) {
5804 // If there's a default constructor which could have been trivial, dig it
5805 // out. Otherwise, if there's any user-provided default constructor, point
5806 // to that as an example of why there's not a trivial one.
5807 CXXConstructorDecl *DefCtor = nullptr;
5808 if (RD->needsImplicitDefaultConstructor())
5809 S.DeclareImplicitDefaultConstructor(RD);
5810 for (auto *CI : RD->ctors()) {
5811 if (!CI->isDefaultConstructor())
5812 continue;
5813 DefCtor = CI;
5814 if (!DefCtor->isUserProvided())
5815 break;
5816 }
5817
5818 *Selected = DefCtor;
5819 }
5820
5821 return false;
5822
5823 case Sema::CXXDestructor:
5824 // C++11 [class.dtor]p5:
5825 // A destructor is trivial if:
5826 // - all the direct [subobjects] have trivial destructors
5827 if (RD->hasTrivialDestructor())
5828 return true;
5829
5830 if (Selected) {
5831 if (RD->needsImplicitDestructor())
5832 S.DeclareImplicitDestructor(RD);
5833 *Selected = RD->getDestructor();
5834 }
5835
5836 return false;
5837
5838 case Sema::CXXCopyConstructor:
5839 // C++11 [class.copy]p12:
5840 // A copy constructor is trivial if:
5841 // - the constructor selected to copy each direct [subobject] is trivial
5842 if (RD->hasTrivialCopyConstructor()) {
5843 if (Quals == Qualifiers::Const)
5844 // We must either select the trivial copy constructor or reach an
5845 // ambiguity; no need to actually perform overload resolution.
5846 return true;
5847 } else if (!Selected) {
5848 return false;
5849 }
5850 // In C++98, we are not supposed to perform overload resolution here, but we
5851 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5852 // cases like B as having a non-trivial copy constructor:
5853 // struct A { template<typename T> A(T&); };
5854 // struct B { mutable A a; };
5855 goto NeedOverloadResolution;
5856
5857 case Sema::CXXCopyAssignment:
5858 // C++11 [class.copy]p25:
5859 // A copy assignment operator is trivial if:
5860 // - the assignment operator selected to copy each direct [subobject] is
5861 // trivial
5862 if (RD->hasTrivialCopyAssignment()) {
5863 if (Quals == Qualifiers::Const)
5864 return true;
5865 } else if (!Selected) {
5866 return false;
5867 }
5868 // In C++98, we are not supposed to perform overload resolution here, but we
5869 // treat that as a language defect.
5870 goto NeedOverloadResolution;
5871
5872 case Sema::CXXMoveConstructor:
5873 case Sema::CXXMoveAssignment:
5874 NeedOverloadResolution:
5875 Sema::SpecialMemberOverloadResult *SMOR =
5876 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5877
5878 // The standard doesn't describe how to behave if the lookup is ambiguous.
5879 // We treat it as not making the member non-trivial, just like the standard
5880 // mandates for the default constructor. This should rarely matter, because
5881 // the member will also be deleted.
5882 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5883 return true;
5884
5885 if (!SMOR->getMethod()) {
5886 assert(SMOR->getKind() ==
5887 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5888 return false;
5889 }
5890
5891 // We deliberately don't check if we found a deleted special member. We're
5892 // not supposed to!
5893 if (Selected)
5894 *Selected = SMOR->getMethod();
5895 return SMOR->getMethod()->isTrivial();
5896 }
5897
5898 llvm_unreachable("unknown special method kind");
5899 }
5900
findUserDeclaredCtor(CXXRecordDecl * RD)5901 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5902 for (auto *CI : RD->ctors())
5903 if (!CI->isImplicit())
5904 return CI;
5905
5906 // Look for constructor templates.
5907 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5908 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5909 if (CXXConstructorDecl *CD =
5910 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5911 return CD;
5912 }
5913
5914 return nullptr;
5915 }
5916
5917 /// The kind of subobject we are checking for triviality. The values of this
5918 /// enumeration are used in diagnostics.
5919 enum TrivialSubobjectKind {
5920 /// The subobject is a base class.
5921 TSK_BaseClass,
5922 /// The subobject is a non-static data member.
5923 TSK_Field,
5924 /// The object is actually the complete object.
5925 TSK_CompleteObject
5926 };
5927
5928 /// Check whether the special member selected for a given type would be trivial.
checkTrivialSubobjectCall(Sema & S,SourceLocation SubobjLoc,QualType SubType,bool ConstRHS,Sema::CXXSpecialMember CSM,TrivialSubobjectKind Kind,bool Diagnose)5929 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5930 QualType SubType, bool ConstRHS,
5931 Sema::CXXSpecialMember CSM,
5932 TrivialSubobjectKind Kind,
5933 bool Diagnose) {
5934 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5935 if (!SubRD)
5936 return true;
5937
5938 CXXMethodDecl *Selected;
5939 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5940 ConstRHS, Diagnose ? &Selected : nullptr))
5941 return true;
5942
5943 if (Diagnose) {
5944 if (ConstRHS)
5945 SubType.addConst();
5946
5947 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5948 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5949 << Kind << SubType.getUnqualifiedType();
5950 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5951 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5952 } else if (!Selected)
5953 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5954 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5955 else if (Selected->isUserProvided()) {
5956 if (Kind == TSK_CompleteObject)
5957 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5958 << Kind << SubType.getUnqualifiedType() << CSM;
5959 else {
5960 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5961 << Kind << SubType.getUnqualifiedType() << CSM;
5962 S.Diag(Selected->getLocation(), diag::note_declared_at);
5963 }
5964 } else {
5965 if (Kind != TSK_CompleteObject)
5966 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5967 << Kind << SubType.getUnqualifiedType() << CSM;
5968
5969 // Explain why the defaulted or deleted special member isn't trivial.
5970 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5971 }
5972 }
5973
5974 return false;
5975 }
5976
5977 /// Check whether the members of a class type allow a special member to be
5978 /// trivial.
checkTrivialClassMembers(Sema & S,CXXRecordDecl * RD,Sema::CXXSpecialMember CSM,bool ConstArg,bool Diagnose)5979 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5980 Sema::CXXSpecialMember CSM,
5981 bool ConstArg, bool Diagnose) {
5982 for (const auto *FI : RD->fields()) {
5983 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5984 continue;
5985
5986 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5987
5988 // Pretend anonymous struct or union members are members of this class.
5989 if (FI->isAnonymousStructOrUnion()) {
5990 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5991 CSM, ConstArg, Diagnose))
5992 return false;
5993 continue;
5994 }
5995
5996 // C++11 [class.ctor]p5:
5997 // A default constructor is trivial if [...]
5998 // -- no non-static data member of its class has a
5999 // brace-or-equal-initializer
6000 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6001 if (Diagnose)
6002 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
6003 return false;
6004 }
6005
6006 // Objective C ARC 4.3.5:
6007 // [...] nontrivally ownership-qualified types are [...] not trivially
6008 // default constructible, copy constructible, move constructible, copy
6009 // assignable, move assignable, or destructible [...]
6010 if (S.getLangOpts().ObjCAutoRefCount &&
6011 FieldType.hasNonTrivialObjCLifetime()) {
6012 if (Diagnose)
6013 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6014 << RD << FieldType.getObjCLifetime();
6015 return false;
6016 }
6017
6018 bool ConstRHS = ConstArg && !FI->isMutable();
6019 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6020 CSM, TSK_Field, Diagnose))
6021 return false;
6022 }
6023
6024 return true;
6025 }
6026
6027 /// Diagnose why the specified class does not have a trivial special member of
6028 /// the given kind.
DiagnoseNontrivial(const CXXRecordDecl * RD,CXXSpecialMember CSM)6029 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6030 QualType Ty = Context.getRecordType(RD);
6031
6032 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6033 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
6034 TSK_CompleteObject, /*Diagnose*/true);
6035 }
6036
6037 /// Determine whether a defaulted or deleted special member function is trivial,
6038 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6039 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
SpecialMemberIsTrivial(CXXMethodDecl * MD,CXXSpecialMember CSM,bool Diagnose)6040 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6041 bool Diagnose) {
6042 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6043
6044 CXXRecordDecl *RD = MD->getParent();
6045
6046 bool ConstArg = false;
6047
6048 // C++11 [class.copy]p12, p25: [DR1593]
6049 // A [special member] is trivial if [...] its parameter-type-list is
6050 // equivalent to the parameter-type-list of an implicit declaration [...]
6051 switch (CSM) {
6052 case CXXDefaultConstructor:
6053 case CXXDestructor:
6054 // Trivial default constructors and destructors cannot have parameters.
6055 break;
6056
6057 case CXXCopyConstructor:
6058 case CXXCopyAssignment: {
6059 // Trivial copy operations always have const, non-volatile parameter types.
6060 ConstArg = true;
6061 const ParmVarDecl *Param0 = MD->getParamDecl(0);
6062 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6063 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6064 if (Diagnose)
6065 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6066 << Param0->getSourceRange() << Param0->getType()
6067 << Context.getLValueReferenceType(
6068 Context.getRecordType(RD).withConst());
6069 return false;
6070 }
6071 break;
6072 }
6073
6074 case CXXMoveConstructor:
6075 case CXXMoveAssignment: {
6076 // Trivial move operations always have non-cv-qualified parameters.
6077 const ParmVarDecl *Param0 = MD->getParamDecl(0);
6078 const RValueReferenceType *RT =
6079 Param0->getType()->getAs<RValueReferenceType>();
6080 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6081 if (Diagnose)
6082 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6083 << Param0->getSourceRange() << Param0->getType()
6084 << Context.getRValueReferenceType(Context.getRecordType(RD));
6085 return false;
6086 }
6087 break;
6088 }
6089
6090 case CXXInvalid:
6091 llvm_unreachable("not a special member");
6092 }
6093
6094 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6095 if (Diagnose)
6096 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6097 diag::note_nontrivial_default_arg)
6098 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6099 return false;
6100 }
6101 if (MD->isVariadic()) {
6102 if (Diagnose)
6103 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6104 return false;
6105 }
6106
6107 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6108 // A copy/move [constructor or assignment operator] is trivial if
6109 // -- the [member] selected to copy/move each direct base class subobject
6110 // is trivial
6111 //
6112 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6113 // A [default constructor or destructor] is trivial if
6114 // -- all the direct base classes have trivial [default constructors or
6115 // destructors]
6116 for (const auto &BI : RD->bases())
6117 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
6118 ConstArg, CSM, TSK_BaseClass, Diagnose))
6119 return false;
6120
6121 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6122 // A copy/move [constructor or assignment operator] for a class X is
6123 // trivial if
6124 // -- for each non-static data member of X that is of class type (or array
6125 // thereof), the constructor selected to copy/move that member is
6126 // trivial
6127 //
6128 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6129 // A [default constructor or destructor] is trivial if
6130 // -- for all of the non-static data members of its class that are of class
6131 // type (or array thereof), each such class has a trivial [default
6132 // constructor or destructor]
6133 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6134 return false;
6135
6136 // C++11 [class.dtor]p5:
6137 // A destructor is trivial if [...]
6138 // -- the destructor is not virtual
6139 if (CSM == CXXDestructor && MD->isVirtual()) {
6140 if (Diagnose)
6141 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6142 return false;
6143 }
6144
6145 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6146 // A [special member] for class X is trivial if [...]
6147 // -- class X has no virtual functions and no virtual base classes
6148 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6149 if (!Diagnose)
6150 return false;
6151
6152 if (RD->getNumVBases()) {
6153 // Check for virtual bases. We already know that the corresponding
6154 // member in all bases is trivial, so vbases must all be direct.
6155 CXXBaseSpecifier &BS = *RD->vbases_begin();
6156 assert(BS.isVirtual());
6157 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6158 return false;
6159 }
6160
6161 // Must have a virtual method.
6162 for (const auto *MI : RD->methods()) {
6163 if (MI->isVirtual()) {
6164 SourceLocation MLoc = MI->getLocStart();
6165 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6166 return false;
6167 }
6168 }
6169
6170 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6171 }
6172
6173 // Looks like it's trivial!
6174 return true;
6175 }
6176
6177 /// \brief Data used with FindHiddenVirtualMethod
6178 namespace {
6179 struct FindHiddenVirtualMethodData {
6180 Sema *S;
6181 CXXMethodDecl *Method;
6182 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6183 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6184 };
6185 }
6186
6187 /// \brief Check whether any most overriden method from MD in Methods
CheckMostOverridenMethods(const CXXMethodDecl * MD,const llvm::SmallPtrSetImpl<const CXXMethodDecl * > & Methods)6188 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
6189 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6190 if (MD->size_overridden_methods() == 0)
6191 return Methods.count(MD->getCanonicalDecl());
6192 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6193 E = MD->end_overridden_methods();
6194 I != E; ++I)
6195 if (CheckMostOverridenMethods(*I, Methods))
6196 return true;
6197 return false;
6198 }
6199
6200 /// \brief Member lookup function that determines whether a given C++
6201 /// method overloads virtual methods in a base class without overriding any,
6202 /// to be used with CXXRecordDecl::lookupInBases().
FindHiddenVirtualMethod(const CXXBaseSpecifier * Specifier,CXXBasePath & Path,void * UserData)6203 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6204 CXXBasePath &Path,
6205 void *UserData) {
6206 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6207
6208 FindHiddenVirtualMethodData &Data
6209 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6210
6211 DeclarationName Name = Data.Method->getDeclName();
6212 assert(Name.getNameKind() == DeclarationName::Identifier);
6213
6214 bool foundSameNameMethod = false;
6215 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6216 for (Path.Decls = BaseRecord->lookup(Name);
6217 !Path.Decls.empty();
6218 Path.Decls = Path.Decls.slice(1)) {
6219 NamedDecl *D = Path.Decls.front();
6220 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6221 MD = MD->getCanonicalDecl();
6222 foundSameNameMethod = true;
6223 // Interested only in hidden virtual methods.
6224 if (!MD->isVirtual())
6225 continue;
6226 // If the method we are checking overrides a method from its base
6227 // don't warn about the other overloaded methods. Clang deviates from GCC
6228 // by only diagnosing overloads of inherited virtual functions that do not
6229 // override any other virtual functions in the base. GCC's
6230 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6231 // function from a base class. These cases may be better served by a
6232 // warning (not specific to virtual functions) on call sites when the call
6233 // would select a different function from the base class, were it visible.
6234 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6235 if (!Data.S->IsOverload(Data.Method, MD, false))
6236 return true;
6237 // Collect the overload only if its hidden.
6238 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
6239 overloadedMethods.push_back(MD);
6240 }
6241 }
6242
6243 if (foundSameNameMethod)
6244 Data.OverloadedMethods.append(overloadedMethods.begin(),
6245 overloadedMethods.end());
6246 return foundSameNameMethod;
6247 }
6248
6249 /// \brief Add the most overriden methods from MD to Methods
AddMostOverridenMethods(const CXXMethodDecl * MD,llvm::SmallPtrSetImpl<const CXXMethodDecl * > & Methods)6250 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6251 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6252 if (MD->size_overridden_methods() == 0)
6253 Methods.insert(MD->getCanonicalDecl());
6254 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6255 E = MD->end_overridden_methods();
6256 I != E; ++I)
6257 AddMostOverridenMethods(*I, Methods);
6258 }
6259
6260 /// \brief Check if a method overloads virtual methods in a base class without
6261 /// overriding any.
FindHiddenVirtualMethods(CXXMethodDecl * MD,SmallVectorImpl<CXXMethodDecl * > & OverloadedMethods)6262 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6263 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6264 if (!MD->getDeclName().isIdentifier())
6265 return;
6266
6267 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6268 /*bool RecordPaths=*/false,
6269 /*bool DetectVirtual=*/false);
6270 FindHiddenVirtualMethodData Data;
6271 Data.Method = MD;
6272 Data.S = this;
6273
6274 // Keep the base methods that were overriden or introduced in the subclass
6275 // by 'using' in a set. A base method not in this set is hidden.
6276 CXXRecordDecl *DC = MD->getParent();
6277 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6278 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6279 NamedDecl *ND = *I;
6280 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6281 ND = shad->getTargetDecl();
6282 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6283 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
6284 }
6285
6286 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6287 OverloadedMethods = Data.OverloadedMethods;
6288 }
6289
NoteHiddenVirtualMethods(CXXMethodDecl * MD,SmallVectorImpl<CXXMethodDecl * > & OverloadedMethods)6290 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6291 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6292 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6293 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6294 PartialDiagnostic PD = PDiag(
6295 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6296 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6297 Diag(overloadedMD->getLocation(), PD);
6298 }
6299 }
6300
6301 /// \brief Diagnose methods which overload virtual methods in a base class
6302 /// without overriding any.
DiagnoseHiddenVirtualMethods(CXXMethodDecl * MD)6303 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6304 if (MD->isInvalidDecl())
6305 return;
6306
6307 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6308 return;
6309
6310 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6311 FindHiddenVirtualMethods(MD, OverloadedMethods);
6312 if (!OverloadedMethods.empty()) {
6313 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6314 << MD << (OverloadedMethods.size() > 1);
6315
6316 NoteHiddenVirtualMethods(MD, OverloadedMethods);
6317 }
6318 }
6319
ActOnFinishCXXMemberSpecification(Scope * S,SourceLocation RLoc,Decl * TagDecl,SourceLocation LBrac,SourceLocation RBrac,AttributeList * AttrList)6320 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6321 Decl *TagDecl,
6322 SourceLocation LBrac,
6323 SourceLocation RBrac,
6324 AttributeList *AttrList) {
6325 if (!TagDecl)
6326 return;
6327
6328 AdjustDeclIfTemplate(TagDecl);
6329
6330 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6331 if (l->getKind() != AttributeList::AT_Visibility)
6332 continue;
6333 l->setInvalid();
6334 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6335 l->getName();
6336 }
6337
6338 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6339 // strict aliasing violation!
6340 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6341 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6342
6343 CheckCompletedCXXClass(
6344 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6345 }
6346
6347 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6348 /// special functions, such as the default constructor, copy
6349 /// constructor, or destructor, to the given C++ class (C++
6350 /// [special]p1). This routine can only be executed just before the
6351 /// definition of the class is complete.
AddImplicitlyDeclaredMembersToClass(CXXRecordDecl * ClassDecl)6352 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6353 if (!ClassDecl->hasUserDeclaredConstructor())
6354 ++ASTContext::NumImplicitDefaultConstructors;
6355
6356 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6357 ++ASTContext::NumImplicitCopyConstructors;
6358
6359 // If the properties or semantics of the copy constructor couldn't be
6360 // determined while the class was being declared, force a declaration
6361 // of it now.
6362 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6363 DeclareImplicitCopyConstructor(ClassDecl);
6364 }
6365
6366 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6367 ++ASTContext::NumImplicitMoveConstructors;
6368
6369 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6370 DeclareImplicitMoveConstructor(ClassDecl);
6371 }
6372
6373 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6374 ++ASTContext::NumImplicitCopyAssignmentOperators;
6375
6376 // If we have a dynamic class, then the copy assignment operator may be
6377 // virtual, so we have to declare it immediately. This ensures that, e.g.,
6378 // it shows up in the right place in the vtable and that we diagnose
6379 // problems with the implicit exception specification.
6380 if (ClassDecl->isDynamicClass() ||
6381 ClassDecl->needsOverloadResolutionForCopyAssignment())
6382 DeclareImplicitCopyAssignment(ClassDecl);
6383 }
6384
6385 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6386 ++ASTContext::NumImplicitMoveAssignmentOperators;
6387
6388 // Likewise for the move assignment operator.
6389 if (ClassDecl->isDynamicClass() ||
6390 ClassDecl->needsOverloadResolutionForMoveAssignment())
6391 DeclareImplicitMoveAssignment(ClassDecl);
6392 }
6393
6394 if (!ClassDecl->hasUserDeclaredDestructor()) {
6395 ++ASTContext::NumImplicitDestructors;
6396
6397 // If we have a dynamic class, then the destructor may be virtual, so we
6398 // have to declare the destructor immediately. This ensures that, e.g., it
6399 // shows up in the right place in the vtable and that we diagnose problems
6400 // with the implicit exception specification.
6401 if (ClassDecl->isDynamicClass() ||
6402 ClassDecl->needsOverloadResolutionForDestructor())
6403 DeclareImplicitDestructor(ClassDecl);
6404 }
6405 }
6406
ActOnReenterTemplateScope(Scope * S,Decl * D)6407 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6408 if (!D)
6409 return 0;
6410
6411 // The order of template parameters is not important here. All names
6412 // get added to the same scope.
6413 SmallVector<TemplateParameterList *, 4> ParameterLists;
6414
6415 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6416 D = TD->getTemplatedDecl();
6417
6418 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6419 ParameterLists.push_back(PSD->getTemplateParameters());
6420
6421 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6422 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6423 ParameterLists.push_back(DD->getTemplateParameterList(i));
6424
6425 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6426 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6427 ParameterLists.push_back(FTD->getTemplateParameters());
6428 }
6429 }
6430
6431 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6432 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6433 ParameterLists.push_back(TD->getTemplateParameterList(i));
6434
6435 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6436 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6437 ParameterLists.push_back(CTD->getTemplateParameters());
6438 }
6439 }
6440
6441 unsigned Count = 0;
6442 for (TemplateParameterList *Params : ParameterLists) {
6443 if (Params->size() > 0)
6444 // Ignore explicit specializations; they don't contribute to the template
6445 // depth.
6446 ++Count;
6447 for (NamedDecl *Param : *Params) {
6448 if (Param->getDeclName()) {
6449 S->AddDecl(Param);
6450 IdResolver.AddDecl(Param);
6451 }
6452 }
6453 }
6454
6455 return Count;
6456 }
6457
ActOnStartDelayedMemberDeclarations(Scope * S,Decl * RecordD)6458 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6459 if (!RecordD) return;
6460 AdjustDeclIfTemplate(RecordD);
6461 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6462 PushDeclContext(S, Record);
6463 }
6464
ActOnFinishDelayedMemberDeclarations(Scope * S,Decl * RecordD)6465 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6466 if (!RecordD) return;
6467 PopDeclContext();
6468 }
6469
6470 /// This is used to implement the constant expression evaluation part of the
6471 /// attribute enable_if extension. There is nothing in standard C++ which would
6472 /// require reentering parameters.
ActOnReenterCXXMethodParameter(Scope * S,ParmVarDecl * Param)6473 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6474 if (!Param)
6475 return;
6476
6477 S->AddDecl(Param);
6478 if (Param->getDeclName())
6479 IdResolver.AddDecl(Param);
6480 }
6481
6482 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6483 /// parsing a top-level (non-nested) C++ class, and we are now
6484 /// parsing those parts of the given Method declaration that could
6485 /// not be parsed earlier (C++ [class.mem]p2), such as default
6486 /// arguments. This action should enter the scope of the given
6487 /// Method declaration as if we had just parsed the qualified method
6488 /// name. However, it should not bring the parameters into scope;
6489 /// that will be performed by ActOnDelayedCXXMethodParameter.
ActOnStartDelayedCXXMethodDeclaration(Scope * S,Decl * MethodD)6490 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6491 }
6492
6493 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6494 /// C++ method declaration. We're (re-)introducing the given
6495 /// function parameter into scope for use in parsing later parts of
6496 /// the method declaration. For example, we could see an
6497 /// ActOnParamDefaultArgument event for this parameter.
ActOnDelayedCXXMethodParameter(Scope * S,Decl * ParamD)6498 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6499 if (!ParamD)
6500 return;
6501
6502 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6503
6504 // If this parameter has an unparsed default argument, clear it out
6505 // to make way for the parsed default argument.
6506 if (Param->hasUnparsedDefaultArg())
6507 Param->setDefaultArg(nullptr);
6508
6509 S->AddDecl(Param);
6510 if (Param->getDeclName())
6511 IdResolver.AddDecl(Param);
6512 }
6513
6514 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6515 /// processing the delayed method declaration for Method. The method
6516 /// declaration is now considered finished. There may be a separate
6517 /// ActOnStartOfFunctionDef action later (not necessarily
6518 /// immediately!) for this method, if it was also defined inside the
6519 /// class body.
ActOnFinishDelayedCXXMethodDeclaration(Scope * S,Decl * MethodD)6520 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6521 if (!MethodD)
6522 return;
6523
6524 AdjustDeclIfTemplate(MethodD);
6525
6526 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6527
6528 // Now that we have our default arguments, check the constructor
6529 // again. It could produce additional diagnostics or affect whether
6530 // the class has implicitly-declared destructors, among other
6531 // things.
6532 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6533 CheckConstructor(Constructor);
6534
6535 // Check the default arguments, which we may have added.
6536 if (!Method->isInvalidDecl())
6537 CheckCXXDefaultArguments(Method);
6538 }
6539
6540 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6541 /// the well-formedness of the constructor declarator @p D with type @p
6542 /// R. If there are any errors in the declarator, this routine will
6543 /// emit diagnostics and set the invalid bit to true. In any case, the type
6544 /// will be updated to reflect a well-formed type for the constructor and
6545 /// returned.
CheckConstructorDeclarator(Declarator & D,QualType R,StorageClass & SC)6546 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6547 StorageClass &SC) {
6548 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6549
6550 // C++ [class.ctor]p3:
6551 // A constructor shall not be virtual (10.3) or static (9.4). A
6552 // constructor can be invoked for a const, volatile or const
6553 // volatile object. A constructor shall not be declared const,
6554 // volatile, or const volatile (9.3.2).
6555 if (isVirtual) {
6556 if (!D.isInvalidType())
6557 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6558 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6559 << SourceRange(D.getIdentifierLoc());
6560 D.setInvalidType();
6561 }
6562 if (SC == SC_Static) {
6563 if (!D.isInvalidType())
6564 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6565 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6566 << SourceRange(D.getIdentifierLoc());
6567 D.setInvalidType();
6568 SC = SC_None;
6569 }
6570
6571 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6572 diagnoseIgnoredQualifiers(
6573 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6574 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6575 D.getDeclSpec().getRestrictSpecLoc(),
6576 D.getDeclSpec().getAtomicSpecLoc());
6577 D.setInvalidType();
6578 }
6579
6580 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6581 if (FTI.TypeQuals != 0) {
6582 if (FTI.TypeQuals & Qualifiers::Const)
6583 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6584 << "const" << SourceRange(D.getIdentifierLoc());
6585 if (FTI.TypeQuals & Qualifiers::Volatile)
6586 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6587 << "volatile" << SourceRange(D.getIdentifierLoc());
6588 if (FTI.TypeQuals & Qualifiers::Restrict)
6589 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6590 << "restrict" << SourceRange(D.getIdentifierLoc());
6591 D.setInvalidType();
6592 }
6593
6594 // C++0x [class.ctor]p4:
6595 // A constructor shall not be declared with a ref-qualifier.
6596 if (FTI.hasRefQualifier()) {
6597 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6598 << FTI.RefQualifierIsLValueRef
6599 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6600 D.setInvalidType();
6601 }
6602
6603 // Rebuild the function type "R" without any type qualifiers (in
6604 // case any of the errors above fired) and with "void" as the
6605 // return type, since constructors don't have return types.
6606 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6607 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6608 return R;
6609
6610 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6611 EPI.TypeQuals = 0;
6612 EPI.RefQualifier = RQ_None;
6613
6614 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6615 }
6616
6617 /// CheckConstructor - Checks a fully-formed constructor for
6618 /// well-formedness, issuing any diagnostics required. Returns true if
6619 /// the constructor declarator is invalid.
CheckConstructor(CXXConstructorDecl * Constructor)6620 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6621 CXXRecordDecl *ClassDecl
6622 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6623 if (!ClassDecl)
6624 return Constructor->setInvalidDecl();
6625
6626 // C++ [class.copy]p3:
6627 // A declaration of a constructor for a class X is ill-formed if
6628 // its first parameter is of type (optionally cv-qualified) X and
6629 // either there are no other parameters or else all other
6630 // parameters have default arguments.
6631 if (!Constructor->isInvalidDecl() &&
6632 ((Constructor->getNumParams() == 1) ||
6633 (Constructor->getNumParams() > 1 &&
6634 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6635 Constructor->getTemplateSpecializationKind()
6636 != TSK_ImplicitInstantiation) {
6637 QualType ParamType = Constructor->getParamDecl(0)->getType();
6638 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6639 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6640 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6641 const char *ConstRef
6642 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6643 : " const &";
6644 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6645 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6646
6647 // FIXME: Rather that making the constructor invalid, we should endeavor
6648 // to fix the type.
6649 Constructor->setInvalidDecl();
6650 }
6651 }
6652 }
6653
6654 /// CheckDestructor - Checks a fully-formed destructor definition for
6655 /// well-formedness, issuing any diagnostics required. Returns true
6656 /// on error.
CheckDestructor(CXXDestructorDecl * Destructor)6657 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6658 CXXRecordDecl *RD = Destructor->getParent();
6659
6660 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6661 SourceLocation Loc;
6662
6663 if (!Destructor->isImplicit())
6664 Loc = Destructor->getLocation();
6665 else
6666 Loc = RD->getLocation();
6667
6668 // If we have a virtual destructor, look up the deallocation function
6669 FunctionDecl *OperatorDelete = nullptr;
6670 DeclarationName Name =
6671 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6672 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6673 return true;
6674 // If there's no class-specific operator delete, look up the global
6675 // non-array delete.
6676 if (!OperatorDelete)
6677 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6678
6679 MarkFunctionReferenced(Loc, OperatorDelete);
6680
6681 Destructor->setOperatorDelete(OperatorDelete);
6682 }
6683
6684 return false;
6685 }
6686
6687 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6688 /// the well-formednes of the destructor declarator @p D with type @p
6689 /// R. If there are any errors in the declarator, this routine will
6690 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6691 /// will be updated to reflect a well-formed type for the destructor and
6692 /// returned.
CheckDestructorDeclarator(Declarator & D,QualType R,StorageClass & SC)6693 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6694 StorageClass& SC) {
6695 // C++ [class.dtor]p1:
6696 // [...] A typedef-name that names a class is a class-name
6697 // (7.1.3); however, a typedef-name that names a class shall not
6698 // be used as the identifier in the declarator for a destructor
6699 // declaration.
6700 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6701 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6702 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6703 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6704 else if (const TemplateSpecializationType *TST =
6705 DeclaratorType->getAs<TemplateSpecializationType>())
6706 if (TST->isTypeAlias())
6707 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6708 << DeclaratorType << 1;
6709
6710 // C++ [class.dtor]p2:
6711 // A destructor is used to destroy objects of its class type. A
6712 // destructor takes no parameters, and no return type can be
6713 // specified for it (not even void). The address of a destructor
6714 // shall not be taken. A destructor shall not be static. A
6715 // destructor can be invoked for a const, volatile or const
6716 // volatile object. A destructor shall not be declared const,
6717 // volatile or const volatile (9.3.2).
6718 if (SC == SC_Static) {
6719 if (!D.isInvalidType())
6720 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6721 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6722 << SourceRange(D.getIdentifierLoc())
6723 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6724
6725 SC = SC_None;
6726 }
6727 if (!D.isInvalidType()) {
6728 // Destructors don't have return types, but the parser will
6729 // happily parse something like:
6730 //
6731 // class X {
6732 // float ~X();
6733 // };
6734 //
6735 // The return type will be eliminated later.
6736 if (D.getDeclSpec().hasTypeSpecifier())
6737 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6738 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6739 << SourceRange(D.getIdentifierLoc());
6740 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6741 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6742 SourceLocation(),
6743 D.getDeclSpec().getConstSpecLoc(),
6744 D.getDeclSpec().getVolatileSpecLoc(),
6745 D.getDeclSpec().getRestrictSpecLoc(),
6746 D.getDeclSpec().getAtomicSpecLoc());
6747 D.setInvalidType();
6748 }
6749 }
6750
6751 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6752 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6753 if (FTI.TypeQuals & Qualifiers::Const)
6754 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6755 << "const" << SourceRange(D.getIdentifierLoc());
6756 if (FTI.TypeQuals & Qualifiers::Volatile)
6757 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6758 << "volatile" << SourceRange(D.getIdentifierLoc());
6759 if (FTI.TypeQuals & Qualifiers::Restrict)
6760 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6761 << "restrict" << SourceRange(D.getIdentifierLoc());
6762 D.setInvalidType();
6763 }
6764
6765 // C++0x [class.dtor]p2:
6766 // A destructor shall not be declared with a ref-qualifier.
6767 if (FTI.hasRefQualifier()) {
6768 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6769 << FTI.RefQualifierIsLValueRef
6770 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6771 D.setInvalidType();
6772 }
6773
6774 // Make sure we don't have any parameters.
6775 if (FTIHasNonVoidParameters(FTI)) {
6776 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6777
6778 // Delete the parameters.
6779 FTI.freeParams();
6780 D.setInvalidType();
6781 }
6782
6783 // Make sure the destructor isn't variadic.
6784 if (FTI.isVariadic) {
6785 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6786 D.setInvalidType();
6787 }
6788
6789 // Rebuild the function type "R" without any type qualifiers or
6790 // parameters (in case any of the errors above fired) and with
6791 // "void" as the return type, since destructors don't have return
6792 // types.
6793 if (!D.isInvalidType())
6794 return R;
6795
6796 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6797 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6798 EPI.Variadic = false;
6799 EPI.TypeQuals = 0;
6800 EPI.RefQualifier = RQ_None;
6801 return Context.getFunctionType(Context.VoidTy, None, EPI);
6802 }
6803
extendLeft(SourceRange & R,const SourceRange & Before)6804 static void extendLeft(SourceRange &R, const SourceRange &Before) {
6805 if (Before.isInvalid())
6806 return;
6807 R.setBegin(Before.getBegin());
6808 if (R.getEnd().isInvalid())
6809 R.setEnd(Before.getEnd());
6810 }
6811
extendRight(SourceRange & R,const SourceRange & After)6812 static void extendRight(SourceRange &R, const SourceRange &After) {
6813 if (After.isInvalid())
6814 return;
6815 if (R.getBegin().isInvalid())
6816 R.setBegin(After.getBegin());
6817 R.setEnd(After.getEnd());
6818 }
6819
6820 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6821 /// well-formednes of the conversion function declarator @p D with
6822 /// type @p R. If there are any errors in the declarator, this routine
6823 /// will emit diagnostics and return true. Otherwise, it will return
6824 /// false. Either way, the type @p R will be updated to reflect a
6825 /// well-formed type for the conversion operator.
CheckConversionDeclarator(Declarator & D,QualType & R,StorageClass & SC)6826 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6827 StorageClass& SC) {
6828 // C++ [class.conv.fct]p1:
6829 // Neither parameter types nor return type can be specified. The
6830 // type of a conversion function (8.3.5) is "function taking no
6831 // parameter returning conversion-type-id."
6832 if (SC == SC_Static) {
6833 if (!D.isInvalidType())
6834 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6835 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6836 << D.getName().getSourceRange();
6837 D.setInvalidType();
6838 SC = SC_None;
6839 }
6840
6841 TypeSourceInfo *ConvTSI = nullptr;
6842 QualType ConvType =
6843 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
6844
6845 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6846 // Conversion functions don't have return types, but the parser will
6847 // happily parse something like:
6848 //
6849 // class X {
6850 // float operator bool();
6851 // };
6852 //
6853 // The return type will be changed later anyway.
6854 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6855 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6856 << SourceRange(D.getIdentifierLoc());
6857 D.setInvalidType();
6858 }
6859
6860 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6861
6862 // Make sure we don't have any parameters.
6863 if (Proto->getNumParams() > 0) {
6864 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6865
6866 // Delete the parameters.
6867 D.getFunctionTypeInfo().freeParams();
6868 D.setInvalidType();
6869 } else if (Proto->isVariadic()) {
6870 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6871 D.setInvalidType();
6872 }
6873
6874 // Diagnose "&operator bool()" and other such nonsense. This
6875 // is actually a gcc extension which we don't support.
6876 if (Proto->getReturnType() != ConvType) {
6877 bool NeedsTypedef = false;
6878 SourceRange Before, After;
6879
6880 // Walk the chunks and extract information on them for our diagnostic.
6881 bool PastFunctionChunk = false;
6882 for (auto &Chunk : D.type_objects()) {
6883 switch (Chunk.Kind) {
6884 case DeclaratorChunk::Function:
6885 if (!PastFunctionChunk) {
6886 if (Chunk.Fun.HasTrailingReturnType) {
6887 TypeSourceInfo *TRT = nullptr;
6888 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6889 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6890 }
6891 PastFunctionChunk = true;
6892 break;
6893 }
6894 // Fall through.
6895 case DeclaratorChunk::Array:
6896 NeedsTypedef = true;
6897 extendRight(After, Chunk.getSourceRange());
6898 break;
6899
6900 case DeclaratorChunk::Pointer:
6901 case DeclaratorChunk::BlockPointer:
6902 case DeclaratorChunk::Reference:
6903 case DeclaratorChunk::MemberPointer:
6904 extendLeft(Before, Chunk.getSourceRange());
6905 break;
6906
6907 case DeclaratorChunk::Paren:
6908 extendLeft(Before, Chunk.Loc);
6909 extendRight(After, Chunk.EndLoc);
6910 break;
6911 }
6912 }
6913
6914 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
6915 After.isValid() ? After.getBegin() :
6916 D.getIdentifierLoc();
6917 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
6918 DB << Before << After;
6919
6920 if (!NeedsTypedef) {
6921 DB << /*don't need a typedef*/0;
6922
6923 // If we can provide a correct fix-it hint, do so.
6924 if (After.isInvalid() && ConvTSI) {
6925 SourceLocation InsertLoc =
6926 PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
6927 DB << FixItHint::CreateInsertion(InsertLoc, " ")
6928 << FixItHint::CreateInsertionFromRange(
6929 InsertLoc, CharSourceRange::getTokenRange(Before))
6930 << FixItHint::CreateRemoval(Before);
6931 }
6932 } else if (!Proto->getReturnType()->isDependentType()) {
6933 DB << /*typedef*/1 << Proto->getReturnType();
6934 } else if (getLangOpts().CPlusPlus11) {
6935 DB << /*alias template*/2 << Proto->getReturnType();
6936 } else {
6937 DB << /*might not be fixable*/3;
6938 }
6939
6940 // Recover by incorporating the other type chunks into the result type.
6941 // Note, this does *not* change the name of the function. This is compatible
6942 // with the GCC extension:
6943 // struct S { &operator int(); } s;
6944 // int &r = s.operator int(); // ok in GCC
6945 // S::operator int&() {} // error in GCC, function name is 'operator int'.
6946 ConvType = Proto->getReturnType();
6947 }
6948
6949 // C++ [class.conv.fct]p4:
6950 // The conversion-type-id shall not represent a function type nor
6951 // an array type.
6952 if (ConvType->isArrayType()) {
6953 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6954 ConvType = Context.getPointerType(ConvType);
6955 D.setInvalidType();
6956 } else if (ConvType->isFunctionType()) {
6957 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6958 ConvType = Context.getPointerType(ConvType);
6959 D.setInvalidType();
6960 }
6961
6962 // Rebuild the function type "R" without any parameters (in case any
6963 // of the errors above fired) and with the conversion type as the
6964 // return type.
6965 if (D.isInvalidType())
6966 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6967
6968 // C++0x explicit conversion operators.
6969 if (D.getDeclSpec().isExplicitSpecified())
6970 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6971 getLangOpts().CPlusPlus11 ?
6972 diag::warn_cxx98_compat_explicit_conversion_functions :
6973 diag::ext_explicit_conversion_functions)
6974 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6975 }
6976
6977 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6978 /// the declaration of the given C++ conversion function. This routine
6979 /// is responsible for recording the conversion function in the C++
6980 /// class, if possible.
ActOnConversionDeclarator(CXXConversionDecl * Conversion)6981 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6982 assert(Conversion && "Expected to receive a conversion function declaration");
6983
6984 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6985
6986 // Make sure we aren't redeclaring the conversion function.
6987 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6988
6989 // C++ [class.conv.fct]p1:
6990 // [...] A conversion function is never used to convert a
6991 // (possibly cv-qualified) object to the (possibly cv-qualified)
6992 // same object type (or a reference to it), to a (possibly
6993 // cv-qualified) base class of that type (or a reference to it),
6994 // or to (possibly cv-qualified) void.
6995 // FIXME: Suppress this warning if the conversion function ends up being a
6996 // virtual function that overrides a virtual function in a base class.
6997 QualType ClassType
6998 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6999 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
7000 ConvType = ConvTypeRef->getPointeeType();
7001 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7002 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
7003 /* Suppress diagnostics for instantiations. */;
7004 else if (ConvType->isRecordType()) {
7005 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7006 if (ConvType == ClassType)
7007 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
7008 << ClassType;
7009 else if (IsDerivedFrom(ClassType, ConvType))
7010 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
7011 << ClassType << ConvType;
7012 } else if (ConvType->isVoidType()) {
7013 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
7014 << ClassType << ConvType;
7015 }
7016
7017 if (FunctionTemplateDecl *ConversionTemplate
7018 = Conversion->getDescribedFunctionTemplate())
7019 return ConversionTemplate;
7020
7021 return Conversion;
7022 }
7023
7024 //===----------------------------------------------------------------------===//
7025 // Namespace Handling
7026 //===----------------------------------------------------------------------===//
7027
7028 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7029 /// reopened.
DiagnoseNamespaceInlineMismatch(Sema & S,SourceLocation KeywordLoc,SourceLocation Loc,IdentifierInfo * II,bool * IsInline,NamespaceDecl * PrevNS)7030 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7031 SourceLocation Loc,
7032 IdentifierInfo *II, bool *IsInline,
7033 NamespaceDecl *PrevNS) {
7034 assert(*IsInline != PrevNS->isInline());
7035
7036 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7037 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7038 // inline namespaces, with the intention of bringing names into namespace std.
7039 //
7040 // We support this just well enough to get that case working; this is not
7041 // sufficient to support reopening namespaces as inline in general.
7042 if (*IsInline && II && II->getName().startswith("__atomic") &&
7043 S.getSourceManager().isInSystemHeader(Loc)) {
7044 // Mark all prior declarations of the namespace as inline.
7045 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7046 NS = NS->getPreviousDecl())
7047 NS->setInline(*IsInline);
7048 // Patch up the lookup table for the containing namespace. This isn't really
7049 // correct, but it's good enough for this particular case.
7050 for (auto *I : PrevNS->decls())
7051 if (auto *ND = dyn_cast<NamedDecl>(I))
7052 PrevNS->getParent()->makeDeclVisibleInContext(ND);
7053 return;
7054 }
7055
7056 if (PrevNS->isInline())
7057 // The user probably just forgot the 'inline', so suggest that it
7058 // be added back.
7059 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7060 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7061 else
7062 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
7063
7064 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7065 *IsInline = PrevNS->isInline();
7066 }
7067
7068 /// ActOnStartNamespaceDef - This is called at the start of a namespace
7069 /// definition.
ActOnStartNamespaceDef(Scope * NamespcScope,SourceLocation InlineLoc,SourceLocation NamespaceLoc,SourceLocation IdentLoc,IdentifierInfo * II,SourceLocation LBrace,AttributeList * AttrList)7070 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
7071 SourceLocation InlineLoc,
7072 SourceLocation NamespaceLoc,
7073 SourceLocation IdentLoc,
7074 IdentifierInfo *II,
7075 SourceLocation LBrace,
7076 AttributeList *AttrList) {
7077 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7078 // For anonymous namespace, take the location of the left brace.
7079 SourceLocation Loc = II ? IdentLoc : LBrace;
7080 bool IsInline = InlineLoc.isValid();
7081 bool IsInvalid = false;
7082 bool IsStd = false;
7083 bool AddToKnown = false;
7084 Scope *DeclRegionScope = NamespcScope->getParent();
7085
7086 NamespaceDecl *PrevNS = nullptr;
7087 if (II) {
7088 // C++ [namespace.def]p2:
7089 // The identifier in an original-namespace-definition shall not
7090 // have been previously defined in the declarative region in
7091 // which the original-namespace-definition appears. The
7092 // identifier in an original-namespace-definition is the name of
7093 // the namespace. Subsequently in that declarative region, it is
7094 // treated as an original-namespace-name.
7095 //
7096 // Since namespace names are unique in their scope, and we don't
7097 // look through using directives, just look for any ordinary names.
7098
7099 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
7100 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7101 Decl::IDNS_Namespace;
7102 NamedDecl *PrevDecl = nullptr;
7103 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7104 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7105 ++I) {
7106 if ((*I)->getIdentifierNamespace() & IDNS) {
7107 PrevDecl = *I;
7108 break;
7109 }
7110 }
7111
7112 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7113
7114 if (PrevNS) {
7115 // This is an extended namespace definition.
7116 if (IsInline != PrevNS->isInline())
7117 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7118 &IsInline, PrevNS);
7119 } else if (PrevDecl) {
7120 // This is an invalid name redefinition.
7121 Diag(Loc, diag::err_redefinition_different_kind)
7122 << II;
7123 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7124 IsInvalid = true;
7125 // Continue on to push Namespc as current DeclContext and return it.
7126 } else if (II->isStr("std") &&
7127 CurContext->getRedeclContext()->isTranslationUnit()) {
7128 // This is the first "real" definition of the namespace "std", so update
7129 // our cache of the "std" namespace to point at this definition.
7130 PrevNS = getStdNamespace();
7131 IsStd = true;
7132 AddToKnown = !IsInline;
7133 } else {
7134 // We've seen this namespace for the first time.
7135 AddToKnown = !IsInline;
7136 }
7137 } else {
7138 // Anonymous namespaces.
7139
7140 // Determine whether the parent already has an anonymous namespace.
7141 DeclContext *Parent = CurContext->getRedeclContext();
7142 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7143 PrevNS = TU->getAnonymousNamespace();
7144 } else {
7145 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
7146 PrevNS = ND->getAnonymousNamespace();
7147 }
7148
7149 if (PrevNS && IsInline != PrevNS->isInline())
7150 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7151 &IsInline, PrevNS);
7152 }
7153
7154 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7155 StartLoc, Loc, II, PrevNS);
7156 if (IsInvalid)
7157 Namespc->setInvalidDecl();
7158
7159 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
7160
7161 // FIXME: Should we be merging attributes?
7162 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
7163 PushNamespaceVisibilityAttr(Attr, Loc);
7164
7165 if (IsStd)
7166 StdNamespace = Namespc;
7167 if (AddToKnown)
7168 KnownNamespaces[Namespc] = false;
7169
7170 if (II) {
7171 PushOnScopeChains(Namespc, DeclRegionScope);
7172 } else {
7173 // Link the anonymous namespace into its parent.
7174 DeclContext *Parent = CurContext->getRedeclContext();
7175 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7176 TU->setAnonymousNamespace(Namespc);
7177 } else {
7178 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
7179 }
7180
7181 CurContext->addDecl(Namespc);
7182
7183 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7184 // behaves as if it were replaced by
7185 // namespace unique { /* empty body */ }
7186 // using namespace unique;
7187 // namespace unique { namespace-body }
7188 // where all occurrences of 'unique' in a translation unit are
7189 // replaced by the same identifier and this identifier differs
7190 // from all other identifiers in the entire program.
7191
7192 // We just create the namespace with an empty name and then add an
7193 // implicit using declaration, just like the standard suggests.
7194 //
7195 // CodeGen enforces the "universally unique" aspect by giving all
7196 // declarations semantically contained within an anonymous
7197 // namespace internal linkage.
7198
7199 if (!PrevNS) {
7200 UsingDirectiveDecl* UD
7201 = UsingDirectiveDecl::Create(Context, Parent,
7202 /* 'using' */ LBrace,
7203 /* 'namespace' */ SourceLocation(),
7204 /* qualifier */ NestedNameSpecifierLoc(),
7205 /* identifier */ SourceLocation(),
7206 Namespc,
7207 /* Ancestor */ Parent);
7208 UD->setImplicit();
7209 Parent->addDecl(UD);
7210 }
7211 }
7212
7213 ActOnDocumentableDecl(Namespc);
7214
7215 // Although we could have an invalid decl (i.e. the namespace name is a
7216 // redefinition), push it as current DeclContext and try to continue parsing.
7217 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7218 // for the namespace has the declarations that showed up in that particular
7219 // namespace definition.
7220 PushDeclContext(NamespcScope, Namespc);
7221 return Namespc;
7222 }
7223
7224 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7225 /// is a namespace alias, returns the namespace it points to.
getNamespaceDecl(NamedDecl * D)7226 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7227 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7228 return AD->getNamespace();
7229 return dyn_cast_or_null<NamespaceDecl>(D);
7230 }
7231
7232 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
7233 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
ActOnFinishNamespaceDef(Decl * Dcl,SourceLocation RBrace)7234 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
7235 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7236 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
7237 Namespc->setRBraceLoc(RBrace);
7238 PopDeclContext();
7239 if (Namespc->hasAttr<VisibilityAttr>())
7240 PopPragmaVisibility(true, RBrace);
7241 }
7242
getStdBadAlloc() const7243 CXXRecordDecl *Sema::getStdBadAlloc() const {
7244 return cast_or_null<CXXRecordDecl>(
7245 StdBadAlloc.get(Context.getExternalSource()));
7246 }
7247
getStdNamespace() const7248 NamespaceDecl *Sema::getStdNamespace() const {
7249 return cast_or_null<NamespaceDecl>(
7250 StdNamespace.get(Context.getExternalSource()));
7251 }
7252
7253 /// \brief Retrieve the special "std" namespace, which may require us to
7254 /// implicitly define the namespace.
getOrCreateStdNamespace()7255 NamespaceDecl *Sema::getOrCreateStdNamespace() {
7256 if (!StdNamespace) {
7257 // The "std" namespace has not yet been defined, so build one implicitly.
7258 StdNamespace = NamespaceDecl::Create(Context,
7259 Context.getTranslationUnitDecl(),
7260 /*Inline=*/false,
7261 SourceLocation(), SourceLocation(),
7262 &PP.getIdentifierTable().get("std"),
7263 /*PrevDecl=*/nullptr);
7264 getStdNamespace()->setImplicit(true);
7265 }
7266
7267 return getStdNamespace();
7268 }
7269
isStdInitializerList(QualType Ty,QualType * Element)7270 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
7271 assert(getLangOpts().CPlusPlus &&
7272 "Looking for std::initializer_list outside of C++.");
7273
7274 // We're looking for implicit instantiations of
7275 // template <typename E> class std::initializer_list.
7276
7277 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7278 return false;
7279
7280 ClassTemplateDecl *Template = nullptr;
7281 const TemplateArgument *Arguments = nullptr;
7282
7283 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7284
7285 ClassTemplateSpecializationDecl *Specialization =
7286 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7287 if (!Specialization)
7288 return false;
7289
7290 Template = Specialization->getSpecializedTemplate();
7291 Arguments = Specialization->getTemplateArgs().data();
7292 } else if (const TemplateSpecializationType *TST =
7293 Ty->getAs<TemplateSpecializationType>()) {
7294 Template = dyn_cast_or_null<ClassTemplateDecl>(
7295 TST->getTemplateName().getAsTemplateDecl());
7296 Arguments = TST->getArgs();
7297 }
7298 if (!Template)
7299 return false;
7300
7301 if (!StdInitializerList) {
7302 // Haven't recognized std::initializer_list yet, maybe this is it.
7303 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7304 if (TemplateClass->getIdentifier() !=
7305 &PP.getIdentifierTable().get("initializer_list") ||
7306 !getStdNamespace()->InEnclosingNamespaceSetOf(
7307 TemplateClass->getDeclContext()))
7308 return false;
7309 // This is a template called std::initializer_list, but is it the right
7310 // template?
7311 TemplateParameterList *Params = Template->getTemplateParameters();
7312 if (Params->getMinRequiredArguments() != 1)
7313 return false;
7314 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7315 return false;
7316
7317 // It's the right template.
7318 StdInitializerList = Template;
7319 }
7320
7321 if (Template != StdInitializerList)
7322 return false;
7323
7324 // This is an instance of std::initializer_list. Find the argument type.
7325 if (Element)
7326 *Element = Arguments[0].getAsType();
7327 return true;
7328 }
7329
LookupStdInitializerList(Sema & S,SourceLocation Loc)7330 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7331 NamespaceDecl *Std = S.getStdNamespace();
7332 if (!Std) {
7333 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7334 return nullptr;
7335 }
7336
7337 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7338 Loc, Sema::LookupOrdinaryName);
7339 if (!S.LookupQualifiedName(Result, Std)) {
7340 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7341 return nullptr;
7342 }
7343 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7344 if (!Template) {
7345 Result.suppressDiagnostics();
7346 // We found something weird. Complain about the first thing we found.
7347 NamedDecl *Found = *Result.begin();
7348 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7349 return nullptr;
7350 }
7351
7352 // We found some template called std::initializer_list. Now verify that it's
7353 // correct.
7354 TemplateParameterList *Params = Template->getTemplateParameters();
7355 if (Params->getMinRequiredArguments() != 1 ||
7356 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7357 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7358 return nullptr;
7359 }
7360
7361 return Template;
7362 }
7363
BuildStdInitializerList(QualType Element,SourceLocation Loc)7364 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7365 if (!StdInitializerList) {
7366 StdInitializerList = LookupStdInitializerList(*this, Loc);
7367 if (!StdInitializerList)
7368 return QualType();
7369 }
7370
7371 TemplateArgumentListInfo Args(Loc, Loc);
7372 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7373 Context.getTrivialTypeSourceInfo(Element,
7374 Loc)));
7375 return Context.getCanonicalType(
7376 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7377 }
7378
isInitListConstructor(const CXXConstructorDecl * Ctor)7379 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7380 // C++ [dcl.init.list]p2:
7381 // A constructor is an initializer-list constructor if its first parameter
7382 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7383 // std::initializer_list<E> for some type E, and either there are no other
7384 // parameters or else all other parameters have default arguments.
7385 if (Ctor->getNumParams() < 1 ||
7386 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7387 return false;
7388
7389 QualType ArgType = Ctor->getParamDecl(0)->getType();
7390 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7391 ArgType = RT->getPointeeType().getUnqualifiedType();
7392
7393 return isStdInitializerList(ArgType, nullptr);
7394 }
7395
7396 /// \brief Determine whether a using statement is in a context where it will be
7397 /// apply in all contexts.
IsUsingDirectiveInToplevelContext(DeclContext * CurContext)7398 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7399 switch (CurContext->getDeclKind()) {
7400 case Decl::TranslationUnit:
7401 return true;
7402 case Decl::LinkageSpec:
7403 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7404 default:
7405 return false;
7406 }
7407 }
7408
7409 namespace {
7410
7411 // Callback to only accept typo corrections that are namespaces.
7412 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7413 public:
ValidateCandidate(const TypoCorrection & candidate)7414 bool ValidateCandidate(const TypoCorrection &candidate) override {
7415 if (NamedDecl *ND = candidate.getCorrectionDecl())
7416 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7417 return false;
7418 }
7419 };
7420
7421 }
7422
TryNamespaceTypoCorrection(Sema & S,LookupResult & R,Scope * Sc,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * Ident)7423 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7424 CXXScopeSpec &SS,
7425 SourceLocation IdentLoc,
7426 IdentifierInfo *Ident) {
7427 R.clear();
7428 if (TypoCorrection Corrected =
7429 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7430 llvm::make_unique<NamespaceValidatorCCC>(),
7431 Sema::CTK_ErrorRecovery)) {
7432 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7433 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7434 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7435 Ident->getName().equals(CorrectedStr);
7436 S.diagnoseTypo(Corrected,
7437 S.PDiag(diag::err_using_directive_member_suggest)
7438 << Ident << DC << DroppedSpecifier << SS.getRange(),
7439 S.PDiag(diag::note_namespace_defined_here));
7440 } else {
7441 S.diagnoseTypo(Corrected,
7442 S.PDiag(diag::err_using_directive_suggest) << Ident,
7443 S.PDiag(diag::note_namespace_defined_here));
7444 }
7445 R.addDecl(Corrected.getCorrectionDecl());
7446 return true;
7447 }
7448 return false;
7449 }
7450
ActOnUsingDirective(Scope * S,SourceLocation UsingLoc,SourceLocation NamespcLoc,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * NamespcName,AttributeList * AttrList)7451 Decl *Sema::ActOnUsingDirective(Scope *S,
7452 SourceLocation UsingLoc,
7453 SourceLocation NamespcLoc,
7454 CXXScopeSpec &SS,
7455 SourceLocation IdentLoc,
7456 IdentifierInfo *NamespcName,
7457 AttributeList *AttrList) {
7458 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7459 assert(NamespcName && "Invalid NamespcName.");
7460 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7461
7462 // This can only happen along a recovery path.
7463 while (S->getFlags() & Scope::TemplateParamScope)
7464 S = S->getParent();
7465 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7466
7467 UsingDirectiveDecl *UDir = nullptr;
7468 NestedNameSpecifier *Qualifier = nullptr;
7469 if (SS.isSet())
7470 Qualifier = SS.getScopeRep();
7471
7472 // Lookup namespace name.
7473 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7474 LookupParsedName(R, S, &SS);
7475 if (R.isAmbiguous())
7476 return nullptr;
7477
7478 if (R.empty()) {
7479 R.clear();
7480 // Allow "using namespace std;" or "using namespace ::std;" even if
7481 // "std" hasn't been defined yet, for GCC compatibility.
7482 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7483 NamespcName->isStr("std")) {
7484 Diag(IdentLoc, diag::ext_using_undefined_std);
7485 R.addDecl(getOrCreateStdNamespace());
7486 R.resolveKind();
7487 }
7488 // Otherwise, attempt typo correction.
7489 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7490 }
7491
7492 if (!R.empty()) {
7493 NamedDecl *Named = R.getFoundDecl();
7494 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7495 && "expected namespace decl");
7496
7497 // The use of a nested name specifier may trigger deprecation warnings.
7498 DiagnoseUseOfDecl(Named, IdentLoc);
7499
7500 // C++ [namespace.udir]p1:
7501 // A using-directive specifies that the names in the nominated
7502 // namespace can be used in the scope in which the
7503 // using-directive appears after the using-directive. During
7504 // unqualified name lookup (3.4.1), the names appear as if they
7505 // were declared in the nearest enclosing namespace which
7506 // contains both the using-directive and the nominated
7507 // namespace. [Note: in this context, "contains" means "contains
7508 // directly or indirectly". ]
7509
7510 // Find enclosing context containing both using-directive and
7511 // nominated namespace.
7512 NamespaceDecl *NS = getNamespaceDecl(Named);
7513 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7514 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7515 CommonAncestor = CommonAncestor->getParent();
7516
7517 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7518 SS.getWithLocInContext(Context),
7519 IdentLoc, Named, CommonAncestor);
7520
7521 if (IsUsingDirectiveInToplevelContext(CurContext) &&
7522 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7523 Diag(IdentLoc, diag::warn_using_directive_in_header);
7524 }
7525
7526 PushUsingDirective(S, UDir);
7527 } else {
7528 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7529 }
7530
7531 if (UDir)
7532 ProcessDeclAttributeList(S, UDir, AttrList);
7533
7534 return UDir;
7535 }
7536
PushUsingDirective(Scope * S,UsingDirectiveDecl * UDir)7537 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7538 // If the scope has an associated entity and the using directive is at
7539 // namespace or translation unit scope, add the UsingDirectiveDecl into
7540 // its lookup structure so qualified name lookup can find it.
7541 DeclContext *Ctx = S->getEntity();
7542 if (Ctx && !Ctx->isFunctionOrMethod())
7543 Ctx->addDecl(UDir);
7544 else
7545 // Otherwise, it is at block scope. The using-directives will affect lookup
7546 // only to the end of the scope.
7547 S->PushUsingDirective(UDir);
7548 }
7549
7550
ActOnUsingDeclaration(Scope * S,AccessSpecifier AS,bool HasUsingKeyword,SourceLocation UsingLoc,CXXScopeSpec & SS,UnqualifiedId & Name,AttributeList * AttrList,bool HasTypenameKeyword,SourceLocation TypenameLoc)7551 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7552 AccessSpecifier AS,
7553 bool HasUsingKeyword,
7554 SourceLocation UsingLoc,
7555 CXXScopeSpec &SS,
7556 UnqualifiedId &Name,
7557 AttributeList *AttrList,
7558 bool HasTypenameKeyword,
7559 SourceLocation TypenameLoc) {
7560 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7561
7562 switch (Name.getKind()) {
7563 case UnqualifiedId::IK_ImplicitSelfParam:
7564 case UnqualifiedId::IK_Identifier:
7565 case UnqualifiedId::IK_OperatorFunctionId:
7566 case UnqualifiedId::IK_LiteralOperatorId:
7567 case UnqualifiedId::IK_ConversionFunctionId:
7568 break;
7569
7570 case UnqualifiedId::IK_ConstructorName:
7571 case UnqualifiedId::IK_ConstructorTemplateId:
7572 // C++11 inheriting constructors.
7573 Diag(Name.getLocStart(),
7574 getLangOpts().CPlusPlus11 ?
7575 diag::warn_cxx98_compat_using_decl_constructor :
7576 diag::err_using_decl_constructor)
7577 << SS.getRange();
7578
7579 if (getLangOpts().CPlusPlus11) break;
7580
7581 return nullptr;
7582
7583 case UnqualifiedId::IK_DestructorName:
7584 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7585 << SS.getRange();
7586 return nullptr;
7587
7588 case UnqualifiedId::IK_TemplateId:
7589 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7590 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7591 return nullptr;
7592 }
7593
7594 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7595 DeclarationName TargetName = TargetNameInfo.getName();
7596 if (!TargetName)
7597 return nullptr;
7598
7599 // Warn about access declarations.
7600 if (!HasUsingKeyword) {
7601 Diag(Name.getLocStart(),
7602 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7603 : diag::warn_access_decl_deprecated)
7604 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7605 }
7606
7607 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7608 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7609 return nullptr;
7610
7611 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7612 TargetNameInfo, AttrList,
7613 /* IsInstantiation */ false,
7614 HasTypenameKeyword, TypenameLoc);
7615 if (UD)
7616 PushOnScopeChains(UD, S, /*AddToContext*/ false);
7617
7618 return UD;
7619 }
7620
7621 /// \brief Determine whether a using declaration considers the given
7622 /// declarations as "equivalent", e.g., if they are redeclarations of
7623 /// the same entity or are both typedefs of the same type.
7624 static bool
IsEquivalentForUsingDecl(ASTContext & Context,NamedDecl * D1,NamedDecl * D2)7625 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7626 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7627 return true;
7628
7629 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7630 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7631 return Context.hasSameType(TD1->getUnderlyingType(),
7632 TD2->getUnderlyingType());
7633
7634 return false;
7635 }
7636
7637
7638 /// Determines whether to create a using shadow decl for a particular
7639 /// decl, given the set of decls existing prior to this using lookup.
CheckUsingShadowDecl(UsingDecl * Using,NamedDecl * Orig,const LookupResult & Previous,UsingShadowDecl * & PrevShadow)7640 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7641 const LookupResult &Previous,
7642 UsingShadowDecl *&PrevShadow) {
7643 // Diagnose finding a decl which is not from a base class of the
7644 // current class. We do this now because there are cases where this
7645 // function will silently decide not to build a shadow decl, which
7646 // will pre-empt further diagnostics.
7647 //
7648 // We don't need to do this in C++0x because we do the check once on
7649 // the qualifier.
7650 //
7651 // FIXME: diagnose the following if we care enough:
7652 // struct A { int foo; };
7653 // struct B : A { using A::foo; };
7654 // template <class T> struct C : A {};
7655 // template <class T> struct D : C<T> { using B::foo; } // <---
7656 // This is invalid (during instantiation) in C++03 because B::foo
7657 // resolves to the using decl in B, which is not a base class of D<T>.
7658 // We can't diagnose it immediately because C<T> is an unknown
7659 // specialization. The UsingShadowDecl in D<T> then points directly
7660 // to A::foo, which will look well-formed when we instantiate.
7661 // The right solution is to not collapse the shadow-decl chain.
7662 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7663 DeclContext *OrigDC = Orig->getDeclContext();
7664
7665 // Handle enums and anonymous structs.
7666 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7667 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7668 while (OrigRec->isAnonymousStructOrUnion())
7669 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7670
7671 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7672 if (OrigDC == CurContext) {
7673 Diag(Using->getLocation(),
7674 diag::err_using_decl_nested_name_specifier_is_current_class)
7675 << Using->getQualifierLoc().getSourceRange();
7676 Diag(Orig->getLocation(), diag::note_using_decl_target);
7677 return true;
7678 }
7679
7680 Diag(Using->getQualifierLoc().getBeginLoc(),
7681 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7682 << Using->getQualifier()
7683 << cast<CXXRecordDecl>(CurContext)
7684 << Using->getQualifierLoc().getSourceRange();
7685 Diag(Orig->getLocation(), diag::note_using_decl_target);
7686 return true;
7687 }
7688 }
7689
7690 if (Previous.empty()) return false;
7691
7692 NamedDecl *Target = Orig;
7693 if (isa<UsingShadowDecl>(Target))
7694 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7695
7696 // If the target happens to be one of the previous declarations, we
7697 // don't have a conflict.
7698 //
7699 // FIXME: but we might be increasing its access, in which case we
7700 // should redeclare it.
7701 NamedDecl *NonTag = nullptr, *Tag = nullptr;
7702 bool FoundEquivalentDecl = false;
7703 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7704 I != E; ++I) {
7705 NamedDecl *D = (*I)->getUnderlyingDecl();
7706 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7707 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7708 PrevShadow = Shadow;
7709 FoundEquivalentDecl = true;
7710 }
7711
7712 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7713 }
7714
7715 if (FoundEquivalentDecl)
7716 return false;
7717
7718 if (FunctionDecl *FD = Target->getAsFunction()) {
7719 NamedDecl *OldDecl = nullptr;
7720 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7721 /*IsForUsingDecl*/ true)) {
7722 case Ovl_Overload:
7723 return false;
7724
7725 case Ovl_NonFunction:
7726 Diag(Using->getLocation(), diag::err_using_decl_conflict);
7727 break;
7728
7729 // We found a decl with the exact signature.
7730 case Ovl_Match:
7731 // If we're in a record, we want to hide the target, so we
7732 // return true (without a diagnostic) to tell the caller not to
7733 // build a shadow decl.
7734 if (CurContext->isRecord())
7735 return true;
7736
7737 // If we're not in a record, this is an error.
7738 Diag(Using->getLocation(), diag::err_using_decl_conflict);
7739 break;
7740 }
7741
7742 Diag(Target->getLocation(), diag::note_using_decl_target);
7743 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7744 return true;
7745 }
7746
7747 // Target is not a function.
7748
7749 if (isa<TagDecl>(Target)) {
7750 // No conflict between a tag and a non-tag.
7751 if (!Tag) return false;
7752
7753 Diag(Using->getLocation(), diag::err_using_decl_conflict);
7754 Diag(Target->getLocation(), diag::note_using_decl_target);
7755 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7756 return true;
7757 }
7758
7759 // No conflict between a tag and a non-tag.
7760 if (!NonTag) return false;
7761
7762 Diag(Using->getLocation(), diag::err_using_decl_conflict);
7763 Diag(Target->getLocation(), diag::note_using_decl_target);
7764 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7765 return true;
7766 }
7767
7768 /// Builds a shadow declaration corresponding to a 'using' declaration.
BuildUsingShadowDecl(Scope * S,UsingDecl * UD,NamedDecl * Orig,UsingShadowDecl * PrevDecl)7769 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7770 UsingDecl *UD,
7771 NamedDecl *Orig,
7772 UsingShadowDecl *PrevDecl) {
7773
7774 // If we resolved to another shadow declaration, just coalesce them.
7775 NamedDecl *Target = Orig;
7776 if (isa<UsingShadowDecl>(Target)) {
7777 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7778 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7779 }
7780
7781 UsingShadowDecl *Shadow
7782 = UsingShadowDecl::Create(Context, CurContext,
7783 UD->getLocation(), UD, Target);
7784 UD->addShadowDecl(Shadow);
7785
7786 Shadow->setAccess(UD->getAccess());
7787 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7788 Shadow->setInvalidDecl();
7789
7790 Shadow->setPreviousDecl(PrevDecl);
7791
7792 if (S)
7793 PushOnScopeChains(Shadow, S);
7794 else
7795 CurContext->addDecl(Shadow);
7796
7797
7798 return Shadow;
7799 }
7800
7801 /// Hides a using shadow declaration. This is required by the current
7802 /// using-decl implementation when a resolvable using declaration in a
7803 /// class is followed by a declaration which would hide or override
7804 /// one or more of the using decl's targets; for example:
7805 ///
7806 /// struct Base { void foo(int); };
7807 /// struct Derived : Base {
7808 /// using Base::foo;
7809 /// void foo(int);
7810 /// };
7811 ///
7812 /// The governing language is C++03 [namespace.udecl]p12:
7813 ///
7814 /// When a using-declaration brings names from a base class into a
7815 /// derived class scope, member functions in the derived class
7816 /// override and/or hide member functions with the same name and
7817 /// parameter types in a base class (rather than conflicting).
7818 ///
7819 /// There are two ways to implement this:
7820 /// (1) optimistically create shadow decls when they're not hidden
7821 /// by existing declarations, or
7822 /// (2) don't create any shadow decls (or at least don't make them
7823 /// visible) until we've fully parsed/instantiated the class.
7824 /// The problem with (1) is that we might have to retroactively remove
7825 /// a shadow decl, which requires several O(n) operations because the
7826 /// decl structures are (very reasonably) not designed for removal.
7827 /// (2) avoids this but is very fiddly and phase-dependent.
HideUsingShadowDecl(Scope * S,UsingShadowDecl * Shadow)7828 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7829 if (Shadow->getDeclName().getNameKind() ==
7830 DeclarationName::CXXConversionFunctionName)
7831 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7832
7833 // Remove it from the DeclContext...
7834 Shadow->getDeclContext()->removeDecl(Shadow);
7835
7836 // ...and the scope, if applicable...
7837 if (S) {
7838 S->RemoveDecl(Shadow);
7839 IdResolver.RemoveDecl(Shadow);
7840 }
7841
7842 // ...and the using decl.
7843 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7844
7845 // TODO: complain somehow if Shadow was used. It shouldn't
7846 // be possible for this to happen, because...?
7847 }
7848
7849 /// Find the base specifier for a base class with the given type.
findDirectBaseWithType(CXXRecordDecl * Derived,QualType DesiredBase,bool & AnyDependentBases)7850 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7851 QualType DesiredBase,
7852 bool &AnyDependentBases) {
7853 // Check whether the named type is a direct base class.
7854 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7855 for (auto &Base : Derived->bases()) {
7856 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7857 if (CanonicalDesiredBase == BaseType)
7858 return &Base;
7859 if (BaseType->isDependentType())
7860 AnyDependentBases = true;
7861 }
7862 return nullptr;
7863 }
7864
7865 namespace {
7866 class UsingValidatorCCC : public CorrectionCandidateCallback {
7867 public:
UsingValidatorCCC(bool HasTypenameKeyword,bool IsInstantiation,NestedNameSpecifier * NNS,CXXRecordDecl * RequireMemberOf)7868 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7869 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7870 : HasTypenameKeyword(HasTypenameKeyword),
7871 IsInstantiation(IsInstantiation), OldNNS(NNS),
7872 RequireMemberOf(RequireMemberOf) {}
7873
ValidateCandidate(const TypoCorrection & Candidate)7874 bool ValidateCandidate(const TypoCorrection &Candidate) override {
7875 NamedDecl *ND = Candidate.getCorrectionDecl();
7876
7877 // Keywords are not valid here.
7878 if (!ND || isa<NamespaceDecl>(ND))
7879 return false;
7880
7881 // Completely unqualified names are invalid for a 'using' declaration.
7882 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7883 return false;
7884
7885 if (RequireMemberOf) {
7886 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7887 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7888 // No-one ever wants a using-declaration to name an injected-class-name
7889 // of a base class, unless they're declaring an inheriting constructor.
7890 ASTContext &Ctx = ND->getASTContext();
7891 if (!Ctx.getLangOpts().CPlusPlus11)
7892 return false;
7893 QualType FoundType = Ctx.getRecordType(FoundRecord);
7894
7895 // Check that the injected-class-name is named as a member of its own
7896 // type; we don't want to suggest 'using Derived::Base;', since that
7897 // means something else.
7898 NestedNameSpecifier *Specifier =
7899 Candidate.WillReplaceSpecifier()
7900 ? Candidate.getCorrectionSpecifier()
7901 : OldNNS;
7902 if (!Specifier->getAsType() ||
7903 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7904 return false;
7905
7906 // Check that this inheriting constructor declaration actually names a
7907 // direct base class of the current class.
7908 bool AnyDependentBases = false;
7909 if (!findDirectBaseWithType(RequireMemberOf,
7910 Ctx.getRecordType(FoundRecord),
7911 AnyDependentBases) &&
7912 !AnyDependentBases)
7913 return false;
7914 } else {
7915 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7916 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7917 return false;
7918
7919 // FIXME: Check that the base class member is accessible?
7920 }
7921 }
7922
7923 if (isa<TypeDecl>(ND))
7924 return HasTypenameKeyword || !IsInstantiation;
7925
7926 return !HasTypenameKeyword;
7927 }
7928
7929 private:
7930 bool HasTypenameKeyword;
7931 bool IsInstantiation;
7932 NestedNameSpecifier *OldNNS;
7933 CXXRecordDecl *RequireMemberOf;
7934 };
7935 } // end anonymous namespace
7936
7937 /// Builds a using declaration.
7938 ///
7939 /// \param IsInstantiation - Whether this call arises from an
7940 /// instantiation of an unresolved using declaration. We treat
7941 /// the lookup differently for these declarations.
BuildUsingDeclaration(Scope * S,AccessSpecifier AS,SourceLocation UsingLoc,CXXScopeSpec & SS,DeclarationNameInfo NameInfo,AttributeList * AttrList,bool IsInstantiation,bool HasTypenameKeyword,SourceLocation TypenameLoc)7942 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7943 SourceLocation UsingLoc,
7944 CXXScopeSpec &SS,
7945 DeclarationNameInfo NameInfo,
7946 AttributeList *AttrList,
7947 bool IsInstantiation,
7948 bool HasTypenameKeyword,
7949 SourceLocation TypenameLoc) {
7950 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7951 SourceLocation IdentLoc = NameInfo.getLoc();
7952 assert(IdentLoc.isValid() && "Invalid TargetName location.");
7953
7954 // FIXME: We ignore attributes for now.
7955
7956 if (SS.isEmpty()) {
7957 Diag(IdentLoc, diag::err_using_requires_qualname);
7958 return nullptr;
7959 }
7960
7961 // Do the redeclaration lookup in the current scope.
7962 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7963 ForRedeclaration);
7964 Previous.setHideTags(false);
7965 if (S) {
7966 LookupName(Previous, S);
7967
7968 // It is really dumb that we have to do this.
7969 LookupResult::Filter F = Previous.makeFilter();
7970 while (F.hasNext()) {
7971 NamedDecl *D = F.next();
7972 if (!isDeclInScope(D, CurContext, S))
7973 F.erase();
7974 // If we found a local extern declaration that's not ordinarily visible,
7975 // and this declaration is being added to a non-block scope, ignore it.
7976 // We're only checking for scope conflicts here, not also for violations
7977 // of the linkage rules.
7978 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7979 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7980 F.erase();
7981 }
7982 F.done();
7983 } else {
7984 assert(IsInstantiation && "no scope in non-instantiation");
7985 assert(CurContext->isRecord() && "scope not record in instantiation");
7986 LookupQualifiedName(Previous, CurContext);
7987 }
7988
7989 // Check for invalid redeclarations.
7990 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7991 SS, IdentLoc, Previous))
7992 return nullptr;
7993
7994 // Check for bad qualifiers.
7995 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
7996 return nullptr;
7997
7998 DeclContext *LookupContext = computeDeclContext(SS);
7999 NamedDecl *D;
8000 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8001 if (!LookupContext) {
8002 if (HasTypenameKeyword) {
8003 // FIXME: not all declaration name kinds are legal here
8004 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8005 UsingLoc, TypenameLoc,
8006 QualifierLoc,
8007 IdentLoc, NameInfo.getName());
8008 } else {
8009 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8010 QualifierLoc, NameInfo);
8011 }
8012 D->setAccess(AS);
8013 CurContext->addDecl(D);
8014 return D;
8015 }
8016
8017 auto Build = [&](bool Invalid) {
8018 UsingDecl *UD =
8019 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8020 HasTypenameKeyword);
8021 UD->setAccess(AS);
8022 CurContext->addDecl(UD);
8023 UD->setInvalidDecl(Invalid);
8024 return UD;
8025 };
8026 auto BuildInvalid = [&]{ return Build(true); };
8027 auto BuildValid = [&]{ return Build(false); };
8028
8029 if (RequireCompleteDeclContext(SS, LookupContext))
8030 return BuildInvalid();
8031
8032 // The normal rules do not apply to inheriting constructor declarations.
8033 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
8034 UsingDecl *UD = BuildValid();
8035 CheckInheritingConstructorUsingDecl(UD);
8036 return UD;
8037 }
8038
8039 // Otherwise, look up the target name.
8040
8041 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8042
8043 // Unlike most lookups, we don't always want to hide tag
8044 // declarations: tag names are visible through the using declaration
8045 // even if hidden by ordinary names, *except* in a dependent context
8046 // where it's important for the sanity of two-phase lookup.
8047 if (!IsInstantiation)
8048 R.setHideTags(false);
8049
8050 // For the purposes of this lookup, we have a base object type
8051 // equal to that of the current context.
8052 if (CurContext->isRecord()) {
8053 R.setBaseObjectType(
8054 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8055 }
8056
8057 LookupQualifiedName(R, LookupContext);
8058
8059 // Try to correct typos if possible.
8060 if (R.empty()) {
8061 if (TypoCorrection Corrected = CorrectTypo(
8062 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8063 llvm::make_unique<UsingValidatorCCC>(
8064 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8065 dyn_cast<CXXRecordDecl>(CurContext)),
8066 CTK_ErrorRecovery)) {
8067 // We reject any correction for which ND would be NULL.
8068 NamedDecl *ND = Corrected.getCorrectionDecl();
8069
8070 // We reject candidates where DroppedSpecifier == true, hence the
8071 // literal '0' below.
8072 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8073 << NameInfo.getName() << LookupContext << 0
8074 << SS.getRange());
8075
8076 // If we corrected to an inheriting constructor, handle it as one.
8077 auto *RD = dyn_cast<CXXRecordDecl>(ND);
8078 if (RD && RD->isInjectedClassName()) {
8079 // Fix up the information we'll use to build the using declaration.
8080 if (Corrected.WillReplaceSpecifier()) {
8081 NestedNameSpecifierLocBuilder Builder;
8082 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8083 QualifierLoc.getSourceRange());
8084 QualifierLoc = Builder.getWithLocInContext(Context);
8085 }
8086
8087 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8088 Context.getCanonicalType(Context.getRecordType(RD))));
8089 NameInfo.setNamedTypeInfo(nullptr);
8090
8091 // Build it and process it as an inheriting constructor.
8092 UsingDecl *UD = BuildValid();
8093 CheckInheritingConstructorUsingDecl(UD);
8094 return UD;
8095 }
8096
8097 // FIXME: Pick up all the declarations if we found an overloaded function.
8098 R.setLookupName(Corrected.getCorrection());
8099 R.addDecl(ND);
8100 } else {
8101 Diag(IdentLoc, diag::err_no_member)
8102 << NameInfo.getName() << LookupContext << SS.getRange();
8103 return BuildInvalid();
8104 }
8105 }
8106
8107 if (R.isAmbiguous())
8108 return BuildInvalid();
8109
8110 if (HasTypenameKeyword) {
8111 // If we asked for a typename and got a non-type decl, error out.
8112 if (!R.getAsSingle<TypeDecl>()) {
8113 Diag(IdentLoc, diag::err_using_typename_non_type);
8114 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8115 Diag((*I)->getUnderlyingDecl()->getLocation(),
8116 diag::note_using_decl_target);
8117 return BuildInvalid();
8118 }
8119 } else {
8120 // If we asked for a non-typename and we got a type, error out,
8121 // but only if this is an instantiation of an unresolved using
8122 // decl. Otherwise just silently find the type name.
8123 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
8124 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8125 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
8126 return BuildInvalid();
8127 }
8128 }
8129
8130 // C++0x N2914 [namespace.udecl]p6:
8131 // A using-declaration shall not name a namespace.
8132 if (R.getAsSingle<NamespaceDecl>()) {
8133 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8134 << SS.getRange();
8135 return BuildInvalid();
8136 }
8137
8138 UsingDecl *UD = BuildValid();
8139 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8140 UsingShadowDecl *PrevDecl = nullptr;
8141 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8142 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
8143 }
8144
8145 return UD;
8146 }
8147
8148 /// Additional checks for a using declaration referring to a constructor name.
CheckInheritingConstructorUsingDecl(UsingDecl * UD)8149 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
8150 assert(!UD->hasTypename() && "expecting a constructor name");
8151
8152 const Type *SourceType = UD->getQualifier()->getAsType();
8153 assert(SourceType &&
8154 "Using decl naming constructor doesn't have type in scope spec.");
8155 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8156
8157 // Check whether the named type is a direct base class.
8158 bool AnyDependentBases = false;
8159 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8160 AnyDependentBases);
8161 if (!Base && !AnyDependentBases) {
8162 Diag(UD->getUsingLoc(),
8163 diag::err_using_decl_constructor_not_in_direct_base)
8164 << UD->getNameInfo().getSourceRange()
8165 << QualType(SourceType, 0) << TargetClass;
8166 UD->setInvalidDecl();
8167 return true;
8168 }
8169
8170 if (Base)
8171 Base->setInheritConstructors();
8172
8173 return false;
8174 }
8175
8176 /// Checks that the given using declaration is not an invalid
8177 /// redeclaration. Note that this is checking only for the using decl
8178 /// itself, not for any ill-formedness among the UsingShadowDecls.
CheckUsingDeclRedeclaration(SourceLocation UsingLoc,bool HasTypenameKeyword,const CXXScopeSpec & SS,SourceLocation NameLoc,const LookupResult & Prev)8179 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
8180 bool HasTypenameKeyword,
8181 const CXXScopeSpec &SS,
8182 SourceLocation NameLoc,
8183 const LookupResult &Prev) {
8184 // C++03 [namespace.udecl]p8:
8185 // C++0x [namespace.udecl]p10:
8186 // A using-declaration is a declaration and can therefore be used
8187 // repeatedly where (and only where) multiple declarations are
8188 // allowed.
8189 //
8190 // That's in non-member contexts.
8191 if (!CurContext->getRedeclContext()->isRecord())
8192 return false;
8193
8194 NestedNameSpecifier *Qual = SS.getScopeRep();
8195
8196 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8197 NamedDecl *D = *I;
8198
8199 bool DTypename;
8200 NestedNameSpecifier *DQual;
8201 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
8202 DTypename = UD->hasTypename();
8203 DQual = UD->getQualifier();
8204 } else if (UnresolvedUsingValueDecl *UD
8205 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8206 DTypename = false;
8207 DQual = UD->getQualifier();
8208 } else if (UnresolvedUsingTypenameDecl *UD
8209 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8210 DTypename = true;
8211 DQual = UD->getQualifier();
8212 } else continue;
8213
8214 // using decls differ if one says 'typename' and the other doesn't.
8215 // FIXME: non-dependent using decls?
8216 if (HasTypenameKeyword != DTypename) continue;
8217
8218 // using decls differ if they name different scopes (but note that
8219 // template instantiation can cause this check to trigger when it
8220 // didn't before instantiation).
8221 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8222 Context.getCanonicalNestedNameSpecifier(DQual))
8223 continue;
8224
8225 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
8226 Diag(D->getLocation(), diag::note_using_decl) << 1;
8227 return true;
8228 }
8229
8230 return false;
8231 }
8232
8233
8234 /// Checks that the given nested-name qualifier used in a using decl
8235 /// in the current context is appropriately related to the current
8236 /// scope. If an error is found, diagnoses it and returns true.
CheckUsingDeclQualifier(SourceLocation UsingLoc,const CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,SourceLocation NameLoc)8237 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8238 const CXXScopeSpec &SS,
8239 const DeclarationNameInfo &NameInfo,
8240 SourceLocation NameLoc) {
8241 DeclContext *NamedContext = computeDeclContext(SS);
8242
8243 if (!CurContext->isRecord()) {
8244 // C++03 [namespace.udecl]p3:
8245 // C++0x [namespace.udecl]p8:
8246 // A using-declaration for a class member shall be a member-declaration.
8247
8248 // If we weren't able to compute a valid scope, it must be a
8249 // dependent class scope.
8250 if (!NamedContext || NamedContext->isRecord()) {
8251 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
8252 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
8253 RD = nullptr;
8254
8255 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8256 << SS.getRange();
8257
8258 // If we have a complete, non-dependent source type, try to suggest a
8259 // way to get the same effect.
8260 if (!RD)
8261 return true;
8262
8263 // Find what this using-declaration was referring to.
8264 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8265 R.setHideTags(false);
8266 R.suppressDiagnostics();
8267 LookupQualifiedName(R, RD);
8268
8269 if (R.getAsSingle<TypeDecl>()) {
8270 if (getLangOpts().CPlusPlus11) {
8271 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8272 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8273 << 0 // alias declaration
8274 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8275 NameInfo.getName().getAsString() +
8276 " = ");
8277 } else {
8278 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8279 SourceLocation InsertLoc =
8280 PP.getLocForEndOfToken(NameInfo.getLocEnd());
8281 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8282 << 1 // typedef declaration
8283 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8284 << FixItHint::CreateInsertion(
8285 InsertLoc, " " + NameInfo.getName().getAsString());
8286 }
8287 } else if (R.getAsSingle<VarDecl>()) {
8288 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8289 // repeating the type of the static data member here.
8290 FixItHint FixIt;
8291 if (getLangOpts().CPlusPlus11) {
8292 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8293 FixIt = FixItHint::CreateReplacement(
8294 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8295 }
8296
8297 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8298 << 2 // reference declaration
8299 << FixIt;
8300 }
8301 return true;
8302 }
8303
8304 // Otherwise, everything is known to be fine.
8305 return false;
8306 }
8307
8308 // The current scope is a record.
8309
8310 // If the named context is dependent, we can't decide much.
8311 if (!NamedContext) {
8312 // FIXME: in C++0x, we can diagnose if we can prove that the
8313 // nested-name-specifier does not refer to a base class, which is
8314 // still possible in some cases.
8315
8316 // Otherwise we have to conservatively report that things might be
8317 // okay.
8318 return false;
8319 }
8320
8321 if (!NamedContext->isRecord()) {
8322 // Ideally this would point at the last name in the specifier,
8323 // but we don't have that level of source info.
8324 Diag(SS.getRange().getBegin(),
8325 diag::err_using_decl_nested_name_specifier_is_not_class)
8326 << SS.getScopeRep() << SS.getRange();
8327 return true;
8328 }
8329
8330 if (!NamedContext->isDependentContext() &&
8331 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8332 return true;
8333
8334 if (getLangOpts().CPlusPlus11) {
8335 // C++0x [namespace.udecl]p3:
8336 // In a using-declaration used as a member-declaration, the
8337 // nested-name-specifier shall name a base class of the class
8338 // being defined.
8339
8340 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8341 cast<CXXRecordDecl>(NamedContext))) {
8342 if (CurContext == NamedContext) {
8343 Diag(NameLoc,
8344 diag::err_using_decl_nested_name_specifier_is_current_class)
8345 << SS.getRange();
8346 return true;
8347 }
8348
8349 Diag(SS.getRange().getBegin(),
8350 diag::err_using_decl_nested_name_specifier_is_not_base_class)
8351 << SS.getScopeRep()
8352 << cast<CXXRecordDecl>(CurContext)
8353 << SS.getRange();
8354 return true;
8355 }
8356
8357 return false;
8358 }
8359
8360 // C++03 [namespace.udecl]p4:
8361 // A using-declaration used as a member-declaration shall refer
8362 // to a member of a base class of the class being defined [etc.].
8363
8364 // Salient point: SS doesn't have to name a base class as long as
8365 // lookup only finds members from base classes. Therefore we can
8366 // diagnose here only if we can prove that that can't happen,
8367 // i.e. if the class hierarchies provably don't intersect.
8368
8369 // TODO: it would be nice if "definitely valid" results were cached
8370 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8371 // need to be repeated.
8372
8373 struct UserData {
8374 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
8375
8376 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8377 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8378 Data->Bases.insert(Base);
8379 return true;
8380 }
8381
8382 bool hasDependentBases(const CXXRecordDecl *Class) {
8383 return !Class->forallBases(collect, this);
8384 }
8385
8386 /// Returns true if the base is dependent or is one of the
8387 /// accumulated base classes.
8388 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8389 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8390 return !Data->Bases.count(Base);
8391 }
8392
8393 bool mightShareBases(const CXXRecordDecl *Class) {
8394 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8395 }
8396 };
8397
8398 UserData Data;
8399
8400 // Returns false if we find a dependent base.
8401 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8402 return false;
8403
8404 // Returns false if the class has a dependent base or if it or one
8405 // of its bases is present in the base set of the current context.
8406 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8407 return false;
8408
8409 Diag(SS.getRange().getBegin(),
8410 diag::err_using_decl_nested_name_specifier_is_not_base_class)
8411 << SS.getScopeRep()
8412 << cast<CXXRecordDecl>(CurContext)
8413 << SS.getRange();
8414
8415 return true;
8416 }
8417
ActOnAliasDeclaration(Scope * S,AccessSpecifier AS,MultiTemplateParamsArg TemplateParamLists,SourceLocation UsingLoc,UnqualifiedId & Name,AttributeList * AttrList,TypeResult Type)8418 Decl *Sema::ActOnAliasDeclaration(Scope *S,
8419 AccessSpecifier AS,
8420 MultiTemplateParamsArg TemplateParamLists,
8421 SourceLocation UsingLoc,
8422 UnqualifiedId &Name,
8423 AttributeList *AttrList,
8424 TypeResult Type) {
8425 // Skip up to the relevant declaration scope.
8426 while (S->getFlags() & Scope::TemplateParamScope)
8427 S = S->getParent();
8428 assert((S->getFlags() & Scope::DeclScope) &&
8429 "got alias-declaration outside of declaration scope");
8430
8431 if (Type.isInvalid())
8432 return nullptr;
8433
8434 bool Invalid = false;
8435 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8436 TypeSourceInfo *TInfo = nullptr;
8437 GetTypeFromParser(Type.get(), &TInfo);
8438
8439 if (DiagnoseClassNameShadow(CurContext, NameInfo))
8440 return nullptr;
8441
8442 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8443 UPPC_DeclarationType)) {
8444 Invalid = true;
8445 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8446 TInfo->getTypeLoc().getBeginLoc());
8447 }
8448
8449 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8450 LookupName(Previous, S);
8451
8452 // Warn about shadowing the name of a template parameter.
8453 if (Previous.isSingleResult() &&
8454 Previous.getFoundDecl()->isTemplateParameter()) {
8455 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8456 Previous.clear();
8457 }
8458
8459 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8460 "name in alias declaration must be an identifier");
8461 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8462 Name.StartLocation,
8463 Name.Identifier, TInfo);
8464
8465 NewTD->setAccess(AS);
8466
8467 if (Invalid)
8468 NewTD->setInvalidDecl();
8469
8470 ProcessDeclAttributeList(S, NewTD, AttrList);
8471
8472 CheckTypedefForVariablyModifiedType(S, NewTD);
8473 Invalid |= NewTD->isInvalidDecl();
8474
8475 bool Redeclaration = false;
8476
8477 NamedDecl *NewND;
8478 if (TemplateParamLists.size()) {
8479 TypeAliasTemplateDecl *OldDecl = nullptr;
8480 TemplateParameterList *OldTemplateParams = nullptr;
8481
8482 if (TemplateParamLists.size() != 1) {
8483 Diag(UsingLoc, diag::err_alias_template_extra_headers)
8484 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8485 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8486 }
8487 TemplateParameterList *TemplateParams = TemplateParamLists[0];
8488
8489 // Only consider previous declarations in the same scope.
8490 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8491 /*ExplicitInstantiationOrSpecialization*/false);
8492 if (!Previous.empty()) {
8493 Redeclaration = true;
8494
8495 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8496 if (!OldDecl && !Invalid) {
8497 Diag(UsingLoc, diag::err_redefinition_different_kind)
8498 << Name.Identifier;
8499
8500 NamedDecl *OldD = Previous.getRepresentativeDecl();
8501 if (OldD->getLocation().isValid())
8502 Diag(OldD->getLocation(), diag::note_previous_definition);
8503
8504 Invalid = true;
8505 }
8506
8507 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8508 if (TemplateParameterListsAreEqual(TemplateParams,
8509 OldDecl->getTemplateParameters(),
8510 /*Complain=*/true,
8511 TPL_TemplateMatch))
8512 OldTemplateParams = OldDecl->getTemplateParameters();
8513 else
8514 Invalid = true;
8515
8516 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8517 if (!Invalid &&
8518 !Context.hasSameType(OldTD->getUnderlyingType(),
8519 NewTD->getUnderlyingType())) {
8520 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8521 // but we can't reasonably accept it.
8522 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8523 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8524 if (OldTD->getLocation().isValid())
8525 Diag(OldTD->getLocation(), diag::note_previous_definition);
8526 Invalid = true;
8527 }
8528 }
8529 }
8530
8531 // Merge any previous default template arguments into our parameters,
8532 // and check the parameter list.
8533 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8534 TPC_TypeAliasTemplate))
8535 return nullptr;
8536
8537 TypeAliasTemplateDecl *NewDecl =
8538 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8539 Name.Identifier, TemplateParams,
8540 NewTD);
8541 NewTD->setDescribedAliasTemplate(NewDecl);
8542
8543 NewDecl->setAccess(AS);
8544
8545 if (Invalid)
8546 NewDecl->setInvalidDecl();
8547 else if (OldDecl)
8548 NewDecl->setPreviousDecl(OldDecl);
8549
8550 NewND = NewDecl;
8551 } else {
8552 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8553 NewND = NewTD;
8554 }
8555
8556 if (!Redeclaration)
8557 PushOnScopeChains(NewND, S);
8558
8559 ActOnDocumentableDecl(NewND);
8560 return NewND;
8561 }
8562
ActOnNamespaceAliasDef(Scope * S,SourceLocation NamespaceLoc,SourceLocation AliasLoc,IdentifierInfo * Alias,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * Ident)8563 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8564 SourceLocation AliasLoc,
8565 IdentifierInfo *Alias, CXXScopeSpec &SS,
8566 SourceLocation IdentLoc,
8567 IdentifierInfo *Ident) {
8568
8569 // Lookup the namespace name.
8570 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8571 LookupParsedName(R, S, &SS);
8572
8573 if (R.isAmbiguous())
8574 return nullptr;
8575
8576 if (R.empty()) {
8577 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8578 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8579 return nullptr;
8580 }
8581 }
8582 assert(!R.isAmbiguous() && !R.empty());
8583
8584 // Check if we have a previous declaration with the same name.
8585 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8586 ForRedeclaration);
8587 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8588 PrevDecl = nullptr;
8589
8590 NamedDecl *ND = R.getFoundDecl();
8591
8592 if (PrevDecl) {
8593 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8594 // We already have an alias with the same name that points to the same
8595 // namespace; check that it matches.
8596 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8597 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8598 << Alias;
8599 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8600 << AD->getNamespace();
8601 return nullptr;
8602 }
8603 } else {
8604 unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8605 ? diag::err_redefinition
8606 : diag::err_redefinition_different_kind;
8607 Diag(AliasLoc, DiagID) << Alias;
8608 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8609 return nullptr;
8610 }
8611 }
8612
8613 // The use of a nested name specifier may trigger deprecation warnings.
8614 DiagnoseUseOfDecl(ND, IdentLoc);
8615
8616 NamespaceAliasDecl *AliasDecl =
8617 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8618 Alias, SS.getWithLocInContext(Context),
8619 IdentLoc, ND);
8620 if (PrevDecl)
8621 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
8622
8623 PushOnScopeChains(AliasDecl, S);
8624 return AliasDecl;
8625 }
8626
8627 Sema::ImplicitExceptionSpecification
ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,CXXMethodDecl * MD)8628 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8629 CXXMethodDecl *MD) {
8630 CXXRecordDecl *ClassDecl = MD->getParent();
8631
8632 // C++ [except.spec]p14:
8633 // An implicitly declared special member function (Clause 12) shall have an
8634 // exception-specification. [...]
8635 ImplicitExceptionSpecification ExceptSpec(*this);
8636 if (ClassDecl->isInvalidDecl())
8637 return ExceptSpec;
8638
8639 // Direct base-class constructors.
8640 for (const auto &B : ClassDecl->bases()) {
8641 if (B.isVirtual()) // Handled below.
8642 continue;
8643
8644 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8645 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8646 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8647 // If this is a deleted function, add it anyway. This might be conformant
8648 // with the standard. This might not. I'm not sure. It might not matter.
8649 if (Constructor)
8650 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8651 }
8652 }
8653
8654 // Virtual base-class constructors.
8655 for (const auto &B : ClassDecl->vbases()) {
8656 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8657 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8658 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8659 // If this is a deleted function, add it anyway. This might be conformant
8660 // with the standard. This might not. I'm not sure. It might not matter.
8661 if (Constructor)
8662 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8663 }
8664 }
8665
8666 // Field constructors.
8667 for (const auto *F : ClassDecl->fields()) {
8668 if (F->hasInClassInitializer()) {
8669 if (Expr *E = F->getInClassInitializer())
8670 ExceptSpec.CalledExpr(E);
8671 } else if (const RecordType *RecordTy
8672 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8673 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8674 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8675 // If this is a deleted function, add it anyway. This might be conformant
8676 // with the standard. This might not. I'm not sure. It might not matter.
8677 // In particular, the problem is that this function never gets called. It
8678 // might just be ill-formed because this function attempts to refer to
8679 // a deleted function here.
8680 if (Constructor)
8681 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8682 }
8683 }
8684
8685 return ExceptSpec;
8686 }
8687
8688 Sema::ImplicitExceptionSpecification
ComputeInheritingCtorExceptionSpec(CXXConstructorDecl * CD)8689 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8690 CXXRecordDecl *ClassDecl = CD->getParent();
8691
8692 // C++ [except.spec]p14:
8693 // An inheriting constructor [...] shall have an exception-specification. [...]
8694 ImplicitExceptionSpecification ExceptSpec(*this);
8695 if (ClassDecl->isInvalidDecl())
8696 return ExceptSpec;
8697
8698 // Inherited constructor.
8699 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8700 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8701 // FIXME: Copying or moving the parameters could add extra exceptions to the
8702 // set, as could the default arguments for the inherited constructor. This
8703 // will be addressed when we implement the resolution of core issue 1351.
8704 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8705
8706 // Direct base-class constructors.
8707 for (const auto &B : ClassDecl->bases()) {
8708 if (B.isVirtual()) // Handled below.
8709 continue;
8710
8711 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8712 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8713 if (BaseClassDecl == InheritedDecl)
8714 continue;
8715 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8716 if (Constructor)
8717 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8718 }
8719 }
8720
8721 // Virtual base-class constructors.
8722 for (const auto &B : ClassDecl->vbases()) {
8723 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8724 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8725 if (BaseClassDecl == InheritedDecl)
8726 continue;
8727 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8728 if (Constructor)
8729 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8730 }
8731 }
8732
8733 // Field constructors.
8734 for (const auto *F : ClassDecl->fields()) {
8735 if (F->hasInClassInitializer()) {
8736 if (Expr *E = F->getInClassInitializer())
8737 ExceptSpec.CalledExpr(E);
8738 } else if (const RecordType *RecordTy
8739 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8740 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8741 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8742 if (Constructor)
8743 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8744 }
8745 }
8746
8747 return ExceptSpec;
8748 }
8749
8750 namespace {
8751 /// RAII object to register a special member as being currently declared.
8752 struct DeclaringSpecialMember {
8753 Sema &S;
8754 Sema::SpecialMemberDecl D;
8755 bool WasAlreadyBeingDeclared;
8756
DeclaringSpecialMember__anon515e6f930e11::DeclaringSpecialMember8757 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8758 : S(S), D(RD, CSM) {
8759 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
8760 if (WasAlreadyBeingDeclared)
8761 // This almost never happens, but if it does, ensure that our cache
8762 // doesn't contain a stale result.
8763 S.SpecialMemberCache.clear();
8764
8765 // FIXME: Register a note to be produced if we encounter an error while
8766 // declaring the special member.
8767 }
~DeclaringSpecialMember__anon515e6f930e11::DeclaringSpecialMember8768 ~DeclaringSpecialMember() {
8769 if (!WasAlreadyBeingDeclared)
8770 S.SpecialMembersBeingDeclared.erase(D);
8771 }
8772
8773 /// \brief Are we already trying to declare this special member?
isAlreadyBeingDeclared__anon515e6f930e11::DeclaringSpecialMember8774 bool isAlreadyBeingDeclared() const {
8775 return WasAlreadyBeingDeclared;
8776 }
8777 };
8778 }
8779
DeclareImplicitDefaultConstructor(CXXRecordDecl * ClassDecl)8780 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8781 CXXRecordDecl *ClassDecl) {
8782 // C++ [class.ctor]p5:
8783 // A default constructor for a class X is a constructor of class X
8784 // that can be called without an argument. If there is no
8785 // user-declared constructor for class X, a default constructor is
8786 // implicitly declared. An implicitly-declared default constructor
8787 // is an inline public member of its class.
8788 assert(ClassDecl->needsImplicitDefaultConstructor() &&
8789 "Should not build implicit default constructor!");
8790
8791 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8792 if (DSM.isAlreadyBeingDeclared())
8793 return nullptr;
8794
8795 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8796 CXXDefaultConstructor,
8797 false);
8798
8799 // Create the actual constructor declaration.
8800 CanQualType ClassType
8801 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8802 SourceLocation ClassLoc = ClassDecl->getLocation();
8803 DeclarationName Name
8804 = Context.DeclarationNames.getCXXConstructorName(ClassType);
8805 DeclarationNameInfo NameInfo(Name, ClassLoc);
8806 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8807 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8808 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8809 /*isImplicitlyDeclared=*/true, Constexpr);
8810 DefaultCon->setAccess(AS_public);
8811 DefaultCon->setDefaulted();
8812
8813 if (getLangOpts().CUDA) {
8814 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8815 DefaultCon,
8816 /* ConstRHS */ false,
8817 /* Diagnose */ false);
8818 }
8819
8820 // Build an exception specification pointing back at this constructor.
8821 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8822 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8823
8824 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8825 // constructors is easy to compute.
8826 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8827
8828 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8829 SetDeclDeleted(DefaultCon, ClassLoc);
8830
8831 // Note that we have declared this constructor.
8832 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8833
8834 if (Scope *S = getScopeForContext(ClassDecl))
8835 PushOnScopeChains(DefaultCon, S, false);
8836 ClassDecl->addDecl(DefaultCon);
8837
8838 return DefaultCon;
8839 }
8840
DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * Constructor)8841 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8842 CXXConstructorDecl *Constructor) {
8843 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8844 !Constructor->doesThisDeclarationHaveABody() &&
8845 !Constructor->isDeleted()) &&
8846 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8847
8848 CXXRecordDecl *ClassDecl = Constructor->getParent();
8849 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8850
8851 SynthesizedFunctionScope Scope(*this, Constructor);
8852 DiagnosticErrorTrap Trap(Diags);
8853 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8854 Trap.hasErrorOccurred()) {
8855 Diag(CurrentLocation, diag::note_member_synthesized_at)
8856 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8857 Constructor->setInvalidDecl();
8858 return;
8859 }
8860
8861 // The exception specification is needed because we are defining the
8862 // function.
8863 ResolveExceptionSpec(CurrentLocation,
8864 Constructor->getType()->castAs<FunctionProtoType>());
8865
8866 SourceLocation Loc = Constructor->getLocEnd().isValid()
8867 ? Constructor->getLocEnd()
8868 : Constructor->getLocation();
8869 Constructor->setBody(new (Context) CompoundStmt(Loc));
8870
8871 Constructor->markUsed(Context);
8872 MarkVTableUsed(CurrentLocation, ClassDecl);
8873
8874 if (ASTMutationListener *L = getASTMutationListener()) {
8875 L->CompletedImplicitDefinition(Constructor);
8876 }
8877
8878 DiagnoseUninitializedFields(*this, Constructor);
8879 }
8880
ActOnFinishDelayedMemberInitializers(Decl * D)8881 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8882 // Perform any delayed checks on exception specifications.
8883 CheckDelayedMemberExceptionSpecs();
8884 }
8885
8886 namespace {
8887 /// Information on inheriting constructors to declare.
8888 class InheritingConstructorInfo {
8889 public:
InheritingConstructorInfo(Sema & SemaRef,CXXRecordDecl * Derived)8890 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8891 : SemaRef(SemaRef), Derived(Derived) {
8892 // Mark the constructors that we already have in the derived class.
8893 //
8894 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8895 // unless there is a user-declared constructor with the same signature in
8896 // the class where the using-declaration appears.
8897 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8898 }
8899
inheritAll(CXXRecordDecl * RD)8900 void inheritAll(CXXRecordDecl *RD) {
8901 visitAll(RD, &InheritingConstructorInfo::inherit);
8902 }
8903
8904 private:
8905 /// Information about an inheriting constructor.
8906 struct InheritingConstructor {
InheritingConstructor__anon515e6f930f11::InheritingConstructorInfo::InheritingConstructor8907 InheritingConstructor()
8908 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
8909
8910 /// If \c true, a constructor with this signature is already declared
8911 /// in the derived class.
8912 bool DeclaredInDerived;
8913
8914 /// The constructor which is inherited.
8915 const CXXConstructorDecl *BaseCtor;
8916
8917 /// The derived constructor we declared.
8918 CXXConstructorDecl *DerivedCtor;
8919 };
8920
8921 /// Inheriting constructors with a given canonical type. There can be at
8922 /// most one such non-template constructor, and any number of templated
8923 /// constructors.
8924 struct InheritingConstructorsForType {
8925 InheritingConstructor NonTemplate;
8926 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8927 Templates;
8928
getEntry__anon515e6f930f11::InheritingConstructorInfo::InheritingConstructorsForType8929 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8930 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8931 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8932 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8933 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8934 false, S.TPL_TemplateMatch))
8935 return Templates[I].second;
8936 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8937 return Templates.back().second;
8938 }
8939
8940 return NonTemplate;
8941 }
8942 };
8943
8944 /// Get or create the inheriting constructor record for a constructor.
getEntry(const CXXConstructorDecl * Ctor,QualType CtorType)8945 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8946 QualType CtorType) {
8947 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8948 .getEntry(SemaRef, Ctor);
8949 }
8950
8951 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8952
8953 /// Process all constructors for a class.
visitAll(const CXXRecordDecl * RD,VisitFn Callback)8954 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8955 for (const auto *Ctor : RD->ctors())
8956 (this->*Callback)(Ctor);
8957 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8958 I(RD->decls_begin()), E(RD->decls_end());
8959 I != E; ++I) {
8960 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8961 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8962 (this->*Callback)(CD);
8963 }
8964 }
8965
8966 /// Note that a constructor (or constructor template) was declared in Derived.
noteDeclaredInDerived(const CXXConstructorDecl * Ctor)8967 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8968 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8969 }
8970
8971 /// Inherit a single constructor.
inherit(const CXXConstructorDecl * Ctor)8972 void inherit(const CXXConstructorDecl *Ctor) {
8973 const FunctionProtoType *CtorType =
8974 Ctor->getType()->castAs<FunctionProtoType>();
8975 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
8976 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8977
8978 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8979
8980 // Core issue (no number yet): the ellipsis is always discarded.
8981 if (EPI.Variadic) {
8982 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8983 SemaRef.Diag(Ctor->getLocation(),
8984 diag::note_using_decl_constructor_ellipsis);
8985 EPI.Variadic = false;
8986 }
8987
8988 // Declare a constructor for each number of parameters.
8989 //
8990 // C++11 [class.inhctor]p1:
8991 // The candidate set of inherited constructors from the class X named in
8992 // the using-declaration consists of [... modulo defects ...] for each
8993 // constructor or constructor template of X, the set of constructors or
8994 // constructor templates that results from omitting any ellipsis parameter
8995 // specification and successively omitting parameters with a default
8996 // argument from the end of the parameter-type-list
8997 unsigned MinParams = minParamsToInherit(Ctor);
8998 unsigned Params = Ctor->getNumParams();
8999 if (Params >= MinParams) {
9000 do
9001 declareCtor(UsingLoc, Ctor,
9002 SemaRef.Context.getFunctionType(
9003 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
9004 while (Params > MinParams &&
9005 Ctor->getParamDecl(--Params)->hasDefaultArg());
9006 }
9007 }
9008
9009 /// Find the using-declaration which specified that we should inherit the
9010 /// constructors of \p Base.
getUsingLoc(const CXXRecordDecl * Base)9011 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9012 // No fancy lookup required; just look for the base constructor name
9013 // directly within the derived class.
9014 ASTContext &Context = SemaRef.Context;
9015 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9016 Context.getCanonicalType(Context.getRecordType(Base)));
9017 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
9018 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9019 }
9020
minParamsToInherit(const CXXConstructorDecl * Ctor)9021 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9022 // C++11 [class.inhctor]p3:
9023 // [F]or each constructor template in the candidate set of inherited
9024 // constructors, a constructor template is implicitly declared
9025 if (Ctor->getDescribedFunctionTemplate())
9026 return 0;
9027
9028 // For each non-template constructor in the candidate set of inherited
9029 // constructors other than a constructor having no parameters or a
9030 // copy/move constructor having a single parameter, a constructor is
9031 // implicitly declared [...]
9032 if (Ctor->getNumParams() == 0)
9033 return 1;
9034 if (Ctor->isCopyOrMoveConstructor())
9035 return 2;
9036
9037 // Per discussion on core reflector, never inherit a constructor which
9038 // would become a default, copy, or move constructor of Derived either.
9039 const ParmVarDecl *PD = Ctor->getParamDecl(0);
9040 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9041 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9042 }
9043
9044 /// Declare a single inheriting constructor, inheriting the specified
9045 /// constructor, with the given type.
declareCtor(SourceLocation UsingLoc,const CXXConstructorDecl * BaseCtor,QualType DerivedType)9046 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9047 QualType DerivedType) {
9048 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9049
9050 // C++11 [class.inhctor]p3:
9051 // ... a constructor is implicitly declared with the same constructor
9052 // characteristics unless there is a user-declared constructor with
9053 // the same signature in the class where the using-declaration appears
9054 if (Entry.DeclaredInDerived)
9055 return;
9056
9057 // C++11 [class.inhctor]p7:
9058 // If two using-declarations declare inheriting constructors with the
9059 // same signature, the program is ill-formed
9060 if (Entry.DerivedCtor) {
9061 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9062 // Only diagnose this once per constructor.
9063 if (Entry.DerivedCtor->isInvalidDecl())
9064 return;
9065 Entry.DerivedCtor->setInvalidDecl();
9066
9067 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9068 SemaRef.Diag(BaseCtor->getLocation(),
9069 diag::note_using_decl_constructor_conflict_current_ctor);
9070 SemaRef.Diag(Entry.BaseCtor->getLocation(),
9071 diag::note_using_decl_constructor_conflict_previous_ctor);
9072 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9073 diag::note_using_decl_constructor_conflict_previous_using);
9074 } else {
9075 // Core issue (no number): if the same inheriting constructor is
9076 // produced by multiple base class constructors from the same base
9077 // class, the inheriting constructor is defined as deleted.
9078 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9079 }
9080
9081 return;
9082 }
9083
9084 ASTContext &Context = SemaRef.Context;
9085 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9086 Context.getCanonicalType(Context.getRecordType(Derived)));
9087 DeclarationNameInfo NameInfo(Name, UsingLoc);
9088
9089 TemplateParameterList *TemplateParams = nullptr;
9090 if (const FunctionTemplateDecl *FTD =
9091 BaseCtor->getDescribedFunctionTemplate()) {
9092 TemplateParams = FTD->getTemplateParameters();
9093 // We're reusing template parameters from a different DeclContext. This
9094 // is questionable at best, but works out because the template depth in
9095 // both places is guaranteed to be 0.
9096 // FIXME: Rebuild the template parameters in the new context, and
9097 // transform the function type to refer to them.
9098 }
9099
9100 // Build type source info pointing at the using-declaration. This is
9101 // required by template instantiation.
9102 TypeSourceInfo *TInfo =
9103 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9104 FunctionProtoTypeLoc ProtoLoc =
9105 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9106
9107 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9108 Context, Derived, UsingLoc, NameInfo, DerivedType,
9109 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9110 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9111
9112 // Build an unevaluated exception specification for this constructor.
9113 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9114 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9115 EPI.ExceptionSpec.Type = EST_Unevaluated;
9116 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
9117 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
9118 FPT->getParamTypes(), EPI));
9119
9120 // Build the parameter declarations.
9121 SmallVector<ParmVarDecl *, 16> ParamDecls;
9122 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
9123 TypeSourceInfo *TInfo =
9124 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
9125 ParmVarDecl *PD = ParmVarDecl::Create(
9126 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9127 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
9128 PD->setScopeInfo(0, I);
9129 PD->setImplicit();
9130 ParamDecls.push_back(PD);
9131 ProtoLoc.setParam(I, PD);
9132 }
9133
9134 // Set up the new constructor.
9135 DerivedCtor->setAccess(BaseCtor->getAccess());
9136 DerivedCtor->setParams(ParamDecls);
9137 DerivedCtor->setInheritedConstructor(BaseCtor);
9138 if (BaseCtor->isDeleted())
9139 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9140
9141 // If this is a constructor template, build the template declaration.
9142 if (TemplateParams) {
9143 FunctionTemplateDecl *DerivedTemplate =
9144 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9145 TemplateParams, DerivedCtor);
9146 DerivedTemplate->setAccess(BaseCtor->getAccess());
9147 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9148 Derived->addDecl(DerivedTemplate);
9149 } else {
9150 Derived->addDecl(DerivedCtor);
9151 }
9152
9153 Entry.BaseCtor = BaseCtor;
9154 Entry.DerivedCtor = DerivedCtor;
9155 }
9156
9157 Sema &SemaRef;
9158 CXXRecordDecl *Derived;
9159 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9160 MapType Map;
9161 };
9162 }
9163
DeclareInheritingConstructors(CXXRecordDecl * ClassDecl)9164 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9165 // Defer declaring the inheriting constructors until the class is
9166 // instantiated.
9167 if (ClassDecl->isDependentContext())
9168 return;
9169
9170 // Find base classes from which we might inherit constructors.
9171 SmallVector<CXXRecordDecl*, 4> InheritedBases;
9172 for (const auto &BaseIt : ClassDecl->bases())
9173 if (BaseIt.getInheritConstructors())
9174 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
9175
9176 // Go no further if we're not inheriting any constructors.
9177 if (InheritedBases.empty())
9178 return;
9179
9180 // Declare the inherited constructors.
9181 InheritingConstructorInfo ICI(*this, ClassDecl);
9182 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9183 ICI.inheritAll(InheritedBases[I]);
9184 }
9185
DefineInheritingConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * Constructor)9186 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9187 CXXConstructorDecl *Constructor) {
9188 CXXRecordDecl *ClassDecl = Constructor->getParent();
9189 assert(Constructor->getInheritedConstructor() &&
9190 !Constructor->doesThisDeclarationHaveABody() &&
9191 !Constructor->isDeleted());
9192
9193 SynthesizedFunctionScope Scope(*this, Constructor);
9194 DiagnosticErrorTrap Trap(Diags);
9195 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9196 Trap.hasErrorOccurred()) {
9197 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9198 << Context.getTagDeclType(ClassDecl);
9199 Constructor->setInvalidDecl();
9200 return;
9201 }
9202
9203 SourceLocation Loc = Constructor->getLocation();
9204 Constructor->setBody(new (Context) CompoundStmt(Loc));
9205
9206 Constructor->markUsed(Context);
9207 MarkVTableUsed(CurrentLocation, ClassDecl);
9208
9209 if (ASTMutationListener *L = getASTMutationListener()) {
9210 L->CompletedImplicitDefinition(Constructor);
9211 }
9212 }
9213
9214
9215 Sema::ImplicitExceptionSpecification
ComputeDefaultedDtorExceptionSpec(CXXMethodDecl * MD)9216 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9217 CXXRecordDecl *ClassDecl = MD->getParent();
9218
9219 // C++ [except.spec]p14:
9220 // An implicitly declared special member function (Clause 12) shall have
9221 // an exception-specification.
9222 ImplicitExceptionSpecification ExceptSpec(*this);
9223 if (ClassDecl->isInvalidDecl())
9224 return ExceptSpec;
9225
9226 // Direct base-class destructors.
9227 for (const auto &B : ClassDecl->bases()) {
9228 if (B.isVirtual()) // Handled below.
9229 continue;
9230
9231 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9232 ExceptSpec.CalledDecl(B.getLocStart(),
9233 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9234 }
9235
9236 // Virtual base-class destructors.
9237 for (const auto &B : ClassDecl->vbases()) {
9238 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9239 ExceptSpec.CalledDecl(B.getLocStart(),
9240 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9241 }
9242
9243 // Field destructors.
9244 for (const auto *F : ClassDecl->fields()) {
9245 if (const RecordType *RecordTy
9246 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
9247 ExceptSpec.CalledDecl(F->getLocation(),
9248 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
9249 }
9250
9251 return ExceptSpec;
9252 }
9253
DeclareImplicitDestructor(CXXRecordDecl * ClassDecl)9254 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9255 // C++ [class.dtor]p2:
9256 // If a class has no user-declared destructor, a destructor is
9257 // declared implicitly. An implicitly-declared destructor is an
9258 // inline public member of its class.
9259 assert(ClassDecl->needsImplicitDestructor());
9260
9261 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9262 if (DSM.isAlreadyBeingDeclared())
9263 return nullptr;
9264
9265 // Create the actual destructor declaration.
9266 CanQualType ClassType
9267 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9268 SourceLocation ClassLoc = ClassDecl->getLocation();
9269 DeclarationName Name
9270 = Context.DeclarationNames.getCXXDestructorName(ClassType);
9271 DeclarationNameInfo NameInfo(Name, ClassLoc);
9272 CXXDestructorDecl *Destructor
9273 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
9274 QualType(), nullptr, /*isInline=*/true,
9275 /*isImplicitlyDeclared=*/true);
9276 Destructor->setAccess(AS_public);
9277 Destructor->setDefaulted();
9278
9279 if (getLangOpts().CUDA) {
9280 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9281 Destructor,
9282 /* ConstRHS */ false,
9283 /* Diagnose */ false);
9284 }
9285
9286 // Build an exception specification pointing back at this destructor.
9287 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
9288 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9289
9290 AddOverriddenMethods(ClassDecl, Destructor);
9291
9292 // We don't need to use SpecialMemberIsTrivial here; triviality for
9293 // destructors is easy to compute.
9294 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9295
9296 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
9297 SetDeclDeleted(Destructor, ClassLoc);
9298
9299 // Note that we have declared this destructor.
9300 ++ASTContext::NumImplicitDestructorsDeclared;
9301
9302 // Introduce this destructor into its scope.
9303 if (Scope *S = getScopeForContext(ClassDecl))
9304 PushOnScopeChains(Destructor, S, false);
9305 ClassDecl->addDecl(Destructor);
9306
9307 return Destructor;
9308 }
9309
DefineImplicitDestructor(SourceLocation CurrentLocation,CXXDestructorDecl * Destructor)9310 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
9311 CXXDestructorDecl *Destructor) {
9312 assert((Destructor->isDefaulted() &&
9313 !Destructor->doesThisDeclarationHaveABody() &&
9314 !Destructor->isDeleted()) &&
9315 "DefineImplicitDestructor - call it for implicit default dtor");
9316 CXXRecordDecl *ClassDecl = Destructor->getParent();
9317 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
9318
9319 if (Destructor->isInvalidDecl())
9320 return;
9321
9322 SynthesizedFunctionScope Scope(*this, Destructor);
9323
9324 DiagnosticErrorTrap Trap(Diags);
9325 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9326 Destructor->getParent());
9327
9328 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9329 Diag(CurrentLocation, diag::note_member_synthesized_at)
9330 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9331
9332 Destructor->setInvalidDecl();
9333 return;
9334 }
9335
9336 // The exception specification is needed because we are defining the
9337 // function.
9338 ResolveExceptionSpec(CurrentLocation,
9339 Destructor->getType()->castAs<FunctionProtoType>());
9340
9341 SourceLocation Loc = Destructor->getLocEnd().isValid()
9342 ? Destructor->getLocEnd()
9343 : Destructor->getLocation();
9344 Destructor->setBody(new (Context) CompoundStmt(Loc));
9345 Destructor->markUsed(Context);
9346 MarkVTableUsed(CurrentLocation, ClassDecl);
9347
9348 if (ASTMutationListener *L = getASTMutationListener()) {
9349 L->CompletedImplicitDefinition(Destructor);
9350 }
9351 }
9352
9353 /// \brief Perform any semantic analysis which needs to be delayed until all
9354 /// pending class member declarations have been parsed.
ActOnFinishCXXMemberDecls()9355 void Sema::ActOnFinishCXXMemberDecls() {
9356 // If the context is an invalid C++ class, just suppress these checks.
9357 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9358 if (Record->isInvalidDecl()) {
9359 DelayedDefaultedMemberExceptionSpecs.clear();
9360 DelayedExceptionSpecChecks.clear();
9361 return;
9362 }
9363 }
9364 }
9365
AdjustDestructorExceptionSpec(CXXRecordDecl * ClassDecl,CXXDestructorDecl * Destructor)9366 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9367 CXXDestructorDecl *Destructor) {
9368 assert(getLangOpts().CPlusPlus11 &&
9369 "adjusting dtor exception specs was introduced in c++11");
9370
9371 // C++11 [class.dtor]p3:
9372 // A declaration of a destructor that does not have an exception-
9373 // specification is implicitly considered to have the same exception-
9374 // specification as an implicit declaration.
9375 const FunctionProtoType *DtorType = Destructor->getType()->
9376 getAs<FunctionProtoType>();
9377 if (DtorType->hasExceptionSpec())
9378 return;
9379
9380 // Replace the destructor's type, building off the existing one. Fortunately,
9381 // the only thing of interest in the destructor type is its extended info.
9382 // The return and arguments are fixed.
9383 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9384 EPI.ExceptionSpec.Type = EST_Unevaluated;
9385 EPI.ExceptionSpec.SourceDecl = Destructor;
9386 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9387
9388 // FIXME: If the destructor has a body that could throw, and the newly created
9389 // spec doesn't allow exceptions, we should emit a warning, because this
9390 // change in behavior can break conforming C++03 programs at runtime.
9391 // However, we don't have a body or an exception specification yet, so it
9392 // needs to be done somewhere else.
9393 }
9394
9395 namespace {
9396 /// \brief An abstract base class for all helper classes used in building the
9397 // copy/move operators. These classes serve as factory functions and help us
9398 // avoid using the same Expr* in the AST twice.
9399 class ExprBuilder {
9400 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9401 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9402
9403 protected:
assertNotNull(Expr * E)9404 static Expr *assertNotNull(Expr *E) {
9405 assert(E && "Expression construction must not fail.");
9406 return E;
9407 }
9408
9409 public:
ExprBuilder()9410 ExprBuilder() {}
~ExprBuilder()9411 virtual ~ExprBuilder() {}
9412
9413 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9414 };
9415
9416 class RefBuilder: public ExprBuilder {
9417 VarDecl *Var;
9418 QualType VarType;
9419
9420 public:
build(Sema & S,SourceLocation Loc) const9421 Expr *build(Sema &S, SourceLocation Loc) const override {
9422 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9423 }
9424
RefBuilder(VarDecl * Var,QualType VarType)9425 RefBuilder(VarDecl *Var, QualType VarType)
9426 : Var(Var), VarType(VarType) {}
9427 };
9428
9429 class ThisBuilder: public ExprBuilder {
9430 public:
build(Sema & S,SourceLocation Loc) const9431 Expr *build(Sema &S, SourceLocation Loc) const override {
9432 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9433 }
9434 };
9435
9436 class CastBuilder: public ExprBuilder {
9437 const ExprBuilder &Builder;
9438 QualType Type;
9439 ExprValueKind Kind;
9440 const CXXCastPath &Path;
9441
9442 public:
build(Sema & S,SourceLocation Loc) const9443 Expr *build(Sema &S, SourceLocation Loc) const override {
9444 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9445 CK_UncheckedDerivedToBase, Kind,
9446 &Path).get());
9447 }
9448
CastBuilder(const ExprBuilder & Builder,QualType Type,ExprValueKind Kind,const CXXCastPath & Path)9449 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9450 const CXXCastPath &Path)
9451 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9452 };
9453
9454 class DerefBuilder: public ExprBuilder {
9455 const ExprBuilder &Builder;
9456
9457 public:
build(Sema & S,SourceLocation Loc) const9458 Expr *build(Sema &S, SourceLocation Loc) const override {
9459 return assertNotNull(
9460 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9461 }
9462
DerefBuilder(const ExprBuilder & Builder)9463 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9464 };
9465
9466 class MemberBuilder: public ExprBuilder {
9467 const ExprBuilder &Builder;
9468 QualType Type;
9469 CXXScopeSpec SS;
9470 bool IsArrow;
9471 LookupResult &MemberLookup;
9472
9473 public:
build(Sema & S,SourceLocation Loc) const9474 Expr *build(Sema &S, SourceLocation Loc) const override {
9475 return assertNotNull(S.BuildMemberReferenceExpr(
9476 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9477 nullptr, MemberLookup, nullptr).get());
9478 }
9479
MemberBuilder(const ExprBuilder & Builder,QualType Type,bool IsArrow,LookupResult & MemberLookup)9480 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9481 LookupResult &MemberLookup)
9482 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9483 MemberLookup(MemberLookup) {}
9484 };
9485
9486 class MoveCastBuilder: public ExprBuilder {
9487 const ExprBuilder &Builder;
9488
9489 public:
build(Sema & S,SourceLocation Loc) const9490 Expr *build(Sema &S, SourceLocation Loc) const override {
9491 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9492 }
9493
MoveCastBuilder(const ExprBuilder & Builder)9494 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9495 };
9496
9497 class LvalueConvBuilder: public ExprBuilder {
9498 const ExprBuilder &Builder;
9499
9500 public:
build(Sema & S,SourceLocation Loc) const9501 Expr *build(Sema &S, SourceLocation Loc) const override {
9502 return assertNotNull(
9503 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9504 }
9505
LvalueConvBuilder(const ExprBuilder & Builder)9506 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9507 };
9508
9509 class SubscriptBuilder: public ExprBuilder {
9510 const ExprBuilder &Base;
9511 const ExprBuilder &Index;
9512
9513 public:
build(Sema & S,SourceLocation Loc) const9514 Expr *build(Sema &S, SourceLocation Loc) const override {
9515 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9516 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9517 }
9518
SubscriptBuilder(const ExprBuilder & Base,const ExprBuilder & Index)9519 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9520 : Base(Base), Index(Index) {}
9521 };
9522
9523 } // end anonymous namespace
9524
9525 /// When generating a defaulted copy or move assignment operator, if a field
9526 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9527 /// do so. This optimization only applies for arrays of scalars, and for arrays
9528 /// of class type where the selected copy/move-assignment operator is trivial.
9529 static StmtResult
buildMemcpyForAssignmentOp(Sema & S,SourceLocation Loc,QualType T,const ExprBuilder & ToB,const ExprBuilder & FromB)9530 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9531 const ExprBuilder &ToB, const ExprBuilder &FromB) {
9532 // Compute the size of the memory buffer to be copied.
9533 QualType SizeType = S.Context.getSizeType();
9534 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9535 S.Context.getTypeSizeInChars(T).getQuantity());
9536
9537 // Take the address of the field references for "from" and "to". We
9538 // directly construct UnaryOperators here because semantic analysis
9539 // does not permit us to take the address of an xvalue.
9540 Expr *From = FromB.build(S, Loc);
9541 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9542 S.Context.getPointerType(From->getType()),
9543 VK_RValue, OK_Ordinary, Loc);
9544 Expr *To = ToB.build(S, Loc);
9545 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9546 S.Context.getPointerType(To->getType()),
9547 VK_RValue, OK_Ordinary, Loc);
9548
9549 const Type *E = T->getBaseElementTypeUnsafe();
9550 bool NeedsCollectableMemCpy =
9551 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9552
9553 // Create a reference to the __builtin_objc_memmove_collectable function
9554 StringRef MemCpyName = NeedsCollectableMemCpy ?
9555 "__builtin_objc_memmove_collectable" :
9556 "__builtin_memcpy";
9557 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9558 Sema::LookupOrdinaryName);
9559 S.LookupName(R, S.TUScope, true);
9560
9561 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9562 if (!MemCpy)
9563 // Something went horribly wrong earlier, and we will have complained
9564 // about it.
9565 return StmtError();
9566
9567 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9568 VK_RValue, Loc, nullptr);
9569 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9570
9571 Expr *CallArgs[] = {
9572 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9573 };
9574 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9575 Loc, CallArgs, Loc);
9576
9577 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9578 return Call.getAs<Stmt>();
9579 }
9580
9581 /// \brief Builds a statement that copies/moves the given entity from \p From to
9582 /// \c To.
9583 ///
9584 /// This routine is used to copy/move the members of a class with an
9585 /// implicitly-declared copy/move assignment operator. When the entities being
9586 /// copied are arrays, this routine builds for loops to copy them.
9587 ///
9588 /// \param S The Sema object used for type-checking.
9589 ///
9590 /// \param Loc The location where the implicit copy/move is being generated.
9591 ///
9592 /// \param T The type of the expressions being copied/moved. Both expressions
9593 /// must have this type.
9594 ///
9595 /// \param To The expression we are copying/moving to.
9596 ///
9597 /// \param From The expression we are copying/moving from.
9598 ///
9599 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9600 /// Otherwise, it's a non-static member subobject.
9601 ///
9602 /// \param Copying Whether we're copying or moving.
9603 ///
9604 /// \param Depth Internal parameter recording the depth of the recursion.
9605 ///
9606 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9607 /// if a memcpy should be used instead.
9608 static StmtResult
buildSingleCopyAssignRecursively(Sema & S,SourceLocation Loc,QualType T,const ExprBuilder & To,const ExprBuilder & From,bool CopyingBaseSubobject,bool Copying,unsigned Depth=0)9609 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9610 const ExprBuilder &To, const ExprBuilder &From,
9611 bool CopyingBaseSubobject, bool Copying,
9612 unsigned Depth = 0) {
9613 // C++11 [class.copy]p28:
9614 // Each subobject is assigned in the manner appropriate to its type:
9615 //
9616 // - if the subobject is of class type, as if by a call to operator= with
9617 // the subobject as the object expression and the corresponding
9618 // subobject of x as a single function argument (as if by explicit
9619 // qualification; that is, ignoring any possible virtual overriding
9620 // functions in more derived classes);
9621 //
9622 // C++03 [class.copy]p13:
9623 // - if the subobject is of class type, the copy assignment operator for
9624 // the class is used (as if by explicit qualification; that is,
9625 // ignoring any possible virtual overriding functions in more derived
9626 // classes);
9627 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9628 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9629
9630 // Look for operator=.
9631 DeclarationName Name
9632 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9633 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9634 S.LookupQualifiedName(OpLookup, ClassDecl, false);
9635
9636 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9637 // operator.
9638 if (!S.getLangOpts().CPlusPlus11) {
9639 LookupResult::Filter F = OpLookup.makeFilter();
9640 while (F.hasNext()) {
9641 NamedDecl *D = F.next();
9642 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9643 if (Method->isCopyAssignmentOperator() ||
9644 (!Copying && Method->isMoveAssignmentOperator()))
9645 continue;
9646
9647 F.erase();
9648 }
9649 F.done();
9650 }
9651
9652 // Suppress the protected check (C++ [class.protected]) for each of the
9653 // assignment operators we found. This strange dance is required when
9654 // we're assigning via a base classes's copy-assignment operator. To
9655 // ensure that we're getting the right base class subobject (without
9656 // ambiguities), we need to cast "this" to that subobject type; to
9657 // ensure that we don't go through the virtual call mechanism, we need
9658 // to qualify the operator= name with the base class (see below). However,
9659 // this means that if the base class has a protected copy assignment
9660 // operator, the protected member access check will fail. So, we
9661 // rewrite "protected" access to "public" access in this case, since we
9662 // know by construction that we're calling from a derived class.
9663 if (CopyingBaseSubobject) {
9664 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9665 L != LEnd; ++L) {
9666 if (L.getAccess() == AS_protected)
9667 L.setAccess(AS_public);
9668 }
9669 }
9670
9671 // Create the nested-name-specifier that will be used to qualify the
9672 // reference to operator=; this is required to suppress the virtual
9673 // call mechanism.
9674 CXXScopeSpec SS;
9675 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9676 SS.MakeTrivial(S.Context,
9677 NestedNameSpecifier::Create(S.Context, nullptr, false,
9678 CanonicalT),
9679 Loc);
9680
9681 // Create the reference to operator=.
9682 ExprResult OpEqualRef
9683 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9684 SS, /*TemplateKWLoc=*/SourceLocation(),
9685 /*FirstQualifierInScope=*/nullptr,
9686 OpLookup,
9687 /*TemplateArgs=*/nullptr,
9688 /*SuppressQualifierCheck=*/true);
9689 if (OpEqualRef.isInvalid())
9690 return StmtError();
9691
9692 // Build the call to the assignment operator.
9693
9694 Expr *FromInst = From.build(S, Loc);
9695 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9696 OpEqualRef.getAs<Expr>(),
9697 Loc, FromInst, Loc);
9698 if (Call.isInvalid())
9699 return StmtError();
9700
9701 // If we built a call to a trivial 'operator=' while copying an array,
9702 // bail out. We'll replace the whole shebang with a memcpy.
9703 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9704 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9705 return StmtResult((Stmt*)nullptr);
9706
9707 // Convert to an expression-statement, and clean up any produced
9708 // temporaries.
9709 return S.ActOnExprStmt(Call);
9710 }
9711
9712 // - if the subobject is of scalar type, the built-in assignment
9713 // operator is used.
9714 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9715 if (!ArrayTy) {
9716 ExprResult Assignment = S.CreateBuiltinBinOp(
9717 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9718 if (Assignment.isInvalid())
9719 return StmtError();
9720 return S.ActOnExprStmt(Assignment);
9721 }
9722
9723 // - if the subobject is an array, each element is assigned, in the
9724 // manner appropriate to the element type;
9725
9726 // Construct a loop over the array bounds, e.g.,
9727 //
9728 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9729 //
9730 // that will copy each of the array elements.
9731 QualType SizeType = S.Context.getSizeType();
9732
9733 // Create the iteration variable.
9734 IdentifierInfo *IterationVarName = nullptr;
9735 {
9736 SmallString<8> Str;
9737 llvm::raw_svector_ostream OS(Str);
9738 OS << "__i" << Depth;
9739 IterationVarName = &S.Context.Idents.get(OS.str());
9740 }
9741 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9742 IterationVarName, SizeType,
9743 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9744 SC_None);
9745
9746 // Initialize the iteration variable to zero.
9747 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9748 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9749
9750 // Creates a reference to the iteration variable.
9751 RefBuilder IterationVarRef(IterationVar, SizeType);
9752 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9753
9754 // Create the DeclStmt that holds the iteration variable.
9755 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9756
9757 // Subscript the "from" and "to" expressions with the iteration variable.
9758 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9759 MoveCastBuilder FromIndexMove(FromIndexCopy);
9760 const ExprBuilder *FromIndex;
9761 if (Copying)
9762 FromIndex = &FromIndexCopy;
9763 else
9764 FromIndex = &FromIndexMove;
9765
9766 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9767
9768 // Build the copy/move for an individual element of the array.
9769 StmtResult Copy =
9770 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9771 ToIndex, *FromIndex, CopyingBaseSubobject,
9772 Copying, Depth + 1);
9773 // Bail out if copying fails or if we determined that we should use memcpy.
9774 if (Copy.isInvalid() || !Copy.get())
9775 return Copy;
9776
9777 // Create the comparison against the array bound.
9778 llvm::APInt Upper
9779 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9780 Expr *Comparison
9781 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9782 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9783 BO_NE, S.Context.BoolTy,
9784 VK_RValue, OK_Ordinary, Loc, false);
9785
9786 // Create the pre-increment of the iteration variable.
9787 Expr *Increment
9788 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9789 SizeType, VK_LValue, OK_Ordinary, Loc);
9790
9791 // Construct the loop that copies all elements of this array.
9792 return S.ActOnForStmt(Loc, Loc, InitStmt,
9793 S.MakeFullExpr(Comparison),
9794 nullptr, S.MakeFullDiscardedValueExpr(Increment),
9795 Loc, Copy.get());
9796 }
9797
9798 static StmtResult
buildSingleCopyAssign(Sema & S,SourceLocation Loc,QualType T,const ExprBuilder & To,const ExprBuilder & From,bool CopyingBaseSubobject,bool Copying)9799 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9800 const ExprBuilder &To, const ExprBuilder &From,
9801 bool CopyingBaseSubobject, bool Copying) {
9802 // Maybe we should use a memcpy?
9803 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9804 T.isTriviallyCopyableType(S.Context))
9805 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9806
9807 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9808 CopyingBaseSubobject,
9809 Copying, 0));
9810
9811 // If we ended up picking a trivial assignment operator for an array of a
9812 // non-trivially-copyable class type, just emit a memcpy.
9813 if (!Result.isInvalid() && !Result.get())
9814 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9815
9816 return Result;
9817 }
9818
9819 Sema::ImplicitExceptionSpecification
ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl * MD)9820 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9821 CXXRecordDecl *ClassDecl = MD->getParent();
9822
9823 ImplicitExceptionSpecification ExceptSpec(*this);
9824 if (ClassDecl->isInvalidDecl())
9825 return ExceptSpec;
9826
9827 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9828 assert(T->getNumParams() == 1 && "not a copy assignment op");
9829 unsigned ArgQuals =
9830 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9831
9832 // C++ [except.spec]p14:
9833 // An implicitly declared special member function (Clause 12) shall have an
9834 // exception-specification. [...]
9835
9836 // It is unspecified whether or not an implicit copy assignment operator
9837 // attempts to deduplicate calls to assignment operators of virtual bases are
9838 // made. As such, this exception specification is effectively unspecified.
9839 // Based on a similar decision made for constness in C++0x, we're erring on
9840 // the side of assuming such calls to be made regardless of whether they
9841 // actually happen.
9842 for (const auto &Base : ClassDecl->bases()) {
9843 if (Base.isVirtual())
9844 continue;
9845
9846 CXXRecordDecl *BaseClassDecl
9847 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9848 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9849 ArgQuals, false, 0))
9850 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9851 }
9852
9853 for (const auto &Base : ClassDecl->vbases()) {
9854 CXXRecordDecl *BaseClassDecl
9855 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9856 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9857 ArgQuals, false, 0))
9858 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9859 }
9860
9861 for (const auto *Field : ClassDecl->fields()) {
9862 QualType FieldType = Context.getBaseElementType(Field->getType());
9863 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9864 if (CXXMethodDecl *CopyAssign =
9865 LookupCopyingAssignment(FieldClassDecl,
9866 ArgQuals | FieldType.getCVRQualifiers(),
9867 false, 0))
9868 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
9869 }
9870 }
9871
9872 return ExceptSpec;
9873 }
9874
DeclareImplicitCopyAssignment(CXXRecordDecl * ClassDecl)9875 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9876 // Note: The following rules are largely analoguous to the copy
9877 // constructor rules. Note that virtual bases are not taken into account
9878 // for determining the argument type of the operator. Note also that
9879 // operators taking an object instead of a reference are allowed.
9880 assert(ClassDecl->needsImplicitCopyAssignment());
9881
9882 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9883 if (DSM.isAlreadyBeingDeclared())
9884 return nullptr;
9885
9886 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9887 QualType RetType = Context.getLValueReferenceType(ArgType);
9888 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9889 if (Const)
9890 ArgType = ArgType.withConst();
9891 ArgType = Context.getLValueReferenceType(ArgType);
9892
9893 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9894 CXXCopyAssignment,
9895 Const);
9896
9897 // An implicitly-declared copy assignment operator is an inline public
9898 // member of its class.
9899 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9900 SourceLocation ClassLoc = ClassDecl->getLocation();
9901 DeclarationNameInfo NameInfo(Name, ClassLoc);
9902 CXXMethodDecl *CopyAssignment =
9903 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9904 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9905 /*isInline=*/true, Constexpr, SourceLocation());
9906 CopyAssignment->setAccess(AS_public);
9907 CopyAssignment->setDefaulted();
9908 CopyAssignment->setImplicit();
9909
9910 if (getLangOpts().CUDA) {
9911 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
9912 CopyAssignment,
9913 /* ConstRHS */ Const,
9914 /* Diagnose */ false);
9915 }
9916
9917 // Build an exception specification pointing back at this member.
9918 FunctionProtoType::ExtProtoInfo EPI =
9919 getImplicitMethodEPI(*this, CopyAssignment);
9920 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9921
9922 // Add the parameter to the operator.
9923 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
9924 ClassLoc, ClassLoc,
9925 /*Id=*/nullptr, ArgType,
9926 /*TInfo=*/nullptr, SC_None,
9927 nullptr);
9928 CopyAssignment->setParams(FromParam);
9929
9930 AddOverriddenMethods(ClassDecl, CopyAssignment);
9931
9932 CopyAssignment->setTrivial(
9933 ClassDecl->needsOverloadResolutionForCopyAssignment()
9934 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9935 : ClassDecl->hasTrivialCopyAssignment());
9936
9937 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
9938 SetDeclDeleted(CopyAssignment, ClassLoc);
9939
9940 // Note that we have added this copy-assignment operator.
9941 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9942
9943 if (Scope *S = getScopeForContext(ClassDecl))
9944 PushOnScopeChains(CopyAssignment, S, false);
9945 ClassDecl->addDecl(CopyAssignment);
9946
9947 return CopyAssignment;
9948 }
9949
9950 /// Diagnose an implicit copy operation for a class which is odr-used, but
9951 /// which is deprecated because the class has a user-declared copy constructor,
9952 /// copy assignment operator, or destructor.
diagnoseDeprecatedCopyOperation(Sema & S,CXXMethodDecl * CopyOp,SourceLocation UseLoc)9953 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9954 SourceLocation UseLoc) {
9955 assert(CopyOp->isImplicit());
9956
9957 CXXRecordDecl *RD = CopyOp->getParent();
9958 CXXMethodDecl *UserDeclaredOperation = nullptr;
9959
9960 // In Microsoft mode, assignment operations don't affect constructors and
9961 // vice versa.
9962 if (RD->hasUserDeclaredDestructor()) {
9963 UserDeclaredOperation = RD->getDestructor();
9964 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9965 RD->hasUserDeclaredCopyConstructor() &&
9966 !S.getLangOpts().MSVCCompat) {
9967 // Find any user-declared copy constructor.
9968 for (auto *I : RD->ctors()) {
9969 if (I->isCopyConstructor()) {
9970 UserDeclaredOperation = I;
9971 break;
9972 }
9973 }
9974 assert(UserDeclaredOperation);
9975 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9976 RD->hasUserDeclaredCopyAssignment() &&
9977 !S.getLangOpts().MSVCCompat) {
9978 // Find any user-declared move assignment operator.
9979 for (auto *I : RD->methods()) {
9980 if (I->isCopyAssignmentOperator()) {
9981 UserDeclaredOperation = I;
9982 break;
9983 }
9984 }
9985 assert(UserDeclaredOperation);
9986 }
9987
9988 if (UserDeclaredOperation) {
9989 S.Diag(UserDeclaredOperation->getLocation(),
9990 diag::warn_deprecated_copy_operation)
9991 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9992 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9993 S.Diag(UseLoc, diag::note_member_synthesized_at)
9994 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9995 : Sema::CXXCopyAssignment)
9996 << RD;
9997 }
9998 }
9999
DefineImplicitCopyAssignment(SourceLocation CurrentLocation,CXXMethodDecl * CopyAssignOperator)10000 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10001 CXXMethodDecl *CopyAssignOperator) {
10002 assert((CopyAssignOperator->isDefaulted() &&
10003 CopyAssignOperator->isOverloadedOperator() &&
10004 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
10005 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10006 !CopyAssignOperator->isDeleted()) &&
10007 "DefineImplicitCopyAssignment called for wrong function");
10008
10009 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10010
10011 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10012 CopyAssignOperator->setInvalidDecl();
10013 return;
10014 }
10015
10016 // C++11 [class.copy]p18:
10017 // The [definition of an implicitly declared copy assignment operator] is
10018 // deprecated if the class has a user-declared copy constructor or a
10019 // user-declared destructor.
10020 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10021 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10022
10023 CopyAssignOperator->markUsed(Context);
10024
10025 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
10026 DiagnosticErrorTrap Trap(Diags);
10027
10028 // C++0x [class.copy]p30:
10029 // The implicitly-defined or explicitly-defaulted copy assignment operator
10030 // for a non-union class X performs memberwise copy assignment of its
10031 // subobjects. The direct base classes of X are assigned first, in the
10032 // order of their declaration in the base-specifier-list, and then the
10033 // immediate non-static data members of X are assigned, in the order in
10034 // which they were declared in the class definition.
10035
10036 // The statements that form the synthesized function body.
10037 SmallVector<Stmt*, 8> Statements;
10038
10039 // The parameter for the "other" object, which we are copying from.
10040 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10041 Qualifiers OtherQuals = Other->getType().getQualifiers();
10042 QualType OtherRefType = Other->getType();
10043 if (const LValueReferenceType *OtherRef
10044 = OtherRefType->getAs<LValueReferenceType>()) {
10045 OtherRefType = OtherRef->getPointeeType();
10046 OtherQuals = OtherRefType.getQualifiers();
10047 }
10048
10049 // Our location for everything implicitly-generated.
10050 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10051 ? CopyAssignOperator->getLocEnd()
10052 : CopyAssignOperator->getLocation();
10053
10054 // Builds a DeclRefExpr for the "other" object.
10055 RefBuilder OtherRef(Other, OtherRefType);
10056
10057 // Builds the "this" pointer.
10058 ThisBuilder This;
10059
10060 // Assign base classes.
10061 bool Invalid = false;
10062 for (auto &Base : ClassDecl->bases()) {
10063 // Form the assignment:
10064 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
10065 QualType BaseType = Base.getType().getUnqualifiedType();
10066 if (!BaseType->isRecordType()) {
10067 Invalid = true;
10068 continue;
10069 }
10070
10071 CXXCastPath BasePath;
10072 BasePath.push_back(&Base);
10073
10074 // Construct the "from" expression, which is an implicit cast to the
10075 // appropriately-qualified base type.
10076 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10077 VK_LValue, BasePath);
10078
10079 // Dereference "this".
10080 DerefBuilder DerefThis(This);
10081 CastBuilder To(DerefThis,
10082 Context.getCVRQualifiedType(
10083 BaseType, CopyAssignOperator->getTypeQualifiers()),
10084 VK_LValue, BasePath);
10085
10086 // Build the copy.
10087 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
10088 To, From,
10089 /*CopyingBaseSubobject=*/true,
10090 /*Copying=*/true);
10091 if (Copy.isInvalid()) {
10092 Diag(CurrentLocation, diag::note_member_synthesized_at)
10093 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10094 CopyAssignOperator->setInvalidDecl();
10095 return;
10096 }
10097
10098 // Success! Record the copy.
10099 Statements.push_back(Copy.getAs<Expr>());
10100 }
10101
10102 // Assign non-static members.
10103 for (auto *Field : ClassDecl->fields()) {
10104 if (Field->isUnnamedBitfield())
10105 continue;
10106
10107 if (Field->isInvalidDecl()) {
10108 Invalid = true;
10109 continue;
10110 }
10111
10112 // Check for members of reference type; we can't copy those.
10113 if (Field->getType()->isReferenceType()) {
10114 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10115 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10116 Diag(Field->getLocation(), diag::note_declared_at);
10117 Diag(CurrentLocation, diag::note_member_synthesized_at)
10118 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10119 Invalid = true;
10120 continue;
10121 }
10122
10123 // Check for members of const-qualified, non-class type.
10124 QualType BaseType = Context.getBaseElementType(Field->getType());
10125 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10126 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10127 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10128 Diag(Field->getLocation(), diag::note_declared_at);
10129 Diag(CurrentLocation, diag::note_member_synthesized_at)
10130 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10131 Invalid = true;
10132 continue;
10133 }
10134
10135 // Suppress assigning zero-width bitfields.
10136 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10137 continue;
10138
10139 QualType FieldType = Field->getType().getNonReferenceType();
10140 if (FieldType->isIncompleteArrayType()) {
10141 assert(ClassDecl->hasFlexibleArrayMember() &&
10142 "Incomplete array type is not valid");
10143 continue;
10144 }
10145
10146 // Build references to the field in the object we're copying from and to.
10147 CXXScopeSpec SS; // Intentionally empty
10148 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10149 LookupMemberName);
10150 MemberLookup.addDecl(Field);
10151 MemberLookup.resolveKind();
10152
10153 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10154
10155 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
10156
10157 // Build the copy of this field.
10158 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
10159 To, From,
10160 /*CopyingBaseSubobject=*/false,
10161 /*Copying=*/true);
10162 if (Copy.isInvalid()) {
10163 Diag(CurrentLocation, diag::note_member_synthesized_at)
10164 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10165 CopyAssignOperator->setInvalidDecl();
10166 return;
10167 }
10168
10169 // Success! Record the copy.
10170 Statements.push_back(Copy.getAs<Stmt>());
10171 }
10172
10173 if (!Invalid) {
10174 // Add a "return *this;"
10175 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10176
10177 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10178 if (Return.isInvalid())
10179 Invalid = true;
10180 else {
10181 Statements.push_back(Return.getAs<Stmt>());
10182
10183 if (Trap.hasErrorOccurred()) {
10184 Diag(CurrentLocation, diag::note_member_synthesized_at)
10185 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10186 Invalid = true;
10187 }
10188 }
10189 }
10190
10191 // The exception specification is needed because we are defining the
10192 // function.
10193 ResolveExceptionSpec(CurrentLocation,
10194 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10195
10196 if (Invalid) {
10197 CopyAssignOperator->setInvalidDecl();
10198 return;
10199 }
10200
10201 StmtResult Body;
10202 {
10203 CompoundScopeRAII CompoundScope(*this);
10204 Body = ActOnCompoundStmt(Loc, Loc, Statements,
10205 /*isStmtExpr=*/false);
10206 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10207 }
10208 CopyAssignOperator->setBody(Body.getAs<Stmt>());
10209
10210 if (ASTMutationListener *L = getASTMutationListener()) {
10211 L->CompletedImplicitDefinition(CopyAssignOperator);
10212 }
10213 }
10214
10215 Sema::ImplicitExceptionSpecification
ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl * MD)10216 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10217 CXXRecordDecl *ClassDecl = MD->getParent();
10218
10219 ImplicitExceptionSpecification ExceptSpec(*this);
10220 if (ClassDecl->isInvalidDecl())
10221 return ExceptSpec;
10222
10223 // C++0x [except.spec]p14:
10224 // An implicitly declared special member function (Clause 12) shall have an
10225 // exception-specification. [...]
10226
10227 // It is unspecified whether or not an implicit move assignment operator
10228 // attempts to deduplicate calls to assignment operators of virtual bases are
10229 // made. As such, this exception specification is effectively unspecified.
10230 // Based on a similar decision made for constness in C++0x, we're erring on
10231 // the side of assuming such calls to be made regardless of whether they
10232 // actually happen.
10233 // Note that a move constructor is not implicitly declared when there are
10234 // virtual bases, but it can still be user-declared and explicitly defaulted.
10235 for (const auto &Base : ClassDecl->bases()) {
10236 if (Base.isVirtual())
10237 continue;
10238
10239 CXXRecordDecl *BaseClassDecl
10240 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10241 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10242 0, false, 0))
10243 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10244 }
10245
10246 for (const auto &Base : ClassDecl->vbases()) {
10247 CXXRecordDecl *BaseClassDecl
10248 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10249 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10250 0, false, 0))
10251 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10252 }
10253
10254 for (const auto *Field : ClassDecl->fields()) {
10255 QualType FieldType = Context.getBaseElementType(Field->getType());
10256 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10257 if (CXXMethodDecl *MoveAssign =
10258 LookupMovingAssignment(FieldClassDecl,
10259 FieldType.getCVRQualifiers(),
10260 false, 0))
10261 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
10262 }
10263 }
10264
10265 return ExceptSpec;
10266 }
10267
DeclareImplicitMoveAssignment(CXXRecordDecl * ClassDecl)10268 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
10269 assert(ClassDecl->needsImplicitMoveAssignment());
10270
10271 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10272 if (DSM.isAlreadyBeingDeclared())
10273 return nullptr;
10274
10275 // Note: The following rules are largely analoguous to the move
10276 // constructor rules.
10277
10278 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10279 QualType RetType = Context.getLValueReferenceType(ArgType);
10280 ArgType = Context.getRValueReferenceType(ArgType);
10281
10282 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10283 CXXMoveAssignment,
10284 false);
10285
10286 // An implicitly-declared move assignment operator is an inline public
10287 // member of its class.
10288 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10289 SourceLocation ClassLoc = ClassDecl->getLocation();
10290 DeclarationNameInfo NameInfo(Name, ClassLoc);
10291 CXXMethodDecl *MoveAssignment =
10292 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10293 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10294 /*isInline=*/true, Constexpr, SourceLocation());
10295 MoveAssignment->setAccess(AS_public);
10296 MoveAssignment->setDefaulted();
10297 MoveAssignment->setImplicit();
10298
10299 if (getLangOpts().CUDA) {
10300 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10301 MoveAssignment,
10302 /* ConstRHS */ false,
10303 /* Diagnose */ false);
10304 }
10305
10306 // Build an exception specification pointing back at this member.
10307 FunctionProtoType::ExtProtoInfo EPI =
10308 getImplicitMethodEPI(*this, MoveAssignment);
10309 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10310
10311 // Add the parameter to the operator.
10312 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
10313 ClassLoc, ClassLoc,
10314 /*Id=*/nullptr, ArgType,
10315 /*TInfo=*/nullptr, SC_None,
10316 nullptr);
10317 MoveAssignment->setParams(FromParam);
10318
10319 AddOverriddenMethods(ClassDecl, MoveAssignment);
10320
10321 MoveAssignment->setTrivial(
10322 ClassDecl->needsOverloadResolutionForMoveAssignment()
10323 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10324 : ClassDecl->hasTrivialMoveAssignment());
10325
10326 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10327 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10328 SetDeclDeleted(MoveAssignment, ClassLoc);
10329 }
10330
10331 // Note that we have added this copy-assignment operator.
10332 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10333
10334 if (Scope *S = getScopeForContext(ClassDecl))
10335 PushOnScopeChains(MoveAssignment, S, false);
10336 ClassDecl->addDecl(MoveAssignment);
10337
10338 return MoveAssignment;
10339 }
10340
10341 /// Check if we're implicitly defining a move assignment operator for a class
10342 /// with virtual bases. Such a move assignment might move-assign the virtual
10343 /// base multiple times.
checkMoveAssignmentForRepeatedMove(Sema & S,CXXRecordDecl * Class,SourceLocation CurrentLocation)10344 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10345 SourceLocation CurrentLocation) {
10346 assert(!Class->isDependentContext() && "should not define dependent move");
10347
10348 // Only a virtual base could get implicitly move-assigned multiple times.
10349 // Only a non-trivial move assignment can observe this. We only want to
10350 // diagnose if we implicitly define an assignment operator that assigns
10351 // two base classes, both of which move-assign the same virtual base.
10352 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10353 Class->getNumBases() < 2)
10354 return;
10355
10356 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10357 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10358 VBaseMap VBases;
10359
10360 for (auto &BI : Class->bases()) {
10361 Worklist.push_back(&BI);
10362 while (!Worklist.empty()) {
10363 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10364 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10365
10366 // If the base has no non-trivial move assignment operators,
10367 // we don't care about moves from it.
10368 if (!Base->hasNonTrivialMoveAssignment())
10369 continue;
10370
10371 // If there's nothing virtual here, skip it.
10372 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10373 continue;
10374
10375 // If we're not actually going to call a move assignment for this base,
10376 // or the selected move assignment is trivial, skip it.
10377 Sema::SpecialMemberOverloadResult *SMOR =
10378 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10379 /*ConstArg*/false, /*VolatileArg*/false,
10380 /*RValueThis*/true, /*ConstThis*/false,
10381 /*VolatileThis*/false);
10382 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10383 !SMOR->getMethod()->isMoveAssignmentOperator())
10384 continue;
10385
10386 if (BaseSpec->isVirtual()) {
10387 // We're going to move-assign this virtual base, and its move
10388 // assignment operator is not trivial. If this can happen for
10389 // multiple distinct direct bases of Class, diagnose it. (If it
10390 // only happens in one base, we'll diagnose it when synthesizing
10391 // that base class's move assignment operator.)
10392 CXXBaseSpecifier *&Existing =
10393 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10394 .first->second;
10395 if (Existing && Existing != &BI) {
10396 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10397 << Class << Base;
10398 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10399 << (Base->getCanonicalDecl() ==
10400 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10401 << Base << Existing->getType() << Existing->getSourceRange();
10402 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10403 << (Base->getCanonicalDecl() ==
10404 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10405 << Base << BI.getType() << BaseSpec->getSourceRange();
10406
10407 // Only diagnose each vbase once.
10408 Existing = nullptr;
10409 }
10410 } else {
10411 // Only walk over bases that have defaulted move assignment operators.
10412 // We assume that any user-provided move assignment operator handles
10413 // the multiple-moves-of-vbase case itself somehow.
10414 if (!SMOR->getMethod()->isDefaulted())
10415 continue;
10416
10417 // We're going to move the base classes of Base. Add them to the list.
10418 for (auto &BI : Base->bases())
10419 Worklist.push_back(&BI);
10420 }
10421 }
10422 }
10423 }
10424
DefineImplicitMoveAssignment(SourceLocation CurrentLocation,CXXMethodDecl * MoveAssignOperator)10425 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10426 CXXMethodDecl *MoveAssignOperator) {
10427 assert((MoveAssignOperator->isDefaulted() &&
10428 MoveAssignOperator->isOverloadedOperator() &&
10429 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10430 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10431 !MoveAssignOperator->isDeleted()) &&
10432 "DefineImplicitMoveAssignment called for wrong function");
10433
10434 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10435
10436 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10437 MoveAssignOperator->setInvalidDecl();
10438 return;
10439 }
10440
10441 MoveAssignOperator->markUsed(Context);
10442
10443 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10444 DiagnosticErrorTrap Trap(Diags);
10445
10446 // C++0x [class.copy]p28:
10447 // The implicitly-defined or move assignment operator for a non-union class
10448 // X performs memberwise move assignment of its subobjects. The direct base
10449 // classes of X are assigned first, in the order of their declaration in the
10450 // base-specifier-list, and then the immediate non-static data members of X
10451 // are assigned, in the order in which they were declared in the class
10452 // definition.
10453
10454 // Issue a warning if our implicit move assignment operator will move
10455 // from a virtual base more than once.
10456 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10457
10458 // The statements that form the synthesized function body.
10459 SmallVector<Stmt*, 8> Statements;
10460
10461 // The parameter for the "other" object, which we are move from.
10462 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10463 QualType OtherRefType = Other->getType()->
10464 getAs<RValueReferenceType>()->getPointeeType();
10465 assert(!OtherRefType.getQualifiers() &&
10466 "Bad argument type of defaulted move assignment");
10467
10468 // Our location for everything implicitly-generated.
10469 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10470 ? MoveAssignOperator->getLocEnd()
10471 : MoveAssignOperator->getLocation();
10472
10473 // Builds a reference to the "other" object.
10474 RefBuilder OtherRef(Other, OtherRefType);
10475 // Cast to rvalue.
10476 MoveCastBuilder MoveOther(OtherRef);
10477
10478 // Builds the "this" pointer.
10479 ThisBuilder This;
10480
10481 // Assign base classes.
10482 bool Invalid = false;
10483 for (auto &Base : ClassDecl->bases()) {
10484 // C++11 [class.copy]p28:
10485 // It is unspecified whether subobjects representing virtual base classes
10486 // are assigned more than once by the implicitly-defined copy assignment
10487 // operator.
10488 // FIXME: Do not assign to a vbase that will be assigned by some other base
10489 // class. For a move-assignment, this can result in the vbase being moved
10490 // multiple times.
10491
10492 // Form the assignment:
10493 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10494 QualType BaseType = Base.getType().getUnqualifiedType();
10495 if (!BaseType->isRecordType()) {
10496 Invalid = true;
10497 continue;
10498 }
10499
10500 CXXCastPath BasePath;
10501 BasePath.push_back(&Base);
10502
10503 // Construct the "from" expression, which is an implicit cast to the
10504 // appropriately-qualified base type.
10505 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10506
10507 // Dereference "this".
10508 DerefBuilder DerefThis(This);
10509
10510 // Implicitly cast "this" to the appropriately-qualified base type.
10511 CastBuilder To(DerefThis,
10512 Context.getCVRQualifiedType(
10513 BaseType, MoveAssignOperator->getTypeQualifiers()),
10514 VK_LValue, BasePath);
10515
10516 // Build the move.
10517 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10518 To, From,
10519 /*CopyingBaseSubobject=*/true,
10520 /*Copying=*/false);
10521 if (Move.isInvalid()) {
10522 Diag(CurrentLocation, diag::note_member_synthesized_at)
10523 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10524 MoveAssignOperator->setInvalidDecl();
10525 return;
10526 }
10527
10528 // Success! Record the move.
10529 Statements.push_back(Move.getAs<Expr>());
10530 }
10531
10532 // Assign non-static members.
10533 for (auto *Field : ClassDecl->fields()) {
10534 if (Field->isUnnamedBitfield())
10535 continue;
10536
10537 if (Field->isInvalidDecl()) {
10538 Invalid = true;
10539 continue;
10540 }
10541
10542 // Check for members of reference type; we can't move those.
10543 if (Field->getType()->isReferenceType()) {
10544 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10545 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10546 Diag(Field->getLocation(), diag::note_declared_at);
10547 Diag(CurrentLocation, diag::note_member_synthesized_at)
10548 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10549 Invalid = true;
10550 continue;
10551 }
10552
10553 // Check for members of const-qualified, non-class type.
10554 QualType BaseType = Context.getBaseElementType(Field->getType());
10555 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10556 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10557 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10558 Diag(Field->getLocation(), diag::note_declared_at);
10559 Diag(CurrentLocation, diag::note_member_synthesized_at)
10560 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10561 Invalid = true;
10562 continue;
10563 }
10564
10565 // Suppress assigning zero-width bitfields.
10566 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10567 continue;
10568
10569 QualType FieldType = Field->getType().getNonReferenceType();
10570 if (FieldType->isIncompleteArrayType()) {
10571 assert(ClassDecl->hasFlexibleArrayMember() &&
10572 "Incomplete array type is not valid");
10573 continue;
10574 }
10575
10576 // Build references to the field in the object we're copying from and to.
10577 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10578 LookupMemberName);
10579 MemberLookup.addDecl(Field);
10580 MemberLookup.resolveKind();
10581 MemberBuilder From(MoveOther, OtherRefType,
10582 /*IsArrow=*/false, MemberLookup);
10583 MemberBuilder To(This, getCurrentThisType(),
10584 /*IsArrow=*/true, MemberLookup);
10585
10586 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10587 "Member reference with rvalue base must be rvalue except for reference "
10588 "members, which aren't allowed for move assignment.");
10589
10590 // Build the move of this field.
10591 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10592 To, From,
10593 /*CopyingBaseSubobject=*/false,
10594 /*Copying=*/false);
10595 if (Move.isInvalid()) {
10596 Diag(CurrentLocation, diag::note_member_synthesized_at)
10597 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10598 MoveAssignOperator->setInvalidDecl();
10599 return;
10600 }
10601
10602 // Success! Record the copy.
10603 Statements.push_back(Move.getAs<Stmt>());
10604 }
10605
10606 if (!Invalid) {
10607 // Add a "return *this;"
10608 ExprResult ThisObj =
10609 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10610
10611 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10612 if (Return.isInvalid())
10613 Invalid = true;
10614 else {
10615 Statements.push_back(Return.getAs<Stmt>());
10616
10617 if (Trap.hasErrorOccurred()) {
10618 Diag(CurrentLocation, diag::note_member_synthesized_at)
10619 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10620 Invalid = true;
10621 }
10622 }
10623 }
10624
10625 // The exception specification is needed because we are defining the
10626 // function.
10627 ResolveExceptionSpec(CurrentLocation,
10628 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10629
10630 if (Invalid) {
10631 MoveAssignOperator->setInvalidDecl();
10632 return;
10633 }
10634
10635 StmtResult Body;
10636 {
10637 CompoundScopeRAII CompoundScope(*this);
10638 Body = ActOnCompoundStmt(Loc, Loc, Statements,
10639 /*isStmtExpr=*/false);
10640 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10641 }
10642 MoveAssignOperator->setBody(Body.getAs<Stmt>());
10643
10644 if (ASTMutationListener *L = getASTMutationListener()) {
10645 L->CompletedImplicitDefinition(MoveAssignOperator);
10646 }
10647 }
10648
10649 Sema::ImplicitExceptionSpecification
ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl * MD)10650 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10651 CXXRecordDecl *ClassDecl = MD->getParent();
10652
10653 ImplicitExceptionSpecification ExceptSpec(*this);
10654 if (ClassDecl->isInvalidDecl())
10655 return ExceptSpec;
10656
10657 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10658 assert(T->getNumParams() >= 1 && "not a copy ctor");
10659 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10660
10661 // C++ [except.spec]p14:
10662 // An implicitly declared special member function (Clause 12) shall have an
10663 // exception-specification. [...]
10664 for (const auto &Base : ClassDecl->bases()) {
10665 // Virtual bases are handled below.
10666 if (Base.isVirtual())
10667 continue;
10668
10669 CXXRecordDecl *BaseClassDecl
10670 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10671 if (CXXConstructorDecl *CopyConstructor =
10672 LookupCopyingConstructor(BaseClassDecl, Quals))
10673 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10674 }
10675 for (const auto &Base : ClassDecl->vbases()) {
10676 CXXRecordDecl *BaseClassDecl
10677 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10678 if (CXXConstructorDecl *CopyConstructor =
10679 LookupCopyingConstructor(BaseClassDecl, Quals))
10680 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10681 }
10682 for (const auto *Field : ClassDecl->fields()) {
10683 QualType FieldType = Context.getBaseElementType(Field->getType());
10684 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10685 if (CXXConstructorDecl *CopyConstructor =
10686 LookupCopyingConstructor(FieldClassDecl,
10687 Quals | FieldType.getCVRQualifiers()))
10688 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10689 }
10690 }
10691
10692 return ExceptSpec;
10693 }
10694
DeclareImplicitCopyConstructor(CXXRecordDecl * ClassDecl)10695 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10696 CXXRecordDecl *ClassDecl) {
10697 // C++ [class.copy]p4:
10698 // If the class definition does not explicitly declare a copy
10699 // constructor, one is declared implicitly.
10700 assert(ClassDecl->needsImplicitCopyConstructor());
10701
10702 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10703 if (DSM.isAlreadyBeingDeclared())
10704 return nullptr;
10705
10706 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10707 QualType ArgType = ClassType;
10708 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10709 if (Const)
10710 ArgType = ArgType.withConst();
10711 ArgType = Context.getLValueReferenceType(ArgType);
10712
10713 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10714 CXXCopyConstructor,
10715 Const);
10716
10717 DeclarationName Name
10718 = Context.DeclarationNames.getCXXConstructorName(
10719 Context.getCanonicalType(ClassType));
10720 SourceLocation ClassLoc = ClassDecl->getLocation();
10721 DeclarationNameInfo NameInfo(Name, ClassLoc);
10722
10723 // An implicitly-declared copy constructor is an inline public
10724 // member of its class.
10725 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10726 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10727 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10728 Constexpr);
10729 CopyConstructor->setAccess(AS_public);
10730 CopyConstructor->setDefaulted();
10731
10732 if (getLangOpts().CUDA) {
10733 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10734 CopyConstructor,
10735 /* ConstRHS */ Const,
10736 /* Diagnose */ false);
10737 }
10738
10739 // Build an exception specification pointing back at this member.
10740 FunctionProtoType::ExtProtoInfo EPI =
10741 getImplicitMethodEPI(*this, CopyConstructor);
10742 CopyConstructor->setType(
10743 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10744
10745 // Add the parameter to the constructor.
10746 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10747 ClassLoc, ClassLoc,
10748 /*IdentifierInfo=*/nullptr,
10749 ArgType, /*TInfo=*/nullptr,
10750 SC_None, nullptr);
10751 CopyConstructor->setParams(FromParam);
10752
10753 CopyConstructor->setTrivial(
10754 ClassDecl->needsOverloadResolutionForCopyConstructor()
10755 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10756 : ClassDecl->hasTrivialCopyConstructor());
10757
10758 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10759 SetDeclDeleted(CopyConstructor, ClassLoc);
10760
10761 // Note that we have declared this constructor.
10762 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10763
10764 if (Scope *S = getScopeForContext(ClassDecl))
10765 PushOnScopeChains(CopyConstructor, S, false);
10766 ClassDecl->addDecl(CopyConstructor);
10767
10768 return CopyConstructor;
10769 }
10770
DefineImplicitCopyConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * CopyConstructor)10771 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10772 CXXConstructorDecl *CopyConstructor) {
10773 assert((CopyConstructor->isDefaulted() &&
10774 CopyConstructor->isCopyConstructor() &&
10775 !CopyConstructor->doesThisDeclarationHaveABody() &&
10776 !CopyConstructor->isDeleted()) &&
10777 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10778
10779 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10780 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10781
10782 // C++11 [class.copy]p7:
10783 // The [definition of an implicitly declared copy constructor] is
10784 // deprecated if the class has a user-declared copy assignment operator
10785 // or a user-declared destructor.
10786 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10787 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10788
10789 SynthesizedFunctionScope Scope(*this, CopyConstructor);
10790 DiagnosticErrorTrap Trap(Diags);
10791
10792 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10793 Trap.hasErrorOccurred()) {
10794 Diag(CurrentLocation, diag::note_member_synthesized_at)
10795 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10796 CopyConstructor->setInvalidDecl();
10797 } else {
10798 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10799 ? CopyConstructor->getLocEnd()
10800 : CopyConstructor->getLocation();
10801 Sema::CompoundScopeRAII CompoundScope(*this);
10802 CopyConstructor->setBody(
10803 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
10804 }
10805
10806 // The exception specification is needed because we are defining the
10807 // function.
10808 ResolveExceptionSpec(CurrentLocation,
10809 CopyConstructor->getType()->castAs<FunctionProtoType>());
10810
10811 CopyConstructor->markUsed(Context);
10812 MarkVTableUsed(CurrentLocation, ClassDecl);
10813
10814 if (ASTMutationListener *L = getASTMutationListener()) {
10815 L->CompletedImplicitDefinition(CopyConstructor);
10816 }
10817 }
10818
10819 Sema::ImplicitExceptionSpecification
ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl * MD)10820 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10821 CXXRecordDecl *ClassDecl = MD->getParent();
10822
10823 // C++ [except.spec]p14:
10824 // An implicitly declared special member function (Clause 12) shall have an
10825 // exception-specification. [...]
10826 ImplicitExceptionSpecification ExceptSpec(*this);
10827 if (ClassDecl->isInvalidDecl())
10828 return ExceptSpec;
10829
10830 // Direct base-class constructors.
10831 for (const auto &B : ClassDecl->bases()) {
10832 if (B.isVirtual()) // Handled below.
10833 continue;
10834
10835 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10836 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10837 CXXConstructorDecl *Constructor =
10838 LookupMovingConstructor(BaseClassDecl, 0);
10839 // If this is a deleted function, add it anyway. This might be conformant
10840 // with the standard. This might not. I'm not sure. It might not matter.
10841 if (Constructor)
10842 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10843 }
10844 }
10845
10846 // Virtual base-class constructors.
10847 for (const auto &B : ClassDecl->vbases()) {
10848 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10849 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10850 CXXConstructorDecl *Constructor =
10851 LookupMovingConstructor(BaseClassDecl, 0);
10852 // If this is a deleted function, add it anyway. This might be conformant
10853 // with the standard. This might not. I'm not sure. It might not matter.
10854 if (Constructor)
10855 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10856 }
10857 }
10858
10859 // Field constructors.
10860 for (const auto *F : ClassDecl->fields()) {
10861 QualType FieldType = Context.getBaseElementType(F->getType());
10862 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10863 CXXConstructorDecl *Constructor =
10864 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10865 // If this is a deleted function, add it anyway. This might be conformant
10866 // with the standard. This might not. I'm not sure. It might not matter.
10867 // In particular, the problem is that this function never gets called. It
10868 // might just be ill-formed because this function attempts to refer to
10869 // a deleted function here.
10870 if (Constructor)
10871 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10872 }
10873 }
10874
10875 return ExceptSpec;
10876 }
10877
DeclareImplicitMoveConstructor(CXXRecordDecl * ClassDecl)10878 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10879 CXXRecordDecl *ClassDecl) {
10880 assert(ClassDecl->needsImplicitMoveConstructor());
10881
10882 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10883 if (DSM.isAlreadyBeingDeclared())
10884 return nullptr;
10885
10886 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10887 QualType ArgType = Context.getRValueReferenceType(ClassType);
10888
10889 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10890 CXXMoveConstructor,
10891 false);
10892
10893 DeclarationName Name
10894 = Context.DeclarationNames.getCXXConstructorName(
10895 Context.getCanonicalType(ClassType));
10896 SourceLocation ClassLoc = ClassDecl->getLocation();
10897 DeclarationNameInfo NameInfo(Name, ClassLoc);
10898
10899 // C++11 [class.copy]p11:
10900 // An implicitly-declared copy/move constructor is an inline public
10901 // member of its class.
10902 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10903 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10904 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10905 Constexpr);
10906 MoveConstructor->setAccess(AS_public);
10907 MoveConstructor->setDefaulted();
10908
10909 if (getLangOpts().CUDA) {
10910 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
10911 MoveConstructor,
10912 /* ConstRHS */ false,
10913 /* Diagnose */ false);
10914 }
10915
10916 // Build an exception specification pointing back at this member.
10917 FunctionProtoType::ExtProtoInfo EPI =
10918 getImplicitMethodEPI(*this, MoveConstructor);
10919 MoveConstructor->setType(
10920 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10921
10922 // Add the parameter to the constructor.
10923 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10924 ClassLoc, ClassLoc,
10925 /*IdentifierInfo=*/nullptr,
10926 ArgType, /*TInfo=*/nullptr,
10927 SC_None, nullptr);
10928 MoveConstructor->setParams(FromParam);
10929
10930 MoveConstructor->setTrivial(
10931 ClassDecl->needsOverloadResolutionForMoveConstructor()
10932 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10933 : ClassDecl->hasTrivialMoveConstructor());
10934
10935 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10936 ClassDecl->setImplicitMoveConstructorIsDeleted();
10937 SetDeclDeleted(MoveConstructor, ClassLoc);
10938 }
10939
10940 // Note that we have declared this constructor.
10941 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10942
10943 if (Scope *S = getScopeForContext(ClassDecl))
10944 PushOnScopeChains(MoveConstructor, S, false);
10945 ClassDecl->addDecl(MoveConstructor);
10946
10947 return MoveConstructor;
10948 }
10949
DefineImplicitMoveConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * MoveConstructor)10950 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10951 CXXConstructorDecl *MoveConstructor) {
10952 assert((MoveConstructor->isDefaulted() &&
10953 MoveConstructor->isMoveConstructor() &&
10954 !MoveConstructor->doesThisDeclarationHaveABody() &&
10955 !MoveConstructor->isDeleted()) &&
10956 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10957
10958 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10959 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10960
10961 SynthesizedFunctionScope Scope(*this, MoveConstructor);
10962 DiagnosticErrorTrap Trap(Diags);
10963
10964 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
10965 Trap.hasErrorOccurred()) {
10966 Diag(CurrentLocation, diag::note_member_synthesized_at)
10967 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10968 MoveConstructor->setInvalidDecl();
10969 } else {
10970 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10971 ? MoveConstructor->getLocEnd()
10972 : MoveConstructor->getLocation();
10973 Sema::CompoundScopeRAII CompoundScope(*this);
10974 MoveConstructor->setBody(ActOnCompoundStmt(
10975 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
10976 }
10977
10978 // The exception specification is needed because we are defining the
10979 // function.
10980 ResolveExceptionSpec(CurrentLocation,
10981 MoveConstructor->getType()->castAs<FunctionProtoType>());
10982
10983 MoveConstructor->markUsed(Context);
10984 MarkVTableUsed(CurrentLocation, ClassDecl);
10985
10986 if (ASTMutationListener *L = getASTMutationListener()) {
10987 L->CompletedImplicitDefinition(MoveConstructor);
10988 }
10989 }
10990
isImplicitlyDeleted(FunctionDecl * FD)10991 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
10992 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
10993 }
10994
DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLocation,CXXConversionDecl * Conv)10995 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10996 SourceLocation CurrentLocation,
10997 CXXConversionDecl *Conv) {
10998 CXXRecordDecl *Lambda = Conv->getParent();
10999 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11000 // If we are defining a specialization of a conversion to function-ptr
11001 // cache the deduced template arguments for this specialization
11002 // so that we can use them to retrieve the corresponding call-operator
11003 // and static-invoker.
11004 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11005
11006 // Retrieve the corresponding call-operator specialization.
11007 if (Lambda->isGenericLambda()) {
11008 assert(Conv->isFunctionTemplateSpecialization());
11009 FunctionTemplateDecl *CallOpTemplate =
11010 CallOp->getDescribedFunctionTemplate();
11011 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
11012 void *InsertPos = nullptr;
11013 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
11014 DeducedTemplateArgs->asArray(),
11015 InsertPos);
11016 assert(CallOpSpec &&
11017 "Conversion operator must have a corresponding call operator");
11018 CallOp = cast<CXXMethodDecl>(CallOpSpec);
11019 }
11020 // Mark the call operator referenced (and add to pending instantiations
11021 // if necessary).
11022 // For both the conversion and static-invoker template specializations
11023 // we construct their body's in this function, so no need to add them
11024 // to the PendingInstantiations.
11025 MarkFunctionReferenced(CurrentLocation, CallOp);
11026
11027 SynthesizedFunctionScope Scope(*this, Conv);
11028 DiagnosticErrorTrap Trap(Diags);
11029
11030 // Retrieve the static invoker...
11031 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11032 // ... and get the corresponding specialization for a generic lambda.
11033 if (Lambda->isGenericLambda()) {
11034 assert(DeducedTemplateArgs &&
11035 "Must have deduced template arguments from Conversion Operator");
11036 FunctionTemplateDecl *InvokeTemplate =
11037 Invoker->getDescribedFunctionTemplate();
11038 void *InsertPos = nullptr;
11039 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
11040 DeducedTemplateArgs->asArray(),
11041 InsertPos);
11042 assert(InvokeSpec &&
11043 "Must have a corresponding static invoker specialization");
11044 Invoker = cast<CXXMethodDecl>(InvokeSpec);
11045 }
11046 // Construct the body of the conversion function { return __invoke; }.
11047 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
11048 VK_LValue, Conv->getLocation()).get();
11049 assert(FunctionRef && "Can't refer to __invoke function?");
11050 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
11051 Conv->setBody(new (Context) CompoundStmt(Context, Return,
11052 Conv->getLocation(),
11053 Conv->getLocation()));
11054
11055 Conv->markUsed(Context);
11056 Conv->setReferenced();
11057
11058 // Fill in the __invoke function with a dummy implementation. IR generation
11059 // will fill in the actual details.
11060 Invoker->markUsed(Context);
11061 Invoker->setReferenced();
11062 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11063
11064 if (ASTMutationListener *L = getASTMutationListener()) {
11065 L->CompletedImplicitDefinition(Conv);
11066 L->CompletedImplicitDefinition(Invoker);
11067 }
11068 }
11069
11070
11071
DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLocation,CXXConversionDecl * Conv)11072 void Sema::DefineImplicitLambdaToBlockPointerConversion(
11073 SourceLocation CurrentLocation,
11074 CXXConversionDecl *Conv)
11075 {
11076 assert(!Conv->getParent()->isGenericLambda());
11077
11078 Conv->markUsed(Context);
11079
11080 SynthesizedFunctionScope Scope(*this, Conv);
11081 DiagnosticErrorTrap Trap(Diags);
11082
11083 // Copy-initialize the lambda object as needed to capture it.
11084 Expr *This = ActOnCXXThis(CurrentLocation).get();
11085 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
11086
11087 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11088 Conv->getLocation(),
11089 Conv, DerefThis);
11090
11091 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11092 // behavior. Note that only the general conversion function does this
11093 // (since it's unusable otherwise); in the case where we inline the
11094 // block literal, it has block literal lifetime semantics.
11095 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
11096 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11097 CK_CopyAndAutoreleaseBlockObject,
11098 BuildBlock.get(), nullptr, VK_RValue);
11099
11100 if (BuildBlock.isInvalid()) {
11101 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11102 Conv->setInvalidDecl();
11103 return;
11104 }
11105
11106 // Create the return statement that returns the block from the conversion
11107 // function.
11108 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
11109 if (Return.isInvalid()) {
11110 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11111 Conv->setInvalidDecl();
11112 return;
11113 }
11114
11115 // Set the body of the conversion function.
11116 Stmt *ReturnS = Return.get();
11117 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
11118 Conv->getLocation(),
11119 Conv->getLocation()));
11120
11121 // We're done; notify the mutation listener, if any.
11122 if (ASTMutationListener *L = getASTMutationListener()) {
11123 L->CompletedImplicitDefinition(Conv);
11124 }
11125 }
11126
11127 /// \brief Determine whether the given list arguments contains exactly one
11128 /// "real" (non-default) argument.
hasOneRealArgument(MultiExprArg Args)11129 static bool hasOneRealArgument(MultiExprArg Args) {
11130 switch (Args.size()) {
11131 case 0:
11132 return false;
11133
11134 default:
11135 if (!Args[1]->isDefaultArgument())
11136 return false;
11137
11138 // fall through
11139 case 1:
11140 return !Args[0]->isDefaultArgument();
11141 }
11142
11143 return false;
11144 }
11145
11146 ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,CXXConstructorDecl * Constructor,MultiExprArg ExprArgs,bool HadMultipleCandidates,bool IsListInitialization,bool IsStdInitListInitialization,bool RequiresZeroInit,unsigned ConstructKind,SourceRange ParenRange)11147 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11148 CXXConstructorDecl *Constructor,
11149 MultiExprArg ExprArgs,
11150 bool HadMultipleCandidates,
11151 bool IsListInitialization,
11152 bool IsStdInitListInitialization,
11153 bool RequiresZeroInit,
11154 unsigned ConstructKind,
11155 SourceRange ParenRange) {
11156 bool Elidable = false;
11157
11158 // C++0x [class.copy]p34:
11159 // When certain criteria are met, an implementation is allowed to
11160 // omit the copy/move construction of a class object, even if the
11161 // copy/move constructor and/or destructor for the object have
11162 // side effects. [...]
11163 // - when a temporary class object that has not been bound to a
11164 // reference (12.2) would be copied/moved to a class object
11165 // with the same cv-unqualified type, the copy/move operation
11166 // can be omitted by constructing the temporary object
11167 // directly into the target of the omitted copy/move
11168 if (ConstructKind == CXXConstructExpr::CK_Complete &&
11169 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
11170 Expr *SubExpr = ExprArgs[0];
11171 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
11172 }
11173
11174 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
11175 Elidable, ExprArgs, HadMultipleCandidates,
11176 IsListInitialization,
11177 IsStdInitListInitialization, RequiresZeroInit,
11178 ConstructKind, ParenRange);
11179 }
11180
11181 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
11182 /// including handling of its default argument expressions.
11183 ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,CXXConstructorDecl * Constructor,bool Elidable,MultiExprArg ExprArgs,bool HadMultipleCandidates,bool IsListInitialization,bool IsStdInitListInitialization,bool RequiresZeroInit,unsigned ConstructKind,SourceRange ParenRange)11184 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11185 CXXConstructorDecl *Constructor, bool Elidable,
11186 MultiExprArg ExprArgs,
11187 bool HadMultipleCandidates,
11188 bool IsListInitialization,
11189 bool IsStdInitListInitialization,
11190 bool RequiresZeroInit,
11191 unsigned ConstructKind,
11192 SourceRange ParenRange) {
11193 MarkFunctionReferenced(ConstructLoc, Constructor);
11194 return CXXConstructExpr::Create(
11195 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
11196 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11197 RequiresZeroInit,
11198 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11199 ParenRange);
11200 }
11201
BuildCXXDefaultInitExpr(SourceLocation Loc,FieldDecl * Field)11202 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11203 assert(Field->hasInClassInitializer());
11204
11205 // If we already have the in-class initializer nothing needs to be done.
11206 if (Field->getInClassInitializer())
11207 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11208
11209 // Maybe we haven't instantiated the in-class initializer. Go check the
11210 // pattern FieldDecl to see if it has one.
11211 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11212
11213 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11214 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11215 DeclContext::lookup_result Lookup =
11216 ClassPattern->lookup(Field->getDeclName());
11217 assert(Lookup.size() == 1);
11218 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11219 if (InstantiateInClassInitializer(Loc, Field, Pattern,
11220 getTemplateInstantiationArgs(Field)))
11221 return ExprError();
11222 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11223 }
11224
11225 // DR1351:
11226 // If the brace-or-equal-initializer of a non-static data member
11227 // invokes a defaulted default constructor of its class or of an
11228 // enclosing class in a potentially evaluated subexpression, the
11229 // program is ill-formed.
11230 //
11231 // This resolution is unworkable: the exception specification of the
11232 // default constructor can be needed in an unevaluated context, in
11233 // particular, in the operand of a noexcept-expression, and we can be
11234 // unable to compute an exception specification for an enclosed class.
11235 //
11236 // Any attempt to resolve the exception specification of a defaulted default
11237 // constructor before the initializer is lexically complete will ultimately
11238 // come here at which point we can diagnose it.
11239 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11240 if (OutermostClass == ParentRD) {
11241 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11242 << ParentRD << Field;
11243 } else {
11244 Diag(Field->getLocEnd(),
11245 diag::err_in_class_initializer_not_yet_parsed_outer_class)
11246 << ParentRD << OutermostClass << Field;
11247 }
11248
11249 return ExprError();
11250 }
11251
FinalizeVarWithDestructor(VarDecl * VD,const RecordType * Record)11252 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
11253 if (VD->isInvalidDecl()) return;
11254
11255 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
11256 if (ClassDecl->isInvalidDecl()) return;
11257 if (ClassDecl->hasIrrelevantDestructor()) return;
11258 if (ClassDecl->isDependentContext()) return;
11259
11260 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11261 MarkFunctionReferenced(VD->getLocation(), Destructor);
11262 CheckDestructorAccess(VD->getLocation(), Destructor,
11263 PDiag(diag::err_access_dtor_var)
11264 << VD->getDeclName()
11265 << VD->getType());
11266 DiagnoseUseOfDecl(Destructor, VD->getLocation());
11267
11268 if (Destructor->isTrivial()) return;
11269 if (!VD->hasGlobalStorage()) return;
11270
11271 // Emit warning for non-trivial dtor in global scope (a real global,
11272 // class-static, function-static).
11273 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11274
11275 // TODO: this should be re-enabled for static locals by !CXAAtExit
11276 if (!VD->isStaticLocal())
11277 Diag(VD->getLocation(), diag::warn_global_destructor);
11278 }
11279
11280 /// \brief Given a constructor and the set of arguments provided for the
11281 /// constructor, convert the arguments and add any required default arguments
11282 /// to form a proper call to this constructor.
11283 ///
11284 /// \returns true if an error occurred, false otherwise.
11285 bool
CompleteConstructorCall(CXXConstructorDecl * Constructor,MultiExprArg ArgsPtr,SourceLocation Loc,SmallVectorImpl<Expr * > & ConvertedArgs,bool AllowExplicit,bool IsListInitialization)11286 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11287 MultiExprArg ArgsPtr,
11288 SourceLocation Loc,
11289 SmallVectorImpl<Expr*> &ConvertedArgs,
11290 bool AllowExplicit,
11291 bool IsListInitialization) {
11292 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11293 unsigned NumArgs = ArgsPtr.size();
11294 Expr **Args = ArgsPtr.data();
11295
11296 const FunctionProtoType *Proto
11297 = Constructor->getType()->getAs<FunctionProtoType>();
11298 assert(Proto && "Constructor without a prototype?");
11299 unsigned NumParams = Proto->getNumParams();
11300
11301 // If too few arguments are available, we'll fill in the rest with defaults.
11302 if (NumArgs < NumParams)
11303 ConvertedArgs.reserve(NumParams);
11304 else
11305 ConvertedArgs.reserve(NumArgs);
11306
11307 VariadicCallType CallType =
11308 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
11309 SmallVector<Expr *, 8> AllArgs;
11310 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
11311 Proto, 0,
11312 llvm::makeArrayRef(Args, NumArgs),
11313 AllArgs,
11314 CallType, AllowExplicit,
11315 IsListInitialization);
11316 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
11317
11318 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
11319
11320 CheckConstructorCall(Constructor,
11321 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
11322 Proto, Loc);
11323
11324 return Invalid;
11325 }
11326
11327 static inline bool
CheckOperatorNewDeleteDeclarationScope(Sema & SemaRef,const FunctionDecl * FnDecl)11328 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11329 const FunctionDecl *FnDecl) {
11330 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
11331 if (isa<NamespaceDecl>(DC)) {
11332 return SemaRef.Diag(FnDecl->getLocation(),
11333 diag::err_operator_new_delete_declared_in_namespace)
11334 << FnDecl->getDeclName();
11335 }
11336
11337 if (isa<TranslationUnitDecl>(DC) &&
11338 FnDecl->getStorageClass() == SC_Static) {
11339 return SemaRef.Diag(FnDecl->getLocation(),
11340 diag::err_operator_new_delete_declared_static)
11341 << FnDecl->getDeclName();
11342 }
11343
11344 return false;
11345 }
11346
11347 static inline bool
CheckOperatorNewDeleteTypes(Sema & SemaRef,const FunctionDecl * FnDecl,CanQualType ExpectedResultType,CanQualType ExpectedFirstParamType,unsigned DependentParamTypeDiag,unsigned InvalidParamTypeDiag)11348 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11349 CanQualType ExpectedResultType,
11350 CanQualType ExpectedFirstParamType,
11351 unsigned DependentParamTypeDiag,
11352 unsigned InvalidParamTypeDiag) {
11353 QualType ResultType =
11354 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
11355
11356 // Check that the result type is not dependent.
11357 if (ResultType->isDependentType())
11358 return SemaRef.Diag(FnDecl->getLocation(),
11359 diag::err_operator_new_delete_dependent_result_type)
11360 << FnDecl->getDeclName() << ExpectedResultType;
11361
11362 // Check that the result type is what we expect.
11363 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11364 return SemaRef.Diag(FnDecl->getLocation(),
11365 diag::err_operator_new_delete_invalid_result_type)
11366 << FnDecl->getDeclName() << ExpectedResultType;
11367
11368 // A function template must have at least 2 parameters.
11369 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11370 return SemaRef.Diag(FnDecl->getLocation(),
11371 diag::err_operator_new_delete_template_too_few_parameters)
11372 << FnDecl->getDeclName();
11373
11374 // The function decl must have at least 1 parameter.
11375 if (FnDecl->getNumParams() == 0)
11376 return SemaRef.Diag(FnDecl->getLocation(),
11377 diag::err_operator_new_delete_too_few_parameters)
11378 << FnDecl->getDeclName();
11379
11380 // Check the first parameter type is not dependent.
11381 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11382 if (FirstParamType->isDependentType())
11383 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11384 << FnDecl->getDeclName() << ExpectedFirstParamType;
11385
11386 // Check that the first parameter type is what we expect.
11387 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
11388 ExpectedFirstParamType)
11389 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11390 << FnDecl->getDeclName() << ExpectedFirstParamType;
11391
11392 return false;
11393 }
11394
11395 static bool
CheckOperatorNewDeclaration(Sema & SemaRef,const FunctionDecl * FnDecl)11396 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
11397 // C++ [basic.stc.dynamic.allocation]p1:
11398 // A program is ill-formed if an allocation function is declared in a
11399 // namespace scope other than global scope or declared static in global
11400 // scope.
11401 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11402 return true;
11403
11404 CanQualType SizeTy =
11405 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11406
11407 // C++ [basic.stc.dynamic.allocation]p1:
11408 // The return type shall be void*. The first parameter shall have type
11409 // std::size_t.
11410 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11411 SizeTy,
11412 diag::err_operator_new_dependent_param_type,
11413 diag::err_operator_new_param_type))
11414 return true;
11415
11416 // C++ [basic.stc.dynamic.allocation]p1:
11417 // The first parameter shall not have an associated default argument.
11418 if (FnDecl->getParamDecl(0)->hasDefaultArg())
11419 return SemaRef.Diag(FnDecl->getLocation(),
11420 diag::err_operator_new_default_arg)
11421 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11422
11423 return false;
11424 }
11425
11426 static bool
CheckOperatorDeleteDeclaration(Sema & SemaRef,FunctionDecl * FnDecl)11427 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11428 // C++ [basic.stc.dynamic.deallocation]p1:
11429 // A program is ill-formed if deallocation functions are declared in a
11430 // namespace scope other than global scope or declared static in global
11431 // scope.
11432 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11433 return true;
11434
11435 // C++ [basic.stc.dynamic.deallocation]p2:
11436 // Each deallocation function shall return void and its first parameter
11437 // shall be void*.
11438 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11439 SemaRef.Context.VoidPtrTy,
11440 diag::err_operator_delete_dependent_param_type,
11441 diag::err_operator_delete_param_type))
11442 return true;
11443
11444 return false;
11445 }
11446
11447 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11448 /// of this overloaded operator is well-formed. If so, returns false;
11449 /// otherwise, emits appropriate diagnostics and returns true.
CheckOverloadedOperatorDeclaration(FunctionDecl * FnDecl)11450 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11451 assert(FnDecl && FnDecl->isOverloadedOperator() &&
11452 "Expected an overloaded operator declaration");
11453
11454 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11455
11456 // C++ [over.oper]p5:
11457 // The allocation and deallocation functions, operator new,
11458 // operator new[], operator delete and operator delete[], are
11459 // described completely in 3.7.3. The attributes and restrictions
11460 // found in the rest of this subclause do not apply to them unless
11461 // explicitly stated in 3.7.3.
11462 if (Op == OO_Delete || Op == OO_Array_Delete)
11463 return CheckOperatorDeleteDeclaration(*this, FnDecl);
11464
11465 if (Op == OO_New || Op == OO_Array_New)
11466 return CheckOperatorNewDeclaration(*this, FnDecl);
11467
11468 // C++ [over.oper]p6:
11469 // An operator function shall either be a non-static member
11470 // function or be a non-member function and have at least one
11471 // parameter whose type is a class, a reference to a class, an
11472 // enumeration, or a reference to an enumeration.
11473 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11474 if (MethodDecl->isStatic())
11475 return Diag(FnDecl->getLocation(),
11476 diag::err_operator_overload_static) << FnDecl->getDeclName();
11477 } else {
11478 bool ClassOrEnumParam = false;
11479 for (auto Param : FnDecl->params()) {
11480 QualType ParamType = Param->getType().getNonReferenceType();
11481 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11482 ParamType->isEnumeralType()) {
11483 ClassOrEnumParam = true;
11484 break;
11485 }
11486 }
11487
11488 if (!ClassOrEnumParam)
11489 return Diag(FnDecl->getLocation(),
11490 diag::err_operator_overload_needs_class_or_enum)
11491 << FnDecl->getDeclName();
11492 }
11493
11494 // C++ [over.oper]p8:
11495 // An operator function cannot have default arguments (8.3.6),
11496 // except where explicitly stated below.
11497 //
11498 // Only the function-call operator allows default arguments
11499 // (C++ [over.call]p1).
11500 if (Op != OO_Call) {
11501 for (auto Param : FnDecl->params()) {
11502 if (Param->hasDefaultArg())
11503 return Diag(Param->getLocation(),
11504 diag::err_operator_overload_default_arg)
11505 << FnDecl->getDeclName() << Param->getDefaultArgRange();
11506 }
11507 }
11508
11509 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11510 { false, false, false }
11511 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11512 , { Unary, Binary, MemberOnly }
11513 #include "clang/Basic/OperatorKinds.def"
11514 };
11515
11516 bool CanBeUnaryOperator = OperatorUses[Op][0];
11517 bool CanBeBinaryOperator = OperatorUses[Op][1];
11518 bool MustBeMemberOperator = OperatorUses[Op][2];
11519
11520 // C++ [over.oper]p8:
11521 // [...] Operator functions cannot have more or fewer parameters
11522 // than the number required for the corresponding operator, as
11523 // described in the rest of this subclause.
11524 unsigned NumParams = FnDecl->getNumParams()
11525 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11526 if (Op != OO_Call &&
11527 ((NumParams == 1 && !CanBeUnaryOperator) ||
11528 (NumParams == 2 && !CanBeBinaryOperator) ||
11529 (NumParams < 1) || (NumParams > 2))) {
11530 // We have the wrong number of parameters.
11531 unsigned ErrorKind;
11532 if (CanBeUnaryOperator && CanBeBinaryOperator) {
11533 ErrorKind = 2; // 2 -> unary or binary.
11534 } else if (CanBeUnaryOperator) {
11535 ErrorKind = 0; // 0 -> unary
11536 } else {
11537 assert(CanBeBinaryOperator &&
11538 "All non-call overloaded operators are unary or binary!");
11539 ErrorKind = 1; // 1 -> binary
11540 }
11541
11542 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11543 << FnDecl->getDeclName() << NumParams << ErrorKind;
11544 }
11545
11546 // Overloaded operators other than operator() cannot be variadic.
11547 if (Op != OO_Call &&
11548 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11549 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11550 << FnDecl->getDeclName();
11551 }
11552
11553 // Some operators must be non-static member functions.
11554 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11555 return Diag(FnDecl->getLocation(),
11556 diag::err_operator_overload_must_be_member)
11557 << FnDecl->getDeclName();
11558 }
11559
11560 // C++ [over.inc]p1:
11561 // The user-defined function called operator++ implements the
11562 // prefix and postfix ++ operator. If this function is a member
11563 // function with no parameters, or a non-member function with one
11564 // parameter of class or enumeration type, it defines the prefix
11565 // increment operator ++ for objects of that type. If the function
11566 // is a member function with one parameter (which shall be of type
11567 // int) or a non-member function with two parameters (the second
11568 // of which shall be of type int), it defines the postfix
11569 // increment operator ++ for objects of that type.
11570 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11571 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11572 QualType ParamType = LastParam->getType();
11573
11574 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11575 !ParamType->isDependentType())
11576 return Diag(LastParam->getLocation(),
11577 diag::err_operator_overload_post_incdec_must_be_int)
11578 << LastParam->getType() << (Op == OO_MinusMinus);
11579 }
11580
11581 return false;
11582 }
11583
11584 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11585 /// of this literal operator function is well-formed. If so, returns
11586 /// false; otherwise, emits appropriate diagnostics and returns true.
CheckLiteralOperatorDeclaration(FunctionDecl * FnDecl)11587 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11588 if (isa<CXXMethodDecl>(FnDecl)) {
11589 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11590 << FnDecl->getDeclName();
11591 return true;
11592 }
11593
11594 if (FnDecl->isExternC()) {
11595 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11596 return true;
11597 }
11598
11599 bool Valid = false;
11600
11601 // This might be the definition of a literal operator template.
11602 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11603 // This might be a specialization of a literal operator template.
11604 if (!TpDecl)
11605 TpDecl = FnDecl->getPrimaryTemplate();
11606
11607 // template <char...> type operator "" name() and
11608 // template <class T, T...> type operator "" name() are the only valid
11609 // template signatures, and the only valid signatures with no parameters.
11610 if (TpDecl) {
11611 if (FnDecl->param_size() == 0) {
11612 // Must have one or two template parameters
11613 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11614 if (Params->size() == 1) {
11615 NonTypeTemplateParmDecl *PmDecl =
11616 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11617
11618 // The template parameter must be a char parameter pack.
11619 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11620 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11621 Valid = true;
11622 } else if (Params->size() == 2) {
11623 TemplateTypeParmDecl *PmType =
11624 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11625 NonTypeTemplateParmDecl *PmArgs =
11626 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11627
11628 // The second template parameter must be a parameter pack with the
11629 // first template parameter as its type.
11630 if (PmType && PmArgs &&
11631 !PmType->isTemplateParameterPack() &&
11632 PmArgs->isTemplateParameterPack()) {
11633 const TemplateTypeParmType *TArgs =
11634 PmArgs->getType()->getAs<TemplateTypeParmType>();
11635 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11636 TArgs->getIndex() == PmType->getIndex()) {
11637 Valid = true;
11638 if (ActiveTemplateInstantiations.empty())
11639 Diag(FnDecl->getLocation(),
11640 diag::ext_string_literal_operator_template);
11641 }
11642 }
11643 }
11644 }
11645 } else if (FnDecl->param_size()) {
11646 // Check the first parameter
11647 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11648
11649 QualType T = (*Param)->getType().getUnqualifiedType();
11650
11651 // unsigned long long int, long double, and any character type are allowed
11652 // as the only parameters.
11653 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11654 Context.hasSameType(T, Context.LongDoubleTy) ||
11655 Context.hasSameType(T, Context.CharTy) ||
11656 Context.hasSameType(T, Context.WideCharTy) ||
11657 Context.hasSameType(T, Context.Char16Ty) ||
11658 Context.hasSameType(T, Context.Char32Ty)) {
11659 if (++Param == FnDecl->param_end())
11660 Valid = true;
11661 goto FinishedParams;
11662 }
11663
11664 // Otherwise it must be a pointer to const; let's strip those qualifiers.
11665 const PointerType *PT = T->getAs<PointerType>();
11666 if (!PT)
11667 goto FinishedParams;
11668 T = PT->getPointeeType();
11669 if (!T.isConstQualified() || T.isVolatileQualified())
11670 goto FinishedParams;
11671 T = T.getUnqualifiedType();
11672
11673 // Move on to the second parameter;
11674 ++Param;
11675
11676 // If there is no second parameter, the first must be a const char *
11677 if (Param == FnDecl->param_end()) {
11678 if (Context.hasSameType(T, Context.CharTy))
11679 Valid = true;
11680 goto FinishedParams;
11681 }
11682
11683 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11684 // are allowed as the first parameter to a two-parameter function
11685 if (!(Context.hasSameType(T, Context.CharTy) ||
11686 Context.hasSameType(T, Context.WideCharTy) ||
11687 Context.hasSameType(T, Context.Char16Ty) ||
11688 Context.hasSameType(T, Context.Char32Ty)))
11689 goto FinishedParams;
11690
11691 // The second and final parameter must be an std::size_t
11692 T = (*Param)->getType().getUnqualifiedType();
11693 if (Context.hasSameType(T, Context.getSizeType()) &&
11694 ++Param == FnDecl->param_end())
11695 Valid = true;
11696 }
11697
11698 // FIXME: This diagnostic is absolutely terrible.
11699 FinishedParams:
11700 if (!Valid) {
11701 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11702 << FnDecl->getDeclName();
11703 return true;
11704 }
11705
11706 // A parameter-declaration-clause containing a default argument is not
11707 // equivalent to any of the permitted forms.
11708 for (auto Param : FnDecl->params()) {
11709 if (Param->hasDefaultArg()) {
11710 Diag(Param->getDefaultArgRange().getBegin(),
11711 diag::err_literal_operator_default_argument)
11712 << Param->getDefaultArgRange();
11713 break;
11714 }
11715 }
11716
11717 StringRef LiteralName
11718 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11719 if (LiteralName[0] != '_') {
11720 // C++11 [usrlit.suffix]p1:
11721 // Literal suffix identifiers that do not start with an underscore
11722 // are reserved for future standardization.
11723 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11724 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11725 }
11726
11727 return false;
11728 }
11729
11730 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11731 /// linkage specification, including the language and (if present)
11732 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11733 /// language string literal. LBraceLoc, if valid, provides the location of
11734 /// the '{' brace. Otherwise, this linkage specification does not
11735 /// have any braces.
ActOnStartLinkageSpecification(Scope * S,SourceLocation ExternLoc,Expr * LangStr,SourceLocation LBraceLoc)11736 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11737 Expr *LangStr,
11738 SourceLocation LBraceLoc) {
11739 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11740 if (!Lit->isAscii()) {
11741 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11742 << LangStr->getSourceRange();
11743 return nullptr;
11744 }
11745
11746 StringRef Lang = Lit->getString();
11747 LinkageSpecDecl::LanguageIDs Language;
11748 if (Lang == "C")
11749 Language = LinkageSpecDecl::lang_c;
11750 else if (Lang == "C++")
11751 Language = LinkageSpecDecl::lang_cxx;
11752 else {
11753 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11754 << LangStr->getSourceRange();
11755 return nullptr;
11756 }
11757
11758 // FIXME: Add all the various semantics of linkage specifications
11759
11760 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11761 LangStr->getExprLoc(), Language,
11762 LBraceLoc.isValid());
11763 CurContext->addDecl(D);
11764 PushDeclContext(S, D);
11765 return D;
11766 }
11767
11768 /// ActOnFinishLinkageSpecification - Complete the definition of
11769 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11770 /// valid, it's the position of the closing '}' brace in a linkage
11771 /// specification that uses braces.
ActOnFinishLinkageSpecification(Scope * S,Decl * LinkageSpec,SourceLocation RBraceLoc)11772 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11773 Decl *LinkageSpec,
11774 SourceLocation RBraceLoc) {
11775 if (RBraceLoc.isValid()) {
11776 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11777 LSDecl->setRBraceLoc(RBraceLoc);
11778 }
11779 PopDeclContext();
11780 return LinkageSpec;
11781 }
11782
ActOnEmptyDeclaration(Scope * S,AttributeList * AttrList,SourceLocation SemiLoc)11783 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11784 AttributeList *AttrList,
11785 SourceLocation SemiLoc) {
11786 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11787 // Attribute declarations appertain to empty declaration so we handle
11788 // them here.
11789 if (AttrList)
11790 ProcessDeclAttributeList(S, ED, AttrList);
11791
11792 CurContext->addDecl(ED);
11793 return ED;
11794 }
11795
11796 /// \brief Perform semantic analysis for the variable declaration that
11797 /// occurs within a C++ catch clause, returning the newly-created
11798 /// variable.
BuildExceptionDeclaration(Scope * S,TypeSourceInfo * TInfo,SourceLocation StartLoc,SourceLocation Loc,IdentifierInfo * Name)11799 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11800 TypeSourceInfo *TInfo,
11801 SourceLocation StartLoc,
11802 SourceLocation Loc,
11803 IdentifierInfo *Name) {
11804 bool Invalid = false;
11805 QualType ExDeclType = TInfo->getType();
11806
11807 // Arrays and functions decay.
11808 if (ExDeclType->isArrayType())
11809 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11810 else if (ExDeclType->isFunctionType())
11811 ExDeclType = Context.getPointerType(ExDeclType);
11812
11813 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11814 // The exception-declaration shall not denote a pointer or reference to an
11815 // incomplete type, other than [cv] void*.
11816 // N2844 forbids rvalue references.
11817 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11818 Diag(Loc, diag::err_catch_rvalue_ref);
11819 Invalid = true;
11820 }
11821
11822 QualType BaseType = ExDeclType;
11823 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11824 unsigned DK = diag::err_catch_incomplete;
11825 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11826 BaseType = Ptr->getPointeeType();
11827 Mode = 1;
11828 DK = diag::err_catch_incomplete_ptr;
11829 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11830 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11831 BaseType = Ref->getPointeeType();
11832 Mode = 2;
11833 DK = diag::err_catch_incomplete_ref;
11834 }
11835 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11836 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11837 Invalid = true;
11838
11839 if (!Invalid && !ExDeclType->isDependentType() &&
11840 RequireNonAbstractType(Loc, ExDeclType,
11841 diag::err_abstract_type_in_decl,
11842 AbstractVariableType))
11843 Invalid = true;
11844
11845 // Only the non-fragile NeXT runtime currently supports C++ catches
11846 // of ObjC types, and no runtime supports catching ObjC types by value.
11847 if (!Invalid && getLangOpts().ObjC1) {
11848 QualType T = ExDeclType;
11849 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11850 T = RT->getPointeeType();
11851
11852 if (T->isObjCObjectType()) {
11853 Diag(Loc, diag::err_objc_object_catch);
11854 Invalid = true;
11855 } else if (T->isObjCObjectPointerType()) {
11856 // FIXME: should this be a test for macosx-fragile specifically?
11857 if (getLangOpts().ObjCRuntime.isFragile())
11858 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
11859 }
11860 }
11861
11862 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
11863 ExDeclType, TInfo, SC_None);
11864 ExDecl->setExceptionVariable(true);
11865
11866 // In ARC, infer 'retaining' for variables of retainable type.
11867 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
11868 Invalid = true;
11869
11870 if (!Invalid && !ExDeclType->isDependentType()) {
11871 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
11872 // Insulate this from anything else we might currently be parsing.
11873 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11874
11875 // C++ [except.handle]p16:
11876 // The object declared in an exception-declaration or, if the
11877 // exception-declaration does not specify a name, a temporary (12.2) is
11878 // copy-initialized (8.5) from the exception object. [...]
11879 // The object is destroyed when the handler exits, after the destruction
11880 // of any automatic objects initialized within the handler.
11881 //
11882 // We just pretend to initialize the object with itself, then make sure
11883 // it can be destroyed later.
11884 QualType initType = ExDeclType;
11885
11886 InitializedEntity entity =
11887 InitializedEntity::InitializeVariable(ExDecl);
11888 InitializationKind initKind =
11889 InitializationKind::CreateCopy(Loc, SourceLocation());
11890
11891 Expr *opaqueValue =
11892 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
11893 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11894 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
11895 if (result.isInvalid())
11896 Invalid = true;
11897 else {
11898 // If the constructor used was non-trivial, set this as the
11899 // "initializer".
11900 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
11901 if (!construct->getConstructor()->isTrivial()) {
11902 Expr *init = MaybeCreateExprWithCleanups(construct);
11903 ExDecl->setInit(init);
11904 }
11905
11906 // And make sure it's destructable.
11907 FinalizeVarWithDestructor(ExDecl, recordType);
11908 }
11909 }
11910 }
11911
11912 if (Invalid)
11913 ExDecl->setInvalidDecl();
11914
11915 return ExDecl;
11916 }
11917
11918 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11919 /// handler.
ActOnExceptionDeclarator(Scope * S,Declarator & D)11920 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
11921 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11922 bool Invalid = D.isInvalidType();
11923
11924 // Check for unexpanded parameter packs.
11925 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11926 UPPC_ExceptionType)) {
11927 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11928 D.getIdentifierLoc());
11929 Invalid = true;
11930 }
11931
11932 IdentifierInfo *II = D.getIdentifier();
11933 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11934 LookupOrdinaryName,
11935 ForRedeclaration)) {
11936 // The scope should be freshly made just for us. There is just no way
11937 // it contains any previous declaration, except for function parameters in
11938 // a function-try-block's catch statement.
11939 assert(!S->isDeclScope(PrevDecl));
11940 if (isDeclInScope(PrevDecl, CurContext, S)) {
11941 Diag(D.getIdentifierLoc(), diag::err_redefinition)
11942 << D.getIdentifier();
11943 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11944 Invalid = true;
11945 } else if (PrevDecl->isTemplateParameter())
11946 // Maybe we will complain about the shadowed template parameter.
11947 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11948 }
11949
11950 if (D.getCXXScopeSpec().isSet() && !Invalid) {
11951 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11952 << D.getCXXScopeSpec().getRange();
11953 Invalid = true;
11954 }
11955
11956 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
11957 D.getLocStart(),
11958 D.getIdentifierLoc(),
11959 D.getIdentifier());
11960 if (Invalid)
11961 ExDecl->setInvalidDecl();
11962
11963 // Add the exception declaration into this scope.
11964 if (II)
11965 PushOnScopeChains(ExDecl, S);
11966 else
11967 CurContext->addDecl(ExDecl);
11968
11969 ProcessDeclAttributes(S, ExDecl, D);
11970 return ExDecl;
11971 }
11972
ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,Expr * AssertExpr,Expr * AssertMessageExpr,SourceLocation RParenLoc)11973 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11974 Expr *AssertExpr,
11975 Expr *AssertMessageExpr,
11976 SourceLocation RParenLoc) {
11977 StringLiteral *AssertMessage =
11978 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
11979
11980 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11981 return nullptr;
11982
11983 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11984 AssertMessage, RParenLoc, false);
11985 }
11986
BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,Expr * AssertExpr,StringLiteral * AssertMessage,SourceLocation RParenLoc,bool Failed)11987 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11988 Expr *AssertExpr,
11989 StringLiteral *AssertMessage,
11990 SourceLocation RParenLoc,
11991 bool Failed) {
11992 assert(AssertExpr != nullptr && "Expected non-null condition");
11993 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11994 !Failed) {
11995 // In a static_assert-declaration, the constant-expression shall be a
11996 // constant expression that can be contextually converted to bool.
11997 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11998 if (Converted.isInvalid())
11999 Failed = true;
12000
12001 llvm::APSInt Cond;
12002 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
12003 diag::err_static_assert_expression_is_not_constant,
12004 /*AllowFold=*/false).isInvalid())
12005 Failed = true;
12006
12007 if (!Failed && !Cond) {
12008 SmallString<256> MsgBuffer;
12009 llvm::raw_svector_ostream Msg(MsgBuffer);
12010 if (AssertMessage)
12011 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
12012 Diag(StaticAssertLoc, diag::err_static_assert_failed)
12013 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
12014 Failed = true;
12015 }
12016 }
12017
12018 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
12019 AssertExpr, AssertMessage, RParenLoc,
12020 Failed);
12021
12022 CurContext->addDecl(Decl);
12023 return Decl;
12024 }
12025
12026 /// \brief Perform semantic analysis of the given friend type declaration.
12027 ///
12028 /// \returns A friend declaration that.
CheckFriendTypeDecl(SourceLocation LocStart,SourceLocation FriendLoc,TypeSourceInfo * TSInfo)12029 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
12030 SourceLocation FriendLoc,
12031 TypeSourceInfo *TSInfo) {
12032 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12033
12034 QualType T = TSInfo->getType();
12035 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
12036
12037 // C++03 [class.friend]p2:
12038 // An elaborated-type-specifier shall be used in a friend declaration
12039 // for a class.*
12040 //
12041 // * The class-key of the elaborated-type-specifier is required.
12042 if (!ActiveTemplateInstantiations.empty()) {
12043 // Do not complain about the form of friend template types during
12044 // template instantiation; we will already have complained when the
12045 // template was declared.
12046 } else {
12047 if (!T->isElaboratedTypeSpecifier()) {
12048 // If we evaluated the type to a record type, suggest putting
12049 // a tag in front.
12050 if (const RecordType *RT = T->getAs<RecordType>()) {
12051 RecordDecl *RD = RT->getDecl();
12052
12053 SmallString<16> InsertionText(" ");
12054 InsertionText += RD->getKindName();
12055
12056 Diag(TypeRange.getBegin(),
12057 getLangOpts().CPlusPlus11 ?
12058 diag::warn_cxx98_compat_unelaborated_friend_type :
12059 diag::ext_unelaborated_friend_type)
12060 << (unsigned) RD->getTagKind()
12061 << T
12062 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
12063 InsertionText);
12064 } else {
12065 Diag(FriendLoc,
12066 getLangOpts().CPlusPlus11 ?
12067 diag::warn_cxx98_compat_nonclass_type_friend :
12068 diag::ext_nonclass_type_friend)
12069 << T
12070 << TypeRange;
12071 }
12072 } else if (T->getAs<EnumType>()) {
12073 Diag(FriendLoc,
12074 getLangOpts().CPlusPlus11 ?
12075 diag::warn_cxx98_compat_enum_friend :
12076 diag::ext_enum_friend)
12077 << T
12078 << TypeRange;
12079 }
12080
12081 // C++11 [class.friend]p3:
12082 // A friend declaration that does not declare a function shall have one
12083 // of the following forms:
12084 // friend elaborated-type-specifier ;
12085 // friend simple-type-specifier ;
12086 // friend typename-specifier ;
12087 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12088 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12089 }
12090
12091 // If the type specifier in a friend declaration designates a (possibly
12092 // cv-qualified) class type, that class is declared as a friend; otherwise,
12093 // the friend declaration is ignored.
12094 return FriendDecl::Create(Context, CurContext,
12095 TSInfo->getTypeLoc().getLocStart(), TSInfo,
12096 FriendLoc);
12097 }
12098
12099 /// Handle a friend tag declaration where the scope specifier was
12100 /// templated.
ActOnTemplatedFriendTag(Scope * S,SourceLocation FriendLoc,unsigned TagSpec,SourceLocation TagLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,AttributeList * Attr,MultiTemplateParamsArg TempParamLists)12101 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12102 unsigned TagSpec, SourceLocation TagLoc,
12103 CXXScopeSpec &SS,
12104 IdentifierInfo *Name,
12105 SourceLocation NameLoc,
12106 AttributeList *Attr,
12107 MultiTemplateParamsArg TempParamLists) {
12108 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12109
12110 bool isExplicitSpecialization = false;
12111 bool Invalid = false;
12112
12113 if (TemplateParameterList *TemplateParams =
12114 MatchTemplateParametersToScopeSpecifier(
12115 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
12116 isExplicitSpecialization, Invalid)) {
12117 if (TemplateParams->size() > 0) {
12118 // This is a declaration of a class template.
12119 if (Invalid)
12120 return nullptr;
12121
12122 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12123 NameLoc, Attr, TemplateParams, AS_public,
12124 /*ModulePrivateLoc=*/SourceLocation(),
12125 FriendLoc, TempParamLists.size() - 1,
12126 TempParamLists.data()).get();
12127 } else {
12128 // The "template<>" header is extraneous.
12129 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12130 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12131 isExplicitSpecialization = true;
12132 }
12133 }
12134
12135 if (Invalid) return nullptr;
12136
12137 bool isAllExplicitSpecializations = true;
12138 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
12139 if (TempParamLists[I]->size()) {
12140 isAllExplicitSpecializations = false;
12141 break;
12142 }
12143 }
12144
12145 // FIXME: don't ignore attributes.
12146
12147 // If it's explicit specializations all the way down, just forget
12148 // about the template header and build an appropriate non-templated
12149 // friend. TODO: for source fidelity, remember the headers.
12150 if (isAllExplicitSpecializations) {
12151 if (SS.isEmpty()) {
12152 bool Owned = false;
12153 bool IsDependent = false;
12154 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
12155 Attr, AS_public,
12156 /*ModulePrivateLoc=*/SourceLocation(),
12157 MultiTemplateParamsArg(), Owned, IsDependent,
12158 /*ScopedEnumKWLoc=*/SourceLocation(),
12159 /*ScopedEnumUsesClassTag=*/false,
12160 /*UnderlyingType=*/TypeResult(),
12161 /*IsTypeSpecifier=*/false);
12162 }
12163
12164 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12165 ElaboratedTypeKeyword Keyword
12166 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12167 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
12168 *Name, NameLoc);
12169 if (T.isNull())
12170 return nullptr;
12171
12172 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12173 if (isa<DependentNameType>(T)) {
12174 DependentNameTypeLoc TL =
12175 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12176 TL.setElaboratedKeywordLoc(TagLoc);
12177 TL.setQualifierLoc(QualifierLoc);
12178 TL.setNameLoc(NameLoc);
12179 } else {
12180 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
12181 TL.setElaboratedKeywordLoc(TagLoc);
12182 TL.setQualifierLoc(QualifierLoc);
12183 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
12184 }
12185
12186 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12187 TSI, FriendLoc, TempParamLists);
12188 Friend->setAccess(AS_public);
12189 CurContext->addDecl(Friend);
12190 return Friend;
12191 }
12192
12193 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12194
12195
12196
12197 // Handle the case of a templated-scope friend class. e.g.
12198 // template <class T> class A<T>::B;
12199 // FIXME: we don't support these right now.
12200 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12201 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
12202 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12203 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12204 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12205 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12206 TL.setElaboratedKeywordLoc(TagLoc);
12207 TL.setQualifierLoc(SS.getWithLocInContext(Context));
12208 TL.setNameLoc(NameLoc);
12209
12210 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12211 TSI, FriendLoc, TempParamLists);
12212 Friend->setAccess(AS_public);
12213 Friend->setUnsupportedFriend(true);
12214 CurContext->addDecl(Friend);
12215 return Friend;
12216 }
12217
12218
12219 /// Handle a friend type declaration. This works in tandem with
12220 /// ActOnTag.
12221 ///
12222 /// Notes on friend class templates:
12223 ///
12224 /// We generally treat friend class declarations as if they were
12225 /// declaring a class. So, for example, the elaborated type specifier
12226 /// in a friend declaration is required to obey the restrictions of a
12227 /// class-head (i.e. no typedefs in the scope chain), template
12228 /// parameters are required to match up with simple template-ids, &c.
12229 /// However, unlike when declaring a template specialization, it's
12230 /// okay to refer to a template specialization without an empty
12231 /// template parameter declaration, e.g.
12232 /// friend class A<T>::B<unsigned>;
12233 /// We permit this as a special case; if there are any template
12234 /// parameters present at all, require proper matching, i.e.
12235 /// template <> template \<class T> friend class A<int>::B;
ActOnFriendTypeDecl(Scope * S,const DeclSpec & DS,MultiTemplateParamsArg TempParams)12236 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
12237 MultiTemplateParamsArg TempParams) {
12238 SourceLocation Loc = DS.getLocStart();
12239
12240 assert(DS.isFriendSpecified());
12241 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12242
12243 // Try to convert the decl specifier to a type. This works for
12244 // friend templates because ActOnTag never produces a ClassTemplateDecl
12245 // for a TUK_Friend.
12246 Declarator TheDeclarator(DS, Declarator::MemberContext);
12247 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12248 QualType T = TSI->getType();
12249 if (TheDeclarator.isInvalidType())
12250 return nullptr;
12251
12252 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
12253 return nullptr;
12254
12255 // This is definitely an error in C++98. It's probably meant to
12256 // be forbidden in C++0x, too, but the specification is just
12257 // poorly written.
12258 //
12259 // The problem is with declarations like the following:
12260 // template <T> friend A<T>::foo;
12261 // where deciding whether a class C is a friend or not now hinges
12262 // on whether there exists an instantiation of A that causes
12263 // 'foo' to equal C. There are restrictions on class-heads
12264 // (which we declare (by fiat) elaborated friend declarations to
12265 // be) that makes this tractable.
12266 //
12267 // FIXME: handle "template <> friend class A<T>;", which
12268 // is possibly well-formed? Who even knows?
12269 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
12270 Diag(Loc, diag::err_tagless_friend_type_template)
12271 << DS.getSourceRange();
12272 return nullptr;
12273 }
12274
12275 // C++98 [class.friend]p1: A friend of a class is a function
12276 // or class that is not a member of the class . . .
12277 // This is fixed in DR77, which just barely didn't make the C++03
12278 // deadline. It's also a very silly restriction that seriously
12279 // affects inner classes and which nobody else seems to implement;
12280 // thus we never diagnose it, not even in -pedantic.
12281 //
12282 // But note that we could warn about it: it's always useless to
12283 // friend one of your own members (it's not, however, worthless to
12284 // friend a member of an arbitrary specialization of your template).
12285
12286 Decl *D;
12287 if (unsigned NumTempParamLists = TempParams.size())
12288 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
12289 NumTempParamLists,
12290 TempParams.data(),
12291 TSI,
12292 DS.getFriendSpecLoc());
12293 else
12294 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
12295
12296 if (!D)
12297 return nullptr;
12298
12299 D->setAccess(AS_public);
12300 CurContext->addDecl(D);
12301
12302 return D;
12303 }
12304
ActOnFriendFunctionDecl(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParams)12305 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12306 MultiTemplateParamsArg TemplateParams) {
12307 const DeclSpec &DS = D.getDeclSpec();
12308
12309 assert(DS.isFriendSpecified());
12310 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12311
12312 SourceLocation Loc = D.getIdentifierLoc();
12313 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12314
12315 // C++ [class.friend]p1
12316 // A friend of a class is a function or class....
12317 // Note that this sees through typedefs, which is intended.
12318 // It *doesn't* see through dependent types, which is correct
12319 // according to [temp.arg.type]p3:
12320 // If a declaration acquires a function type through a
12321 // type dependent on a template-parameter and this causes
12322 // a declaration that does not use the syntactic form of a
12323 // function declarator to have a function type, the program
12324 // is ill-formed.
12325 if (!TInfo->getType()->isFunctionType()) {
12326 Diag(Loc, diag::err_unexpected_friend);
12327
12328 // It might be worthwhile to try to recover by creating an
12329 // appropriate declaration.
12330 return nullptr;
12331 }
12332
12333 // C++ [namespace.memdef]p3
12334 // - If a friend declaration in a non-local class first declares a
12335 // class or function, the friend class or function is a member
12336 // of the innermost enclosing namespace.
12337 // - The name of the friend is not found by simple name lookup
12338 // until a matching declaration is provided in that namespace
12339 // scope (either before or after the class declaration granting
12340 // friendship).
12341 // - If a friend function is called, its name may be found by the
12342 // name lookup that considers functions from namespaces and
12343 // classes associated with the types of the function arguments.
12344 // - When looking for a prior declaration of a class or a function
12345 // declared as a friend, scopes outside the innermost enclosing
12346 // namespace scope are not considered.
12347
12348 CXXScopeSpec &SS = D.getCXXScopeSpec();
12349 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12350 DeclarationName Name = NameInfo.getName();
12351 assert(Name);
12352
12353 // Check for unexpanded parameter packs.
12354 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12355 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12356 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
12357 return nullptr;
12358
12359 // The context we found the declaration in, or in which we should
12360 // create the declaration.
12361 DeclContext *DC;
12362 Scope *DCScope = S;
12363 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12364 ForRedeclaration);
12365
12366 // There are five cases here.
12367 // - There's no scope specifier and we're in a local class. Only look
12368 // for functions declared in the immediately-enclosing block scope.
12369 // We recover from invalid scope qualifiers as if they just weren't there.
12370 FunctionDecl *FunctionContainingLocalClass = nullptr;
12371 if ((SS.isInvalid() || !SS.isSet()) &&
12372 (FunctionContainingLocalClass =
12373 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12374 // C++11 [class.friend]p11:
12375 // If a friend declaration appears in a local class and the name
12376 // specified is an unqualified name, a prior declaration is
12377 // looked up without considering scopes that are outside the
12378 // innermost enclosing non-class scope. For a friend function
12379 // declaration, if there is no prior declaration, the program is
12380 // ill-formed.
12381
12382 // Find the innermost enclosing non-class scope. This is the block
12383 // scope containing the local class definition (or for a nested class,
12384 // the outer local class).
12385 DCScope = S->getFnParent();
12386
12387 // Look up the function name in the scope.
12388 Previous.clear(LookupLocalFriendName);
12389 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12390
12391 if (!Previous.empty()) {
12392 // All possible previous declarations must have the same context:
12393 // either they were declared at block scope or they are members of
12394 // one of the enclosing local classes.
12395 DC = Previous.getRepresentativeDecl()->getDeclContext();
12396 } else {
12397 // This is ill-formed, but provide the context that we would have
12398 // declared the function in, if we were permitted to, for error recovery.
12399 DC = FunctionContainingLocalClass;
12400 }
12401 adjustContextForLocalExternDecl(DC);
12402
12403 // C++ [class.friend]p6:
12404 // A function can be defined in a friend declaration of a class if and
12405 // only if the class is a non-local class (9.8), the function name is
12406 // unqualified, and the function has namespace scope.
12407 if (D.isFunctionDefinition()) {
12408 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12409 }
12410
12411 // - There's no scope specifier, in which case we just go to the
12412 // appropriate scope and look for a function or function template
12413 // there as appropriate.
12414 } else if (SS.isInvalid() || !SS.isSet()) {
12415 // C++11 [namespace.memdef]p3:
12416 // If the name in a friend declaration is neither qualified nor
12417 // a template-id and the declaration is a function or an
12418 // elaborated-type-specifier, the lookup to determine whether
12419 // the entity has been previously declared shall not consider
12420 // any scopes outside the innermost enclosing namespace.
12421 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12422
12423 // Find the appropriate context according to the above.
12424 DC = CurContext;
12425
12426 // Skip class contexts. If someone can cite chapter and verse
12427 // for this behavior, that would be nice --- it's what GCC and
12428 // EDG do, and it seems like a reasonable intent, but the spec
12429 // really only says that checks for unqualified existing
12430 // declarations should stop at the nearest enclosing namespace,
12431 // not that they should only consider the nearest enclosing
12432 // namespace.
12433 while (DC->isRecord())
12434 DC = DC->getParent();
12435
12436 DeclContext *LookupDC = DC;
12437 while (LookupDC->isTransparentContext())
12438 LookupDC = LookupDC->getParent();
12439
12440 while (true) {
12441 LookupQualifiedName(Previous, LookupDC);
12442
12443 if (!Previous.empty()) {
12444 DC = LookupDC;
12445 break;
12446 }
12447
12448 if (isTemplateId) {
12449 if (isa<TranslationUnitDecl>(LookupDC)) break;
12450 } else {
12451 if (LookupDC->isFileContext()) break;
12452 }
12453 LookupDC = LookupDC->getParent();
12454 }
12455
12456 DCScope = getScopeForDeclContext(S, DC);
12457
12458 // - There's a non-dependent scope specifier, in which case we
12459 // compute it and do a previous lookup there for a function
12460 // or function template.
12461 } else if (!SS.getScopeRep()->isDependent()) {
12462 DC = computeDeclContext(SS);
12463 if (!DC) return nullptr;
12464
12465 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12466
12467 LookupQualifiedName(Previous, DC);
12468
12469 // Ignore things found implicitly in the wrong scope.
12470 // TODO: better diagnostics for this case. Suggesting the right
12471 // qualified scope would be nice...
12472 LookupResult::Filter F = Previous.makeFilter();
12473 while (F.hasNext()) {
12474 NamedDecl *D = F.next();
12475 if (!DC->InEnclosingNamespaceSetOf(
12476 D->getDeclContext()->getRedeclContext()))
12477 F.erase();
12478 }
12479 F.done();
12480
12481 if (Previous.empty()) {
12482 D.setInvalidType();
12483 Diag(Loc, diag::err_qualified_friend_not_found)
12484 << Name << TInfo->getType();
12485 return nullptr;
12486 }
12487
12488 // C++ [class.friend]p1: A friend of a class is a function or
12489 // class that is not a member of the class . . .
12490 if (DC->Equals(CurContext))
12491 Diag(DS.getFriendSpecLoc(),
12492 getLangOpts().CPlusPlus11 ?
12493 diag::warn_cxx98_compat_friend_is_member :
12494 diag::err_friend_is_member);
12495
12496 if (D.isFunctionDefinition()) {
12497 // C++ [class.friend]p6:
12498 // A function can be defined in a friend declaration of a class if and
12499 // only if the class is a non-local class (9.8), the function name is
12500 // unqualified, and the function has namespace scope.
12501 SemaDiagnosticBuilder DB
12502 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12503
12504 DB << SS.getScopeRep();
12505 if (DC->isFileContext())
12506 DB << FixItHint::CreateRemoval(SS.getRange());
12507 SS.clear();
12508 }
12509
12510 // - There's a scope specifier that does not match any template
12511 // parameter lists, in which case we use some arbitrary context,
12512 // create a method or method template, and wait for instantiation.
12513 // - There's a scope specifier that does match some template
12514 // parameter lists, which we don't handle right now.
12515 } else {
12516 if (D.isFunctionDefinition()) {
12517 // C++ [class.friend]p6:
12518 // A function can be defined in a friend declaration of a class if and
12519 // only if the class is a non-local class (9.8), the function name is
12520 // unqualified, and the function has namespace scope.
12521 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12522 << SS.getScopeRep();
12523 }
12524
12525 DC = CurContext;
12526 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12527 }
12528
12529 if (!DC->isRecord()) {
12530 // This implies that it has to be an operator or function.
12531 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12532 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12533 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
12534 Diag(Loc, diag::err_introducing_special_friend) <<
12535 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12536 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
12537 return nullptr;
12538 }
12539 }
12540
12541 // FIXME: This is an egregious hack to cope with cases where the scope stack
12542 // does not contain the declaration context, i.e., in an out-of-line
12543 // definition of a class.
12544 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12545 if (!DCScope) {
12546 FakeDCScope.setEntity(DC);
12547 DCScope = &FakeDCScope;
12548 }
12549
12550 bool AddToScope = true;
12551 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12552 TemplateParams, AddToScope);
12553 if (!ND) return nullptr;
12554
12555 assert(ND->getLexicalDeclContext() == CurContext);
12556
12557 // If we performed typo correction, we might have added a scope specifier
12558 // and changed the decl context.
12559 DC = ND->getDeclContext();
12560
12561 // Add the function declaration to the appropriate lookup tables,
12562 // adjusting the redeclarations list as necessary. We don't
12563 // want to do this yet if the friending class is dependent.
12564 //
12565 // Also update the scope-based lookup if the target context's
12566 // lookup context is in lexical scope.
12567 if (!CurContext->isDependentContext()) {
12568 DC = DC->getRedeclContext();
12569 DC->makeDeclVisibleInContext(ND);
12570 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12571 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12572 }
12573
12574 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12575 D.getIdentifierLoc(), ND,
12576 DS.getFriendSpecLoc());
12577 FrD->setAccess(AS_public);
12578 CurContext->addDecl(FrD);
12579
12580 if (ND->isInvalidDecl()) {
12581 FrD->setInvalidDecl();
12582 } else {
12583 if (DC->isRecord()) CheckFriendAccess(ND);
12584
12585 FunctionDecl *FD;
12586 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12587 FD = FTD->getTemplatedDecl();
12588 else
12589 FD = cast<FunctionDecl>(ND);
12590
12591 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12592 // default argument expression, that declaration shall be a definition
12593 // and shall be the only declaration of the function or function
12594 // template in the translation unit.
12595 if (functionDeclHasDefaultArgument(FD)) {
12596 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12597 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12598 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12599 } else if (!D.isFunctionDefinition())
12600 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12601 }
12602
12603 // Mark templated-scope function declarations as unsupported.
12604 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12605 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12606 << SS.getScopeRep() << SS.getRange()
12607 << cast<CXXRecordDecl>(CurContext);
12608 FrD->setUnsupportedFriend(true);
12609 }
12610 }
12611
12612 return ND;
12613 }
12614
SetDeclDeleted(Decl * Dcl,SourceLocation DelLoc)12615 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12616 AdjustDeclIfTemplate(Dcl);
12617
12618 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12619 if (!Fn) {
12620 Diag(DelLoc, diag::err_deleted_non_function);
12621 return;
12622 }
12623
12624 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12625 // Don't consider the implicit declaration we generate for explicit
12626 // specializations. FIXME: Do not generate these implicit declarations.
12627 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12628 Prev->getPreviousDecl()) &&
12629 !Prev->isDefined()) {
12630 Diag(DelLoc, diag::err_deleted_decl_not_first);
12631 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12632 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12633 : diag::note_previous_declaration);
12634 }
12635 // If the declaration wasn't the first, we delete the function anyway for
12636 // recovery.
12637 Fn = Fn->getCanonicalDecl();
12638 }
12639
12640 // dllimport/dllexport cannot be deleted.
12641 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12642 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12643 Fn->setInvalidDecl();
12644 }
12645
12646 if (Fn->isDeleted())
12647 return;
12648
12649 // See if we're deleting a function which is already known to override a
12650 // non-deleted virtual function.
12651 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12652 bool IssuedDiagnostic = false;
12653 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12654 E = MD->end_overridden_methods();
12655 I != E; ++I) {
12656 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12657 if (!IssuedDiagnostic) {
12658 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12659 IssuedDiagnostic = true;
12660 }
12661 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12662 }
12663 }
12664 }
12665
12666 // C++11 [basic.start.main]p3:
12667 // A program that defines main as deleted [...] is ill-formed.
12668 if (Fn->isMain())
12669 Diag(DelLoc, diag::err_deleted_main);
12670
12671 Fn->setDeletedAsWritten();
12672 }
12673
SetDeclDefaulted(Decl * Dcl,SourceLocation DefaultLoc)12674 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12675 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12676
12677 if (MD) {
12678 if (MD->getParent()->isDependentType()) {
12679 MD->setDefaulted();
12680 MD->setExplicitlyDefaulted();
12681 return;
12682 }
12683
12684 CXXSpecialMember Member = getSpecialMember(MD);
12685 if (Member == CXXInvalid) {
12686 if (!MD->isInvalidDecl())
12687 Diag(DefaultLoc, diag::err_default_special_members);
12688 return;
12689 }
12690
12691 MD->setDefaulted();
12692 MD->setExplicitlyDefaulted();
12693
12694 // If this definition appears within the record, do the checking when
12695 // the record is complete.
12696 const FunctionDecl *Primary = MD;
12697 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12698 // Find the uninstantiated declaration that actually had the '= default'
12699 // on it.
12700 Pattern->isDefined(Primary);
12701
12702 // If the method was defaulted on its first declaration, we will have
12703 // already performed the checking in CheckCompletedCXXClass. Such a
12704 // declaration doesn't trigger an implicit definition.
12705 if (Primary == Primary->getCanonicalDecl())
12706 return;
12707
12708 CheckExplicitlyDefaultedSpecialMember(MD);
12709
12710 if (MD->isInvalidDecl())
12711 return;
12712
12713 switch (Member) {
12714 case CXXDefaultConstructor:
12715 DefineImplicitDefaultConstructor(DefaultLoc,
12716 cast<CXXConstructorDecl>(MD));
12717 break;
12718 case CXXCopyConstructor:
12719 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12720 break;
12721 case CXXCopyAssignment:
12722 DefineImplicitCopyAssignment(DefaultLoc, MD);
12723 break;
12724 case CXXDestructor:
12725 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12726 break;
12727 case CXXMoveConstructor:
12728 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12729 break;
12730 case CXXMoveAssignment:
12731 DefineImplicitMoveAssignment(DefaultLoc, MD);
12732 break;
12733 case CXXInvalid:
12734 llvm_unreachable("Invalid special member.");
12735 }
12736 } else {
12737 Diag(DefaultLoc, diag::err_default_special_members);
12738 }
12739 }
12740
SearchForReturnInStmt(Sema & Self,Stmt * S)12741 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12742 for (Stmt::child_range CI = S->children(); CI; ++CI) {
12743 Stmt *SubStmt = *CI;
12744 if (!SubStmt)
12745 continue;
12746 if (isa<ReturnStmt>(SubStmt))
12747 Self.Diag(SubStmt->getLocStart(),
12748 diag::err_return_in_constructor_handler);
12749 if (!isa<Expr>(SubStmt))
12750 SearchForReturnInStmt(Self, SubStmt);
12751 }
12752 }
12753
DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt * TryBlock)12754 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12755 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12756 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12757 SearchForReturnInStmt(*this, Handler);
12758 }
12759 }
12760
CheckOverridingFunctionAttributes(const CXXMethodDecl * New,const CXXMethodDecl * Old)12761 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12762 const CXXMethodDecl *Old) {
12763 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12764 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12765
12766 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12767
12768 // If the calling conventions match, everything is fine
12769 if (NewCC == OldCC)
12770 return false;
12771
12772 // If the calling conventions mismatch because the new function is static,
12773 // suppress the calling convention mismatch error; the error about static
12774 // function override (err_static_overrides_virtual from
12775 // Sema::CheckFunctionDeclaration) is more clear.
12776 if (New->getStorageClass() == SC_Static)
12777 return false;
12778
12779 Diag(New->getLocation(),
12780 diag::err_conflicting_overriding_cc_attributes)
12781 << New->getDeclName() << New->getType() << Old->getType();
12782 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12783 return true;
12784 }
12785
CheckOverridingFunctionReturnType(const CXXMethodDecl * New,const CXXMethodDecl * Old)12786 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12787 const CXXMethodDecl *Old) {
12788 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12789 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12790
12791 if (Context.hasSameType(NewTy, OldTy) ||
12792 NewTy->isDependentType() || OldTy->isDependentType())
12793 return false;
12794
12795 // Check if the return types are covariant
12796 QualType NewClassTy, OldClassTy;
12797
12798 /// Both types must be pointers or references to classes.
12799 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12800 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12801 NewClassTy = NewPT->getPointeeType();
12802 OldClassTy = OldPT->getPointeeType();
12803 }
12804 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12805 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12806 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12807 NewClassTy = NewRT->getPointeeType();
12808 OldClassTy = OldRT->getPointeeType();
12809 }
12810 }
12811 }
12812
12813 // The return types aren't either both pointers or references to a class type.
12814 if (NewClassTy.isNull()) {
12815 Diag(New->getLocation(),
12816 diag::err_different_return_type_for_overriding_virtual_function)
12817 << New->getDeclName() << NewTy << OldTy
12818 << New->getReturnTypeSourceRange();
12819 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12820 << Old->getReturnTypeSourceRange();
12821
12822 return true;
12823 }
12824
12825 // C++ [class.virtual]p6:
12826 // If the return type of D::f differs from the return type of B::f, the
12827 // class type in the return type of D::f shall be complete at the point of
12828 // declaration of D::f or shall be the class type D.
12829 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12830 if (!RT->isBeingDefined() &&
12831 RequireCompleteType(New->getLocation(), NewClassTy,
12832 diag::err_covariant_return_incomplete,
12833 New->getDeclName()))
12834 return true;
12835 }
12836
12837 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12838 // Check if the new class derives from the old class.
12839 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12840 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12841 << New->getDeclName() << NewTy << OldTy
12842 << New->getReturnTypeSourceRange();
12843 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12844 << Old->getReturnTypeSourceRange();
12845 return true;
12846 }
12847
12848 // Check if we the conversion from derived to base is valid.
12849 if (CheckDerivedToBaseConversion(
12850 NewClassTy, OldClassTy,
12851 diag::err_covariant_return_inaccessible_base,
12852 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12853 New->getLocation(), New->getReturnTypeSourceRange(),
12854 New->getDeclName(), nullptr)) {
12855 // FIXME: this note won't trigger for delayed access control
12856 // diagnostics, and it's impossible to get an undelayed error
12857 // here from access control during the original parse because
12858 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
12859 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12860 << Old->getReturnTypeSourceRange();
12861 return true;
12862 }
12863 }
12864
12865 // The qualifiers of the return types must be the same.
12866 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
12867 Diag(New->getLocation(),
12868 diag::err_covariant_return_type_different_qualifications)
12869 << New->getDeclName() << NewTy << OldTy
12870 << New->getReturnTypeSourceRange();
12871 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12872 << Old->getReturnTypeSourceRange();
12873 return true;
12874 };
12875
12876
12877 // The new class type must have the same or less qualifiers as the old type.
12878 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12879 Diag(New->getLocation(),
12880 diag::err_covariant_return_type_class_type_more_qualified)
12881 << New->getDeclName() << NewTy << OldTy
12882 << New->getReturnTypeSourceRange();
12883 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12884 << Old->getReturnTypeSourceRange();
12885 return true;
12886 };
12887
12888 return false;
12889 }
12890
12891 /// \brief Mark the given method pure.
12892 ///
12893 /// \param Method the method to be marked pure.
12894 ///
12895 /// \param InitRange the source range that covers the "0" initializer.
CheckPureMethod(CXXMethodDecl * Method,SourceRange InitRange)12896 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
12897 SourceLocation EndLoc = InitRange.getEnd();
12898 if (EndLoc.isValid())
12899 Method->setRangeEnd(EndLoc);
12900
12901 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12902 Method->setPure();
12903 return false;
12904 }
12905
12906 if (!Method->isInvalidDecl())
12907 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12908 << Method->getDeclName() << InitRange;
12909 return true;
12910 }
12911
12912 /// \brief Determine whether the given declaration is a static data member.
isStaticDataMember(const Decl * D)12913 static bool isStaticDataMember(const Decl *D) {
12914 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12915 return Var->isStaticDataMember();
12916
12917 return false;
12918 }
12919
12920 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12921 /// an initializer for the out-of-line declaration 'Dcl'. The scope
12922 /// is a fresh scope pushed for just this purpose.
12923 ///
12924 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12925 /// static data member of class X, names should be looked up in the scope of
12926 /// class X.
ActOnCXXEnterDeclInitializer(Scope * S,Decl * D)12927 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
12928 // If there is no declaration, there was an error parsing it.
12929 if (!D || D->isInvalidDecl())
12930 return;
12931
12932 // We will always have a nested name specifier here, but this declaration
12933 // might not be out of line if the specifier names the current namespace:
12934 // extern int n;
12935 // int ::n = 0;
12936 if (D->isOutOfLine())
12937 EnterDeclaratorContext(S, D->getDeclContext());
12938
12939 // If we are parsing the initializer for a static data member, push a
12940 // new expression evaluation context that is associated with this static
12941 // data member.
12942 if (isStaticDataMember(D))
12943 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
12944 }
12945
12946 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
12947 /// initializer for the out-of-line declaration 'D'.
ActOnCXXExitDeclInitializer(Scope * S,Decl * D)12948 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
12949 // If there is no declaration, there was an error parsing it.
12950 if (!D || D->isInvalidDecl())
12951 return;
12952
12953 if (isStaticDataMember(D))
12954 PopExpressionEvaluationContext();
12955
12956 if (D->isOutOfLine())
12957 ExitDeclaratorContext(S);
12958 }
12959
12960 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12961 /// C++ if/switch/while/for statement.
12962 /// e.g: "if (int x = f()) {...}"
ActOnCXXConditionDeclaration(Scope * S,Declarator & D)12963 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
12964 // C++ 6.4p2:
12965 // The declarator shall not specify a function or an array.
12966 // The type-specifier-seq shall not contain typedef and shall not declare a
12967 // new class or enumeration.
12968 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12969 "Parser allowed 'typedef' as storage class of condition decl.");
12970
12971 Decl *Dcl = ActOnDeclarator(S, D);
12972 if (!Dcl)
12973 return true;
12974
12975 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12976 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
12977 << D.getSourceRange();
12978 return true;
12979 }
12980
12981 return Dcl;
12982 }
12983
LoadExternalVTableUses()12984 void Sema::LoadExternalVTableUses() {
12985 if (!ExternalSource)
12986 return;
12987
12988 SmallVector<ExternalVTableUse, 4> VTables;
12989 ExternalSource->ReadUsedVTables(VTables);
12990 SmallVector<VTableUse, 4> NewUses;
12991 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12992 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12993 = VTablesUsed.find(VTables[I].Record);
12994 // Even if a definition wasn't required before, it may be required now.
12995 if (Pos != VTablesUsed.end()) {
12996 if (!Pos->second && VTables[I].DefinitionRequired)
12997 Pos->second = true;
12998 continue;
12999 }
13000
13001 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13002 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13003 }
13004
13005 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13006 }
13007
MarkVTableUsed(SourceLocation Loc,CXXRecordDecl * Class,bool DefinitionRequired)13008 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13009 bool DefinitionRequired) {
13010 // Ignore any vtable uses in unevaluated operands or for classes that do
13011 // not have a vtable.
13012 if (!Class->isDynamicClass() || Class->isDependentContext() ||
13013 CurContext->isDependentContext() || isUnevaluatedContext())
13014 return;
13015
13016 // Try to insert this class into the map.
13017 LoadExternalVTableUses();
13018 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13019 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13020 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13021 if (!Pos.second) {
13022 // If we already had an entry, check to see if we are promoting this vtable
13023 // to require a definition. If so, we need to reappend to the VTableUses
13024 // list, since we may have already processed the first entry.
13025 if (DefinitionRequired && !Pos.first->second) {
13026 Pos.first->second = true;
13027 } else {
13028 // Otherwise, we can early exit.
13029 return;
13030 }
13031 } else {
13032 // The Microsoft ABI requires that we perform the destructor body
13033 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13034 // the deleting destructor is emitted with the vtable, not with the
13035 // destructor definition as in the Itanium ABI.
13036 // If it has a definition, we do the check at that point instead.
13037 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13038 Class->hasUserDeclaredDestructor() &&
13039 !Class->getDestructor()->isDefined() &&
13040 !Class->getDestructor()->isDeleted()) {
13041 CXXDestructorDecl *DD = Class->getDestructor();
13042 ContextRAII SavedContext(*this, DD);
13043 CheckDestructor(DD);
13044 }
13045 }
13046
13047 // Local classes need to have their virtual members marked
13048 // immediately. For all other classes, we mark their virtual members
13049 // at the end of the translation unit.
13050 if (Class->isLocalClass())
13051 MarkVirtualMembersReferenced(Loc, Class);
13052 else
13053 VTableUses.push_back(std::make_pair(Class, Loc));
13054 }
13055
DefineUsedVTables()13056 bool Sema::DefineUsedVTables() {
13057 LoadExternalVTableUses();
13058 if (VTableUses.empty())
13059 return false;
13060
13061 // Note: The VTableUses vector could grow as a result of marking
13062 // the members of a class as "used", so we check the size each
13063 // time through the loop and prefer indices (which are stable) to
13064 // iterators (which are not).
13065 bool DefinedAnything = false;
13066 for (unsigned I = 0; I != VTableUses.size(); ++I) {
13067 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
13068 if (!Class)
13069 continue;
13070
13071 SourceLocation Loc = VTableUses[I].second;
13072
13073 bool DefineVTable = true;
13074
13075 // If this class has a key function, but that key function is
13076 // defined in another translation unit, we don't need to emit the
13077 // vtable even though we're using it.
13078 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
13079 if (KeyFunction && !KeyFunction->hasBody()) {
13080 // The key function is in another translation unit.
13081 DefineVTable = false;
13082 TemplateSpecializationKind TSK =
13083 KeyFunction->getTemplateSpecializationKind();
13084 assert(TSK != TSK_ExplicitInstantiationDefinition &&
13085 TSK != TSK_ImplicitInstantiation &&
13086 "Instantiations don't have key functions");
13087 (void)TSK;
13088 } else if (!KeyFunction) {
13089 // If we have a class with no key function that is the subject
13090 // of an explicit instantiation declaration, suppress the
13091 // vtable; it will live with the explicit instantiation
13092 // definition.
13093 bool IsExplicitInstantiationDeclaration
13094 = Class->getTemplateSpecializationKind()
13095 == TSK_ExplicitInstantiationDeclaration;
13096 for (auto R : Class->redecls()) {
13097 TemplateSpecializationKind TSK
13098 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
13099 if (TSK == TSK_ExplicitInstantiationDeclaration)
13100 IsExplicitInstantiationDeclaration = true;
13101 else if (TSK == TSK_ExplicitInstantiationDefinition) {
13102 IsExplicitInstantiationDeclaration = false;
13103 break;
13104 }
13105 }
13106
13107 if (IsExplicitInstantiationDeclaration)
13108 DefineVTable = false;
13109 }
13110
13111 // The exception specifications for all virtual members may be needed even
13112 // if we are not providing an authoritative form of the vtable in this TU.
13113 // We may choose to emit it available_externally anyway.
13114 if (!DefineVTable) {
13115 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13116 continue;
13117 }
13118
13119 // Mark all of the virtual members of this class as referenced, so
13120 // that we can build a vtable. Then, tell the AST consumer that a
13121 // vtable for this class is required.
13122 DefinedAnything = true;
13123 MarkVirtualMembersReferenced(Loc, Class);
13124 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13125 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
13126
13127 // Optionally warn if we're emitting a weak vtable.
13128 if (Class->isExternallyVisible() &&
13129 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
13130 const FunctionDecl *KeyFunctionDef = nullptr;
13131 if (!KeyFunction ||
13132 (KeyFunction->hasBody(KeyFunctionDef) &&
13133 KeyFunctionDef->isInlined()))
13134 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13135 TSK_ExplicitInstantiationDefinition
13136 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13137 << Class;
13138 }
13139 }
13140 VTableUses.clear();
13141
13142 return DefinedAnything;
13143 }
13144
MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,const CXXRecordDecl * RD)13145 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13146 const CXXRecordDecl *RD) {
13147 for (const auto *I : RD->methods())
13148 if (I->isVirtual() && !I->isPure())
13149 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
13150 }
13151
MarkVirtualMembersReferenced(SourceLocation Loc,const CXXRecordDecl * RD)13152 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13153 const CXXRecordDecl *RD) {
13154 // Mark all functions which will appear in RD's vtable as used.
13155 CXXFinalOverriderMap FinalOverriders;
13156 RD->getFinalOverriders(FinalOverriders);
13157 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13158 E = FinalOverriders.end();
13159 I != E; ++I) {
13160 for (OverridingMethods::const_iterator OI = I->second.begin(),
13161 OE = I->second.end();
13162 OI != OE; ++OI) {
13163 assert(OI->second.size() > 0 && "no final overrider");
13164 CXXMethodDecl *Overrider = OI->second.front().Method;
13165
13166 // C++ [basic.def.odr]p2:
13167 // [...] A virtual member function is used if it is not pure. [...]
13168 if (!Overrider->isPure())
13169 MarkFunctionReferenced(Loc, Overrider);
13170 }
13171 }
13172
13173 // Only classes that have virtual bases need a VTT.
13174 if (RD->getNumVBases() == 0)
13175 return;
13176
13177 for (const auto &I : RD->bases()) {
13178 const CXXRecordDecl *Base =
13179 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
13180 if (Base->getNumVBases() == 0)
13181 continue;
13182 MarkVirtualMembersReferenced(Loc, Base);
13183 }
13184 }
13185
13186 /// SetIvarInitializers - This routine builds initialization ASTs for the
13187 /// Objective-C implementation whose ivars need be initialized.
SetIvarInitializers(ObjCImplementationDecl * ObjCImplementation)13188 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
13189 if (!getLangOpts().CPlusPlus)
13190 return;
13191 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
13192 SmallVector<ObjCIvarDecl*, 8> ivars;
13193 CollectIvarsToConstructOrDestruct(OID, ivars);
13194 if (ivars.empty())
13195 return;
13196 SmallVector<CXXCtorInitializer*, 32> AllToInit;
13197 for (unsigned i = 0; i < ivars.size(); i++) {
13198 FieldDecl *Field = ivars[i];
13199 if (Field->isInvalidDecl())
13200 continue;
13201
13202 CXXCtorInitializer *Member;
13203 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13204 InitializationKind InitKind =
13205 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
13206
13207 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13208 ExprResult MemberInit =
13209 InitSeq.Perform(*this, InitEntity, InitKind, None);
13210 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
13211 // Note, MemberInit could actually come back empty if no initialization
13212 // is required (e.g., because it would call a trivial default constructor)
13213 if (!MemberInit.get() || MemberInit.isInvalid())
13214 continue;
13215
13216 Member =
13217 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13218 SourceLocation(),
13219 MemberInit.getAs<Expr>(),
13220 SourceLocation());
13221 AllToInit.push_back(Member);
13222
13223 // Be sure that the destructor is accessible and is marked as referenced.
13224 if (const RecordType *RecordTy =
13225 Context.getBaseElementType(Field->getType())
13226 ->getAs<RecordType>()) {
13227 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
13228 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
13229 MarkFunctionReferenced(Field->getLocation(), Destructor);
13230 CheckDestructorAccess(Field->getLocation(), Destructor,
13231 PDiag(diag::err_access_dtor_ivar)
13232 << Context.getBaseElementType(Field->getType()));
13233 }
13234 }
13235 }
13236 ObjCImplementation->setIvarInitializers(Context,
13237 AllToInit.data(), AllToInit.size());
13238 }
13239 }
13240
13241 static
DelegatingCycleHelper(CXXConstructorDecl * Ctor,llvm::SmallSet<CXXConstructorDecl *,4> & Valid,llvm::SmallSet<CXXConstructorDecl *,4> & Invalid,llvm::SmallSet<CXXConstructorDecl *,4> & Current,Sema & S)13242 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13243 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13244 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13245 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13246 Sema &S) {
13247 if (Ctor->isInvalidDecl())
13248 return;
13249
13250 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13251
13252 // Target may not be determinable yet, for instance if this is a dependent
13253 // call in an uninstantiated template.
13254 if (Target) {
13255 const FunctionDecl *FNTarget = nullptr;
13256 (void)Target->hasBody(FNTarget);
13257 Target = const_cast<CXXConstructorDecl*>(
13258 cast_or_null<CXXConstructorDecl>(FNTarget));
13259 }
13260
13261 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13262 // Avoid dereferencing a null pointer here.
13263 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
13264
13265 if (!Current.insert(Canonical).second)
13266 return;
13267
13268 // We know that beyond here, we aren't chaining into a cycle.
13269 if (!Target || !Target->isDelegatingConstructor() ||
13270 Target->isInvalidDecl() || Valid.count(TCanonical)) {
13271 Valid.insert(Current.begin(), Current.end());
13272 Current.clear();
13273 // We've hit a cycle.
13274 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13275 Current.count(TCanonical)) {
13276 // If we haven't diagnosed this cycle yet, do so now.
13277 if (!Invalid.count(TCanonical)) {
13278 S.Diag((*Ctor->init_begin())->getSourceLocation(),
13279 diag::warn_delegating_ctor_cycle)
13280 << Ctor;
13281
13282 // Don't add a note for a function delegating directly to itself.
13283 if (TCanonical != Canonical)
13284 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13285
13286 CXXConstructorDecl *C = Target;
13287 while (C->getCanonicalDecl() != Canonical) {
13288 const FunctionDecl *FNTarget = nullptr;
13289 (void)C->getTargetConstructor()->hasBody(FNTarget);
13290 assert(FNTarget && "Ctor cycle through bodiless function");
13291
13292 C = const_cast<CXXConstructorDecl*>(
13293 cast<CXXConstructorDecl>(FNTarget));
13294 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13295 }
13296 }
13297
13298 Invalid.insert(Current.begin(), Current.end());
13299 Current.clear();
13300 } else {
13301 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13302 }
13303 }
13304
13305
CheckDelegatingCtorCycles()13306 void Sema::CheckDelegatingCtorCycles() {
13307 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13308
13309 for (DelegatingCtorDeclsType::iterator
13310 I = DelegatingCtorDecls.begin(ExternalSource),
13311 E = DelegatingCtorDecls.end();
13312 I != E; ++I)
13313 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
13314
13315 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13316 CE = Invalid.end();
13317 CI != CE; ++CI)
13318 (*CI)->setInvalidDecl();
13319 }
13320
13321 namespace {
13322 /// \brief AST visitor that finds references to the 'this' expression.
13323 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13324 Sema &S;
13325
13326 public:
FindCXXThisExpr(Sema & S)13327 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13328
VisitCXXThisExpr(CXXThisExpr * E)13329 bool VisitCXXThisExpr(CXXThisExpr *E) {
13330 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13331 << E->isImplicit();
13332 return false;
13333 }
13334 };
13335 }
13336
checkThisInStaticMemberFunctionType(CXXMethodDecl * Method)13337 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13338 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13339 if (!TSInfo)
13340 return false;
13341
13342 TypeLoc TL = TSInfo->getTypeLoc();
13343 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13344 if (!ProtoTL)
13345 return false;
13346
13347 // C++11 [expr.prim.general]p3:
13348 // [The expression this] shall not appear before the optional
13349 // cv-qualifier-seq and it shall not appear within the declaration of a
13350 // static member function (although its type and value category are defined
13351 // within a static member function as they are within a non-static member
13352 // function). [ Note: this is because declaration matching does not occur
13353 // until the complete declarator is known. - end note ]
13354 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13355 FindCXXThisExpr Finder(*this);
13356
13357 // If the return type came after the cv-qualifier-seq, check it now.
13358 if (Proto->hasTrailingReturn() &&
13359 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
13360 return true;
13361
13362 // Check the exception specification.
13363 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13364 return true;
13365
13366 return checkThisInStaticMemberFunctionAttributes(Method);
13367 }
13368
checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl * Method)13369 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13370 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13371 if (!TSInfo)
13372 return false;
13373
13374 TypeLoc TL = TSInfo->getTypeLoc();
13375 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13376 if (!ProtoTL)
13377 return false;
13378
13379 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13380 FindCXXThisExpr Finder(*this);
13381
13382 switch (Proto->getExceptionSpecType()) {
13383 case EST_Unparsed:
13384 case EST_Uninstantiated:
13385 case EST_Unevaluated:
13386 case EST_BasicNoexcept:
13387 case EST_DynamicNone:
13388 case EST_MSAny:
13389 case EST_None:
13390 break;
13391
13392 case EST_ComputedNoexcept:
13393 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13394 return true;
13395
13396 case EST_Dynamic:
13397 for (const auto &E : Proto->exceptions()) {
13398 if (!Finder.TraverseType(E))
13399 return true;
13400 }
13401 break;
13402 }
13403
13404 return false;
13405 }
13406
checkThisInStaticMemberFunctionAttributes(CXXMethodDecl * Method)13407 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13408 FindCXXThisExpr Finder(*this);
13409
13410 // Check attributes.
13411 for (const auto *A : Method->attrs()) {
13412 // FIXME: This should be emitted by tblgen.
13413 Expr *Arg = nullptr;
13414 ArrayRef<Expr *> Args;
13415 if (const auto *G = dyn_cast<GuardedByAttr>(A))
13416 Arg = G->getArg();
13417 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13418 Arg = G->getArg();
13419 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13420 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13421 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13422 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13423 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13424 Arg = ETLF->getSuccessValue();
13425 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13426 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13427 Arg = STLF->getSuccessValue();
13428 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13429 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13430 Arg = LR->getArg();
13431 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13432 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13433 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13434 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13435 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13436 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13437 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13438 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13439 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13440 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13441
13442 if (Arg && !Finder.TraverseStmt(Arg))
13443 return true;
13444
13445 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13446 if (!Finder.TraverseStmt(Args[I]))
13447 return true;
13448 }
13449 }
13450
13451 return false;
13452 }
13453
checkExceptionSpecification(bool IsTopLevel,ExceptionSpecificationType EST,ArrayRef<ParsedType> DynamicExceptions,ArrayRef<SourceRange> DynamicExceptionRanges,Expr * NoexceptExpr,SmallVectorImpl<QualType> & Exceptions,FunctionProtoType::ExceptionSpecInfo & ESI)13454 void Sema::checkExceptionSpecification(
13455 bool IsTopLevel, ExceptionSpecificationType EST,
13456 ArrayRef<ParsedType> DynamicExceptions,
13457 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13458 SmallVectorImpl<QualType> &Exceptions,
13459 FunctionProtoType::ExceptionSpecInfo &ESI) {
13460 Exceptions.clear();
13461 ESI.Type = EST;
13462 if (EST == EST_Dynamic) {
13463 Exceptions.reserve(DynamicExceptions.size());
13464 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13465 // FIXME: Preserve type source info.
13466 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13467
13468 if (IsTopLevel) {
13469 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13470 collectUnexpandedParameterPacks(ET, Unexpanded);
13471 if (!Unexpanded.empty()) {
13472 DiagnoseUnexpandedParameterPacks(
13473 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13474 Unexpanded);
13475 continue;
13476 }
13477 }
13478
13479 // Check that the type is valid for an exception spec, and
13480 // drop it if not.
13481 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13482 Exceptions.push_back(ET);
13483 }
13484 ESI.Exceptions = Exceptions;
13485 return;
13486 }
13487
13488 if (EST == EST_ComputedNoexcept) {
13489 // If an error occurred, there's no expression here.
13490 if (NoexceptExpr) {
13491 assert((NoexceptExpr->isTypeDependent() ||
13492 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13493 Context.BoolTy) &&
13494 "Parser should have made sure that the expression is boolean");
13495 if (IsTopLevel && NoexceptExpr &&
13496 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13497 ESI.Type = EST_BasicNoexcept;
13498 return;
13499 }
13500
13501 if (!NoexceptExpr->isValueDependent())
13502 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13503 diag::err_noexcept_needs_constant_expression,
13504 /*AllowFold*/ false).get();
13505 ESI.NoexceptExpr = NoexceptExpr;
13506 }
13507 return;
13508 }
13509 }
13510
actOnDelayedExceptionSpecification(Decl * MethodD,ExceptionSpecificationType EST,SourceRange SpecificationRange,ArrayRef<ParsedType> DynamicExceptions,ArrayRef<SourceRange> DynamicExceptionRanges,Expr * NoexceptExpr)13511 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13512 ExceptionSpecificationType EST,
13513 SourceRange SpecificationRange,
13514 ArrayRef<ParsedType> DynamicExceptions,
13515 ArrayRef<SourceRange> DynamicExceptionRanges,
13516 Expr *NoexceptExpr) {
13517 if (!MethodD)
13518 return;
13519
13520 // Dig out the method we're referring to.
13521 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13522 MethodD = FunTmpl->getTemplatedDecl();
13523
13524 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13525 if (!Method)
13526 return;
13527
13528 // Check the exception specification.
13529 llvm::SmallVector<QualType, 4> Exceptions;
13530 FunctionProtoType::ExceptionSpecInfo ESI;
13531 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13532 DynamicExceptionRanges, NoexceptExpr, Exceptions,
13533 ESI);
13534
13535 // Update the exception specification on the function type.
13536 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13537
13538 if (Method->isStatic())
13539 checkThisInStaticMemberFunctionExceptionSpec(Method);
13540
13541 if (Method->isVirtual()) {
13542 // Check overrides, which we previously had to delay.
13543 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13544 OEnd = Method->end_overridden_methods();
13545 O != OEnd; ++O)
13546 CheckOverridingFunctionExceptionSpec(Method, *O);
13547 }
13548 }
13549
13550 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13551 ///
HandleMSProperty(Scope * S,RecordDecl * Record,SourceLocation DeclStart,Declarator & D,Expr * BitWidth,InClassInitStyle InitStyle,AccessSpecifier AS,AttributeList * MSPropertyAttr)13552 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13553 SourceLocation DeclStart,
13554 Declarator &D, Expr *BitWidth,
13555 InClassInitStyle InitStyle,
13556 AccessSpecifier AS,
13557 AttributeList *MSPropertyAttr) {
13558 IdentifierInfo *II = D.getIdentifier();
13559 if (!II) {
13560 Diag(DeclStart, diag::err_anonymous_property);
13561 return nullptr;
13562 }
13563 SourceLocation Loc = D.getIdentifierLoc();
13564
13565 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13566 QualType T = TInfo->getType();
13567 if (getLangOpts().CPlusPlus) {
13568 CheckExtraCXXDefaultArguments(D);
13569
13570 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13571 UPPC_DataMemberType)) {
13572 D.setInvalidType();
13573 T = Context.IntTy;
13574 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13575 }
13576 }
13577
13578 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13579
13580 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13581 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13582 diag::err_invalid_thread)
13583 << DeclSpec::getSpecifierName(TSCS);
13584
13585 // Check to see if this name was declared as a member previously
13586 NamedDecl *PrevDecl = nullptr;
13587 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13588 LookupName(Previous, S);
13589 switch (Previous.getResultKind()) {
13590 case LookupResult::Found:
13591 case LookupResult::FoundUnresolvedValue:
13592 PrevDecl = Previous.getAsSingle<NamedDecl>();
13593 break;
13594
13595 case LookupResult::FoundOverloaded:
13596 PrevDecl = Previous.getRepresentativeDecl();
13597 break;
13598
13599 case LookupResult::NotFound:
13600 case LookupResult::NotFoundInCurrentInstantiation:
13601 case LookupResult::Ambiguous:
13602 break;
13603 }
13604
13605 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13606 // Maybe we will complain about the shadowed template parameter.
13607 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13608 // Just pretend that we didn't see the previous declaration.
13609 PrevDecl = nullptr;
13610 }
13611
13612 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13613 PrevDecl = nullptr;
13614
13615 SourceLocation TSSL = D.getLocStart();
13616 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13617 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13618 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13619 ProcessDeclAttributes(TUScope, NewPD, D);
13620 NewPD->setAccess(AS);
13621
13622 if (NewPD->isInvalidDecl())
13623 Record->setInvalidDecl();
13624
13625 if (D.getDeclSpec().isModulePrivateSpecified())
13626 NewPD->setModulePrivate();
13627
13628 if (NewPD->isInvalidDecl() && PrevDecl) {
13629 // Don't introduce NewFD into scope; there's already something
13630 // with the same name in the same scope.
13631 } else if (II) {
13632 PushOnScopeChains(NewPD, S);
13633 } else
13634 Record->addDecl(NewPD);
13635
13636 return NewPD;
13637 }
13638