Bug Summary

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