Bug Summary

File:tools/clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 640, column 29
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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