Bug Summary

File:tools/clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 14315, column 7
Value stored to 'IsMemberSpecialization' is never read

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