Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDeclCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-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~svn338205/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn338205/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/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/8/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-class-memaccess -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn338205/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-29-043837-17923-1 -x c++ /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp -faddrsig
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~svn338205/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~svn338205/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~svn338205/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~svn338205/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~svn338205/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~svn338205/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~svn338205/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()
1
Assuming the condition is false
2
'?' condition is false
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;
3
Assuming pointer value is null
4
Loop condition is false. Execution continues on line 497
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
5
'?' condition is false
6
Loop condition is false. Execution continues on line 625
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~svn338205/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()) {
7
Called C++ object pointer is null
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~svn338205/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~svn338205/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~svn338205/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~svn338205/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~svn338205/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~svn338205/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~svn338205/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~svn338205/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~svn338205/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~svn338205/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~svn338205/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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2244, __extension__ __PRETTY_FUNCTION__))
;
2245
2246 // Microsoft docs say:
2247 // "If a base-class has a code_seg attribute, derived classes must have the
2248 // same attribute."
2249 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2250 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2251 if ((DerivedCSA || BaseCSA) &&
2252 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2253 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2254 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2255 << CXXBaseDecl;
2256 return nullptr;
2257 }
2258
2259 // A class which contains a flexible array member is not suitable for use as a
2260 // base class:
2261 // - If the layout determines that a base comes before another base,
2262 // the flexible array member would index into the subsequent base.
2263 // - If the layout determines that base comes before the derived class,
2264 // the flexible array member would index into the derived class.
2265 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2266 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2267 << CXXBaseDecl->getDeclName();
2268 return nullptr;
2269 }
2270
2271 // C++ [class]p3:
2272 // If a class is marked final and it appears as a base-type-specifier in
2273 // base-clause, the program is ill-formed.
2274 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2275 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2276 << CXXBaseDecl->getDeclName()
2277 << FA->isSpelledAsSealed();
2278 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2279 << CXXBaseDecl->getDeclName() << FA->getRange();
2280 return nullptr;
2281 }
2282
2283 if (BaseDecl->isInvalidDecl())
2284 Class->setInvalidDecl();
2285
2286 // Create the base specifier.
2287 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2288 Class->getTagKind() == TTK_Class,
2289 Access, TInfo, EllipsisLoc);
2290}
2291
2292/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2293/// one entry in the base class list of a class specifier, for
2294/// example:
2295/// class foo : public bar, virtual private baz {
2296/// 'public bar' and 'virtual private baz' are each base-specifiers.
2297BaseResult
2298Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2299 ParsedAttributes &Attributes,
2300 bool Virtual, AccessSpecifier Access,
2301 ParsedType basetype, SourceLocation BaseLoc,
2302 SourceLocation EllipsisLoc) {
2303 if (!classdecl)
2304 return true;
2305
2306 AdjustDeclIfTemplate(classdecl);
2307 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2308 if (!Class)
2309 return true;
2310
2311 // We haven't yet attached the base specifiers.
2312 Class->setIsParsingBaseSpecifiers();
2313
2314 // We do not support any C++11 attributes on base-specifiers yet.
2315 // Diagnose any attributes we see.
2316 for (const ParsedAttr &AL : Attributes) {
2317 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2318 continue;
2319 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2320 ? diag::warn_unknown_attribute_ignored
2321 : diag::err_base_specifier_attribute)
2322 << AL.getName();
2323 }
2324
2325 TypeSourceInfo *TInfo = nullptr;
2326 GetTypeFromParser(basetype, &TInfo);
2327
2328 if (EllipsisLoc.isInvalid() &&
2329 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2330 UPPC_BaseType))
2331 return true;
2332
2333 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2334 Virtual, Access, TInfo,
2335 EllipsisLoc))
2336 return BaseSpec;
2337 else
2338 Class->setInvalidDecl();
2339
2340 return true;
2341}
2342
2343/// Use small set to collect indirect bases. As this is only used
2344/// locally, there's no need to abstract the small size parameter.
2345typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2346
2347/// Recursively add the bases of Type. Don't add Type itself.
2348static void
2349NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2350 const QualType &Type)
2351{
2352 // Even though the incoming type is a base, it might not be
2353 // a class -- it could be a template parm, for instance.
2354 if (auto Rec = Type->getAs<RecordType>()) {
2355 auto Decl = Rec->getAsCXXRecordDecl();
2356
2357 // Iterate over its bases.
2358 for (const auto &BaseSpec : Decl->bases()) {
2359 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2360 .getUnqualifiedType();
2361 if (Set.insert(Base).second)
2362 // If we've not already seen it, recurse.
2363 NoteIndirectBases(Context, Set, Base);
2364 }
2365 }
2366}
2367
2368/// Performs the actual work of attaching the given base class
2369/// specifiers to a C++ class.
2370bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2371 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2372 if (Bases.empty())
2373 return false;
2374
2375 // Used to keep track of which base types we have already seen, so
2376 // that we can properly diagnose redundant direct base types. Note
2377 // that the key is always the unqualified canonical type of the base
2378 // class.
2379 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2380
2381 // Used to track indirect bases so we can see if a direct base is
2382 // ambiguous.
2383 IndirectBaseSet IndirectBaseTypes;
2384
2385 // Copy non-redundant base specifiers into permanent storage.
2386 unsigned NumGoodBases = 0;
2387 bool Invalid = false;
2388 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2389 QualType NewBaseType
2390 = Context.getCanonicalType(Bases[idx]->getType());
2391 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2392
2393 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2394 if (KnownBase) {
2395 // C++ [class.mi]p3:
2396 // A class shall not be specified as a direct base class of a
2397 // derived class more than once.
2398 Diag(Bases[idx]->getLocStart(),
2399 diag::err_duplicate_base_class)
2400 << KnownBase->getType()
2401 << Bases[idx]->getSourceRange();
2402
2403 // Delete the duplicate base class specifier; we're going to
2404 // overwrite its pointer later.
2405 Context.Deallocate(Bases[idx]);
2406
2407 Invalid = true;
2408 } else {
2409 // Okay, add this new base class.
2410 KnownBase = Bases[idx];
2411 Bases[NumGoodBases++] = Bases[idx];
2412
2413 // Note this base's direct & indirect bases, if there could be ambiguity.
2414 if (Bases.size() > 1)
2415 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2416
2417 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2418 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2419 if (Class->isInterface() &&
2420 (!RD->isInterfaceLike() ||
2421 KnownBase->getAccessSpecifier() != AS_public)) {
2422 // The Microsoft extension __interface does not permit bases that
2423 // are not themselves public interfaces.
2424 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2425 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2426 << RD->getSourceRange();
2427 Invalid = true;
2428 }
2429 if (RD->hasAttr<WeakAttr>())
2430 Class->addAttr(WeakAttr::CreateImplicit(Context));
2431 }
2432 }
2433 }
2434
2435 // Attach the remaining base class specifiers to the derived class.
2436 Class->setBases(Bases.data(), NumGoodBases);
2437
2438 // Check that the only base classes that are duplicate are virtual.
2439 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2440 // Check whether this direct base is inaccessible due to ambiguity.
2441 QualType BaseType = Bases[idx]->getType();
2442
2443 // Skip all dependent types in templates being used as base specifiers.
2444 // Checks below assume that the base specifier is a CXXRecord.
2445 if (BaseType->isDependentType())
2446 continue;
2447
2448 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2449 .getUnqualifiedType();
2450
2451 if (IndirectBaseTypes.count(CanonicalBase)) {
2452 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2453 /*DetectVirtual=*/true);
2454 bool found
2455 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2456 assert(found)(static_cast <bool> (found) ? void (0) : __assert_fail (
"found", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2456, __extension__ __PRETTY_FUNCTION__))
;
2457 (void)found;
2458
2459 if (Paths.isAmbiguous(CanonicalBase))
2460 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2461 << BaseType << getAmbiguousPathsDisplayString(Paths)
2462 << Bases[idx]->getSourceRange();
2463 else
2464 assert(Bases[idx]->isVirtual())(static_cast <bool> (Bases[idx]->isVirtual()) ? void
(0) : __assert_fail ("Bases[idx]->isVirtual()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2464, __extension__ __PRETTY_FUNCTION__))
;
2465 }
2466
2467 // Delete the base class specifier, since its data has been copied
2468 // into the CXXRecordDecl.
2469 Context.Deallocate(Bases[idx]);
2470 }
2471
2472 return Invalid;
2473}
2474
2475/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2476/// class, after checking whether there are any duplicate base
2477/// classes.
2478void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2479 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2480 if (!ClassDecl || Bases.empty())
2481 return;
2482
2483 AdjustDeclIfTemplate(ClassDecl);
2484 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2485}
2486
2487/// Determine whether the type \p Derived is a C++ class that is
2488/// derived from the type \p Base.
2489bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2490 if (!getLangOpts().CPlusPlus)
2491 return false;
2492
2493 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2494 if (!DerivedRD)
2495 return false;
2496
2497 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2498 if (!BaseRD)
2499 return false;
2500
2501 // If either the base or the derived type is invalid, don't try to
2502 // check whether one is derived from the other.
2503 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2504 return false;
2505
2506 // FIXME: In a modules build, do we need the entire path to be visible for us
2507 // to be able to use the inheritance relationship?
2508 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2509 return false;
2510
2511 return DerivedRD->isDerivedFrom(BaseRD);
2512}
2513
2514/// Determine whether the type \p Derived is a C++ class that is
2515/// derived from the type \p Base.
2516bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2517 CXXBasePaths &Paths) {
2518 if (!getLangOpts().CPlusPlus)
2519 return false;
2520
2521 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2522 if (!DerivedRD)
2523 return false;
2524
2525 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2526 if (!BaseRD)
2527 return false;
2528
2529 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2530 return false;
2531
2532 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2533}
2534
2535static void BuildBasePathArray(const CXXBasePath &Path,
2536 CXXCastPath &BasePathArray) {
2537 // We first go backward and check if we have a virtual base.
2538 // FIXME: It would be better if CXXBasePath had the base specifier for
2539 // the nearest virtual base.
2540 unsigned Start = 0;
2541 for (unsigned I = Path.size(); I != 0; --I) {
2542 if (Path[I - 1].Base->isVirtual()) {
2543 Start = I - 1;
2544 break;
2545 }
2546 }
2547
2548 // Now add all bases.
2549 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2550 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2551}
2552
2553
2554void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2555 CXXCastPath &BasePathArray) {
2556 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2556, __extension__ __PRETTY_FUNCTION__))
;
2557 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2557, __extension__ __PRETTY_FUNCTION__))
;
2558 return ::BuildBasePathArray(Paths.front(), BasePathArray);
2559}
2560/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2561/// conversion (where Derived and Base are class types) is
2562/// well-formed, meaning that the conversion is unambiguous (and
2563/// that all of the base classes are accessible). Returns true
2564/// and emits a diagnostic if the code is ill-formed, returns false
2565/// otherwise. Loc is the location where this routine should point to
2566/// if there is an error, and Range is the source range to highlight
2567/// if there is an error.
2568///
2569/// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2570/// diagnostic for the respective type of error will be suppressed, but the
2571/// check for ill-formed code will still be performed.
2572bool
2573Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2574 unsigned InaccessibleBaseID,
2575 unsigned AmbigiousBaseConvID,
2576 SourceLocation Loc, SourceRange Range,
2577 DeclarationName Name,
2578 CXXCastPath *BasePath,
2579 bool IgnoreAccess) {
2580 // First, determine whether the path from Derived to Base is
2581 // ambiguous. This is slightly more expensive than checking whether
2582 // the Derived to Base conversion exists, because here we need to
2583 // explore multiple paths to determine if there is an ambiguity.
2584 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2585 /*DetectVirtual=*/false);
2586 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2587 if (!DerivationOkay)
2588 return true;
2589
2590 const CXXBasePath *Path = nullptr;
2591 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2592 Path = &Paths.front();
2593
2594 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2595 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2596 // user to access such bases.
2597 if (!Path && getLangOpts().MSVCCompat) {
2598 for (const CXXBasePath &PossiblePath : Paths) {
2599 if (PossiblePath.size() == 1) {
2600 Path = &PossiblePath;
2601 if (AmbigiousBaseConvID)
2602 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2603 << Base << Derived << Range;
2604 break;
2605 }
2606 }
2607 }
2608
2609 if (Path) {
2610 if (!IgnoreAccess) {
2611 // Check that the base class can be accessed.
2612 switch (
2613 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2614 case AR_inaccessible:
2615 return true;
2616 case AR_accessible:
2617 case AR_dependent:
2618 case AR_delayed:
2619 break;
2620 }
2621 }
2622
2623 // Build a base path if necessary.
2624 if (BasePath)
2625 ::BuildBasePathArray(*Path, *BasePath);
2626 return false;
2627 }
2628
2629 if (AmbigiousBaseConvID) {
2630 // We know that the derived-to-base conversion is ambiguous, and
2631 // we're going to produce a diagnostic. Perform the derived-to-base
2632 // search just one more time to compute all of the possible paths so
2633 // that we can print them out. This is more expensive than any of
2634 // the previous derived-to-base checks we've done, but at this point
2635 // performance isn't as much of an issue.
2636 Paths.clear();
2637 Paths.setRecordingPaths(true);
2638 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2639 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2639, __extension__ __PRETTY_FUNCTION__))
;
2640 (void)StillOkay;
2641
2642 // Build up a textual representation of the ambiguous paths, e.g.,
2643 // D -> B -> A, that will be used to illustrate the ambiguous
2644 // conversions in the diagnostic. We only print one of the paths
2645 // to each base class subobject.
2646 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2647
2648 Diag(Loc, AmbigiousBaseConvID)
2649 << Derived << Base << PathDisplayStr << Range << Name;
2650 }
2651 return true;
2652}
2653
2654bool
2655Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2656 SourceLocation Loc, SourceRange Range,
2657 CXXCastPath *BasePath,
2658 bool IgnoreAccess) {
2659 return CheckDerivedToBaseConversion(
2660 Derived, Base, diag::err_upcast_to_inaccessible_base,
2661 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2662 BasePath, IgnoreAccess);
2663}
2664
2665
2666/// Builds a string representing ambiguous paths from a
2667/// specific derived class to different subobjects of the same base
2668/// class.
2669///
2670/// This function builds a string that can be used in error messages
2671/// to show the different paths that one can take through the
2672/// inheritance hierarchy to go from the derived class to different
2673/// subobjects of a base class. The result looks something like this:
2674/// @code
2675/// struct D -> struct B -> struct A
2676/// struct D -> struct C -> struct A
2677/// @endcode
2678std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2679 std::string PathDisplayStr;
2680 std::set<unsigned> DisplayedPaths;
2681 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2682 Path != Paths.end(); ++Path) {
2683 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2684 // We haven't displayed a path to this particular base
2685 // class subobject yet.
2686 PathDisplayStr += "\n ";
2687 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2688 for (CXXBasePath::const_iterator Element = Path->begin();
2689 Element != Path->end(); ++Element)
2690 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2691 }
2692 }
2693
2694 return PathDisplayStr;
2695}
2696
2697//===----------------------------------------------------------------------===//
2698// C++ class member Handling
2699//===----------------------------------------------------------------------===//
2700
2701/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2702bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2703 SourceLocation ColonLoc,
2704 const ParsedAttributesView &Attrs) {
2705 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2705, __extension__ __PRETTY_FUNCTION__))
;
2706 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2707 ASLoc, ColonLoc);
2708 CurContext->addHiddenDecl(ASDecl);
2709 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2710}
2711
2712/// CheckOverrideControl - Check C++11 override control semantics.
2713void Sema::CheckOverrideControl(NamedDecl *D) {
2714 if (D->isInvalidDecl())
2715 return;
2716
2717 // We only care about "override" and "final" declarations.
2718 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2719 return;
2720
2721 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2722
2723 // We can't check dependent instance methods.
2724 if (MD && MD->isInstance() &&
2725 (MD->getParent()->hasAnyDependentBases() ||
2726 MD->getType()->isDependentType()))
2727 return;
2728
2729 if (MD && !MD->isVirtual()) {
2730 // If we have a non-virtual method, check if if hides a virtual method.
2731 // (In that case, it's most likely the method has the wrong type.)
2732 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2733 FindHiddenVirtualMethods(MD, OverloadedMethods);
2734
2735 if (!OverloadedMethods.empty()) {
2736 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2737 Diag(OA->getLocation(),
2738 diag::override_keyword_hides_virtual_member_function)
2739 << "override" << (OverloadedMethods.size() > 1);
2740 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2741 Diag(FA->getLocation(),
2742 diag::override_keyword_hides_virtual_member_function)
2743 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2744 << (OverloadedMethods.size() > 1);
2745 }
2746 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2747 MD->setInvalidDecl();
2748 return;
2749 }
2750 // Fall through into the general case diagnostic.
2751 // FIXME: We might want to attempt typo correction here.
2752 }
2753
2754 if (!MD || !MD->isVirtual()) {
2755 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2756 Diag(OA->getLocation(),
2757 diag::override_keyword_only_allowed_on_virtual_member_functions)
2758 << "override" << FixItHint::CreateRemoval(OA->getLocation());
2759 D->dropAttr<OverrideAttr>();
2760 }
2761 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2762 Diag(FA->getLocation(),
2763 diag::override_keyword_only_allowed_on_virtual_member_functions)
2764 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2765 << FixItHint::CreateRemoval(FA->getLocation());
2766 D->dropAttr<FinalAttr>();
2767 }
2768 return;
2769 }
2770
2771 // C++11 [class.virtual]p5:
2772 // If a function is marked with the virt-specifier override and
2773 // does not override a member function of a base class, the program is
2774 // ill-formed.
2775 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2776 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2777 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2778 << MD->getDeclName();
2779}
2780
2781void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2782 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2783 return;
2784 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2785 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2786 return;
2787
2788 SourceLocation Loc = MD->getLocation();
2789 SourceLocation SpellingLoc = Loc;
2790 if (getSourceManager().isMacroArgExpansion(Loc))
2791 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2792 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2793 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2794 return;
2795
2796 if (MD->size_overridden_methods() > 0) {
2797 unsigned DiagID = isa<CXXDestructorDecl>(MD)
2798 ? diag::warn_destructor_marked_not_override_overriding
2799 : diag::warn_function_marked_not_override_overriding;
2800 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2801 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2802 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2803 }
2804}
2805
2806/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2807/// function overrides a virtual member function marked 'final', according to
2808/// C++11 [class.virtual]p4.
2809bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2810 const CXXMethodDecl *Old) {
2811 FinalAttr *FA = Old->getAttr<FinalAttr>();
2812 if (!FA)
2813 return false;
2814
2815 Diag(New->getLocation(), diag::err_final_function_overridden)
2816 << New->getDeclName()
2817 << FA->isSpelledAsSealed();
2818 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2819 return true;
2820}
2821
2822static bool InitializationHasSideEffects(const FieldDecl &FD) {
2823 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2824 // FIXME: Destruction of ObjC lifetime types has side-effects.
2825 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2826 return !RD->isCompleteDefinition() ||
2827 !RD->hasTrivialDefaultConstructor() ||
2828 !RD->hasTrivialDestructor();
2829 return false;
2830}
2831
2832static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
2833 ParsedAttributesView::const_iterator Itr =
2834 llvm::find_if(list, [](const ParsedAttr &AL) {
2835 return AL.isDeclspecPropertyAttribute();
2836 });
2837 if (Itr != list.end())
2838 return &*Itr;
2839 return nullptr;
2840}
2841
2842// Check if there is a field shadowing.
2843void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2844 DeclarationName FieldName,
2845 const CXXRecordDecl *RD) {
2846 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2847 return;
2848
2849 // To record a shadowed field in a base
2850 std::map<CXXRecordDecl*, NamedDecl*> Bases;
2851 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2852 CXXBasePath &Path) {
2853 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2854 // Record an ambiguous path directly
2855 if (Bases.find(Base) != Bases.end())
2856 return true;
2857 for (const auto Field : Base->lookup(FieldName)) {
2858 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2859 Field->getAccess() != AS_private) {
2860 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2860, __extension__ __PRETTY_FUNCTION__))
;
2861 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2861, __extension__ __PRETTY_FUNCTION__))
;
2862 Bases[Base] = Field;
2863 return true;
2864 }
2865 }
2866 return false;
2867 };
2868
2869 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2870 /*DetectVirtual=*/true);
2871 if (!RD->lookupInBases(FieldShadowed, Paths))
2872 return;
2873
2874 for (const auto &P : Paths) {
2875 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2876 auto It = Bases.find(Base);
2877 // Skip duplicated bases
2878 if (It == Bases.end())
2879 continue;
2880 auto BaseField = It->second;
2881 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2881, __extension__ __PRETTY_FUNCTION__))
;
2882 if (AS_none !=
2883 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2884 Diag(Loc, diag::warn_shadow_field)
2885 << FieldName << RD << Base;
2886 Diag(BaseField->getLocation(), diag::note_shadow_field);
2887 Bases.erase(It);
2888 }
2889 }
2890}
2891
2892/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2893/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2894/// bitfield width if there is one, 'InitExpr' specifies the initializer if
2895/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2896/// present (but parsing it has been deferred).
2897NamedDecl *
2898Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2899 MultiTemplateParamsArg TemplateParameterLists,
2900 Expr *BW, const VirtSpecifiers &VS,
2901 InClassInitStyle InitStyle) {
2902 const DeclSpec &DS = D.getDeclSpec();
2903 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2904 DeclarationName Name = NameInfo.getName();
2905 SourceLocation Loc = NameInfo.getLoc();
2906
2907 // For anonymous bitfields, the location should point to the type.
2908 if (Loc.isInvalid())
2909 Loc = D.getLocStart();
2910
2911 Expr *BitWidth = static_cast<Expr*>(BW);
2912
2913 assert(isa<CXXRecordDecl>(CurContext))(static_cast <bool> (isa<CXXRecordDecl>(CurContext
)) ? void (0) : __assert_fail ("isa<CXXRecordDecl>(CurContext)"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2913, __extension__ __PRETTY_FUNCTION__))
;
2914 assert(!DS.isFriendSpecified())(static_cast <bool> (!DS.isFriendSpecified()) ? void (0
) : __assert_fail ("!DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2914, __extension__ __PRETTY_FUNCTION__))
;
2915
2916 bool isFunc = D.isDeclarationOfFunction();
2917 const ParsedAttr *MSPropertyAttr =
2918 getMSPropertyAttr(D.getDeclSpec().getAttributes());
2919
2920 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2921 // The Microsoft extension __interface only permits public member functions
2922 // and prohibits constructors, destructors, operators, non-public member
2923 // functions, static methods and data members.
2924 unsigned InvalidDecl;
2925 bool ShowDeclName = true;
2926 if (!isFunc &&
2927 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2928 InvalidDecl = 0;
2929 else if (!isFunc)
2930 InvalidDecl = 1;
2931 else if (AS != AS_public)
2932 InvalidDecl = 2;
2933 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2934 InvalidDecl = 3;
2935 else switch (Name.getNameKind()) {
2936 case DeclarationName::CXXConstructorName:
2937 InvalidDecl = 4;
2938 ShowDeclName = false;
2939 break;
2940
2941 case DeclarationName::CXXDestructorName:
2942 InvalidDecl = 5;
2943 ShowDeclName = false;
2944 break;
2945
2946 case DeclarationName::CXXOperatorName:
2947 case DeclarationName::CXXConversionFunctionName:
2948 InvalidDecl = 6;
2949 break;
2950
2951 default:
2952 InvalidDecl = 0;
2953 break;
2954 }
2955
2956 if (InvalidDecl) {
2957 if (ShowDeclName)
2958 Diag(Loc, diag::err_invalid_member_in_interface)
2959 << (InvalidDecl-1) << Name;
2960 else
2961 Diag(Loc, diag::err_invalid_member_in_interface)
2962 << (InvalidDecl-1) << "";
2963 return nullptr;
2964 }
2965 }
2966
2967 // C++ 9.2p6: A member shall not be declared to have automatic storage
2968 // duration (auto, register) or with the extern storage-class-specifier.
2969 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2970 // data members and cannot be applied to names declared const or static,
2971 // and cannot be applied to reference members.
2972 switch (DS.getStorageClassSpec()) {
2973 case DeclSpec::SCS_unspecified:
2974 case DeclSpec::SCS_typedef:
2975 case DeclSpec::SCS_static:
2976 break;
2977 case DeclSpec::SCS_mutable:
2978 if (isFunc) {
2979 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2980
2981 // FIXME: It would be nicer if the keyword was ignored only for this
2982 // declarator. Otherwise we could get follow-up errors.
2983 D.getMutableDeclSpec().ClearStorageClassSpecs();
2984 }
2985 break;
2986 default:
2987 Diag(DS.getStorageClassSpecLoc(),
2988 diag::err_storageclass_invalid_for_member);
2989 D.getMutableDeclSpec().ClearStorageClassSpecs();
2990 break;
2991 }
2992
2993 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2994 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2995 !isFunc);
2996
2997 if (DS.isConstexprSpecified() && isInstField) {
2998 SemaDiagnosticBuilder B =
2999 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3000 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3001 if (InitStyle == ICIS_NoInit) {
3002 B << 0 << 0;
3003 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3004 B << FixItHint::CreateRemoval(ConstexprLoc);
3005 else {
3006 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3007 D.getMutableDeclSpec().ClearConstexprSpec();
3008 const char *PrevSpec;
3009 unsigned DiagID;
3010 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3011 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3012 (void)Failed;
3013 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3013, __extension__ __PRETTY_FUNCTION__))
;
3014 }
3015 } else {
3016 B << 1;
3017 const char *PrevSpec;
3018 unsigned DiagID;
3019 if (D.getMutableDeclSpec().SetStorageClassSpec(
3020 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3021 Context.getPrintingPolicy())) {
3022 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3023, __extension__ __PRETTY_FUNCTION__))
3023 "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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3023, __extension__ __PRETTY_FUNCTION__))
;
3024 B << 1;
3025 } else {
3026 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3027 isInstField = false;
3028 }
3029 }
3030 }
3031
3032 NamedDecl *Member;
3033 if (isInstField) {
3034 CXXScopeSpec &SS = D.getCXXScopeSpec();
3035
3036 // Data members must have identifiers for names.
3037 if (!Name.isIdentifier()) {
3038 Diag(Loc, diag::err_bad_variable_name)
3039 << Name;
3040 return nullptr;
3041 }
3042
3043 IdentifierInfo *II = Name.getAsIdentifierInfo();
3044
3045 // Member field could not be with "template" keyword.
3046 // So TemplateParameterLists should be empty in this case.
3047 if (TemplateParameterLists.size()) {
3048 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3049 if (TemplateParams->size()) {
3050 // There is no such thing as a member field template.
3051 Diag(D.getIdentifierLoc(), diag::err_template_member)
3052 << II
3053 << SourceRange(TemplateParams->getTemplateLoc(),
3054 TemplateParams->getRAngleLoc());
3055 } else {
3056 // There is an extraneous 'template<>' for this member.
3057 Diag(TemplateParams->getTemplateLoc(),
3058 diag::err_template_member_noparams)
3059 << II
3060 << SourceRange(TemplateParams->getTemplateLoc(),
3061 TemplateParams->getRAngleLoc());
3062 }
3063 return nullptr;
3064 }
3065
3066 if (SS.isSet() && !SS.isInvalid()) {
3067 // The user provided a superfluous scope specifier inside a class
3068 // definition:
3069 //
3070 // class X {
3071 // int X::member;
3072 // };
3073 if (DeclContext *DC = computeDeclContext(SS, false))
3074 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3075 D.getName().getKind() ==
3076 UnqualifiedIdKind::IK_TemplateId);
3077 else
3078 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3079 << Name << SS.getRange();
3080
3081 SS.clear();
3082 }
3083
3084 if (MSPropertyAttr) {
3085 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3086 BitWidth, InitStyle, AS, *MSPropertyAttr);
3087 if (!Member)
3088 return nullptr;
3089 isInstField = false;
3090 } else {
3091 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3092 BitWidth, InitStyle, AS);
3093 if (!Member)
3094 return nullptr;
3095 }
3096
3097 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3098 } else {
3099 Member = HandleDeclarator(S, D, TemplateParameterLists);
3100 if (!Member)
3101 return nullptr;
3102
3103 // Non-instance-fields can't have a bitfield.
3104 if (BitWidth) {
3105 if (Member->isInvalidDecl()) {
3106 // don't emit another diagnostic.
3107 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3108 // C++ 9.6p3: A bit-field shall not be a static member.
3109 // "static member 'A' cannot be a bit-field"
3110 Diag(Loc, diag::err_static_not_bitfield)
3111 << Name << BitWidth->getSourceRange();
3112 } else if (isa<TypedefDecl>(Member)) {
3113 // "typedef member 'x' cannot be a bit-field"
3114 Diag(Loc, diag::err_typedef_not_bitfield)
3115 << Name << BitWidth->getSourceRange();
3116 } else {
3117 // A function typedef ("typedef int f(); f a;").
3118 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3119 Diag(Loc, diag::err_not_integral_type_bitfield)
3120 << Name << cast<ValueDecl>(Member)->getType()
3121 << BitWidth->getSourceRange();
3122 }
3123
3124 BitWidth = nullptr;
3125 Member->setInvalidDecl();
3126 }
3127
3128 NamedDecl *NonTemplateMember = Member;
3129 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3130 NonTemplateMember = FunTmpl->getTemplatedDecl();
3131 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3132 NonTemplateMember = VarTmpl->getTemplatedDecl();
3133
3134 Member->setAccess(AS);
3135
3136 // If we have declared a member function template or static data member
3137 // template, set the access of the templated declaration as well.
3138 if (NonTemplateMember != Member)
3139 NonTemplateMember->setAccess(AS);
3140
3141 // C++ [temp.deduct.guide]p3:
3142 // A deduction guide [...] for a member class template [shall be
3143 // declared] with the same access [as the template].
3144 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3145 auto *TD = DG->getDeducedTemplate();
3146 if (AS != TD->getAccess()) {
3147 Diag(DG->getLocStart(), diag::err_deduction_guide_wrong_access);
3148 Diag(TD->getLocStart(), diag::note_deduction_guide_template_access)
3149 << TD->getAccess();
3150 const AccessSpecDecl *LastAccessSpec = nullptr;
3151 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3152 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3153 LastAccessSpec = AccessSpec;
3154 }
3155 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3155, __extension__ __PRETTY_FUNCTION__))
;
3156 Diag(LastAccessSpec->getLocStart(), diag::note_deduction_guide_access)
3157 << AS;
3158 }
3159 }
3160 }
3161
3162 if (VS.isOverrideSpecified())
3163 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3164 if (VS.isFinalSpecified())
3165 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3166 VS.isFinalSpelledSealed()));
3167
3168 if (VS.getLastLocation().isValid()) {
3169 // Update the end location of a method that has a virt-specifiers.
3170 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3171 MD->setRangeEnd(VS.getLastLocation());
3172 }
3173
3174 CheckOverrideControl(Member);
3175
3176 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3176, __extension__ __PRETTY_FUNCTION__))
;
3177
3178 if (isInstField) {
3179 FieldDecl *FD = cast<FieldDecl>(Member);
3180 FieldCollector->Add(FD);
3181
3182 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3183 // Remember all explicit private FieldDecls that have a name, no side
3184 // effects and are not part of a dependent type declaration.
3185 if (!FD->isImplicit() && FD->getDeclName() &&
3186 FD->getAccess() == AS_private &&
3187 !FD->hasAttr<UnusedAttr>() &&
3188 !FD->getParent()->isDependentContext() &&
3189 !InitializationHasSideEffects(*FD))
3190 UnusedPrivateFields.insert(FD);
3191 }
3192 }
3193
3194 return Member;
3195}
3196
3197namespace {
3198 class UninitializedFieldVisitor
3199 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3200 Sema &S;
3201 // List of Decls to generate a warning on. Also remove Decls that become
3202 // initialized.
3203 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3204 // List of base classes of the record. Classes are removed after their
3205 // initializers.
3206 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3207 // Vector of decls to be removed from the Decl set prior to visiting the
3208 // nodes. These Decls may have been initialized in the prior initializer.
3209 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3210 // If non-null, add a note to the warning pointing back to the constructor.
3211 const CXXConstructorDecl *Constructor;
3212 // Variables to hold state when processing an initializer list. When
3213 // InitList is true, special case initialization of FieldDecls matching
3214 // InitListFieldDecl.
3215 bool InitList;
3216 FieldDecl *InitListFieldDecl;
3217 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3218
3219 public:
3220 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3221 UninitializedFieldVisitor(Sema &S,
3222 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3223 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3224 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3225 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3226
3227 // Returns true if the use of ME is not an uninitialized use.
3228 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3229 bool CheckReferenceOnly) {
3230 llvm::SmallVector<FieldDecl*, 4> Fields;
3231 bool ReferenceField = false;
3232 while (ME) {
3233 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3234 if (!FD)
3235 return false;
3236 Fields.push_back(FD);
3237 if (FD->getType()->isReferenceType())
3238 ReferenceField = true;
3239 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3240 }
3241
3242 // Binding a reference to an unintialized field is not an
3243 // uninitialized use.
3244 if (CheckReferenceOnly && !ReferenceField)
3245 return true;
3246
3247 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3248 // Discard the first field since it is the field decl that is being
3249 // initialized.
3250 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3251 UsedFieldIndex.push_back((*I)->getFieldIndex());
3252 }
3253
3254 for (auto UsedIter = UsedFieldIndex.begin(),
3255 UsedEnd = UsedFieldIndex.end(),
3256 OrigIter = InitFieldIndex.begin(),
3257 OrigEnd = InitFieldIndex.end();
3258 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3259 if (*UsedIter < *OrigIter)
3260 return true;
3261 if (*UsedIter > *OrigIter)
3262 break;
3263 }
3264
3265 return false;
3266 }
3267
3268 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3269 bool AddressOf) {
3270 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3271 return;
3272
3273 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3274 // or union.
3275 MemberExpr *FieldME = ME;
3276
3277 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3278
3279 Expr *Base = ME;
3280 while (MemberExpr *SubME =
3281 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3282
3283 if (isa<VarDecl>(SubME->getMemberDecl()))
3284 return;
3285
3286 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3287 if (!FD->isAnonymousStructOrUnion())
3288 FieldME = SubME;
3289
3290 if (!FieldME->getType().isPODType(S.Context))
3291 AllPODFields = false;
3292
3293 Base = SubME->getBase();
3294 }
3295
3296 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3297 return;
3298
3299 if (AddressOf && AllPODFields)
3300 return;
3301
3302 ValueDecl* FoundVD = FieldME->getMemberDecl();
3303
3304 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3305 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3306 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3307 }
3308
3309 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3310 QualType T = BaseCast->getType();
3311 if (T->isPointerType() &&
3312 BaseClasses.count(T->getPointeeType())) {
3313 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3314 << T->getPointeeType() << FoundVD;
3315 }
3316 }
3317 }
3318
3319 if (!Decls.count(FoundVD))
3320 return;
3321
3322 const bool IsReference = FoundVD->getType()->isReferenceType();
3323
3324 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3325 // Special checking for initializer lists.
3326 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3327 return;
3328 }
3329 } else {
3330 // Prevent double warnings on use of unbounded references.
3331 if (CheckReferenceOnly && !IsReference)
3332 return;
3333 }
3334
3335 unsigned diag = IsReference
3336 ? diag::warn_reference_field_is_uninit
3337 : diag::warn_field_is_uninit;
3338 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3339 if (Constructor)
3340 S.Diag(Constructor->getLocation(),
3341 diag::note_uninit_in_this_constructor)
3342 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3343
3344 }
3345
3346 void HandleValue(Expr *E, bool AddressOf) {
3347 E = E->IgnoreParens();
3348
3349 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3350 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3351 AddressOf /*AddressOf*/);
3352 return;
3353 }
3354
3355 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3356 Visit(CO->getCond());
3357 HandleValue(CO->getTrueExpr(), AddressOf);
3358 HandleValue(CO->getFalseExpr(), AddressOf);
3359 return;
3360 }
3361
3362 if (BinaryConditionalOperator *BCO =
3363 dyn_cast<BinaryConditionalOperator>(E)) {
3364 Visit(BCO->getCond());
3365 HandleValue(BCO->getFalseExpr(), AddressOf);
3366 return;
3367 }
3368
3369 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3370 HandleValue(OVE->getSourceExpr(), AddressOf);
3371 return;
3372 }
3373
3374 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3375 switch (BO->getOpcode()) {
3376 default:
3377 break;
3378 case(BO_PtrMemD):
3379 case(BO_PtrMemI):
3380 HandleValue(BO->getLHS(), AddressOf);
3381 Visit(BO->getRHS());
3382 return;
3383 case(BO_Comma):
3384 Visit(BO->getLHS());
3385 HandleValue(BO->getRHS(), AddressOf);
3386 return;
3387 }
3388 }
3389
3390 Visit(E);
3391 }
3392
3393 void CheckInitListExpr(InitListExpr *ILE) {
3394 InitFieldIndex.push_back(0);
3395 for (auto Child : ILE->children()) {
3396 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3397 CheckInitListExpr(SubList);
3398 } else {
3399 Visit(Child);
3400 }
3401 ++InitFieldIndex.back();
3402 }
3403 InitFieldIndex.pop_back();
3404 }
3405
3406 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3407 FieldDecl *Field, const Type *BaseClass) {
3408 // Remove Decls that may have been initialized in the previous
3409 // initializer.
3410 for (ValueDecl* VD : DeclsToRemove)
3411 Decls.erase(VD);
3412 DeclsToRemove.clear();
3413
3414 Constructor = FieldConstructor;
3415 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3416
3417 if (ILE && Field) {
3418 InitList = true;
3419 InitListFieldDecl = Field;
3420 InitFieldIndex.clear();
3421 CheckInitListExpr(ILE);
3422 } else {
3423 InitList = false;
3424 Visit(E);
3425 }
3426
3427 if (Field)
3428 Decls.erase(Field);
3429 if (BaseClass)
3430 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3431 }
3432
3433 void VisitMemberExpr(MemberExpr *ME) {
3434 // All uses of unbounded reference fields will warn.
3435 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3436 }
3437
3438 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3439 if (E->getCastKind() == CK_LValueToRValue) {
3440 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3441 return;
3442 }
3443
3444 Inherited::VisitImplicitCastExpr(E);
3445 }
3446
3447 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3448 if (E->getConstructor()->isCopyConstructor()) {
3449 Expr *ArgExpr = E->getArg(0);
3450 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3451 if (ILE->getNumInits() == 1)
3452 ArgExpr = ILE->getInit(0);
3453 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3454 if (ICE->getCastKind() == CK_NoOp)
3455 ArgExpr = ICE->getSubExpr();
3456 HandleValue(ArgExpr, false /*AddressOf*/);
3457 return;
3458 }
3459 Inherited::VisitCXXConstructExpr(E);
3460 }
3461
3462 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3463 Expr *Callee = E->getCallee();
3464 if (isa<MemberExpr>(Callee)) {
3465 HandleValue(Callee, false /*AddressOf*/);
3466 for (auto Arg : E->arguments())
3467 Visit(Arg);
3468 return;
3469 }
3470
3471 Inherited::VisitCXXMemberCallExpr(E);
3472 }
3473
3474 void VisitCallExpr(CallExpr *E) {
3475 // Treat std::move as a use.
3476 if (E->isCallToStdMove()) {
3477 HandleValue(E->getArg(0), /*AddressOf=*/false);
3478 return;
3479 }
3480
3481 Inherited::VisitCallExpr(E);
3482 }
3483
3484 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3485 Expr *Callee = E->getCallee();
3486
3487 if (isa<UnresolvedLookupExpr>(Callee))
3488 return Inherited::VisitCXXOperatorCallExpr(E);
3489
3490 Visit(Callee);
3491 for (auto Arg : E->arguments())
3492 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3493 }
3494
3495 void VisitBinaryOperator(BinaryOperator *E) {
3496 // If a field assignment is detected, remove the field from the
3497 // uninitiailized field set.
3498 if (E->getOpcode() == BO_Assign)
3499 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3500 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3501 if (!FD->getType()->isReferenceType())
3502 DeclsToRemove.push_back(FD);
3503
3504 if (E->isCompoundAssignmentOp()) {
3505 HandleValue(E->getLHS(), false /*AddressOf*/);
3506 Visit(E->getRHS());
3507 return;
3508 }
3509
3510 Inherited::VisitBinaryOperator(E);
3511 }
3512
3513 void VisitUnaryOperator(UnaryOperator *E) {
3514 if (E->isIncrementDecrementOp()) {
3515 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3516 return;
3517 }
3518 if (E->getOpcode() == UO_AddrOf) {
3519 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3520 HandleValue(ME->getBase(), true /*AddressOf*/);
3521 return;
3522 }
3523 }
3524
3525 Inherited::VisitUnaryOperator(E);
3526 }
3527 };
3528
3529 // Diagnose value-uses of fields to initialize themselves, e.g.
3530 // foo(foo)
3531 // where foo is not also a parameter to the constructor.
3532 // Also diagnose across field uninitialized use such as
3533 // x(y), y(x)
3534 // TODO: implement -Wuninitialized and fold this into that framework.
3535 static void DiagnoseUninitializedFields(
3536 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3537
3538 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3539 Constructor->getLocation())) {
3540 return;
3541 }
3542
3543 if (Constructor->isInvalidDecl())
3544 return;
3545
3546 const CXXRecordDecl *RD = Constructor->getParent();
3547
3548 if (RD->getDescribedClassTemplate())
3549 return;
3550
3551 // Holds fields that are uninitialized.
3552 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3553
3554 // At the beginning, all fields are uninitialized.
3555 for (auto *I : RD->decls()) {
3556 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3557 UninitializedFields.insert(FD);
3558 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3559 UninitializedFields.insert(IFD->getAnonField());
3560 }
3561 }
3562
3563 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3564 for (auto I : RD->bases())
3565 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3566
3567 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3568 return;
3569
3570 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3571 UninitializedFields,
3572 UninitializedBaseClasses);
3573
3574 for (const auto *FieldInit : Constructor->inits()) {
3575 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3576 break;
3577
3578 Expr *InitExpr = FieldInit->getInit();
3579 if (!InitExpr)
3580 continue;
3581
3582 if (CXXDefaultInitExpr *Default =
3583 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3584 InitExpr = Default->getExpr();
3585 if (!InitExpr)
3586 continue;
3587 // In class initializers will point to the constructor.
3588 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3589 FieldInit->getAnyMember(),
3590 FieldInit->getBaseClass());
3591 } else {
3592 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3593 FieldInit->getAnyMember(),
3594 FieldInit->getBaseClass());
3595 }
3596 }
3597 }
3598} // namespace
3599
3600/// Enter a new C++ default initializer scope. After calling this, the
3601/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3602/// parsing or instantiating the initializer failed.
3603void Sema::ActOnStartCXXInClassMemberInitializer() {
3604 // Create a synthetic function scope to represent the call to the constructor
3605 // that notionally surrounds a use of this initializer.
3606 PushFunctionScope();
3607}
3608
3609/// This is invoked after parsing an in-class initializer for a
3610/// non-static C++ class member, and after instantiating an in-class initializer
3611/// in a class template. Such actions are deferred until the class is complete.
3612void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3613 SourceLocation InitLoc,
3614 Expr *InitExpr) {
3615 // Pop the notional constructor scope we created earlier.
3616 PopFunctionScopeInfo(nullptr, D);
3617
3618 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3619 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3620, __extension__ __PRETTY_FUNCTION__))
3620 "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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3620, __extension__ __PRETTY_FUNCTION__))
;
3621
3622 if (!InitExpr) {
3623 D->setInvalidDecl();
3624 if (FD)
3625 FD->removeInClassInitializer();
3626 return;
3627 }
3628
3629 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3630 FD->setInvalidDecl();
3631 FD->removeInClassInitializer();
3632 return;
3633 }
3634
3635 ExprResult Init = InitExpr;
3636 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3637 InitializedEntity Entity =
3638 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3639 InitializationKind Kind =
3640 FD->getInClassInitStyle() == ICIS_ListInit
3641 ? InitializationKind::CreateDirectList(InitExpr->getLocStart(),
3642 InitExpr->getLocStart(),
3643 InitExpr->getLocEnd())
3644 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3645 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3646 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3647 if (Init.isInvalid()) {
3648 FD->setInvalidDecl();
3649 return;
3650 }
3651 }
3652
3653 // C++11 [class.base.init]p7:
3654 // The initialization of each base and member constitutes a
3655 // full-expression.
3656 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3657 if (Init.isInvalid()) {
3658 FD->setInvalidDecl();
3659 return;
3660 }
3661
3662 InitExpr = Init.get();
3663
3664 FD->setInClassInitializer(InitExpr);
3665}
3666
3667/// Find the direct and/or virtual base specifiers that
3668/// correspond to the given base type, for use in base initialization
3669/// within a constructor.
3670static bool FindBaseInitializer(Sema &SemaRef,
3671 CXXRecordDecl *ClassDecl,
3672 QualType BaseType,
3673 const CXXBaseSpecifier *&DirectBaseSpec,
3674 const CXXBaseSpecifier *&VirtualBaseSpec) {
3675 // First, check for a direct base class.
3676 DirectBaseSpec = nullptr;
3677 for (const auto &Base : ClassDecl->bases()) {
3678 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3679 // We found a direct base of this type. That's what we're
3680 // initializing.
3681 DirectBaseSpec = &Base;
3682 break;
3683 }
3684 }
3685
3686 // Check for a virtual base class.
3687 // FIXME: We might be able to short-circuit this if we know in advance that
3688 // there are no virtual bases.
3689 VirtualBaseSpec = nullptr;
3690 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3691 // We haven't found a base yet; search the class hierarchy for a
3692 // virtual base class.
3693 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3694 /*DetectVirtual=*/false);
3695 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3696 SemaRef.Context.getTypeDeclType(ClassDecl),
3697 BaseType, Paths)) {
3698 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3699 Path != Paths.end(); ++Path) {
3700 if (Path->back().Base->isVirtual()) {
3701 VirtualBaseSpec = Path->back().Base;
3702 break;
3703 }
3704 }
3705 }
3706 }
3707
3708 return DirectBaseSpec || VirtualBaseSpec;
3709}
3710
3711/// Handle a C++ member initializer using braced-init-list syntax.
3712MemInitResult
3713Sema::ActOnMemInitializer(Decl *ConstructorD,
3714 Scope *S,
3715 CXXScopeSpec &SS,
3716 IdentifierInfo *MemberOrBase,
3717 ParsedType TemplateTypeTy,
3718 const DeclSpec &DS,
3719 SourceLocation IdLoc,
3720 Expr *InitList,
3721 SourceLocation EllipsisLoc) {
3722 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3723 DS, IdLoc, InitList,
3724 EllipsisLoc);
3725}
3726
3727/// Handle a C++ member initializer using parentheses syntax.
3728MemInitResult
3729Sema::ActOnMemInitializer(Decl *ConstructorD,
3730 Scope *S,
3731 CXXScopeSpec &SS,
3732 IdentifierInfo *MemberOrBase,
3733 ParsedType TemplateTypeTy,
3734 const DeclSpec &DS,
3735 SourceLocation IdLoc,
3736 SourceLocation LParenLoc,
3737 ArrayRef<Expr *> Args,
3738 SourceLocation RParenLoc,
3739 SourceLocation EllipsisLoc) {
3740 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3741 Args, RParenLoc);
3742 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3743 DS, IdLoc, List, EllipsisLoc);
3744}
3745
3746namespace {
3747
3748// Callback to only accept typo corrections that can be a valid C++ member
3749// intializer: either a non-static field member or a base class.
3750class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3751public:
3752 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3753 : ClassDecl(ClassDecl) {}
3754
3755 bool ValidateCandidate(const TypoCorrection &candidate) override {
3756 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3757 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3758 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3759 return isa<TypeDecl>(ND);
3760 }
3761 return false;
3762 }
3763
3764private:
3765 CXXRecordDecl *ClassDecl;
3766};
3767
3768}
3769
3770/// Handle a C++ member initializer.
3771MemInitResult
3772Sema::BuildMemInitializer(Decl *ConstructorD,
3773 Scope *S,
3774 CXXScopeSpec &SS,
3775 IdentifierInfo *MemberOrBase,
3776 ParsedType TemplateTypeTy,
3777 const DeclSpec &DS,
3778 SourceLocation IdLoc,
3779 Expr *Init,
3780 SourceLocation EllipsisLoc) {
3781 ExprResult Res = CorrectDelayedTyposInExpr(Init);
3782 if (!Res.isUsable())
3783 return true;
3784 Init = Res.get();
3785
3786 if (!ConstructorD)
3787 return true;
3788
3789 AdjustDeclIfTemplate(ConstructorD);
3790
3791 CXXConstructorDecl *Constructor
3792 = dyn_cast<CXXConstructorDecl>(ConstructorD);
3793 if (!Constructor) {
3794 // The user wrote a constructor initializer on a function that is
3795 // not a C++ constructor. Ignore the error for now, because we may
3796 // have more member initializers coming; we'll diagnose it just
3797 // once in ActOnMemInitializers.
3798 return true;
3799 }
3800
3801 CXXRecordDecl *ClassDecl = Constructor->getParent();
3802
3803 // C++ [class.base.init]p2:
3804 // Names in a mem-initializer-id are looked up in the scope of the
3805 // constructor's class and, if not found in that scope, are looked
3806 // up in the scope containing the constructor's definition.
3807 // [Note: if the constructor's class contains a member with the
3808 // same name as a direct or virtual base class of the class, a
3809 // mem-initializer-id naming the member or base class and composed
3810 // of a single identifier refers to the class member. A
3811 // mem-initializer-id for the hidden base class may be specified
3812 // using a qualified name. ]
3813 if (!SS.getScopeRep() && !TemplateTypeTy) {
3814 // Look for a member, first.
3815 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3816 if (!Result.empty()) {
3817 ValueDecl *Member;
3818 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3819 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3820 if (EllipsisLoc.isValid())
3821 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3822 << MemberOrBase
3823 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3824
3825 return BuildMemberInitializer(Member, Init, IdLoc);
3826 }
3827 }
3828 }
3829 // It didn't name a member, so see if it names a class.
3830 QualType BaseType;
3831 TypeSourceInfo *TInfo = nullptr;
3832
3833 if (TemplateTypeTy) {
3834 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3835 } else if (DS.getTypeSpecType() == TST_decltype) {
3836 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3837 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3838 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3839 return true;
3840 } else {
3841 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3842 LookupParsedName(R, S, &SS);
3843
3844 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3845 if (!TyD) {
3846 if (R.isAmbiguous()) return true;
3847
3848 // We don't want access-control diagnostics here.
3849 R.suppressDiagnostics();
3850
3851 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3852 bool NotUnknownSpecialization = false;
3853 DeclContext *DC = computeDeclContext(SS, false);
3854 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3855 NotUnknownSpecialization = !Record->hasAnyDependentBases();
3856
3857 if (!NotUnknownSpecialization) {
3858 // When the scope specifier can refer to a member of an unknown
3859 // specialization, we take it as a type name.
3860 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3861 SS.getWithLocInContext(Context),
3862 *MemberOrBase, IdLoc);
3863 if (BaseType.isNull())
3864 return true;
3865
3866 TInfo = Context.CreateTypeSourceInfo(BaseType);
3867 DependentNameTypeLoc TL =
3868 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3869 if (!TL.isNull()) {
3870 TL.setNameLoc(IdLoc);
3871 TL.setElaboratedKeywordLoc(SourceLocation());
3872 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3873 }
3874
3875 R.clear();
3876 R.setLookupName(MemberOrBase);
3877 }
3878 }
3879
3880 // If no results were found, try to correct typos.
3881 TypoCorrection Corr;
3882 if (R.empty() && BaseType.isNull() &&
3883 (Corr = CorrectTypo(
3884 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3885 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3886 CTK_ErrorRecovery, ClassDecl))) {
3887 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3888 // We have found a non-static data member with a similar
3889 // name to what was typed; complain and initialize that
3890 // member.
3891 diagnoseTypo(Corr,
3892 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3893 << MemberOrBase << true);
3894 return BuildMemberInitializer(Member, Init, IdLoc);
3895 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3896 const CXXBaseSpecifier *DirectBaseSpec;
3897 const CXXBaseSpecifier *VirtualBaseSpec;
3898 if (FindBaseInitializer(*this, ClassDecl,
3899 Context.getTypeDeclType(Type),
3900 DirectBaseSpec, VirtualBaseSpec)) {
3901 // We have found a direct or virtual base class with a
3902 // similar name to what was typed; complain and initialize
3903 // that base class.
3904 diagnoseTypo(Corr,
3905 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3906 << MemberOrBase << false,
3907 PDiag() /*Suppress note, we provide our own.*/);
3908
3909 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3910 : VirtualBaseSpec;
3911 Diag(BaseSpec->getLocStart(),
3912 diag::note_base_class_specified_here)
3913 << BaseSpec->getType()
3914 << BaseSpec->getSourceRange();
3915
3916 TyD = Type;
3917 }
3918 }
3919 }
3920
3921 if (!TyD && BaseType.isNull()) {
3922 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3923 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3924 return true;
3925 }
3926 }
3927
3928 if (BaseType.isNull()) {
3929 BaseType = Context.getTypeDeclType(TyD);
3930 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3931 if (SS.isSet()) {
3932 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3933 BaseType);
3934 TInfo = Context.CreateTypeSourceInfo(BaseType);
3935 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3936 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3937 TL.setElaboratedKeywordLoc(SourceLocation());
3938 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3939 }
3940 }
3941 }
3942
3943 if (!TInfo)
3944 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3945
3946 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3947}
3948
3949MemInitResult
3950Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3951 SourceLocation IdLoc) {
3952 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3953 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3954 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3955, __extension__ __PRETTY_FUNCTION__))
3955 "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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3955, __extension__ __PRETTY_FUNCTION__))
;
3956
3957 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3958 return true;
3959
3960 if (Member->isInvalidDecl())
3961 return true;
3962
3963 MultiExprArg Args;
3964 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3965 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3966 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3967 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3968 } else {
3969 // Template instantiation doesn't reconstruct ParenListExprs for us.
3970 Args = Init;
3971 }
3972
3973 SourceRange InitRange = Init->getSourceRange();
3974
3975 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3976 // Can't check initialization for a member of dependent type or when
3977 // any of the arguments are type-dependent expressions.
3978 DiscardCleanupsInEvaluationContext();
3979 } else {
3980 bool InitList = false;
3981 if (isa<InitListExpr>(Init)) {
3982 InitList = true;
3983 Args = Init;
3984 }
3985
3986 // Initialize the member.
3987 InitializedEntity MemberEntity =
3988 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3989 : InitializedEntity::InitializeMember(IndirectMember,
3990 nullptr);
3991 InitializationKind Kind =
3992 InitList ? InitializationKind::CreateDirectList(
3993 IdLoc, Init->getLocStart(), Init->getLocEnd())
3994 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3995 InitRange.getEnd());
3996
3997 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3998 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3999 nullptr);
4000 if (MemberInit.isInvalid())
4001 return true;
4002
4003 // C++11 [class.base.init]p7:
4004 // The initialization of each base and member constitutes a
4005 // full-expression.
4006 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
4007 if (MemberInit.isInvalid())
4008 return true;
4009
4010 Init = MemberInit.get();
4011 }
4012
4013 if (DirectMember) {
4014 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4015 InitRange.getBegin(), Init,
4016 InitRange.getEnd());
4017 } else {
4018 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4019 InitRange.getBegin(), Init,
4020 InitRange.getEnd());
4021 }
4022}
4023
4024MemInitResult
4025Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4026 CXXRecordDecl *ClassDecl) {
4027 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4028 if (!LangOpts.CPlusPlus11)
4029 return Diag(NameLoc, diag::err_delegating_ctor)
4030 << TInfo->getTypeLoc().getLocalSourceRange();
4031 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4032
4033 bool InitList = true;
4034 MultiExprArg Args = Init;
4035 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4036 InitList = false;
4037 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4038 }
4039
4040 SourceRange InitRange = Init->getSourceRange();
4041 // Initialize the object.
4042 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4043 QualType(ClassDecl->getTypeForDecl(), 0));
4044 InitializationKind Kind =
4045 InitList ? InitializationKind::CreateDirectList(
4046 NameLoc, Init->getLocStart(), Init->getLocEnd())
4047 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4048 InitRange.getEnd());
4049 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4050 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4051 Args, nullptr);
4052 if (DelegationInit.isInvalid())
4053 return true;
4054
4055 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4056, __extension__ __PRETTY_FUNCTION__))
4056 "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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4056, __extension__ __PRETTY_FUNCTION__))
;
4057
4058 // C++11 [class.base.init]p7:
4059 // The initialization of each base and member constitutes a
4060 // full-expression.
4061 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4062 InitRange.getBegin());
4063 if (DelegationInit.isInvalid())
4064 return true;
4065
4066 // If we are in a dependent context, template instantiation will
4067 // perform this type-checking again. Just save the arguments that we
4068 // received in a ParenListExpr.
4069 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4070 // of the information that we have about the base
4071 // initializer. However, deconstructing the ASTs is a dicey process,
4072 // and this approach is far more likely to get the corner cases right.
4073 if (CurContext->isDependentContext())
4074 DelegationInit = Init;
4075
4076 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4077 DelegationInit.getAs<Expr>(),
4078 InitRange.getEnd());
4079}
4080
4081MemInitResult
4082Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4083 Expr *Init, CXXRecordDecl *ClassDecl,
4084 SourceLocation EllipsisLoc) {
4085 SourceLocation BaseLoc
4086 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4087
4088 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4089 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4090 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4091
4092 // C++ [class.base.init]p2:
4093 // [...] Unless the mem-initializer-id names a nonstatic data
4094 // member of the constructor's class or a direct or virtual base
4095 // of that class, the mem-initializer is ill-formed. A
4096 // mem-initializer-list can initialize a base class using any
4097 // name that denotes that base class type.
4098 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4099
4100 SourceRange InitRange = Init->getSourceRange();
4101 if (EllipsisLoc.isValid()) {
4102 // This is a pack expansion.
4103 if (!BaseType->containsUnexpandedParameterPack()) {
4104 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4105 << SourceRange(BaseLoc, InitRange.getEnd());
4106
4107 EllipsisLoc = SourceLocation();
4108 }
4109 } else {
4110 // Check for any unexpanded parameter packs.
4111 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4112 return true;
4113
4114 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4115 return true;
4116 }
4117
4118 // Check for direct and virtual base classes.
4119 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4120 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4121 if (!Dependent) {
4122 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4123 BaseType))
4124 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4125
4126 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4127 VirtualBaseSpec);
4128
4129 // C++ [base.class.init]p2:
4130 // Unless the mem-initializer-id names a nonstatic data member of the
4131 // constructor's class or a direct or virtual base of that class, the
4132 // mem-initializer is ill-formed.
4133 if (!DirectBaseSpec && !VirtualBaseSpec) {
4134 // If the class has any dependent bases, then it's possible that
4135 // one of those types will resolve to the same type as
4136 // BaseType. Therefore, just treat this as a dependent base
4137 // class initialization. FIXME: Should we try to check the
4138 // initialization anyway? It seems odd.
4139 if (ClassDecl->hasAnyDependentBases())
4140 Dependent = true;
4141 else
4142 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4143 << BaseType << Context.getTypeDeclType(ClassDecl)
4144 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4145 }
4146 }
4147
4148 if (Dependent) {
4149 DiscardCleanupsInEvaluationContext();
4150
4151 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4152 /*IsVirtual=*/false,
4153 InitRange.getBegin(), Init,
4154 InitRange.getEnd(), EllipsisLoc);
4155 }
4156
4157 // C++ [base.class.init]p2:
4158 // If a mem-initializer-id is ambiguous because it designates both
4159 // a direct non-virtual base class and an inherited virtual base
4160 // class, the mem-initializer is ill-formed.
4161 if (DirectBaseSpec && VirtualBaseSpec)
4162 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4163 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4164
4165 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4166 if (!BaseSpec)
4167 BaseSpec = VirtualBaseSpec;
4168
4169 // Initialize the base.
4170 bool InitList = true;
4171 MultiExprArg Args = Init;
4172 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4173 InitList = false;
4174 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4175 }
4176
4177 InitializedEntity BaseEntity =
4178 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4179 InitializationKind Kind =
4180 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4181 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4182 InitRange.getEnd());
4183 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4184 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4185 if (BaseInit.isInvalid())
4186 return true;
4187
4188 // C++11 [class.base.init]p7:
4189 // The initialization of each base and member constitutes a
4190 // full-expression.
4191 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4192 if (BaseInit.isInvalid())
4193 return true;
4194
4195 // If we are in a dependent context, template instantiation will
4196 // perform this type-checking again. Just save the arguments that we
4197 // received in a ParenListExpr.
4198 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4199 // of the information that we have about the base
4200 // initializer. However, deconstructing the ASTs is a dicey process,
4201 // and this approach is far more likely to get the corner cases right.
4202 if (CurContext->isDependentContext())
4203 BaseInit = Init;
4204
4205 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4206 BaseSpec->isVirtual(),
4207 InitRange.getBegin(),
4208 BaseInit.getAs<Expr>(),
4209 InitRange.getEnd(), EllipsisLoc);
4210}
4211
4212// Create a static_cast\<T&&>(expr).
4213static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4214 if (T.isNull()) T = E->getType();
4215 QualType TargetType = SemaRef.BuildReferenceType(
4216 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4217 SourceLocation ExprLoc = E->getLocStart();
4218 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4219 TargetType, ExprLoc);
4220
4221 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4222 SourceRange(ExprLoc, ExprLoc),
4223 E->getSourceRange()).get();
4224}
4225
4226/// ImplicitInitializerKind - How an implicit base or member initializer should
4227/// initialize its base or member.
4228enum ImplicitInitializerKind {
4229 IIK_Default,
4230 IIK_Copy,
4231 IIK_Move,
4232 IIK_Inherit
4233};
4234
4235static bool
4236BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4237 ImplicitInitializerKind ImplicitInitKind,
4238 CXXBaseSpecifier *BaseSpec,
4239 bool IsInheritedVirtualBase,
4240 CXXCtorInitializer *&CXXBaseInit) {
4241 InitializedEntity InitEntity
4242 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4243 IsInheritedVirtualBase);
4244
4245 ExprResult BaseInit;
4246
4247 switch (ImplicitInitKind) {
4248 case IIK_Inherit:
4249 case IIK_Default: {
4250 InitializationKind InitKind
4251 = InitializationKind::CreateDefault(Constructor->getLocation());
4252 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4253 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4254 break;
4255 }
4256
4257 case IIK_Move:
4258 case IIK_Copy: {
4259 bool Moving = ImplicitInitKind == IIK_Move;
4260 ParmVarDecl *Param = Constructor->getParamDecl(0);
4261 QualType ParamType = Param->getType().getNonReferenceType();
4262
4263 Expr *CopyCtorArg =
4264 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4265 SourceLocation(), Param, false,
4266 Constructor->getLocation(), ParamType,
4267 VK_LValue, nullptr);
4268
4269 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4270
4271 // Cast to the base class to avoid ambiguities.
4272 QualType ArgTy =
4273 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4274 ParamType.getQualifiers());
4275
4276 if (Moving) {
4277 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4278 }
4279
4280 CXXCastPath BasePath;
4281 BasePath.push_back(BaseSpec);
4282 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4283 CK_UncheckedDerivedToBase,
4284 Moving ? VK_XValue : VK_LValue,
4285 &BasePath).get();
4286
4287 InitializationKind InitKind
4288 = InitializationKind::CreateDirect(Constructor->getLocation(),
4289 SourceLocation(), SourceLocation());
4290 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4291 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4292 break;
4293 }
4294 }
4295
4296 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4297 if (BaseInit.isInvalid())
4298 return true;
4299
4300 CXXBaseInit =
4301 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4302 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4303 SourceLocation()),
4304 BaseSpec->isVirtual(),
4305 SourceLocation(),
4306 BaseInit.getAs<Expr>(),
4307 SourceLocation(),
4308 SourceLocation());
4309
4310 return false;
4311}
4312
4313static bool RefersToRValueRef(Expr *MemRef) {
4314 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4315 return Referenced->getType()->isRValueReferenceType();
4316}
4317
4318static bool
4319BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4320 ImplicitInitializerKind ImplicitInitKind,
4321 FieldDecl *Field, IndirectFieldDecl *Indirect,
4322 CXXCtorInitializer *&CXXMemberInit) {
4323 if (Field->isInvalidDecl())
4324 return true;
4325
4326 SourceLocation Loc = Constructor->getLocation();
4327
4328 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4329 bool Moving = ImplicitInitKind == IIK_Move;
4330 ParmVarDecl *Param = Constructor->getParamDecl(0);
4331 QualType ParamType = Param->getType().getNonReferenceType();
4332
4333 // Suppress copying zero-width bitfields.
4334 if (Field->isZeroLengthBitField(SemaRef.Context))
4335 return false;
4336
4337 Expr *MemberExprBase =
4338 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4339 SourceLocation(), Param, false,
4340 Loc, ParamType, VK_LValue, nullptr);
4341
4342 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4343
4344 if (Moving) {
4345 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4346 }
4347
4348 // Build a reference to this field within the parameter.
4349 CXXScopeSpec SS;
4350 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4351 Sema::LookupMemberName);
4352 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4353 : cast<ValueDecl>(Field), AS_public);
4354 MemberLookup.resolveKind();
4355 ExprResult CtorArg
4356 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4357 ParamType, Loc,
4358 /*IsArrow=*/false,
4359 SS,
4360 /*TemplateKWLoc=*/SourceLocation(),
4361 /*FirstQualifierInScope=*/nullptr,
4362 MemberLookup,
4363 /*TemplateArgs=*/nullptr,
4364 /*S*/nullptr);
4365 if (CtorArg.isInvalid())
4366 return true;
4367
4368 // C++11 [class.copy]p15:
4369 // - if a member m has rvalue reference type T&&, it is direct-initialized
4370 // with static_cast<T&&>(x.m);
4371 if (RefersToRValueRef(CtorArg.get())) {
4372 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4373 }
4374
4375 InitializedEntity Entity =
4376 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4377 /*Implicit*/ true)
4378 : InitializedEntity::InitializeMember(Field, nullptr,
4379 /*Implicit*/ true);
4380
4381 // Direct-initialize to use the copy constructor.
4382 InitializationKind InitKind =
4383 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4384
4385 Expr *CtorArgE = CtorArg.getAs<Expr>();
4386 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4387 ExprResult MemberInit =
4388 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4389 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4390 if (MemberInit.isInvalid())
4391 return true;
4392
4393 if (Indirect)
4394 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4395 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4396 else
4397 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4398 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4399 return false;
4400 }
4401
4402 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4403, __extension__ __PRETTY_FUNCTION__))
4403 "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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4403, __extension__ __PRETTY_FUNCTION__))
;
4404
4405 QualType FieldBaseElementType =
4406 SemaRef.Context.getBaseElementType(Field->getType());
4407
4408 if (FieldBaseElementType->isRecordType()) {
4409 InitializedEntity InitEntity =
4410 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4411 /*Implicit*/ true)
4412 : InitializedEntity::InitializeMember(Field, nullptr,
4413 /*Implicit*/ true);
4414 InitializationKind InitKind =
4415 InitializationKind::CreateDefault(Loc);
4416
4417 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4418 ExprResult MemberInit =
4419 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4420
4421 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4422 if (MemberInit.isInvalid())
4423 return true;
4424
4425 if (Indirect)
4426 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4427 Indirect, Loc,
4428 Loc,
4429 MemberInit.get(),
4430 Loc);
4431 else
4432 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4433 Field, Loc, Loc,
4434 MemberInit.get(),
4435 Loc);
4436 return false;
4437 }
4438
4439 if (!Field->getParent()->isUnion()) {
4440 if (FieldBaseElementType->isReferenceType()) {
4441 SemaRef.Diag(Constructor->getLocation(),
4442 diag::err_uninitialized_member_in_ctor)
4443 << (int)Constructor->isImplicit()
4444 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4445 << 0 << Field->getDeclName();
4446 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4447 return true;
4448 }
4449
4450 if (FieldBaseElementType.isConstQualified()) {
4451 SemaRef.Diag(Constructor->getLocation(),
4452 diag::err_uninitialized_member_in_ctor)
4453 << (int)Constructor->isImplicit()
4454 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4455 << 1 << Field->getDeclName();
4456 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4457 return true;
4458 }
4459 }
4460
4461 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4462 // ARC and Weak:
4463 // Default-initialize Objective-C pointers to NULL.
4464 CXXMemberInit
4465 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4466 Loc, Loc,
4467 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4468 Loc);
4469 return false;
4470 }
4471
4472 // Nothing to initialize.
4473 CXXMemberInit = nullptr;
4474 return false;
4475}
4476
4477namespace {
4478struct BaseAndFieldInfo {
4479 Sema &S;
4480 CXXConstructorDecl *Ctor;
4481 bool AnyErrorsInInits;
4482 ImplicitInitializerKind IIK;
4483 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4484 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4485 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4486
4487 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4488 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4489 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4490 if (Ctor->getInheritedConstructor())
4491 IIK = IIK_Inherit;
4492 else if (Generated && Ctor->isCopyConstructor())
4493 IIK = IIK_Copy;
4494 else if (Generated && Ctor->isMoveConstructor())
4495 IIK = IIK_Move;
4496 else
4497 IIK = IIK_Default;
4498 }
4499
4500 bool isImplicitCopyOrMove() const {
4501 switch (IIK) {
4502 case IIK_Copy:
4503 case IIK_Move:
4504 return true;
4505
4506 case IIK_Default:
4507 case IIK_Inherit:
4508 return false;
4509 }
4510
4511 llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4511)
;
4512 }
4513
4514 bool addFieldInitializer(CXXCtorInitializer *Init) {
4515 AllToInit.push_back(Init);
4516
4517 // Check whether this initializer makes the field "used".
4518 if (Init->getInit()->HasSideEffects(S.Context))
4519 S.UnusedPrivateFields.remove(Init->getAnyMember());
4520
4521 return false;
4522 }
4523
4524 bool isInactiveUnionMember(FieldDecl *Field) {
4525 RecordDecl *Record = Field->getParent();
4526 if (!Record->isUnion())
4527 return false;
4528
4529 if (FieldDecl *Active =
4530 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4531 return Active != Field->getCanonicalDecl();
4532
4533 // In an implicit copy or move constructor, ignore any in-class initializer.
4534 if (isImplicitCopyOrMove())
4535 return true;
4536
4537 // If there's no explicit initialization, the field is active only if it
4538 // has an in-class initializer...
4539 if (Field->hasInClassInitializer())
4540 return false;
4541 // ... or it's an anonymous struct or union whose class has an in-class
4542 // initializer.
4543 if (!Field->isAnonymousStructOrUnion())
4544 return true;
4545 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4546 return !FieldRD->hasInClassInitializer();
4547 }
4548
4549 /// Determine whether the given field is, or is within, a union member
4550 /// that is inactive (because there was an initializer given for a different
4551 /// member of the union, or because the union was not initialized at all).
4552 bool isWithinInactiveUnionMember(FieldDecl *Field,
4553 IndirectFieldDecl *Indirect) {
4554 if (!Indirect)
4555 return isInactiveUnionMember(Field);
4556
4557 for (auto *C : Indirect->chain()) {
4558 FieldDecl *Field = dyn_cast<FieldDecl>(C);
4559 if (Field && isInactiveUnionMember(Field))
4560 return true;
4561 }
4562 return false;
4563 }
4564};
4565}
4566
4567/// Determine whether the given type is an incomplete or zero-lenfgth
4568/// array type.
4569static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4570 if (T->isIncompleteArrayType())
4571 return true;
4572
4573 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4574 if (!ArrayT->getSize())
4575 return true;
4576
4577 T = ArrayT->getElementType();
4578 }
4579
4580 return false;
4581}
4582
4583static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4584 FieldDecl *Field,
4585 IndirectFieldDecl *Indirect = nullptr) {
4586 if (Field->isInvalidDecl())
4587 return false;
4588
4589 // Overwhelmingly common case: we have a direct initializer for this field.
4590 if (CXXCtorInitializer *Init =
4591 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4592 return Info.addFieldInitializer(Init);
4593
4594 // C++11 [class.base.init]p8:
4595 // if the entity is a non-static data member that has a
4596 // brace-or-equal-initializer and either
4597 // -- the constructor's class is a union and no other variant member of that
4598 // union is designated by a mem-initializer-id or
4599 // -- the constructor's class is not a union, and, if the entity is a member
4600 // of an anonymous union, no other member of that union is designated by
4601 // a mem-initializer-id,
4602 // the entity is initialized as specified in [dcl.init].
4603 //
4604 // We also apply the same rules to handle anonymous structs within anonymous
4605 // unions.
4606 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4607 return false;
4608
4609 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4610 ExprResult DIE =
4611 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4612 if (DIE.isInvalid())
4613 return true;
4614
4615 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4616 SemaRef.checkInitializerLifetime(Entity, DIE.get());
4617
4618 CXXCtorInitializer *Init;
4619 if (Indirect)
4620 Init = new (SemaRef.Context)
4621 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4622 SourceLocation(), DIE.get(), SourceLocation());
4623 else
4624 Init = new (SemaRef.Context)
4625 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4626 SourceLocation(), DIE.get(), SourceLocation());
4627 return Info.addFieldInitializer(Init);
4628 }
4629
4630 // Don't initialize incomplete or zero-length arrays.
4631 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4632 return false;
4633
4634 // Don't try to build an implicit initializer if there were semantic
4635 // errors in any of the initializers (and therefore we might be
4636 // missing some that the user actually wrote).
4637 if (Info.AnyErrorsInInits)
4638 return false;
4639
4640 CXXCtorInitializer *Init = nullptr;
4641 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4642 Indirect, Init))
4643 return true;
4644
4645 if (!Init)
4646 return false;
4647
4648 return Info.addFieldInitializer(Init);
4649}
4650
4651bool
4652Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4653 CXXCtorInitializer *Initializer) {
4654 assert(Initializer->isDelegatingInitializer())(static_cast <bool> (Initializer->isDelegatingInitializer
()) ? void (0) : __assert_fail ("Initializer->isDelegatingInitializer()"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4654, __extension__ __PRETTY_FUNCTION__))
;
4655 Constructor->setNumCtorInitializers(1);
4656 CXXCtorInitializer **initializer =
4657 new (Context) CXXCtorInitializer*[1];
4658 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4659 Constructor->setCtorInitializers(initializer);
4660
4661 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4662 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4663 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4664 }
4665
4666 DelegatingCtorDecls.push_back(Constructor);
4667
4668 DiagnoseUninitializedFields(*this, Constructor);
4669
4670 return false;
4671}
4672
4673bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4674 ArrayRef<CXXCtorInitializer *> Initializers) {
4675 if (Constructor->isDependentContext()) {
4676 // Just store the initializers as written, they will be checked during
4677 // instantiation.
4678 if (!Initializers.empty()) {
4679 Constructor->setNumCtorInitializers(Initializers.size());
4680 CXXCtorInitializer **baseOrMemberInitializers =
4681 new (Context) CXXCtorInitializer*[Initializers.size()];
4682 memcpy(baseOrMemberInitializers, Initializers.data(),
4683 Initializers.size() * sizeof(CXXCtorInitializer*));
4684 Constructor->setCtorInitializers(baseOrMemberInitializers);
4685 }
4686
4687 // Let template instantiation know whether we had errors.
4688 if (AnyErrors)
4689 Constructor->setInvalidDecl();
4690
4691 return false;
4692 }
4693
4694 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4695
4696 // We need to build the initializer AST according to order of construction
4697 // and not what user specified in the Initializers list.
4698 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4699 if (!ClassDecl)
4700 return true;
4701
4702 bool HadError = false;
4703
4704 for (unsigned i = 0; i < Initializers.size(); i++) {
4705 CXXCtorInitializer *Member = Initializers[i];
4706
4707 if (Member->isBaseInitializer())
4708 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4709 else {
4710 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4711
4712 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4713 for (auto *C : F->chain()) {
4714 FieldDecl *FD = dyn_cast<FieldDecl>(C);
4715 if (FD && FD->getParent()->isUnion())
4716 Info.ActiveUnionMember.insert(std::make_pair(
4717 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4718 }
4719 } else if (FieldDecl *FD = Member->getMember()) {
4720 if (FD->getParent()->isUnion())
4721 Info.ActiveUnionMember.insert(std::make_pair(
4722 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4723 }
4724 }
4725 }
4726
4727 // Keep track of the direct virtual bases.
4728 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4729 for (auto &I : ClassDecl->bases()) {
4730 if (I.isVirtual())
4731 DirectVBases.insert(&I);
4732 }
4733
4734 // Push virtual bases before others.
4735 for (auto &VBase : ClassDecl->vbases()) {
4736 if (CXXCtorInitializer *Value
4737 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4738 // [class.base.init]p7, per DR257:
4739 // A mem-initializer where the mem-initializer-id names a virtual base
4740 // class is ignored during execution of a constructor of any class that
4741 // is not the most derived class.
4742 if (ClassDecl->isAbstract()) {
4743 // FIXME: Provide a fixit to remove the base specifier. This requires
4744 // tracking the location of the associated comma for a base specifier.
4745 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4746 << VBase.getType() << ClassDecl;
4747 DiagnoseAbstractType(ClassDecl);
4748 }
4749
4750 Info.AllToInit.push_back(Value);
4751 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4752 // [class.base.init]p8, per DR257:
4753 // If a given [...] base class is not named by a mem-initializer-id
4754 // [...] and the entity is not a virtual base class of an abstract
4755 // class, then [...] the entity is default-initialized.
4756 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4757 CXXCtorInitializer *CXXBaseInit;
4758 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4759 &VBase, IsInheritedVirtualBase,
4760 CXXBaseInit)) {
4761 HadError = true;
4762 continue;
4763 }
4764
4765 Info.AllToInit.push_back(CXXBaseInit);
4766 }
4767 }
4768
4769 // Non-virtual bases.
4770 for (auto &Base : ClassDecl->bases()) {
4771 // Virtuals are in the virtual base list and already constructed.
4772 if (Base.isVirtual())
4773 continue;
4774
4775 if (CXXCtorInitializer *Value
4776 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4777 Info.AllToInit.push_back(Value);
4778 } else if (!AnyErrors) {
4779 CXXCtorInitializer *CXXBaseInit;
4780 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4781 &Base, /*IsInheritedVirtualBase=*/false,
4782 CXXBaseInit)) {
4783 HadError = true;
4784 continue;
4785 }
4786
4787 Info.AllToInit.push_back(CXXBaseInit);
4788 }
4789 }
4790
4791 // Fields.
4792 for (auto *Mem : ClassDecl->decls()) {
4793 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4794 // C++ [class.bit]p2:
4795 // A declaration for a bit-field that omits the identifier declares an
4796 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4797 // initialized.
4798 if (F->isUnnamedBitfield())
4799 continue;
4800
4801 // If we're not generating the implicit copy/move constructor, then we'll
4802 // handle anonymous struct/union fields based on their individual
4803 // indirect fields.
4804 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4805 continue;
4806
4807 if (CollectFieldInitializer(*this, Info, F))
4808 HadError = true;
4809 continue;
4810 }
4811
4812 // Beyond this point, we only consider default initialization.
4813 if (Info.isImplicitCopyOrMove())
4814 continue;
4815
4816 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4817 if (F->getType()->isIncompleteArrayType()) {
4818 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4819, __extension__ __PRETTY_FUNCTION__))
4819 "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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4819, __extension__ __PRETTY_FUNCTION__))
;
4820 continue;
4821 }
4822
4823 // Initialize each field of an anonymous struct individually.
4824 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4825 HadError = true;
4826
4827 continue;
4828 }
4829 }
4830
4831 unsigned NumInitializers = Info.AllToInit.size();
4832 if (NumInitializers > 0) {
4833 Constructor->setNumCtorInitializers(NumInitializers);
4834 CXXCtorInitializer **baseOrMemberInitializers =
4835 new (Context) CXXCtorInitializer*[NumInitializers];
4836 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4837 NumInitializers * sizeof(CXXCtorInitializer*));
4838 Constructor->setCtorInitializers(baseOrMemberInitializers);
4839
4840 // Constructors implicitly reference the base and member
4841 // destructors.
4842 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4843 Constructor->getParent());
4844 }
4845
4846 return HadError;
4847}
4848
4849static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4850 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4851 const RecordDecl *RD = RT->getDecl();
4852 if (RD->isAnonymousStructOrUnion()) {
4853 for (auto *Field : RD->fields())
4854 PopulateKeysForFields(Field, IdealInits);
4855 return;
4856 }
4857 }
4858 IdealInits.push_back(Field->getCanonicalDecl());
4859}
4860
4861static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4862 return Context.getCanonicalType(BaseType).getTypePtr();
4863}
4864
4865static const void *GetKeyForMember(ASTContext &Context,
4866 CXXCtorInitializer *Member) {
4867 if (!Member->isAnyMemberInitializer())
4868 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4869
4870 return Member->getAnyMember()->getCanonicalDecl();
4871}
4872
4873static void DiagnoseBaseOrMemInitializerOrder(
4874 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4875 ArrayRef<CXXCtorInitializer *> Inits) {
4876 if (Constructor->getDeclContext()->isDependentContext())
4877 return;
4878
4879 // Don't check initializers order unless the warning is enabled at the
4880 // location of at least one initializer.
4881 bool ShouldCheckOrder = false;
4882 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4883 CXXCtorInitializer *Init = Inits[InitIndex];
4884 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4885 Init->getSourceLocation())) {
4886 ShouldCheckOrder = true;
4887 break;
4888 }
4889 }
4890 if (!ShouldCheckOrder)
4891 return;
4892
4893 // Build the list of bases and members in the order that they'll
4894 // actually be initialized. The explicit initializers should be in
4895 // this same order but may be missing things.
4896 SmallVector<const void*, 32> IdealInitKeys;
4897
4898 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4899
4900 // 1. Virtual bases.
4901 for (const auto &VBase : ClassDecl->vbases())
4902 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4903
4904 // 2. Non-virtual bases.
4905 for (const auto &Base : ClassDecl->bases()) {
4906 if (Base.isVirtual())
4907 continue;
4908 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4909 }
4910
4911 // 3. Direct fields.
4912 for (auto *Field : ClassDecl->fields()) {
4913 if (Field->isUnnamedBitfield())
4914 continue;
4915
4916 PopulateKeysForFields(Field, IdealInitKeys);
4917 }
4918
4919 unsigned NumIdealInits = IdealInitKeys.size();
4920 unsigned IdealIndex = 0;
4921
4922 CXXCtorInitializer *PrevInit = nullptr;
4923 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4924 CXXCtorInitializer *Init = Inits[InitIndex];
4925 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4926
4927 // Scan forward to try to find this initializer in the idealized
4928 // initializers list.
4929 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4930 if (InitKey == IdealInitKeys[IdealIndex])
4931 break;
4932
4933 // If we didn't find this initializer, it must be because we
4934 // scanned past it on a previous iteration. That can only
4935 // happen if we're out of order; emit a warning.
4936 if (IdealIndex == NumIdealInits && PrevInit) {
4937 Sema::SemaDiagnosticBuilder D =
4938 SemaRef.Diag(PrevInit->getSourceLocation(),
4939 diag::warn_initializer_out_of_order);
4940
4941 if (PrevInit->isAnyMemberInitializer())
4942 D << 0 << PrevInit->getAnyMember()->getDeclName();
4943 else
4944 D << 1 << PrevInit->getTypeSourceInfo()->getType();
4945
4946 if (Init->isAnyMemberInitializer())
4947 D << 0 << Init->getAnyMember()->getDeclName();
4948 else
4949 D << 1 << Init->getTypeSourceInfo()->getType();
4950
4951 // Move back to the initializer's location in the ideal list.
4952 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4953 if (InitKey == IdealInitKeys[IdealIndex])
4954 break;
4955
4956 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4957, __extension__ __PRETTY_FUNCTION__))
4957 "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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4957, __extension__ __PRETTY_FUNCTION__))
;
4958 }
4959
4960 PrevInit = Init;
4961 }
4962}
4963
4964namespace {
4965bool CheckRedundantInit(Sema &S,
4966 CXXCtorInitializer *Init,
4967 CXXCtorInitializer *&PrevInit) {
4968 if (!PrevInit) {
4969 PrevInit = Init;
4970 return false;
4971 }
4972
4973 if (FieldDecl *Field = Init->getAnyMember())
4974 S.Diag(Init->getSourceLocation(),
4975 diag::err_multiple_mem_initialization)
4976 << Field->getDeclName()
4977 << Init->getSourceRange();
4978 else {
4979 const Type *BaseClass = Init->getBaseClass();
4980 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4980, __extension__ __PRETTY_FUNCTION__))
;
4981 S.Diag(Init->getSourceLocation(),
4982 diag::err_multiple_base_initialization)
4983 << QualType(BaseClass, 0)
4984 << Init->getSourceRange();
4985 }
4986 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4987 << 0 << PrevInit->getSourceRange();
4988
4989 return true;
4990}
4991
4992typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4993typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4994
4995bool CheckRedundantUnionInit(Sema &S,
4996 CXXCtorInitializer *Init,
4997 RedundantUnionMap &Unions) {
4998 FieldDecl *Field = Init->getAnyMember();
4999 RecordDecl *Parent = Field->getParent();
5000 NamedDecl *Child = Field;
5001
5002 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5003 if (Parent->isUnion()) {
5004 UnionEntry &En = Unions[Parent];
5005 if (En.first && En.first != Child) {
5006 S.Diag(Init->getSourceLocation(),
5007 diag::err_multiple_mem_union_initialization)
5008 << Field->getDeclName()
5009 << Init->getSourceRange();
5010 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5011 << 0 << En.second->getSourceRange();
5012 return true;
5013 }
5014 if (!En.first) {
5015 En.first = Child;
5016 En.second = Init;
5017 }
5018 if (!Parent->isAnonymousStructOrUnion())
5019 return false;
5020 }
5021
5022 Child = Parent;
5023 Parent = cast<RecordDecl>(Parent->getDeclContext());
5024 }
5025
5026 return false;
5027}
5028}
5029
5030/// ActOnMemInitializers - Handle the member initializers for a constructor.
5031void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5032 SourceLocation ColonLoc,
5033 ArrayRef<CXXCtorInitializer*> MemInits,
5034 bool AnyErrors) {
5035 if (!ConstructorDecl)
5036 return;
5037
5038 AdjustDeclIfTemplate(ConstructorDecl);
5039
5040 CXXConstructorDecl *Constructor
5041 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5042
5043 if (!Constructor) {
5044 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5045 return;
5046 }
5047
5048 // Mapping for the duplicate initializers check.
5049 // For member initializers, this is keyed with a FieldDecl*.
5050 // For base initializers, this is keyed with a Type*.
5051 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5052
5053 // Mapping for the inconsistent anonymous-union initializers check.
5054 RedundantUnionMap MemberUnions;
5055
5056 bool HadError = false;
5057 for (unsigned i = 0; i < MemInits.size(); i++) {
5058 CXXCtorInitializer *Init = MemInits[i];
5059
5060 // Set the source order index.
5061 Init->setSourceOrder(i);
5062
5063 if (Init->isAnyMemberInitializer()) {
5064 const void *Key = GetKeyForMember(Context, Init);
5065 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5066 CheckRedundantUnionInit(*this, Init, MemberUnions))
5067 HadError = true;
5068 } else if (Init->isBaseInitializer()) {
5069 const void *Key = GetKeyForMember(Context, Init);
5070 if (CheckRedundantInit(*this, Init, Members[Key]))
5071 HadError = true;
5072 } else {
5073 assert(Init->isDelegatingInitializer())(static_cast <bool> (Init->isDelegatingInitializer()
) ? void (0) : __assert_fail ("Init->isDelegatingInitializer()"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5073, __extension__ __PRETTY_FUNCTION__))
;
5074 // This must be the only initializer
5075 if (MemInits.size() != 1) {
5076 Diag(Init->getSourceLocation(),
5077 diag::err_delegating_initializer_alone)
5078 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5079 // We will treat this as being the only initializer.
5080 }
5081 SetDelegatingInitializer(Constructor, MemInits[i]);
5082 // Return immediately as the initializer is set.
5083 return;
5084 }
5085 }
5086
5087 if (HadError)
5088 return;
5089
5090 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5091
5092 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5093
5094 DiagnoseUninitializedFields(*this, Constructor);
5095}
5096
5097void
5098Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5099 CXXRecordDecl *ClassDecl) {
5100 // Ignore dependent contexts. Also ignore unions, since their members never
5101 // have destructors implicitly called.
5102 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5103 return;
5104
5105 // FIXME: all the access-control diagnostics are positioned on the
5106 // field/base declaration. That's probably good; that said, the
5107 // user might reasonably want to know why the destructor is being
5108 // emitted, and we currently don't say.
5109
5110 // Non-static data members.
5111 for (auto *Field : ClassDecl->fields()) {
5112 if (Field->isInvalidDecl())
5113 continue;
5114
5115 // Don't destroy incomplete or zero-length arrays.
5116 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5117 continue;
5118
5119 QualType FieldType = Context.getBaseElementType(Field->getType());
5120
5121 const RecordType* RT = FieldType->getAs<RecordType>();
5122 if (!RT)
5123 continue;
5124
5125 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5126 if (FieldClassDecl->isInvalidDecl())
5127 continue;
5128 if (FieldClassDecl->hasIrrelevantDestructor())
5129 continue;
5130 // The destructor for an implicit anonymous union member is never invoked.
5131 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5132 continue;
5133
5134 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5135 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5135, __extension__ __PRETTY_FUNCTION__))
;
5136 CheckDestructorAccess(Field->getLocation(), Dtor,
5137 PDiag(diag::err_access_dtor_field)
5138 << Field->getDeclName()
5139 << FieldType);
5140
5141 MarkFunctionReferenced(Location, Dtor);
5142 DiagnoseUseOfDecl(Dtor, Location);
5143 }
5144
5145 // We only potentially invoke the destructors of potentially constructed
5146 // subobjects.
5147 bool VisitVirtualBases = !ClassDecl->isAbstract();
5148
5149 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5150
5151 // Bases.
5152 for (const auto &Base : ClassDecl->bases()) {
5153 // Bases are always records in a well-formed non-dependent class.
5154 const RecordType *RT = Base.getType()->getAs<RecordType>();
5155
5156 // Remember direct virtual bases.
5157 if (Base.isVirtual()) {
5158 if (!VisitVirtualBases)
5159 continue;
5160 DirectVirtualBases.insert(RT);
5161 }
5162
5163 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5164 // If our base class is invalid, we probably can't get its dtor anyway.
5165 if (BaseClassDecl->isInvalidDecl())
5166 continue;
5167 if (BaseClassDecl->hasIrrelevantDestructor())
5168 continue;
5169
5170 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5171 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5171, __extension__ __PRETTY_FUNCTION__))
;
5172
5173 // FIXME: caret should be on the start of the class name
5174 CheckDestructorAccess(Base.getLocStart(), Dtor,
5175 PDiag(diag::err_access_dtor_base)
5176 << Base.getType()
5177 << Base.getSourceRange(),
5178 Context.getTypeDeclType(ClassDecl));
5179
5180 MarkFunctionReferenced(Location, Dtor);
5181 DiagnoseUseOfDecl(Dtor, Location);
5182 }
5183
5184 if (!VisitVirtualBases)
5185 return;
5186
5187 // Virtual bases.
5188 for (const auto &VBase : ClassDecl->vbases()) {
5189 // Bases are always records in a well-formed non-dependent class.
5190 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5191
5192 // Ignore direct virtual bases.
5193 if (DirectVirtualBases.count(RT))
5194 continue;
5195
5196 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5197 // If our base class is invalid, we probably can't get its dtor anyway.
5198 if (BaseClassDecl->isInvalidDecl())
5199 continue;
5200 if (BaseClassDecl->hasIrrelevantDestructor())
5201 continue;
5202
5203 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5204 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5204, __extension__ __PRETTY_FUNCTION__))
;
5205 if (CheckDestructorAccess(
5206 ClassDecl->getLocation(), Dtor,
5207 PDiag(diag::err_access_dtor_vbase)
5208 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5209 Context.getTypeDeclType(ClassDecl)) ==
5210 AR_accessible) {
5211 CheckDerivedToBaseConversion(
5212 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5213 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5214 SourceRange(), DeclarationName(), nullptr);
5215 }
5216
5217 MarkFunctionReferenced(Location, Dtor);
5218 DiagnoseUseOfDecl(Dtor, Location);
5219 }
5220}
5221
5222void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5223 if (!CDtorDecl)
5224 return;
5225
5226 if (CXXConstructorDecl *Constructor
5227 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5228 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5229 DiagnoseUninitializedFields(*this, Constructor);
5230 }
5231}
5232
5233bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5234 if (!getLangOpts().CPlusPlus)
5235 return false;
5236
5237 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5238 if (!RD)
5239 return false;
5240
5241 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5242 // class template specialization here, but doing so breaks a lot of code.
5243
5244 // We can't answer whether something is abstract until it has a
5245 // definition. If it's currently being defined, we'll walk back
5246 // over all the declarations when we have a full definition.
5247 const CXXRecordDecl *Def = RD->getDefinition();
5248 if (!Def || Def->isBeingDefined())
5249 return false;
5250
5251 return RD->isAbstract();
5252}
5253
5254bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5255 TypeDiagnoser &Diagnoser) {
5256 if (!isAbstractType(Loc, T))
5257 return false;
5258
5259 T = Context.getBaseElementType(T);
5260 Diagnoser.diagnose(*this, Loc, T);
5261 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5262 return true;
5263}
5264
5265void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5266 // Check if we've already emitted the list of pure virtual functions
5267 // for this class.
5268 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5269 return;
5270
5271 // If the diagnostic is suppressed, don't emit the notes. We're only
5272 // going to emit them once, so try to attach them to a diagnostic we're
5273 // actually going to show.
5274 if (Diags.isLastDiagnosticIgnored())
5275 return;
5276
5277 CXXFinalOverriderMap FinalOverriders;
5278 RD->getFinalOverriders(FinalOverriders);
5279
5280 // Keep a set of seen pure methods so we won't diagnose the same method
5281 // more than once.
5282 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5283
5284 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5285 MEnd = FinalOverriders.end();
5286 M != MEnd;
5287 ++M) {
5288 for (OverridingMethods::iterator SO = M->second.begin(),
5289 SOEnd = M->second.end();
5290 SO != SOEnd; ++SO) {
5291 // C++ [class.abstract]p4:
5292 // A class is abstract if it contains or inherits at least one
5293 // pure virtual function for which the final overrider is pure
5294 // virtual.
5295
5296 //
5297 if (SO->second.size() != 1)
5298 continue;
5299
5300 if (!SO->second.front().Method->isPure())
5301 continue;
5302
5303 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5304 continue;
5305
5306 Diag(SO->second.front().Method->getLocation(),
5307 diag::note_pure_virtual_function)
5308 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5309 }
5310 }
5311
5312 if (!PureVirtualClassDiagSet)
5313 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5314 PureVirtualClassDiagSet->insert(RD);
5315}
5316
5317namespace {
5318struct AbstractUsageInfo {
5319 Sema &S;
5320 CXXRecordDecl *Record;
5321 CanQualType AbstractType;
5322 bool Invalid;
5323
5324 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5325 : S(S), Record(Record),
5326 AbstractType(S.Context.getCanonicalType(
5327 S.Context.getTypeDeclType(Record))),
5328 Invalid(false) {}
5329
5330 void DiagnoseAbstractType() {
5331 if (Invalid) return;
5332 S.DiagnoseAbstractType(Record);
5333 Invalid = true;
5334 }
5335
5336 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5337};
5338
5339struct CheckAbstractUsage {
5340 AbstractUsageInfo &Info;
5341 const NamedDecl *Ctx;
5342
5343 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5344 : Info(Info), Ctx(Ctx) {}
5345
5346 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5347 switch (TL.getTypeLocClass()) {
5348#define ABSTRACT_TYPELOC(CLASS, PARENT)
5349#define TYPELOC(CLASS, PARENT) \
5350 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5351#include "clang/AST/TypeLocNodes.def"
5352 }
5353 }
5354
5355 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5356 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5357 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5358 if (!TL.getParam(I))
5359 continue;
5360
5361 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5362 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5363 }
5364 }
5365
5366 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5367 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5368 }
5369
5370 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5371 // Visit the type parameters from a permissive context.
5372 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5373 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5374 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5375 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5376 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5377 // TODO: other template argument types?
5378 }
5379 }
5380
5381 // Visit pointee types from a permissive context.
5382#define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc
(), Sema::AbstractNone); }
\
5383 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5384 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5385 }
5386 CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5387 CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5388 CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5389 CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5390 CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5391
5392 /// Handle all the types we haven't given a more specific
5393 /// implementation for above.
5394 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5395 // Every other kind of type that we haven't called out already
5396 // that has an inner type is either (1) sugar or (2) contains that
5397 // inner type in some way as a subobject.
5398 if (TypeLoc Next = TL.getNextTypeLoc())
5399 return Visit(Next, Sel);
5400
5401 // If there's no inner type and we're in a permissive context,
5402 // don't diagnose.
5403 if (Sel == Sema::AbstractNone) return;
5404
5405 // Check whether the type matches the abstract type.
5406 QualType T = TL.getType();
5407 if (T->isArrayType()) {
5408 Sel = Sema::AbstractArrayType;
5409 T = Info.S.Context.getBaseElementType(T);
5410 }
5411 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5412 if (CT != Info.AbstractType) return;
5413
5414 // It matched; do some magic.
5415 if (Sel == Sema::AbstractArrayType) {
5416 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5417 << T << TL.getSourceRange();
5418 } else {
5419 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5420 << Sel << T << TL.getSourceRange();
5421 }
5422 Info.DiagnoseAbstractType();
5423 }
5424};
5425
5426void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5427 Sema::AbstractDiagSelID Sel) {
5428 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5429}
5430
5431}
5432
5433/// Check for invalid uses of an abstract type in a method declaration.
5434static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5435 CXXMethodDecl *MD) {
5436 // No need to do the check on definitions, which require that
5437 // the return/param types be complete.
5438 if (MD->doesThisDeclarationHaveABody())
5439 return;
5440
5441 // For safety's sake, just ignore it if we don't have type source
5442 // information. This should never happen for non-implicit methods,
5443 // but...
5444 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5445 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5446}
5447
5448/// Check for invalid uses of an abstract type within a class definition.
5449static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5450 CXXRecordDecl *RD) {
5451 for (auto *D : RD->decls()) {
5452 if (D->isImplicit()) continue;
5453
5454 // Methods and method templates.
5455 if (isa<CXXMethodDecl>(D)) {
5456 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5457 } else if (isa<FunctionTemplateDecl>(D)) {
5458 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5459 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5460
5461 // Fields and static variables.
5462 } else if (isa<FieldDecl>(D)) {
5463 FieldDecl *FD = cast<FieldDecl>(D);
5464 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5465 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5466 } else if (isa<VarDecl>(D)) {
5467 VarDecl *VD = cast<VarDecl>(D);
5468 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5469 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5470
5471 // Nested classes and class templates.
5472 } else if (isa<CXXRecordDecl>(D)) {
5473 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5474 } else if (isa<ClassTemplateDecl>(D)) {
5475 CheckAbstractClassUsage(Info,
5476 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5477 }
5478 }
5479}
5480
5481static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5482 Attr *ClassAttr = getDLLAttr(Class);
5483 if (!ClassAttr)
5484 return;
5485
5486 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5486, __extension__ __PRETTY_FUNCTION__))
;
5487
5488 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5489
5490 if (TSK == TSK_ExplicitInstantiationDeclaration)
5491 // Don't go any further if this is just an explicit instantiation
5492 // declaration.
5493 return;
5494
5495 for (Decl *Member : Class->decls()) {
5496 // Defined static variables that are members of an exported base
5497 // class must be marked export too.
5498 auto *VD = dyn_cast<VarDecl>(Member);
5499 if (VD && Member->getAttr<DLLExportAttr>() &&
5500 VD->getStorageClass() == SC_Static &&
5501 TSK == TSK_ImplicitInstantiation)
5502 S.MarkVariableReferenced(VD->getLocation(), VD);
5503
5504 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5505 if (!MD)
5506 continue;
5507
5508 if (Member->getAttr<DLLExportAttr>()) {
5509 if (MD->isUserProvided()) {
5510 // Instantiate non-default class member functions ...
5511
5512 // .. except for certain kinds of template specializations.
5513 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5514 continue;
5515
5516 S.MarkFunctionReferenced(Class->getLocation(), MD);
5517
5518 // The function will be passed to the consumer when its definition is
5519 // encountered.
5520 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5521 MD->isCopyAssignmentOperator() ||
5522 MD->isMoveAssignmentOperator()) {
5523 // Synthesize and instantiate non-trivial implicit methods, explicitly
5524 // defaulted methods, and the copy and move assignment operators. The
5525 // latter are exported even if they are trivial, because the address of
5526 // an operator can be taken and should compare equal across libraries.
5527 DiagnosticErrorTrap Trap(S.Diags);
5528 S.MarkFunctionReferenced(Class->getLocation(), MD);
5529 if (Trap.hasErrorOccurred()) {
5530 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5531 << Class << !S.getLangOpts().CPlusPlus11;
5532 break;
5533 }
5534
5535 // There is no later point when we will see the definition of this
5536 // function, so pass it to the consumer now.
5537 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5538 }
5539 }
5540 }
5541}
5542
5543static void checkForMultipleExportedDefaultConstructors(Sema &S,
5544 CXXRecordDecl *Class) {
5545 // Only the MS ABI has default constructor closures, so we don't need to do
5546 // this semantic checking anywhere else.
5547 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5548 return;
5549
5550 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5551 for (Decl *Member : Class->decls()) {
5552 // Look for exported default constructors.
5553 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5554 if (!CD || !CD->isDefaultConstructor())
5555 continue;
5556 auto *Attr = CD->getAttr<DLLExportAttr>();
5557 if (!Attr)
5558 continue;
5559
5560 // If the class is non-dependent, mark the default arguments as ODR-used so
5561 // that we can properly codegen the constructor closure.
5562 if (!Class->isDependentContext()) {
5563 for (ParmVarDecl *PD : CD->parameters()) {
5564 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5565 S.DiscardCleanupsInEvaluationContext();
5566 }
5567 }
5568
5569 if (LastExportedDefaultCtor) {
5570 S.Diag(LastExportedDefaultCtor->getLocation(),
5571 diag::err_attribute_dll_ambiguous_default_ctor)
5572 << Class;
5573 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5574 << CD->getDeclName();
5575 return;
5576 }
5577 LastExportedDefaultCtor = CD;
5578 }
5579}
5580
5581void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5582 // Mark any compiler-generated routines with the implicit code_seg attribute.
5583 for (auto *Method : Class->methods()) {
5584 if (Method->isUserProvided())
5585 continue;
5586 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5587 Method->addAttr(A);
5588 }
5589}
5590
5591/// Check class-level dllimport/dllexport attribute.
5592void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5593 Attr *ClassAttr = getDLLAttr(Class);
5594
5595 // MSVC inherits DLL attributes to partial class template specializations.
5596 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5597 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5598 if (Attr *TemplateAttr =
5599 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5600 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5601 A->setInherited(true);
5602 ClassAttr = A;
5603 }
5604 }
5605 }
5606
5607 if (!ClassAttr)
5608 return;
5609
5610 if (!Class->isExternallyVisible()) {
5611 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5612 << Class << ClassAttr;
5613 return;
5614 }
5615
5616 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5617 !ClassAttr->isInherited()) {
5618 // Diagnose dll attributes on members of class with dll attribute.
5619 for (Decl *Member : Class->decls()) {
5620 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5621 continue;
5622 InheritableAttr *MemberAttr = getDLLAttr(Member);
5623 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5624 continue;
5625
5626 Diag(MemberAttr->getLocation(),
5627 diag::err_attribute_dll_member_of_dll_class)
5628 << MemberAttr << ClassAttr;
5629 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5630 Member->setInvalidDecl();
5631 }
5632 }
5633
5634 if (Class->getDescribedClassTemplate())
5635 // Don't inherit dll attribute until the template is instantiated.
5636 return;
5637
5638 // The class is either imported or exported.
5639 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5640
5641 // Check if this was a dllimport attribute propagated from a derived class to
5642 // a base class template specialization. We don't apply these attributes to
5643 // static data members.
5644 const bool PropagatedImport =
5645 !ClassExported &&
5646 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5647
5648 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5649
5650 // Ignore explicit dllexport on explicit class template instantiation declarations.
5651 if (ClassExported && !ClassAttr->isInherited() &&
5652 TSK == TSK_ExplicitInstantiationDeclaration) {
5653 Class->dropAttr<DLLExportAttr>();
5654 return;
5655 }
5656
5657 // Force declaration of implicit members so they can inherit the attribute.
5658 ForceDeclarationOfImplicitMembers(Class);
5659
5660 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5661 // seem to be true in practice?
5662
5663 for (Decl *Member : Class->decls()) {
5664 VarDecl *VD = dyn_cast<VarDecl>(Member);
5665 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5666
5667 // Only methods and static fields inherit the attributes.
5668 if (!VD && !MD)
5669 continue;
5670
5671 if (MD) {
5672 // Don't process deleted methods.
5673 if (MD->isDeleted())
5674 continue;
5675
5676 if (MD->isInlined()) {
5677 // MinGW does not import or export inline methods.
5678 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5679 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5680 continue;
5681
5682 // MSVC versions before 2015 don't export the move assignment operators
5683 // and move constructor, so don't attempt to import/export them if
5684 // we have a definition.
5685 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5686 if ((MD->isMoveAssignmentOperator() ||
5687 (Ctor && Ctor->isMoveConstructor())) &&
5688 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5689 continue;
5690
5691 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5692 // operator is exported anyway.
5693 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5694 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5695 continue;
5696 }
5697 }
5698
5699 // Don't apply dllimport attributes to static data members of class template
5700 // instantiations when the attribute is propagated from a derived class.
5701 if (VD && PropagatedImport)
5702 continue;
5703
5704 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5705 continue;
5706
5707 if (!getDLLAttr(Member)) {
5708 auto *NewAttr =
5709 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5710 NewAttr->setInherited(true);
5711 Member->addAttr(NewAttr);
5712
5713 if (MD) {
5714 // Propagate DLLAttr to friend re-declarations of MD that have already
5715 // been constructed.
5716 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5717 FD = FD->getPreviousDecl()) {
5718 if (FD->getFriendObjectKind() == Decl::FOK_None)
5719 continue;
5720 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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5721, __extension__ __PRETTY_FUNCTION__))
5721 "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~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5721, __extension__ __PRETTY_FUNCTION__))
;
5722 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5723 NewAttr->setInherited(true);
5724 FD->addAttr(NewAttr);
5725 }
5726 }
5727 }
5728 }
5729
5730 if (ClassExported)
5731 DelayedDllExportClasses.push_back(Class);
5732}
5733
5734/// Perform propagation of DLL attributes from a derived class to a
5735/// templated base class for MS compatibility.
5736void Sema::propagateDLLAttrToBaseClassTemplate(
5737 CXXRecordDecl *Class, Attr *ClassAttr,
5738 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5739 if (getDLLAttr(
5740 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5741 // If the base class template has a DLL attribute, don't try to change it.
5742 return;
5743 }
5744
5745 auto TSK = BaseTemplateSpec->getSpecializationKind();
5746 if (!getDLLAttr(BaseTemplateSpec) &&
5747 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5748 TSK == TSK_ImplicitInstantiation)) {
5749 // The template hasn't been instantiated yet (or it has, but only as an
5750 // explicit instantiation declaration or implicit instantiation, which means
5751 // we haven't codegenned any members yet), so propagate the attribute.
5752 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5753 NewAttr->setInherited(true);
5754 BaseTemplateSpec->addAttr(NewAttr);
5755
5756 // If this was an import, mark that we propagated it from a derived class to
5757 // a base class template specialization.
5758 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5759 ImportAttr->setPropagatedToBaseTemplate();
5760
5761 // If the template is already instantiated, checkDLLAttributeRedeclaration()
5762 // needs to be run again to work see the new attribute. Otherwise this will
5763 // get run whenever the template is instantiated.
5764 if (TSK != TSK_Undeclared)
5765 checkClassLevelDLLAttribute(BaseTemplateSpec);
5766
5767 return;
5768 }
5769
5770 if (getDLLAttr(BaseTemplateSpec)) {
5771 // The template has already been specialized or instantiated with an
5772 // attribute, explicitly or through propagation. We should not try to change
5773 // it.
5774 return;
5775 }
5776
5777 // The template was previously instantiated or explicitly specialized without
5778 // a dll attribute, It's too late for us to add an attribute, so warn that
5779 // this is unsupported.
5780 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5781 << BaseTemplateSpec->isExplicitSpecialization();
5782 Diag(ClassAttr->getLocation(), diag::note_attribute);
5783 if (BaseTemplateSpec->isExplicitSpecialization()) {
5784 Diag(BaseTemplateSpec->getLocation(),
5785 diag::note_template_class_explicit_specialization_was_here)
5786 << BaseTemplateSpec;
5787 } else {
5788 Diag(BaseTemplateSpec->getPointOfInstantiation(),
5789 diag::note_template_class_instantiation_was_here)
5790 << BaseTemplateSpec;
5791 }
5792}
5793
5794static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5795 SourceLocation DefaultLoc) {
5796 switch (S.getSpecialMember(MD)) {
5797 case Sema::CXXDefaultConstructor:
5798 S.DefineImplicitDefaultConstructor(DefaultLoc,
5799 cast<CXXConstructorDecl>(MD));
5800 break;
5801 case Sema::CXXCopyConstructor:
5802 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5803 break;
5804 case Sema::CXXCopyAssignment:
5805 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5806 break;
5807 case Sema::CXXDestructor:
5808 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5809 break;
5810 case Sema::CXXMoveConstructor:
5811 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5812 break;
5813 case Sema::CXXMoveAssignment:
5814 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5815 break;
5816 case Sema::CXXInvalid:
5817 llvm_unreachable("Invalid special member.")::llvm::llvm_unreachable_internal("Invalid special member.", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5817)
;
5818 }
5819}
5820
5821/// Determine whether a type is permitted to be passed or returned in
5822/// registers, per C++ [class.temporary]p3.
5823static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5824 TargetInfo::CallingConvKind CCK) {
5825 if (D->isDependentType() || D->isInvalidDecl())
5826 return false;
5827
5828 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5829 // The PS4 platform ABI follows the behavior of Clang 3.2.
5830 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5831 return !D->hasNonTrivialDestructorForCall() &&
5832 !D->hasNonTrivialCopyConstructorForCall();
5833
5834 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
5835 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5836 bool DtorIsTrivialForCall = false;
5837
5838 // If a class has at least one non-deleted, trivial copy constructor, it
5839 // is passed according to the C ABI. Otherwise, it is passed indirectly.
5840 //
5841 // Note: This permits classes with non-trivial copy or move ctors to be
5842 // passed in registers, so long as they *also* have a trivial copy ctor,
5843 // which is non-conforming.
5844 if (D->needsImplicitCopyConstructor()) {
5845 if (!D->defaultedCopyConstructorIsDeleted()) {
5846 if (D->hasTrivialCopyConstructor())
5847 CopyCtorIsTrivial = true;
5848 if (D->hasTrivialCopyConstructorForCall())
5849 CopyCtorIsTrivialForCall = true;
5850 }
5851 } else {
5852 for (const CXXConstructorDecl *CD : D->ctors()) {
5853 if (CD->isCopyConstructor() && !CD->isDeleted()) {
5854 if (CD->isTrivial())
5855 CopyCtorIsTrivial = true;
5856 if (CD->isTrivialForCall())
5857 CopyCtorIsTrivialForCall = true;
5858 }
5859 }
5860 }
5861
5862 if (D->needsImplicitDestructor()) {
5863 if (!D->defaultedDestructorIsDeleted() &&
5864 D->hasTrivialDestructorForCall())
5865 DtorIsTrivialForCall = true;
5866 } else if (const auto *DD = D->getDestructor()) {
5867 if (!DD->isDeleted() && DD->isTrivialForCall())
5868 DtorIsTrivialForCall = true;
5869 }
5870
5871 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5872 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5873 return true;
5874
5875 // If a class has a destructor, we'd really like to pass it indirectly
5876 // because it allows us to elide copies. Unfortunately, MSVC makes that
5877 // impossible for small types, which it will pass in a single register or
5878 // stack slot. Most objects with dtors are large-ish, so handle that early.
5879 // We can't call out all large objects as being indirect because there are
5880 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5881 // how we pass large POD types.
5882
5883 // Note: This permits small classes with nontrivial destructors to be
5884 // passed in registers, which is non-conforming.
5885 if (CopyCtorIsTrivial &&
5886 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64)
5887 return true;
5888 return false;
5889 }
5890
5891 // Per C++ [class.temporary]p3, the relevant condition is:
5892 // each copy constructor, move constructor, and destructor of X is
5893 // either trivial or deleted, and X has at least one non-deleted copy
5894 // or move constructor
5895 bool HasNonDeletedCopyOrMove = false;
5896
5897 if (D->needsImplicitCopyConstructor() &&
5898 !D->defaultedCopyConstructorIsDeleted()) {
5899 if (!D->hasTrivialCopyConstructorForCall())
5900 return false;
5901 HasNonDeletedCopyOrMove = true;
5902 }
5903
5904 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5905 !D->defaultedMoveConstructorIsDeleted()) {
5906 if (!D->hasTrivialMoveConstructorForCall())
5907 return false;
5908 HasNonDeletedCopyOrMove = true;
5909 }
5910
5911 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5912 !D->hasTrivialDestructorForCall())
5913 return false;
5914
5915 for (const CXXMethodDecl *MD : D->methods()) {
5916 if (MD->isDeleted())
5917 continue;
5918
5919 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5920 if (CD && CD->isCopyOrMoveConstructor())
5921 HasNonDeletedCopyOrMove = true;
5922 else if (!isa<CXXDestructorDecl>(MD))
5923 continue;
5924
5925 if (!MD->isTrivialForCall())
5926 return false;
5927 }
5928
5929 return HasNonDeletedCopyOrMove;
5930}
5931
5932/// Perform semantic checks on a class definition that has been
5933/// completing, introducing implicitly-declared members, checking for
5934/// abstract types, etc.
5935void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5936 if (!Record)
5937 return;
5938
5939 if (Record->isAbstract() && !Record->isInvalidDecl()) {
5940 AbstractUsageInfo Info(*this, Record);
5941 CheckAbstractClassUsage(Info, Record);
5942 }
5943
5944 // If this is not an aggregate type and has no user-declared constructor,
5945 // complain about any non-static data members of reference or const scalar
5946 // type, since they will never get initializers.
5947 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5948 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5949 !Record->isLambda()) {
5950 bool Complained = false;
5951 for (const auto *F : Record->fields()) {
5952 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5953 continue;
5954
5955 if (F->getType()->isReferenceType() ||
5956 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5957 if (!Complained) {
5958 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5959 << Record->getTagKind() << Record;
5960 Complained = true;
5961 }
5962
5963 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5964 << F->getType()->isReferenceType()
5965 << F->getDeclName();
5966 }
5967 }
5968 }
5969
5970 if (Record->getIdentifier()) {
5971 // C++ [class.mem]p13:
5972 // If T is the name of a class, then each of the following shall have a
5973 // name different from T:
5974 // - every member of every anonymous union that is a member of class T.
5975 //
5976 // C++ [class.mem]p14:
5977 // In addition, if class T has a user-declared constructor (12.1), every
5978 // non-static data member of class T shall have a name different from T.
5979 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5980 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5981 ++I) {
5982 NamedDecl *D = (*I)->getUnderlyingDecl();
5983 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
5984 Record->hasUserDeclaredConstructor()) ||
5985 isa<IndirectFieldDecl>(D)) {
5986 Diag((*I)->getLocation(), diag::err_member_name_of_class)
5987 << D->getDeclName();
5988 break;
5989 }
5990 }
5991 }
5992
5993 // Warn if the class has virtual methods but non-virtual public destructor.
5994 if (Record->isPolymorphic() && !Record->isDependentType()) {
5995 CXXDestructorDecl *dtor = Record->getDestructor();
5996 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5997 !Record->hasAttr<FinalAttr>())
5998 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5999 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6000 }
6001
6002 if (Record->isAbstract()) {
6003 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6004 Diag(Record->getLocation(), diag::warn_abstract_final_class)
6005 << FA->isSpelledAsSealed();
6006 DiagnoseAbstractType(Record);
6007 }
6008 }
6009
6010 // See if trivial_abi has to be dropped.
6011 if (Record->hasAttr<TrivialABIAttr>())
6012 checkIllFormedTrivialABIStruct(*Record);
6013
6014 // Set HasTrivialSpecialMemberForCall if the record has attribute
6015 // "trivial_abi".
6016 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6017
6018 if (HasTrivialABI)
6019 Record->setHasTrivialSpecialMemberForCall();
6020
6021 bool HasMethodWithOverrideControl = false,
6022 HasOverridingMethodWithoutOverrideControl = false;
6023 if (!Record->isDependentType()) {
6024 for (auto *M : Record->methods()) {
6025 // See if a method overloads virtual methods in a base
6026 // class without overriding any.
6027 if (!M->isStatic())
6028 DiagnoseHiddenVirtualMethods(M);
6029 if (M->hasAttr<OverrideAttr>())
6030 HasMethodWithOverrideControl = true;
6031 else if (M->size_overridden_methods() > 0)
6032 HasOverridingMethodWithoutOverrideControl = true;
6033 // Check whether the explicitly-defaulted special members are valid.
6034 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6035 CheckExplicitlyDefaultedSpecialMember(M);
6036
6037 // For an explicitly defaulted or deleted special member, we defer
6038 // determining triviality until the class is complete. That time is now!
6039 CXXSpecialMember CSM = getSpecialMember(M);
6040 if (!M->isImplicit() && !M->isUserProvided()) {
6041 if (CSM != CXXInvalid) {
6042 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6043 // Inform the class that we've finished declaring this member.
6044 Record->finishedDefaultedOrDeletedMember(M);
6045 M->setTrivialForCall(
6046 HasTrivialABI ||
6047 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6048 Record->setTrivialForCallFlags(M);
6049 }
6050 }
6051
6052 // Set triviality for the purpose of calls if this is a user-provided
6053 // copy/move constructor or destructor.
6054 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6055 CSM == CXXDestructor) && M->isUserProvided()) {
6056 M->setTrivialForCall(HasTrivialABI);
6057 Record->setTrivialForCallFlags(M);
6058 }
6059
6060 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6061 M->hasAttr<DLLExportAttr>()) {
6062 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6063 M->isTrivial() &&
6064 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6065 CSM == CXXDestructor))
6066 M->dropAttr<DLLExportAttr>();
6067
6068 if (M->hasAttr<DLLExportAttr>()) {
6069 DefineImplicitSpecialMember(*this, M, M->getLocation());
6070 ActOnFinishInlineFunctionDef(M);
6071 }
6072 }
6073 }
6074 }
6075
6076 if (HasMethodWithOverrideControl &&
6077 HasOverridingMethodWithoutOverrideControl) {
6078 // At least one method has the 'override' control declared.
6079 // Diagnose all other overridden methods which do not have 'override' specified on them.
6080 for (auto *M : Record->methods())
6081 DiagnoseAbsenceOfOverrideControl(M);
6082 }
6083
6084 // ms_struct is a request to use the same ABI rules as MSVC. Check
6085 // whether this class uses any C++ features that are implemented
6086 // completely differently in MSVC, and if so, emit a diagnostic.
6087 // That diagnostic defaults to an error, but we allow projects to
6088 // map it down to a warning (or ignore it). It's a fairly common
6089 // practice among users of the ms_struct pragma to mass-annotate
6090 // headers, sweeping up a bunch of types that the project doesn't
6091 // really rely on MSVC-compatible layout for. We must therefore
6092 // support "ms_struct except for C++ stuff" as a secondary ABI.
6093 if (Record->isMsStruct(Context) &&
6094 (Record->isPolymorphic() || Record->getNumBases())) {
6095 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6096 }
6097
6098 checkClassLevelDLLAttribute(Record);
6099 checkClassLevelCodeSegAttribute(Record);
6100
6101 bool ClangABICompat4 =
6102 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6103 TargetInfo::CallingConvKind CCK =
6104 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6105 bool CanPass = canPassInRegisters(*this, Record, CCK);
6106
6107 // Do not change ArgPassingRestrictions if it has already been set to
6108 // APK_CanNeverPassInRegs.
6109 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6110 Record->setArgPassingRestrictions(CanPass
6111 ? RecordDecl::APK_CanPassInRegs
6112 : RecordDecl::APK_CannotPassInRegs);
6113
6114 // If canPassInRegisters returns true despite the record having a non-trivial
6115 // destructor, the record is destructed in the callee. This happens only when
6116 // the record or one of its subobjects has a field annotated with trivial_abi
6117 // or a field qualified with ObjC __strong/__weak.
6118 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6119 Record->setParamDestroyedInCallee(true);
6120 else if (Record->hasNonTrivialDestructor())
6121 Record->setParamDestroyedInCallee(CanPass);
6122
6123 if (getLangOpts().ForceEmitVTables) {
6124 // If we want to emit all the vtables, we need to mark it as used. This
6125 // is especially required for cases like vtable assumption loads.
6126 MarkVTableUsed(Record->getInnerLocStart(), Record);
6127 }
6128}
6129
6130/// Look up the special member function that would be called by a special
6131/// member function for a subobject of class type.
6132///
6133/// \param Class The class type of the subobject.
6134/// \param CSM The kind of special member f