Bug Summary

File:tools/clang/lib/Sema/SemaExprCXX.cpp
Warning:line 512, column 7
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 SemaExprCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn361465/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-9~svn361465/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn361465/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn361465/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn361465/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn361465/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn361465=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-05-24-031927-21217-1 -x c++ /build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp -faddrsig
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// Implements semantic analysis for C++ expressions.
11///
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
15#include "TreeTransform.h"
16#include "TypeLocBuilder.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/ASTLambda.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/RecursiveASTVisitor.h"
25#include "clang/AST/TypeLoc.h"
26#include "clang/Basic/AlignedAllocation.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Lex/Preprocessor.h"
30#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ParsedTemplate.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ScopeInfo.h"
36#include "clang/Sema/SemaLambda.h"
37#include "clang/Sema/TemplateDeduction.h"
38#include "llvm/ADT/APInt.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/Support/ErrorHandling.h"
41using namespace clang;
42using namespace sema;
43
44/// Handle the result of the special case name lookup for inheriting
45/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46/// constructor names in member using declarations, even if 'X' is not the
47/// name of the corresponding type.
48ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
49 SourceLocation NameLoc,
50 IdentifierInfo &Name) {
51 NestedNameSpecifier *NNS = SS.getScopeRep();
52
53 // Convert the nested-name-specifier into a type.
54 QualType Type;
55 switch (NNS->getKind()) {
56 case NestedNameSpecifier::TypeSpec:
57 case NestedNameSpecifier::TypeSpecWithTemplate:
58 Type = QualType(NNS->getAsType(), 0);
59 break;
60
61 case NestedNameSpecifier::Identifier:
62 // Strip off the last layer of the nested-name-specifier and build a
63 // typename type for it.
64 assert(NNS->getAsIdentifier() == &Name && "not a constructor name")((NNS->getAsIdentifier() == &Name && "not a constructor name"
) ? static_cast<void> (0) : __assert_fail ("NNS->getAsIdentifier() == &Name && \"not a constructor name\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 64, __PRETTY_FUNCTION__))
;
65 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66 NNS->getAsIdentifier());
67 break;
68
69 case NestedNameSpecifier::Global:
70 case NestedNameSpecifier::Super:
71 case NestedNameSpecifier::Namespace:
72 case NestedNameSpecifier::NamespaceAlias:
73 llvm_unreachable("Nested name specifier is not a type for inheriting ctor")::llvm::llvm_unreachable_internal("Nested name specifier is not a type for inheriting ctor"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 73)
;
74 }
75
76 // This reference to the type is located entirely at the location of the
77 // final identifier in the qualified-id.
78 return CreateParsedType(Type,
79 Context.getTrivialTypeSourceInfo(Type, NameLoc));
80}
81
82ParsedType Sema::getConstructorName(IdentifierInfo &II,
83 SourceLocation NameLoc,
84 Scope *S, CXXScopeSpec &SS,
85 bool EnteringContext) {
86 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
87 assert(CurClass && &II == CurClass->getIdentifier() &&((CurClass && &II == CurClass->getIdentifier()
&& "not a constructor name") ? static_cast<void>
(0) : __assert_fail ("CurClass && &II == CurClass->getIdentifier() && \"not a constructor name\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 88, __PRETTY_FUNCTION__))
88 "not a constructor name")((CurClass && &II == CurClass->getIdentifier()
&& "not a constructor name") ? static_cast<void>
(0) : __assert_fail ("CurClass && &II == CurClass->getIdentifier() && \"not a constructor name\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 88, __PRETTY_FUNCTION__))
;
89
90 // When naming a constructor as a member of a dependent context (eg, in a
91 // friend declaration or an inherited constructor declaration), form an
92 // unresolved "typename" type.
93 if (CurClass->isDependentContext() && !EnteringContext) {
94 QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
95 return ParsedType::make(T);
96 }
97
98 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
99 return ParsedType();
100
101 // Find the injected-class-name declaration. Note that we make no attempt to
102 // diagnose cases where the injected-class-name is shadowed: the only
103 // declaration that can validly shadow the injected-class-name is a
104 // non-static data member, and if the class contains both a non-static data
105 // member and a constructor then it is ill-formed (we check that in
106 // CheckCompletedCXXClass).
107 CXXRecordDecl *InjectedClassName = nullptr;
108 for (NamedDecl *ND : CurClass->lookup(&II)) {
109 auto *RD = dyn_cast<CXXRecordDecl>(ND);
110 if (RD && RD->isInjectedClassName()) {
111 InjectedClassName = RD;
112 break;
113 }
114 }
115 if (!InjectedClassName) {
116 if (!CurClass->isInvalidDecl()) {
117 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
118 // properly. Work around it here for now.
119 Diag(SS.getLastQualifierNameLoc(),
120 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
121 }
122 return ParsedType();
123 }
124
125 QualType T = Context.getTypeDeclType(InjectedClassName);
126 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
127 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
128
129 return ParsedType::make(T);
130}
131
132ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
133 IdentifierInfo &II,
134 SourceLocation NameLoc,
135 Scope *S, CXXScopeSpec &SS,
136 ParsedType ObjectTypePtr,
137 bool EnteringContext) {
138 // Determine where to perform name lookup.
139
140 // FIXME: This area of the standard is very messy, and the current
141 // wording is rather unclear about which scopes we search for the
142 // destructor name; see core issues 399 and 555. Issue 399 in
143 // particular shows where the current description of destructor name
144 // lookup is completely out of line with existing practice, e.g.,
145 // this appears to be ill-formed:
146 //
147 // namespace N {
148 // template <typename T> struct S {
149 // ~S();
150 // };
151 // }
152 //
153 // void f(N::S<int>* s) {
154 // s->N::S<int>::~S();
155 // }
156 //
157 // See also PR6358 and PR6359.
158 // For this reason, we're currently only doing the C++03 version of this
159 // code; the C++0x version has to wait until we get a proper spec.
160 QualType SearchType;
161 DeclContext *LookupCtx = nullptr;
162 bool isDependent = false;
163 bool LookInScope = false;
164
165 if (SS.isInvalid())
166 return nullptr;
167
168 // If we have an object type, it's because we are in a
169 // pseudo-destructor-expression or a member access expression, and
170 // we know what type we're looking for.
171 if (ObjectTypePtr)
172 SearchType = GetTypeFromParser(ObjectTypePtr);
173
174 if (SS.isSet()) {
175 NestedNameSpecifier *NNS = SS.getScopeRep();
176
177 bool AlreadySearched = false;
178 bool LookAtPrefix = true;
179 // C++11 [basic.lookup.qual]p6:
180 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
181 // the type-names are looked up as types in the scope designated by the
182 // nested-name-specifier. Similarly, in a qualified-id of the form:
183 //
184 // nested-name-specifier[opt] class-name :: ~ class-name
185 //
186 // the second class-name is looked up in the same scope as the first.
187 //
188 // Here, we determine whether the code below is permitted to look at the
189 // prefix of the nested-name-specifier.
190 DeclContext *DC = computeDeclContext(SS, EnteringContext);
191 if (DC && DC->isFileContext()) {
192 AlreadySearched = true;
193 LookupCtx = DC;
194 isDependent = false;
195 } else if (DC && isa<CXXRecordDecl>(DC)) {
196 LookAtPrefix = false;
197 LookInScope = true;
198 }
199
200 // The second case from the C++03 rules quoted further above.
201 NestedNameSpecifier *Prefix = nullptr;
202 if (AlreadySearched) {
203 // Nothing left to do.
204 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
205 CXXScopeSpec PrefixSS;
206 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
207 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
208 isDependent = isDependentScopeSpecifier(PrefixSS);
209 } else if (ObjectTypePtr) {
210 LookupCtx = computeDeclContext(SearchType);
211 isDependent = SearchType->isDependentType();
212 } else {
213 LookupCtx = computeDeclContext(SS, EnteringContext);
214 isDependent = LookupCtx && LookupCtx->isDependentContext();
215 }
216 } else if (ObjectTypePtr) {
217 // C++ [basic.lookup.classref]p3:
218 // If the unqualified-id is ~type-name, the type-name is looked up
219 // in the context of the entire postfix-expression. If the type T
220 // of the object expression is of a class type C, the type-name is
221 // also looked up in the scope of class C. At least one of the
222 // lookups shall find a name that refers to (possibly
223 // cv-qualified) T.
224 LookupCtx = computeDeclContext(SearchType);
225 isDependent = SearchType->isDependentType();
226 assert((isDependent || !SearchType->isIncompleteType()) &&(((isDependent || !SearchType->isIncompleteType()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(isDependent || !SearchType->isIncompleteType()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 227, __PRETTY_FUNCTION__))
227 "Caller should have completed object type")(((isDependent || !SearchType->isIncompleteType()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(isDependent || !SearchType->isIncompleteType()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 227, __PRETTY_FUNCTION__))
;
228
229 LookInScope = true;
230 } else {
231 // Perform lookup into the current scope (only).
232 LookInScope = true;
233 }
234
235 TypeDecl *NonMatchingTypeDecl = nullptr;
236 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
237 for (unsigned Step = 0; Step != 2; ++Step) {
238 // Look for the name first in the computed lookup context (if we
239 // have one) and, if that fails to find a match, in the scope (if
240 // we're allowed to look there).
241 Found.clear();
242 if (Step == 0 && LookupCtx) {
243 if (RequireCompleteDeclContext(SS, LookupCtx))
244 return nullptr;
245 LookupQualifiedName(Found, LookupCtx);
246 } else if (Step == 1 && LookInScope && S) {
247 LookupName(Found, S);
248 } else {
249 continue;
250 }
251
252 // FIXME: Should we be suppressing ambiguities here?
253 if (Found.isAmbiguous())
254 return nullptr;
255
256 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
257 QualType T = Context.getTypeDeclType(Type);
258 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
259
260 if (SearchType.isNull() || SearchType->isDependentType() ||
261 Context.hasSameUnqualifiedType(T, SearchType)) {
262 // We found our type!
263
264 return CreateParsedType(T,
265 Context.getTrivialTypeSourceInfo(T, NameLoc));
266 }
267
268 if (!SearchType.isNull())
269 NonMatchingTypeDecl = Type;
270 }
271
272 // If the name that we found is a class template name, and it is
273 // the same name as the template name in the last part of the
274 // nested-name-specifier (if present) or the object type, then
275 // this is the destructor for that class.
276 // FIXME: This is a workaround until we get real drafting for core
277 // issue 399, for which there isn't even an obvious direction.
278 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
279 QualType MemberOfType;
280 if (SS.isSet()) {
281 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
282 // Figure out the type of the context, if it has one.
283 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
284 MemberOfType = Context.getTypeDeclType(Record);
285 }
286 }
287 if (MemberOfType.isNull())
288 MemberOfType = SearchType;
289
290 if (MemberOfType.isNull())
291 continue;
292
293 // We're referring into a class template specialization. If the
294 // class template we found is the same as the template being
295 // specialized, we found what we are looking for.
296 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
297 if (ClassTemplateSpecializationDecl *Spec
298 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
299 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
300 Template->getCanonicalDecl())
301 return CreateParsedType(
302 MemberOfType,
303 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
304 }
305
306 continue;
307 }
308
309 // We're referring to an unresolved class template
310 // specialization. Determine whether we class template we found
311 // is the same as the template being specialized or, if we don't
312 // know which template is being specialized, that it at least
313 // has the same name.
314 if (const TemplateSpecializationType *SpecType
315 = MemberOfType->getAs<TemplateSpecializationType>()) {
316 TemplateName SpecName = SpecType->getTemplateName();
317
318 // The class template we found is the same template being
319 // specialized.
320 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
321 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
322 return CreateParsedType(
323 MemberOfType,
324 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
325
326 continue;
327 }
328
329 // The class template we found has the same name as the
330 // (dependent) template name being specialized.
331 if (DependentTemplateName *DepTemplate
332 = SpecName.getAsDependentTemplateName()) {
333 if (DepTemplate->isIdentifier() &&
334 DepTemplate->getIdentifier() == Template->getIdentifier())
335 return CreateParsedType(
336 MemberOfType,
337 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
338
339 continue;
340 }
341 }
342 }
343 }
344
345 if (isDependent) {
346 // We didn't find our type, but that's okay: it's dependent
347 // anyway.
348
349 // FIXME: What if we have no nested-name-specifier?
350 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
351 SS.getWithLocInContext(Context),
352 II, NameLoc);
353 return ParsedType::make(T);
354 }
355
356 if (NonMatchingTypeDecl) {
357 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
358 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
359 << T << SearchType;
360 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
361 << T;
362 } else if (ObjectTypePtr)
363 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
364 << &II;
365 else {
366 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
367 diag::err_destructor_class_name);
368 if (S) {
369 const DeclContext *Ctx = S->getEntity();
370 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
371 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
372 Class->getNameAsString());
373 }
374 }
375
376 return nullptr;
377}
378
379ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
380 ParsedType ObjectType) {
381 if (DS.getTypeSpecType() == DeclSpec::TST_error)
382 return nullptr;
383
384 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
385 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
386 return nullptr;
387 }
388
389 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&((DS.getTypeSpecType() == DeclSpec::TST_decltype && "unexpected type in getDestructorType"
) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 390, __PRETTY_FUNCTION__))
390 "unexpected type in getDestructorType")((DS.getTypeSpecType() == DeclSpec::TST_decltype && "unexpected type in getDestructorType"
) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 390, __PRETTY_FUNCTION__))
;
391 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
392
393 // If we know the type of the object, check that the correct destructor
394 // type was named now; we can give better diagnostics this way.
395 QualType SearchType = GetTypeFromParser(ObjectType);
396 if (!SearchType.isNull() && !SearchType->isDependentType() &&
397 !Context.hasSameUnqualifiedType(T, SearchType)) {
398 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
399 << T << SearchType;
400 return nullptr;
401 }
402
403 return ParsedType::make(T);
404}
405
406bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
407 const UnqualifiedId &Name) {
408 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId)((Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) ?
static_cast<void> (0) : __assert_fail ("Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 408, __PRETTY_FUNCTION__))
;
409
410 if (!SS.isValid())
411 return false;
412
413 switch (SS.getScopeRep()->getKind()) {
414 case NestedNameSpecifier::Identifier:
415 case NestedNameSpecifier::TypeSpec:
416 case NestedNameSpecifier::TypeSpecWithTemplate:
417 // Per C++11 [over.literal]p2, literal operators can only be declared at
418 // namespace scope. Therefore, this unqualified-id cannot name anything.
419 // Reject it early, because we have no AST representation for this in the
420 // case where the scope is dependent.
421 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
422 << SS.getScopeRep();
423 return true;
424
425 case NestedNameSpecifier::Global:
426 case NestedNameSpecifier::Super:
427 case NestedNameSpecifier::Namespace:
428 case NestedNameSpecifier::NamespaceAlias:
429 return false;
430 }
431
432 llvm_unreachable("unknown nested name specifier kind")::llvm::llvm_unreachable_internal("unknown nested name specifier kind"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 432)
;
433}
434
435/// Build a C++ typeid expression with a type operand.
436ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
437 SourceLocation TypeidLoc,
438 TypeSourceInfo *Operand,
439 SourceLocation RParenLoc) {
440 // C++ [expr.typeid]p4:
441 // The top-level cv-qualifiers of the lvalue expression or the type-id
442 // that is the operand of typeid are always ignored.
443 // If the type of the type-id is a class type or a reference to a class
444 // type, the class shall be completely-defined.
445 Qualifiers Quals;
446 QualType T
447 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
448 Quals);
449 if (T->getAs<RecordType>() &&
450 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
451 return ExprError();
452
453 if (T->isVariablyModifiedType())
454 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
455
456 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
457 SourceRange(TypeidLoc, RParenLoc));
458}
459
460/// Build a C++ typeid expression with an expression operand.
461ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
462 SourceLocation TypeidLoc,
463 Expr *E,
464 SourceLocation RParenLoc) {
465 bool WasEvaluated = false;
466 if (E && !E->isTypeDependent()) {
13
Assuming 'E' is null
467 if (E->getType()->isPlaceholderType()) {
468 ExprResult result = CheckPlaceholderExpr(E);
469 if (result.isInvalid()) return ExprError();
470 E = result.get();
471 }
472
473 QualType T = E->getType();
474 if (const RecordType *RecordT = T->getAs<RecordType>()) {
475 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
476 // C++ [expr.typeid]p3:
477 // [...] If the type of the expression is a class type, the class
478 // shall be completely-defined.
479 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
480 return ExprError();
481
482 // C++ [expr.typeid]p3:
483 // When typeid is applied to an expression other than an glvalue of a
484 // polymorphic class type [...] [the] expression is an unevaluated
485 // operand. [...]
486 if (RecordD->isPolymorphic() && E->isGLValue()) {
487 // The subexpression is potentially evaluated; switch the context
488 // and recheck the subexpression.
489 ExprResult Result = TransformToPotentiallyEvaluated(E);
490 if (Result.isInvalid()) return ExprError();
491 E = Result.get();
492
493 // We require a vtable to query the type at run time.
494 MarkVTableUsed(TypeidLoc, RecordD);
495 WasEvaluated = true;
496 }
497 }
498
499 // C++ [expr.typeid]p4:
500 // [...] If the type of the type-id is a reference to a possibly
501 // cv-qualified type, the result of the typeid expression refers to a
502 // std::type_info object representing the cv-unqualified referenced
503 // type.
504 Qualifiers Quals;
505 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
506 if (!Context.hasSameType(T, UnqualT)) {
507 T = UnqualT;
508 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
509 }
510 }
511
512 if (E->getType()->isVariablyModifiedType())
14
Called C++ object pointer is null
513 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
514 << E->getType());
515 else if (!inTemplateInstantiation() &&
516 E->HasSideEffects(Context, WasEvaluated)) {
517 // The expression operand for typeid is in an unevaluated expression
518 // context, so side effects could result in unintended consequences.
519 Diag(E->getExprLoc(), WasEvaluated
520 ? diag::warn_side_effects_typeid
521 : diag::warn_side_effects_unevaluated_context);
522 }
523
524 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
525 SourceRange(TypeidLoc, RParenLoc));
526}
527
528/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
529ExprResult
530Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
531 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
532 // OpenCL C++ 1.0 s2.9: typeid is not supported.
533 if (getLangOpts().OpenCLCPlusPlus) {
1
Assuming the condition is false
2
Taking false branch
534 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
535 << "typeid");
536 }
537
538 // Find the std::type_info type.
539 if (!getStdNamespace())
3
Assuming the condition is false
4
Taking false branch
540 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
541
542 if (!CXXTypeInfoDecl) {
5
Assuming the condition is false
6
Taking false branch
543 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
544 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
545 LookupQualifiedName(R, getStdNamespace());
546 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
547 // Microsoft's typeinfo doesn't have type_info in std but in the global
548 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
549 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
550 LookupQualifiedName(R, Context.getTranslationUnitDecl());
551 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
552 }
553 if (!CXXTypeInfoDecl)
554 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
555 }
556
557 if (!getLangOpts().RTTI) {
7
Assuming the condition is false
8
Taking false branch
558 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
559 }
560
561 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
562
563 if (isType) {
9
Assuming 'isType' is 0
10
Taking false branch
564 // The operand is a type; handle it as such.
565 TypeSourceInfo *TInfo = nullptr;
566 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
567 &TInfo);
568 if (T.isNull())
569 return ExprError();
570
571 if (!TInfo)
572 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
573
574 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
575 }
576
577 // The operand is an expression.
578 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
11
Passing value via 3rd parameter 'E'
12
Calling 'Sema::BuildCXXTypeId'
579}
580
581/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
582/// a single GUID.
583static void
584getUuidAttrOfType(Sema &SemaRef, QualType QT,
585 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
586 // Optionally remove one level of pointer, reference or array indirection.
587 const Type *Ty = QT.getTypePtr();
588 if (QT->isPointerType() || QT->isReferenceType())
589 Ty = QT->getPointeeType().getTypePtr();
590 else if (QT->isArrayType())
591 Ty = Ty->getBaseElementTypeUnsafe();
592
593 const auto *TD = Ty->getAsTagDecl();
594 if (!TD)
595 return;
596
597 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
598 UuidAttrs.insert(Uuid);
599 return;
600 }
601
602 // __uuidof can grab UUIDs from template arguments.
603 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
604 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
605 for (const TemplateArgument &TA : TAL.asArray()) {
606 const UuidAttr *UuidForTA = nullptr;
607 if (TA.getKind() == TemplateArgument::Type)
608 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
609 else if (TA.getKind() == TemplateArgument::Declaration)
610 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
611
612 if (UuidForTA)
613 UuidAttrs.insert(UuidForTA);
614 }
615 }
616}
617
618/// Build a Microsoft __uuidof expression with a type operand.
619ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
620 SourceLocation TypeidLoc,
621 TypeSourceInfo *Operand,
622 SourceLocation RParenLoc) {
623 StringRef UuidStr;
624 if (!Operand->getType()->isDependentType()) {
625 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
626 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
627 if (UuidAttrs.empty())
628 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
629 if (UuidAttrs.size() > 1)
630 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
631 UuidStr = UuidAttrs.back()->getGuid();
632 }
633
634 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
635 SourceRange(TypeidLoc, RParenLoc));
636}
637
638/// Build a Microsoft __uuidof expression with an expression operand.
639ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
640 SourceLocation TypeidLoc,
641 Expr *E,
642 SourceLocation RParenLoc) {
643 StringRef UuidStr;
644 if (!E->getType()->isDependentType()) {
645 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
646 UuidStr = "00000000-0000-0000-0000-000000000000";
647 } else {
648 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
649 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
650 if (UuidAttrs.empty())
651 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
652 if (UuidAttrs.size() > 1)
653 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
654 UuidStr = UuidAttrs.back()->getGuid();
655 }
656 }
657
658 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
659 SourceRange(TypeidLoc, RParenLoc));
660}
661
662/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
663ExprResult
664Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
665 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
666 // If MSVCGuidDecl has not been cached, do the lookup.
667 if (!MSVCGuidDecl) {
668 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
669 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
670 LookupQualifiedName(R, Context.getTranslationUnitDecl());
671 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
672 if (!MSVCGuidDecl)
673 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
674 }
675
676 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
677
678 if (isType) {
679 // The operand is a type; handle it as such.
680 TypeSourceInfo *TInfo = nullptr;
681 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
682 &TInfo);
683 if (T.isNull())
684 return ExprError();
685
686 if (!TInfo)
687 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
688
689 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
690 }
691
692 // The operand is an expression.
693 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
694}
695
696/// ActOnCXXBoolLiteral - Parse {true,false} literals.
697ExprResult
698Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
699 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&(((Kind == tok::kw_true || Kind == tok::kw_false) && "Unknown C++ Boolean value!"
) ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 700, __PRETTY_FUNCTION__))
700 "Unknown C++ Boolean value!")(((Kind == tok::kw_true || Kind == tok::kw_false) && "Unknown C++ Boolean value!"
) ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 700, __PRETTY_FUNCTION__))
;
701 return new (Context)
702 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
703}
704
705/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
706ExprResult
707Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
708 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
709}
710
711/// ActOnCXXThrow - Parse throw expressions.
712ExprResult
713Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
714 bool IsThrownVarInScope = false;
715 if (Ex) {
716 // C++0x [class.copymove]p31:
717 // When certain criteria are met, an implementation is allowed to omit the
718 // copy/move construction of a class object [...]
719 //
720 // - in a throw-expression, when the operand is the name of a
721 // non-volatile automatic object (other than a function or catch-
722 // clause parameter) whose scope does not extend beyond the end of the
723 // innermost enclosing try-block (if there is one), the copy/move
724 // operation from the operand to the exception object (15.1) can be
725 // omitted by constructing the automatic object directly into the
726 // exception object
727 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
728 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
729 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
730 for( ; S; S = S->getParent()) {
731 if (S->isDeclScope(Var)) {
732 IsThrownVarInScope = true;
733 break;
734 }
735
736 if (S->getFlags() &
737 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
738 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
739 Scope::TryScope))
740 break;
741 }
742 }
743 }
744 }
745
746 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
747}
748
749ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
750 bool IsThrownVarInScope) {
751 // Don't report an error if 'throw' is used in system headers.
752 if (!getLangOpts().CXXExceptions &&
753 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
754 // Delay error emission for the OpenMP device code.
755 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
756 }
757
758 // Exceptions aren't allowed in CUDA device code.
759 if (getLangOpts().CUDA)
760 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
761 << "throw" << CurrentCUDATarget();
762
763 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
764 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
765
766 if (Ex && !Ex->isTypeDependent()) {
767 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
768 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
769 return ExprError();
770
771 // Initialize the exception result. This implicitly weeds out
772 // abstract types or types with inaccessible copy constructors.
773
774 // C++0x [class.copymove]p31:
775 // When certain criteria are met, an implementation is allowed to omit the
776 // copy/move construction of a class object [...]
777 //
778 // - in a throw-expression, when the operand is the name of a
779 // non-volatile automatic object (other than a function or
780 // catch-clause
781 // parameter) whose scope does not extend beyond the end of the
782 // innermost enclosing try-block (if there is one), the copy/move
783 // operation from the operand to the exception object (15.1) can be
784 // omitted by constructing the automatic object directly into the
785 // exception object
786 const VarDecl *NRVOVariable = nullptr;
787 if (IsThrownVarInScope)
788 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
789
790 InitializedEntity Entity = InitializedEntity::InitializeException(
791 OpLoc, ExceptionObjectTy,
792 /*NRVO=*/NRVOVariable != nullptr);
793 ExprResult Res = PerformMoveOrCopyInitialization(
794 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
795 if (Res.isInvalid())
796 return ExprError();
797 Ex = Res.get();
798 }
799
800 return new (Context)
801 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
802}
803
804static void
805collectPublicBases(CXXRecordDecl *RD,
806 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
807 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
808 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
809 bool ParentIsPublic) {
810 for (const CXXBaseSpecifier &BS : RD->bases()) {
811 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
812 bool NewSubobject;
813 // Virtual bases constitute the same subobject. Non-virtual bases are
814 // always distinct subobjects.
815 if (BS.isVirtual())
816 NewSubobject = VBases.insert(BaseDecl).second;
817 else
818 NewSubobject = true;
819
820 if (NewSubobject)
821 ++SubobjectsSeen[BaseDecl];
822
823 // Only add subobjects which have public access throughout the entire chain.
824 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
825 if (PublicPath)
826 PublicSubobjectsSeen.insert(BaseDecl);
827
828 // Recurse on to each base subobject.
829 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
830 PublicPath);
831 }
832}
833
834static void getUnambiguousPublicSubobjects(
835 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
836 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
837 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
838 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
839 SubobjectsSeen[RD] = 1;
840 PublicSubobjectsSeen.insert(RD);
841 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
842 /*ParentIsPublic=*/true);
843
844 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
845 // Skip ambiguous objects.
846 if (SubobjectsSeen[PublicSubobject] > 1)
847 continue;
848
849 Objects.push_back(PublicSubobject);
850 }
851}
852
853/// CheckCXXThrowOperand - Validate the operand of a throw.
854bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
855 QualType ExceptionObjectTy, Expr *E) {
856 // If the type of the exception would be an incomplete type or a pointer
857 // to an incomplete type other than (cv) void the program is ill-formed.
858 QualType Ty = ExceptionObjectTy;
859 bool isPointer = false;
860 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
861 Ty = Ptr->getPointeeType();
862 isPointer = true;
863 }
864 if (!isPointer || !Ty->isVoidType()) {
865 if (RequireCompleteType(ThrowLoc, Ty,
866 isPointer ? diag::err_throw_incomplete_ptr
867 : diag::err_throw_incomplete,
868 E->getSourceRange()))
869 return true;
870
871 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
872 diag::err_throw_abstract_type, E))
873 return true;
874 }
875
876 // If the exception has class type, we need additional handling.
877 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
878 if (!RD)
879 return false;
880
881 // If we are throwing a polymorphic class type or pointer thereof,
882 // exception handling will make use of the vtable.
883 MarkVTableUsed(ThrowLoc, RD);
884
885 // If a pointer is thrown, the referenced object will not be destroyed.
886 if (isPointer)
887 return false;
888
889 // If the class has a destructor, we must be able to call it.
890 if (!RD->hasIrrelevantDestructor()) {
891 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
892 MarkFunctionReferenced(E->getExprLoc(), Destructor);
893 CheckDestructorAccess(E->getExprLoc(), Destructor,
894 PDiag(diag::err_access_dtor_exception) << Ty);
895 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
896 return true;
897 }
898 }
899
900 // The MSVC ABI creates a list of all types which can catch the exception
901 // object. This list also references the appropriate copy constructor to call
902 // if the object is caught by value and has a non-trivial copy constructor.
903 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
904 // We are only interested in the public, unambiguous bases contained within
905 // the exception object. Bases which are ambiguous or otherwise
906 // inaccessible are not catchable types.
907 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
908 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
909
910 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
911 // Attempt to lookup the copy constructor. Various pieces of machinery
912 // will spring into action, like template instantiation, which means this
913 // cannot be a simple walk of the class's decls. Instead, we must perform
914 // lookup and overload resolution.
915 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
916 if (!CD)
917 continue;
918
919 // Mark the constructor referenced as it is used by this throw expression.
920 MarkFunctionReferenced(E->getExprLoc(), CD);
921
922 // Skip this copy constructor if it is trivial, we don't need to record it
923 // in the catchable type data.
924 if (CD->isTrivial())
925 continue;
926
927 // The copy constructor is non-trivial, create a mapping from this class
928 // type to this constructor.
929 // N.B. The selection of copy constructor is not sensitive to this
930 // particular throw-site. Lookup will be performed at the catch-site to
931 // ensure that the copy constructor is, in fact, accessible (via
932 // friendship or any other means).
933 Context.addCopyConstructorForExceptionObject(Subobject, CD);
934
935 // We don't keep the instantiated default argument expressions around so
936 // we must rebuild them here.
937 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
938 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
939 return true;
940 }
941 }
942 }
943
944 // Under the Itanium C++ ABI, memory for the exception object is allocated by
945 // the runtime with no ability for the compiler to request additional
946 // alignment. Warn if the exception type requires alignment beyond the minimum
947 // guaranteed by the target C++ runtime.
948 if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
949 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
950 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
951 if (ExnObjAlign < TypeAlign) {
952 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
953 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
954 << Ty << (unsigned)TypeAlign.getQuantity()
955 << (unsigned)ExnObjAlign.getQuantity();
956 }
957 }
958
959 return false;
960}
961
962static QualType adjustCVQualifiersForCXXThisWithinLambda(
963 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
964 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
965
966 QualType ClassType = ThisTy->getPointeeType();
967 LambdaScopeInfo *CurLSI = nullptr;
968 DeclContext *CurDC = CurSemaContext;
969
970 // Iterate through the stack of lambdas starting from the innermost lambda to
971 // the outermost lambda, checking if '*this' is ever captured by copy - since
972 // that could change the cv-qualifiers of the '*this' object.
973 // The object referred to by '*this' starts out with the cv-qualifiers of its
974 // member function. We then start with the innermost lambda and iterate
975 // outward checking to see if any lambda performs a by-copy capture of '*this'
976 // - and if so, any nested lambda must respect the 'constness' of that
977 // capturing lamdbda's call operator.
978 //
979
980 // Since the FunctionScopeInfo stack is representative of the lexical
981 // nesting of the lambda expressions during initial parsing (and is the best
982 // place for querying information about captures about lambdas that are
983 // partially processed) and perhaps during instantiation of function templates
984 // that contain lambda expressions that need to be transformed BUT not
985 // necessarily during instantiation of a nested generic lambda's function call
986 // operator (which might even be instantiated at the end of the TU) - at which
987 // time the DeclContext tree is mature enough to query capture information
988 // reliably - we use a two pronged approach to walk through all the lexically
989 // enclosing lambda expressions:
990 //
991 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
992 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
993 // enclosed by the call-operator of the LSI below it on the stack (while
994 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
995 // the stack represents the innermost lambda.
996 //
997 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
998 // represents a lambda's call operator. If it does, we must be instantiating
999 // a generic lambda's call operator (represented by the Current LSI, and
1000 // should be the only scenario where an inconsistency between the LSI and the
1001 // DeclContext should occur), so climb out the DeclContexts if they
1002 // represent lambdas, while querying the corresponding closure types
1003 // regarding capture information.
1004
1005 // 1) Climb down the function scope info stack.
1006 for (int I = FunctionScopes.size();
1007 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1008 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1009 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1010 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1011 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1012
1013 if (!CurLSI->isCXXThisCaptured())
1014 continue;
1015
1016 auto C = CurLSI->getCXXThisCapture();
1017
1018 if (C.isCopyCapture()) {
1019 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1020 if (CurLSI->CallOperator->isConst())
1021 ClassType.addConst();
1022 return ASTCtx.getPointerType(ClassType);
1023 }
1024 }
1025
1026 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1027 // happen during instantiation of its nested generic lambda call operator)
1028 if (isLambdaCallOperator(CurDC)) {
1029 assert(CurLSI && "While computing 'this' capture-type for a generic "((CurLSI && "While computing 'this' capture-type for a generic "
"lambda, we must have a corresponding LambdaScopeInfo") ? static_cast
<void> (0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1030, __PRETTY_FUNCTION__))
1030 "lambda, we must have a corresponding LambdaScopeInfo")((CurLSI && "While computing 'this' capture-type for a generic "
"lambda, we must have a corresponding LambdaScopeInfo") ? static_cast
<void> (0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1030, __PRETTY_FUNCTION__))
;
1031 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1035, __PRETTY_FUNCTION__))
1032 "While computing 'this' capture-type for a generic lambda, when we "((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1035, __PRETTY_FUNCTION__))
1033 "run out of enclosing LSI's, yet the enclosing DC is a "((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1035, __PRETTY_FUNCTION__))
1034 "lambda-call-operator we must be (i.e. Current LSI) in a generic "((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1035, __PRETTY_FUNCTION__))
1035 "lambda call oeprator")((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1035, __PRETTY_FUNCTION__))
;
1036 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator))((CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator
)) ? static_cast<void> (0) : __assert_fail ("CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1036, __PRETTY_FUNCTION__))
;
1037
1038 auto IsThisCaptured =
1039 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1040 IsConst = false;
1041 IsByCopy = false;
1042 for (auto &&C : Closure->captures()) {
1043 if (C.capturesThis()) {
1044 if (C.getCaptureKind() == LCK_StarThis)
1045 IsByCopy = true;
1046 if (Closure->getLambdaCallOperator()->isConst())
1047 IsConst = true;
1048 return true;
1049 }
1050 }
1051 return false;
1052 };
1053
1054 bool IsByCopyCapture = false;
1055 bool IsConstCapture = false;
1056 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1057 while (Closure &&
1058 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1059 if (IsByCopyCapture) {
1060 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1061 if (IsConstCapture)
1062 ClassType.addConst();
1063 return ASTCtx.getPointerType(ClassType);
1064 }
1065 Closure = isLambdaCallOperator(Closure->getParent())
1066 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1067 : nullptr;
1068 }
1069 }
1070 return ASTCtx.getPointerType(ClassType);
1071}
1072
1073QualType Sema::getCurrentThisType() {
1074 DeclContext *DC = getFunctionLevelDeclContext();
1075 QualType ThisTy = CXXThisTypeOverride;
1076
1077 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1078 if (method && method->isInstance())
1079 ThisTy = method->getThisType();
1080 }
1081
1082 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1083 inTemplateInstantiation()) {
1084
1085 assert(isa<CXXRecordDecl>(DC) &&((isa<CXXRecordDecl>(DC) && "Trying to get 'this' type from static method?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(DC) && \"Trying to get 'this' type from static method?\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1086, __PRETTY_FUNCTION__))
1086 "Trying to get 'this' type from static method?")((isa<CXXRecordDecl>(DC) && "Trying to get 'this' type from static method?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(DC) && \"Trying to get 'this' type from static method?\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1086, __PRETTY_FUNCTION__))
;
1087
1088 // This is a lambda call operator that is being instantiated as a default
1089 // initializer. DC must point to the enclosing class type, so we can recover
1090 // the 'this' type from it.
1091
1092 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1093 // There are no cv-qualifiers for 'this' within default initializers,
1094 // per [expr.prim.general]p4.
1095 ThisTy = Context.getPointerType(ClassTy);
1096 }
1097
1098 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1099 // might need to be adjusted if the lambda or any of its enclosing lambda's
1100 // captures '*this' by copy.
1101 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1102 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1103 CurContext, Context);
1104 return ThisTy;
1105}
1106
1107Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1108 Decl *ContextDecl,
1109 Qualifiers CXXThisTypeQuals,
1110 bool Enabled)
1111 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1112{
1113 if (!Enabled || !ContextDecl)
1114 return;
1115
1116 CXXRecordDecl *Record = nullptr;
1117 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1118 Record = Template->getTemplatedDecl();
1119 else
1120 Record = cast<CXXRecordDecl>(ContextDecl);
1121
1122 QualType T = S.Context.getRecordType(Record);
1123 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1124
1125 S.CXXThisTypeOverride = S.Context.getPointerType(T);
1126
1127 this->Enabled = true;
1128}
1129
1130
1131Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1132 if (Enabled) {
1133 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1134 }
1135}
1136
1137static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1138 QualType ThisTy, SourceLocation Loc,
1139 const bool ByCopy) {
1140
1141 QualType AdjustedThisTy = ThisTy;
1142 // The type of the corresponding data member (not a 'this' pointer if 'by
1143 // copy').
1144 QualType CaptureThisFieldTy = ThisTy;
1145 if (ByCopy) {
1146 // If we are capturing the object referred to by '*this' by copy, ignore any
1147 // cv qualifiers inherited from the type of the member function for the type
1148 // of the closure-type's corresponding data member and any use of 'this'.
1149 CaptureThisFieldTy = ThisTy->getPointeeType();
1150 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1151 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1152 }
1153
1154 FieldDecl *Field = FieldDecl::Create(
1155 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1156 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1157 ICIS_NoInit);
1158
1159 Field->setImplicit(true);
1160 Field->setAccess(AS_private);
1161 RD->addDecl(Field);
1162 Expr *This =
1163 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
1164 if (ByCopy) {
1165 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1166 UO_Deref,
1167 This).get();
1168 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1169 nullptr, CaptureThisFieldTy, Loc);
1170 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1171 InitializationSequence Init(S, Entity, InitKind, StarThis);
1172 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1173 if (ER.isInvalid()) return nullptr;
1174 return ER.get();
1175 }
1176 return This;
1177}
1178
1179bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1180 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1181 const bool ByCopy) {
1182 // We don't need to capture this in an unevaluated context.
1183 if (isUnevaluatedContext() && !Explicit)
1184 return true;
1185
1186 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value")(((!ByCopy || Explicit) && "cannot implicitly capture *this by value"
) ? static_cast<void> (0) : __assert_fail ("(!ByCopy || Explicit) && \"cannot implicitly capture *this by value\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1186, __PRETTY_FUNCTION__))
;
1187
1188 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1189 ? *FunctionScopeIndexToStopAt
1190 : FunctionScopes.size() - 1;
1191
1192 // Check that we can capture the *enclosing object* (referred to by '*this')
1193 // by the capturing-entity/closure (lambda/block/etc) at
1194 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1195
1196 // Note: The *enclosing object* can only be captured by-value by a
1197 // closure that is a lambda, using the explicit notation:
1198 // [*this] { ... }.
1199 // Every other capture of the *enclosing object* results in its by-reference
1200 // capture.
1201
1202 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1203 // stack), we can capture the *enclosing object* only if:
1204 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1205 // - or, 'L' has an implicit capture.
1206 // AND
1207 // -- there is no enclosing closure
1208 // -- or, there is some enclosing closure 'E' that has already captured the
1209 // *enclosing object*, and every intervening closure (if any) between 'E'
1210 // and 'L' can implicitly capture the *enclosing object*.
1211 // -- or, every enclosing closure can implicitly capture the
1212 // *enclosing object*
1213
1214
1215 unsigned NumCapturingClosures = 0;
1216 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1217 if (CapturingScopeInfo *CSI =
1218 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1219 if (CSI->CXXThisCaptureIndex != 0) {
1220 // 'this' is already being captured; there isn't anything more to do.
1221 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1222 break;
1223 }
1224 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1225 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1226 // This context can't implicitly capture 'this'; fail out.
1227 if (BuildAndDiagnose)
1228 Diag(Loc, diag::err_this_capture)
1229 << (Explicit && idx == MaxFunctionScopesIndex);
1230 return true;
1231 }
1232 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1233 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1234 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1235 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1236 (Explicit && idx == MaxFunctionScopesIndex)) {
1237 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1238 // iteration through can be an explicit capture, all enclosing closures,
1239 // if any, must perform implicit captures.
1240
1241 // This closure can capture 'this'; continue looking upwards.
1242 NumCapturingClosures++;
1243 continue;
1244 }
1245 // This context can't implicitly capture 'this'; fail out.
1246 if (BuildAndDiagnose)
1247 Diag(Loc, diag::err_this_capture)
1248 << (Explicit && idx == MaxFunctionScopesIndex);
1249 return true;
1250 }
1251 break;
1252 }
1253 if (!BuildAndDiagnose) return false;
1254
1255 // If we got here, then the closure at MaxFunctionScopesIndex on the
1256 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1257 // (including implicit by-reference captures in any enclosing closures).
1258
1259 // In the loop below, respect the ByCopy flag only for the closure requesting
1260 // the capture (i.e. first iteration through the loop below). Ignore it for
1261 // all enclosing closure's up to NumCapturingClosures (since they must be
1262 // implicitly capturing the *enclosing object* by reference (see loop
1263 // above)).
1264 assert((!ByCopy ||(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[
MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? static_cast<void> (0) : __assert_fail
("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1267, __PRETTY_FUNCTION__))
1265 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[
MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? static_cast<void> (0) : __assert_fail
("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1267, __PRETTY_FUNCTION__))
1266 "Only a lambda can capture the enclosing object (referred to by "(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[
MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? static_cast<void> (0) : __assert_fail
("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1267, __PRETTY_FUNCTION__))
1267 "*this) by copy")(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[
MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? static_cast<void> (0) : __assert_fail
("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1267, __PRETTY_FUNCTION__))
;
1268 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1269 // contexts.
1270 QualType ThisTy = getCurrentThisType();
1271 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1272 --idx, --NumCapturingClosures) {
1273 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1274 Expr *ThisExpr = nullptr;
1275
1276 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1277 // For lambda expressions, build a field and an initializing expression,
1278 // and capture the *enclosing object* by copy only if this is the first
1279 // iteration.
1280 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1281 ByCopy && idx == MaxFunctionScopesIndex);
1282
1283 } else if (CapturedRegionScopeInfo *RSI
1284 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
1285 ThisExpr =
1286 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1287 false/*ByCopy*/);
1288
1289 bool isNested = NumCapturingClosures > 1;
1290 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
1291 }
1292 return false;
1293}
1294
1295ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1296 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1297 /// is a non-lvalue expression whose value is the address of the object for
1298 /// which the function is called.
1299
1300 QualType ThisTy = getCurrentThisType();
1301 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
1302
1303 CheckCXXThisCapture(Loc);
1304 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
1305}
1306
1307bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1308 // If we're outside the body of a member function, then we'll have a specified
1309 // type for 'this'.
1310 if (CXXThisTypeOverride.isNull())
1311 return false;
1312
1313 // Determine whether we're looking into a class that's currently being
1314 // defined.
1315 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1316 return Class && Class->isBeingDefined();
1317}
1318
1319/// Parse construction of a specified type.
1320/// Can be interpreted either as function-style casting ("int(x)")
1321/// or class type construction ("ClassType(x,y,z)")
1322/// or creation of a value-initialized type ("int()").
1323ExprResult
1324Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1325 SourceLocation LParenOrBraceLoc,
1326 MultiExprArg exprs,
1327 SourceLocation RParenOrBraceLoc,
1328 bool ListInitialization) {
1329 if (!TypeRep)
1330 return ExprError();
1331
1332 TypeSourceInfo *TInfo;
1333 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1334 if (!TInfo)
1335 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1336
1337 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1338 RParenOrBraceLoc, ListInitialization);
1339 // Avoid creating a non-type-dependent expression that contains typos.
1340 // Non-type-dependent expressions are liable to be discarded without
1341 // checking for embedded typos.
1342 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1343 !Result.get()->isTypeDependent())
1344 Result = CorrectDelayedTyposInExpr(Result.get());
1345 return Result;
1346}
1347
1348ExprResult
1349Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1350 SourceLocation LParenOrBraceLoc,
1351 MultiExprArg Exprs,
1352 SourceLocation RParenOrBraceLoc,
1353 bool ListInitialization) {
1354 QualType Ty = TInfo->getType();
1355 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1356
1357 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
1358 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1359 // directly. We work around this by dropping the locations of the braces.
1360 SourceRange Locs = ListInitialization
1361 ? SourceRange()
1362 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1363 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1364 Exprs, Locs.getEnd());
1365 }
1366
1367 assert((!ListInitialization ||(((!ListInitialization || (Exprs.size() == 1 && isa<
InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression."
) ? static_cast<void> (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1369, __PRETTY_FUNCTION__))
1368 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&(((!ListInitialization || (Exprs.size() == 1 && isa<
InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression."
) ? static_cast<void> (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1369, __PRETTY_FUNCTION__))
1369 "List initialization must have initializer list as expression.")(((!ListInitialization || (Exprs.size() == 1 && isa<
InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression."
) ? static_cast<void> (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1369, __PRETTY_FUNCTION__))
;
1370 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1371
1372 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1373 InitializationKind Kind =
1374 Exprs.size()
1375 ? ListInitialization
1376 ? InitializationKind::CreateDirectList(
1377 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1378 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1379 RParenOrBraceLoc)
1380 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1381 RParenOrBraceLoc);
1382
1383 // C++1z [expr.type.conv]p1:
1384 // If the type is a placeholder for a deduced class type, [...perform class
1385 // template argument deduction...]
1386 DeducedType *Deduced = Ty->getContainedDeducedType();
1387 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1388 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1389 Kind, Exprs);
1390 if (Ty.isNull())
1391 return ExprError();
1392 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1393 }
1394
1395 // C++ [expr.type.conv]p1:
1396 // If the expression list is a parenthesized single expression, the type
1397 // conversion expression is equivalent (in definedness, and if defined in
1398 // meaning) to the corresponding cast expression.
1399 if (Exprs.size() == 1 && !ListInitialization &&
1400 !isa<InitListExpr>(Exprs[0])) {
1401 Expr *Arg = Exprs[0];
1402 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1403 RParenOrBraceLoc);
1404 }
1405
1406 // For an expression of the form T(), T shall not be an array type.
1407 QualType ElemTy = Ty;
1408 if (Ty->isArrayType()) {
1409 if (!ListInitialization)
1410 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1411 << FullRange);
1412 ElemTy = Context.getBaseElementType(Ty);
1413 }
1414
1415 // There doesn't seem to be an explicit rule against this but sanity demands
1416 // we only construct objects with object types.
1417 if (Ty->isFunctionType())
1418 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1419 << Ty << FullRange);
1420
1421 // C++17 [expr.type.conv]p2:
1422 // If the type is cv void and the initializer is (), the expression is a
1423 // prvalue of the specified type that performs no initialization.
1424 if (!Ty->isVoidType() &&
1425 RequireCompleteType(TyBeginLoc, ElemTy,
1426 diag::err_invalid_incomplete_type_use, FullRange))
1427 return ExprError();
1428
1429 // Otherwise, the expression is a prvalue of the specified type whose
1430 // result object is direct-initialized (11.6) with the initializer.
1431 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1432 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1433
1434 if (Result.isInvalid())
1435 return Result;
1436
1437 Expr *Inner = Result.get();
1438 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1439 Inner = BTE->getSubExpr();
1440 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1441 !isa<CXXScalarValueInitExpr>(Inner)) {
1442 // If we created a CXXTemporaryObjectExpr, that node also represents the
1443 // functional cast. Otherwise, create an explicit cast to represent
1444 // the syntactic form of a functional-style cast that was used here.
1445 //
1446 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1447 // would give a more consistent AST representation than using a
1448 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1449 // is sometimes handled by initialization and sometimes not.
1450 QualType ResultType = Result.get()->getType();
1451 SourceRange Locs = ListInitialization
1452 ? SourceRange()
1453 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1454 Result = CXXFunctionalCastExpr::Create(
1455 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1456 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
1457 }
1458
1459 return Result;
1460}
1461
1462bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1463 // [CUDA] Ignore this function, if we can't call it.
1464 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1465 if (getLangOpts().CUDA &&
1466 IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1467 return false;
1468
1469 SmallVector<const FunctionDecl*, 4> PreventedBy;
1470 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1471
1472 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1473 return Result;
1474
1475 // In case of CUDA, return true if none of the 1-argument deallocator
1476 // functions are actually callable.
1477 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1478 assert(FD->getNumParams() == 1 &&((FD->getNumParams() == 1 && "Only single-operand functions should be in PreventedBy"
) ? static_cast<void> (0) : __assert_fail ("FD->getNumParams() == 1 && \"Only single-operand functions should be in PreventedBy\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1479, __PRETTY_FUNCTION__))
1479 "Only single-operand functions should be in PreventedBy")((FD->getNumParams() == 1 && "Only single-operand functions should be in PreventedBy"
) ? static_cast<void> (0) : __assert_fail ("FD->getNumParams() == 1 && \"Only single-operand functions should be in PreventedBy\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1479, __PRETTY_FUNCTION__))
;
1480 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1481 });
1482}
1483
1484/// Determine whether the given function is a non-placement
1485/// deallocation function.
1486static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1487 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1488 return S.isUsualDeallocationFunction(Method);
1489
1490 if (FD->getOverloadedOperator() != OO_Delete &&
1491 FD->getOverloadedOperator() != OO_Array_Delete)
1492 return false;
1493
1494 unsigned UsualParams = 1;
1495
1496 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1497 S.Context.hasSameUnqualifiedType(
1498 FD->getParamDecl(UsualParams)->getType(),
1499 S.Context.getSizeType()))
1500 ++UsualParams;
1501
1502 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1503 S.Context.hasSameUnqualifiedType(
1504 FD->getParamDecl(UsualParams)->getType(),
1505 S.Context.getTypeDeclType(S.getStdAlignValT())))
1506 ++UsualParams;
1507
1508 return UsualParams == FD->getNumParams();
1509}
1510
1511namespace {
1512 struct UsualDeallocFnInfo {
1513 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1514 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1515 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1516 Destroying(false), HasSizeT(false), HasAlignValT(false),
1517 CUDAPref(Sema::CFP_Native) {
1518 // A function template declaration is never a usual deallocation function.
1519 if (!FD)
1520 return;
1521 unsigned NumBaseParams = 1;
1522 if (FD->isDestroyingOperatorDelete()) {
1523 Destroying = true;
1524 ++NumBaseParams;
1525 }
1526
1527 if (NumBaseParams < FD->getNumParams() &&
1528 S.Context.hasSameUnqualifiedType(
1529 FD->getParamDecl(NumBaseParams)->getType(),
1530 S.Context.getSizeType())) {
1531 ++NumBaseParams;
1532 HasSizeT = true;
1533 }
1534
1535 if (NumBaseParams < FD->getNumParams() &&
1536 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1537 ++NumBaseParams;
1538 HasAlignValT = true;
1539 }
1540
1541 // In CUDA, determine how much we'd like / dislike to call this.
1542 if (S.getLangOpts().CUDA)
1543 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1544 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1545 }
1546
1547 explicit operator bool() const { return FD; }
1548
1549 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1550 bool WantAlign) const {
1551 // C++ P0722:
1552 // A destroying operator delete is preferred over a non-destroying
1553 // operator delete.
1554 if (Destroying != Other.Destroying)
1555 return Destroying;
1556
1557 // C++17 [expr.delete]p10:
1558 // If the type has new-extended alignment, a function with a parameter
1559 // of type std::align_val_t is preferred; otherwise a function without
1560 // such a parameter is preferred
1561 if (HasAlignValT != Other.HasAlignValT)
1562 return HasAlignValT == WantAlign;
1563
1564 if (HasSizeT != Other.HasSizeT)
1565 return HasSizeT == WantSize;
1566
1567 // Use CUDA call preference as a tiebreaker.
1568 return CUDAPref > Other.CUDAPref;
1569 }
1570
1571 DeclAccessPair Found;
1572 FunctionDecl *FD;
1573 bool Destroying, HasSizeT, HasAlignValT;
1574 Sema::CUDAFunctionPreference CUDAPref;
1575 };
1576}
1577
1578/// Determine whether a type has new-extended alignment. This may be called when
1579/// the type is incomplete (for a delete-expression with an incomplete pointee
1580/// type), in which case it will conservatively return false if the alignment is
1581/// not known.
1582static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1583 return S.getLangOpts().AlignedAllocation &&
1584 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1585 S.getASTContext().getTargetInfo().getNewAlign();
1586}
1587
1588/// Select the correct "usual" deallocation function to use from a selection of
1589/// deallocation functions (either global or class-scope).
1590static UsualDeallocFnInfo resolveDeallocationOverload(
1591 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1592 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1593 UsualDeallocFnInfo Best;
1594
1595 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1596 UsualDeallocFnInfo Info(S, I.getPair());
1597 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1598 Info.CUDAPref == Sema::CFP_Never)
1599 continue;
1600
1601 if (!Best) {
1602 Best = Info;
1603 if (BestFns)
1604 BestFns->push_back(Info);
1605 continue;
1606 }
1607
1608 if (Best.isBetterThan(Info, WantSize, WantAlign))
1609 continue;
1610
1611 // If more than one preferred function is found, all non-preferred
1612 // functions are eliminated from further consideration.
1613 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1614 BestFns->clear();
1615
1616 Best = Info;
1617 if (BestFns)
1618 BestFns->push_back(Info);
1619 }
1620
1621 return Best;
1622}
1623
1624/// Determine whether a given type is a class for which 'delete[]' would call
1625/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1626/// we need to store the array size (even if the type is
1627/// trivially-destructible).
1628static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1629 QualType allocType) {
1630 const RecordType *record =
1631 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1632 if (!record) return false;
1633
1634 // Try to find an operator delete[] in class scope.
1635
1636 DeclarationName deleteName =
1637 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1638 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1639 S.LookupQualifiedName(ops, record->getDecl());
1640
1641 // We're just doing this for information.
1642 ops.suppressDiagnostics();
1643
1644 // Very likely: there's no operator delete[].
1645 if (ops.empty()) return false;
1646
1647 // If it's ambiguous, it should be illegal to call operator delete[]
1648 // on this thing, so it doesn't matter if we allocate extra space or not.
1649 if (ops.isAmbiguous()) return false;
1650
1651 // C++17 [expr.delete]p10:
1652 // If the deallocation functions have class scope, the one without a
1653 // parameter of type std::size_t is selected.
1654 auto Best = resolveDeallocationOverload(
1655 S, ops, /*WantSize*/false,
1656 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1657 return Best && Best.HasSizeT;
1658}
1659
1660/// Parsed a C++ 'new' expression (C++ 5.3.4).
1661///
1662/// E.g.:
1663/// @code new (memory) int[size][4] @endcode
1664/// or
1665/// @code ::new Foo(23, "hello") @endcode
1666///
1667/// \param StartLoc The first location of the expression.
1668/// \param UseGlobal True if 'new' was prefixed with '::'.
1669/// \param PlacementLParen Opening paren of the placement arguments.
1670/// \param PlacementArgs Placement new arguments.
1671/// \param PlacementRParen Closing paren of the placement arguments.
1672/// \param TypeIdParens If the type is in parens, the source range.
1673/// \param D The type to be allocated, as well as array dimensions.
1674/// \param Initializer The initializing expression or initializer-list, or null
1675/// if there is none.
1676ExprResult
1677Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1678 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1679 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1680 Declarator &D, Expr *Initializer) {
1681 Optional<Expr *> ArraySize;
1682 // If the specified type is an array, unwrap it and save the expression.
1683 if (D.getNumTypeObjects() > 0 &&
1684 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1685 DeclaratorChunk &Chunk = D.getTypeObject(0);
1686 if (D.getDeclSpec().hasAutoTypeSpec())
1687 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1688 << D.getSourceRange());
1689 if (Chunk.Arr.hasStatic)
1690 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1691 << D.getSourceRange());
1692 if (!Chunk.Arr.NumElts && !Initializer)
1693 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1694 << D.getSourceRange());
1695
1696 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1697 D.DropFirstTypeObject();
1698 }
1699
1700 // Every dimension shall be of constant size.
1701 if (ArraySize) {
1702 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1703 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1704 break;
1705
1706 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1707 if (Expr *NumElts = (Expr *)Array.NumElts) {
1708 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1709 if (getLangOpts().CPlusPlus14) {
1710 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1711 // shall be a converted constant expression (5.19) of type std::size_t
1712 // and shall evaluate to a strictly positive value.
1713 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1714 assert(IntWidth && "Builtin type of size 0?")((IntWidth && "Builtin type of size 0?") ? static_cast
<void> (0) : __assert_fail ("IntWidth && \"Builtin type of size 0?\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1714, __PRETTY_FUNCTION__))
;
1715 llvm::APSInt Value(IntWidth);
1716 Array.NumElts
1717 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1718 CCEK_NewExpr)
1719 .get();
1720 } else {
1721 Array.NumElts
1722 = VerifyIntegerConstantExpression(NumElts, nullptr,
1723 diag::err_new_array_nonconst)
1724 .get();
1725 }
1726 if (!Array.NumElts)
1727 return ExprError();
1728 }
1729 }
1730 }
1731 }
1732
1733 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1734 QualType AllocType = TInfo->getType();
1735 if (D.isInvalidType())
1736 return ExprError();
1737
1738 SourceRange DirectInitRange;
1739 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1740 DirectInitRange = List->getSourceRange();
1741
1742 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1743 PlacementLParen, PlacementArgs, PlacementRParen,
1744 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1745 Initializer);
1746}
1747
1748static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1749 Expr *Init) {
1750 if (!Init)
1751 return true;
1752 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1753 return PLE->getNumExprs() == 0;
1754 if (isa<ImplicitValueInitExpr>(Init))
1755 return true;
1756 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1757 return !CCE->isListInitialization() &&
1758 CCE->getConstructor()->isDefaultConstructor();
1759 else if (Style == CXXNewExpr::ListInit) {
1760 assert(isa<InitListExpr>(Init) &&((isa<InitListExpr>(Init) && "Shouldn't create list CXXConstructExprs for arrays."
) ? static_cast<void> (0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1761, __PRETTY_FUNCTION__))
1761 "Shouldn't create list CXXConstructExprs for arrays.")((isa<InitListExpr>(Init) && "Shouldn't create list CXXConstructExprs for arrays."
) ? static_cast<void> (0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1761, __PRETTY_FUNCTION__))
;
1762 return true;
1763 }
1764 return false;
1765}
1766
1767bool
1768Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1769 if (!getLangOpts().AlignedAllocationUnavailable)
1770 return false;
1771 if (FD.isDefined())
1772 return false;
1773 bool IsAligned = false;
1774 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned)
1775 return true;
1776 return false;
1777}
1778
1779// Emit a diagnostic if an aligned allocation/deallocation function that is not
1780// implemented in the standard library is selected.
1781void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1782 SourceLocation Loc) {
1783 if (isUnavailableAlignedAllocationFunction(FD)) {
1784 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
1785 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1786 getASTContext().getTargetInfo().getPlatformName());
1787
1788 OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1789 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1790 Diag(Loc, diag::err_aligned_allocation_unavailable)
1791 << IsDelete << FD.getType().getAsString() << OSName
1792 << alignedAllocMinVersion(T.getOS()).getAsString();
1793 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
1794 }
1795}
1796
1797ExprResult
1798Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1799 SourceLocation PlacementLParen,
1800 MultiExprArg PlacementArgs,
1801 SourceLocation PlacementRParen,
1802 SourceRange TypeIdParens,
1803 QualType AllocType,
1804 TypeSourceInfo *AllocTypeInfo,
1805 Optional<Expr *> ArraySize,
1806 SourceRange DirectInitRange,
1807 Expr *Initializer) {
1808 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1809 SourceLocation StartLoc = Range.getBegin();
1810
1811 CXXNewExpr::InitializationStyle initStyle;
1812 if (DirectInitRange.isValid()) {
1813 assert(Initializer && "Have parens but no initializer.")((Initializer && "Have parens but no initializer.") ?
static_cast<void> (0) : __assert_fail ("Initializer && \"Have parens but no initializer.\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1813, __PRETTY_FUNCTION__))
;
1814 initStyle = CXXNewExpr::CallInit;
1815 } else if (Initializer && isa<InitListExpr>(Initializer))
1816 initStyle = CXXNewExpr::ListInit;
1817 else {
1818 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||(((!Initializer || isa<ImplicitValueInitExpr>(Initializer
) || isa<CXXConstructExpr>(Initializer)) && "Initializer expression that cannot have been implicitly created."
) ? static_cast<void> (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1820, __PRETTY_FUNCTION__))
1819 isa<CXXConstructExpr>(Initializer)) &&(((!Initializer || isa<ImplicitValueInitExpr>(Initializer
) || isa<CXXConstructExpr>(Initializer)) && "Initializer expression that cannot have been implicitly created."
) ? static_cast<void> (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1820, __PRETTY_FUNCTION__))
1820 "Initializer expression that cannot have been implicitly created.")(((!Initializer || isa<ImplicitValueInitExpr>(Initializer
) || isa<CXXConstructExpr>(Initializer)) && "Initializer expression that cannot have been implicitly created."
) ? static_cast<void> (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1820, __PRETTY_FUNCTION__))
;
1821 initStyle = CXXNewExpr::NoInit;
1822 }
1823
1824 Expr **Inits = &Initializer;
1825 unsigned NumInits = Initializer ? 1 : 0;
1826 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1827 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init")((initStyle == CXXNewExpr::CallInit && "paren init for non-call init"
) ? static_cast<void> (0) : __assert_fail ("initStyle == CXXNewExpr::CallInit && \"paren init for non-call init\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1827, __PRETTY_FUNCTION__))
;
1828 Inits = List->getExprs();
1829 NumInits = List->getNumExprs();
1830 }
1831
1832 // C++11 [expr.new]p15:
1833 // A new-expression that creates an object of type T initializes that
1834 // object as follows:
1835 InitializationKind Kind
1836 // - If the new-initializer is omitted, the object is default-
1837 // initialized (8.5); if no initialization is performed,
1838 // the object has indeterminate value
1839 = initStyle == CXXNewExpr::NoInit
1840 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1841 // - Otherwise, the new-initializer is interpreted according to
1842 // the
1843 // initialization rules of 8.5 for direct-initialization.
1844 : initStyle == CXXNewExpr::ListInit
1845 ? InitializationKind::CreateDirectList(
1846 TypeRange.getBegin(), Initializer->getBeginLoc(),
1847 Initializer->getEndLoc())
1848 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1849 DirectInitRange.getBegin(),
1850 DirectInitRange.getEnd());
1851
1852 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1853 auto *Deduced = AllocType->getContainedDeducedType();
1854 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1855 if (ArraySize)
1856 return ExprError(
1857 Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
1858 diag::err_deduced_class_template_compound_type)
1859 << /*array*/ 2
1860 << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
1861
1862 InitializedEntity Entity
1863 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1864 AllocType = DeduceTemplateSpecializationFromInitializer(
1865 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1866 if (AllocType.isNull())
1867 return ExprError();
1868 } else if (Deduced) {
1869 bool Braced = (initStyle == CXXNewExpr::ListInit);
1870 if (NumInits == 1) {
1871 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1872 Inits = p->getInits();
1873 NumInits = p->getNumInits();
1874 Braced = true;
1875 }
1876 }
1877
1878 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1879 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1880 << AllocType << TypeRange);
1881 if (NumInits > 1) {
1882 Expr *FirstBad = Inits[1];
1883 return ExprError(Diag(FirstBad->getBeginLoc(),
1884 diag::err_auto_new_ctor_multiple_expressions)
1885 << AllocType << TypeRange);
1886 }
1887 if (Braced && !getLangOpts().CPlusPlus17)
1888 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
1889 << AllocType << TypeRange;
1890 Expr *Deduce = Inits[0];
1891 QualType DeducedType;
1892 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1893 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1894 << AllocType << Deduce->getType()
1895 << TypeRange << Deduce->getSourceRange());
1896 if (DeducedType.isNull())
1897 return ExprError();
1898 AllocType = DeducedType;
1899 }
1900
1901 // Per C++0x [expr.new]p5, the type being constructed may be a
1902 // typedef of an array type.
1903 if (!ArraySize) {
1904 if (const ConstantArrayType *Array
1905 = Context.getAsConstantArrayType(AllocType)) {
1906 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1907 Context.getSizeType(),
1908 TypeRange.getEnd());
1909 AllocType = Array->getElementType();
1910 }
1911 }
1912
1913 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1914 return ExprError();
1915
1916 // In ARC, infer 'retaining' for the allocated
1917 if (getLangOpts().ObjCAutoRefCount &&
1918 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1919 AllocType->isObjCLifetimeType()) {
1920 AllocType = Context.getLifetimeQualifiedType(AllocType,
1921 AllocType->getObjCARCImplicitLifetime());
1922 }
1923
1924 QualType ResultType = Context.getPointerType(AllocType);
1925
1926 if (ArraySize && *ArraySize &&
1927 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
1928 ExprResult result = CheckPlaceholderExpr(*ArraySize);
1929 if (result.isInvalid()) return ExprError();
1930 ArraySize = result.get();
1931 }
1932 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1933 // integral or enumeration type with a non-negative value."
1934 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1935 // enumeration type, or a class type for which a single non-explicit
1936 // conversion function to integral or unscoped enumeration type exists.
1937 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1938 // std::size_t.
1939 llvm::Optional<uint64_t> KnownArraySize;
1940 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
1941 ExprResult ConvertedSize;
1942 if (getLangOpts().CPlusPlus14) {
1943 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?")((Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?"
) ? static_cast<void> (0) : __assert_fail ("Context.getTargetInfo().getIntWidth() && \"Builtin type of size 0?\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1943, __PRETTY_FUNCTION__))
;
1944
1945 ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
1946 AA_Converting);
1947
1948 if (!ConvertedSize.isInvalid() &&
1949 (*ArraySize)->getType()->getAs<RecordType>())
1950 // Diagnose the compatibility of this conversion.
1951 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1952 << (*ArraySize)->getType() << 0 << "'size_t'";
1953 } else {
1954 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1955 protected:
1956 Expr *ArraySize;
1957
1958 public:
1959 SizeConvertDiagnoser(Expr *ArraySize)
1960 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1961 ArraySize(ArraySize) {}
1962
1963 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1964 QualType T) override {
1965 return S.Diag(Loc, diag::err_array_size_not_integral)
1966 << S.getLangOpts().CPlusPlus11 << T;
1967 }
1968
1969 SemaDiagnosticBuilder diagnoseIncomplete(
1970 Sema &S, SourceLocation Loc, QualType T) override {
1971 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1972 << T << ArraySize->getSourceRange();
1973 }
1974
1975 SemaDiagnosticBuilder diagnoseExplicitConv(
1976 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1977 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1978 }
1979
1980 SemaDiagnosticBuilder noteExplicitConv(
1981 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1982 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1983 << ConvTy->isEnumeralType() << ConvTy;
1984 }
1985
1986 SemaDiagnosticBuilder diagnoseAmbiguous(
1987 Sema &S, SourceLocation Loc, QualType T) override {
1988 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1989 }
1990
1991 SemaDiagnosticBuilder noteAmbiguous(
1992 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1993 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1994 << ConvTy->isEnumeralType() << ConvTy;
1995 }
1996
1997 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1998 QualType T,
1999 QualType ConvTy) override {
2000 return S.Diag(Loc,
2001 S.getLangOpts().CPlusPlus11
2002 ? diag::warn_cxx98_compat_array_size_conversion
2003 : diag::ext_array_size_conversion)
2004 << T << ConvTy->isEnumeralType() << ConvTy;
2005 }
2006 } SizeDiagnoser(*ArraySize);
2007
2008 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2009 SizeDiagnoser);
2010 }
2011 if (ConvertedSize.isInvalid())
2012 return ExprError();
2013
2014 ArraySize = ConvertedSize.get();
2015 QualType SizeType = (*ArraySize)->getType();
2016
2017 if (!SizeType->isIntegralOrUnscopedEnumerationType())
2018 return ExprError();
2019
2020 // C++98 [expr.new]p7:
2021 // The expression in a direct-new-declarator shall have integral type
2022 // with a non-negative value.
2023 //
2024 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2025 // per CWG1464. Otherwise, if it's not a constant, we must have an
2026 // unparenthesized array type.
2027 if (!(*ArraySize)->isValueDependent()) {
2028 llvm::APSInt Value;
2029 // We've already performed any required implicit conversion to integer or
2030 // unscoped enumeration type.
2031 // FIXME: Per CWG1464, we are required to check the value prior to
2032 // converting to size_t. This will never find a negative array size in
2033 // C++14 onwards, because Value is always unsigned here!
2034 if ((*ArraySize)->isIntegerConstantExpr(Value, Context)) {
2035 if (Value.isSigned() && Value.isNegative()) {
2036 return ExprError(Diag((*ArraySize)->getBeginLoc(),
2037 diag::err_typecheck_negative_array_size)
2038 << (*ArraySize)->getSourceRange());
2039 }
2040
2041 if (!AllocType->isDependentType()) {
2042 unsigned ActiveSizeBits =
2043 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
2044 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2045 return ExprError(
2046 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2047 << Value.toString(10) << (*ArraySize)->getSourceRange());
2048 }
2049
2050 KnownArraySize = Value.getZExtValue();
2051 } else if (TypeIdParens.isValid()) {
2052 // Can't have dynamic array size when the type-id is in parentheses.
2053 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2054 << (*ArraySize)->getSourceRange()
2055 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2056 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2057
2058 TypeIdParens = SourceRange();
2059 }
2060 }
2061
2062 // Note that we do *not* convert the argument in any way. It can
2063 // be signed, larger than size_t, whatever.
2064 }
2065
2066 FunctionDecl *OperatorNew = nullptr;
2067 FunctionDecl *OperatorDelete = nullptr;
2068 unsigned Alignment =
2069 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2070 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2071 bool PassAlignment = getLangOpts().AlignedAllocation &&
2072 Alignment > NewAlignment;
2073
2074 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
2075 if (!AllocType->isDependentType() &&
2076 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2077 FindAllocationFunctions(
2078 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2079 AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs,
2080 OperatorNew, OperatorDelete))
2081 return ExprError();
2082
2083 // If this is an array allocation, compute whether the usual array
2084 // deallocation function for the type has a size_t parameter.
2085 bool UsualArrayDeleteWantsSize = false;
2086 if (ArraySize && !AllocType->isDependentType())
2087 UsualArrayDeleteWantsSize =
2088 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2089
2090 SmallVector<Expr *, 8> AllPlaceArgs;
2091 if (OperatorNew) {
2092 const FunctionProtoType *Proto =
2093 OperatorNew->getType()->getAs<FunctionProtoType>();
2094 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2095 : VariadicDoesNotApply;
2096
2097 // We've already converted the placement args, just fill in any default
2098 // arguments. Skip the first parameter because we don't have a corresponding
2099 // argument. Skip the second parameter too if we're passing in the
2100 // alignment; we've already filled it in.
2101 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2102 PassAlignment ? 2 : 1, PlacementArgs,
2103 AllPlaceArgs, CallType))
2104 return ExprError();
2105
2106 if (!AllPlaceArgs.empty())
2107 PlacementArgs = AllPlaceArgs;
2108
2109 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
2110 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
2111
2112 // FIXME: Missing call to CheckFunctionCall or equivalent
2113
2114 // Warn if the type is over-aligned and is being allocated by (unaligned)
2115 // global operator new.
2116 if (PlacementArgs.empty() && !PassAlignment &&
2117 (OperatorNew->isImplicit() ||
2118 (OperatorNew->getBeginLoc().isValid() &&
2119 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2120 if (Alignment > NewAlignment)
2121 Diag(StartLoc, diag::warn_overaligned_type)
2122 << AllocType
2123 << unsigned(Alignment / Context.getCharWidth())
2124 << unsigned(NewAlignment / Context.getCharWidth());
2125 }
2126 }
2127
2128 // Array 'new' can't have any initializers except empty parentheses.
2129 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2130 // dialect distinction.
2131 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2132 SourceRange InitRange(Inits[0]->getBeginLoc(),
2133 Inits[NumInits - 1]->getEndLoc());
2134 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2135 return ExprError();
2136 }
2137
2138 // If we can perform the initialization, and we've not already done so,
2139 // do it now.
2140 if (!AllocType->isDependentType() &&
2141 !Expr::hasAnyTypeDependentArguments(
2142 llvm::makeArrayRef(Inits, NumInits))) {
2143 // The type we initialize is the complete type, including the array bound.
2144 QualType InitType;
2145 if (KnownArraySize)
2146 InitType = Context.getConstantArrayType(
2147 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2148 *KnownArraySize),
2149 ArrayType::Normal, 0);
2150 else if (ArraySize)
2151 InitType =
2152 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2153 else
2154 InitType = AllocType;
2155
2156 InitializedEntity Entity
2157 = InitializedEntity::InitializeNew(StartLoc, InitType);
2158 InitializationSequence InitSeq(*this, Entity, Kind,
2159 MultiExprArg(Inits, NumInits));
2160 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2161 MultiExprArg(Inits, NumInits));
2162 if (FullInit.isInvalid())
2163 return ExprError();
2164
2165 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2166 // we don't want the initialized object to be destructed.
2167 // FIXME: We should not create these in the first place.
2168 if (CXXBindTemporaryExpr *Binder =
2169 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2170 FullInit = Binder->getSubExpr();
2171
2172 Initializer = FullInit.get();
2173
2174 // FIXME: If we have a KnownArraySize, check that the array bound of the
2175 // initializer is no greater than that constant value.
2176
2177 if (ArraySize && !*ArraySize) {
2178 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2179 if (CAT) {
2180 // FIXME: Track that the array size was inferred rather than explicitly
2181 // specified.
2182 ArraySize = IntegerLiteral::Create(
2183 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2184 } else {
2185 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2186 << Initializer->getSourceRange();
2187 }
2188 }
2189 }
2190
2191 // Mark the new and delete operators as referenced.
2192 if (OperatorNew) {
2193 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2194 return ExprError();
2195 MarkFunctionReferenced(StartLoc, OperatorNew);
2196 }
2197 if (OperatorDelete) {
2198 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2199 return ExprError();
2200 MarkFunctionReferenced(StartLoc, OperatorDelete);
2201 }
2202
2203 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2204 PassAlignment, UsualArrayDeleteWantsSize,
2205 PlacementArgs, TypeIdParens, ArraySize, initStyle,
2206 Initializer, ResultType, AllocTypeInfo, Range,
2207 DirectInitRange);
2208}
2209
2210/// Checks that a type is suitable as the allocated type
2211/// in a new-expression.
2212bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2213 SourceRange R) {
2214 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2215 // abstract class type or array thereof.
2216 if (AllocType->isFunctionType())
2217 return Diag(Loc, diag::err_bad_new_type)
2218 << AllocType << 0 << R;
2219 else if (AllocType->isReferenceType())
2220 return Diag(Loc, diag::err_bad_new_type)
2221 << AllocType << 1 << R;
2222 else if (!AllocType->isDependentType() &&
2223 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
2224 return true;
2225 else if (RequireNonAbstractType(Loc, AllocType,
2226 diag::err_allocation_of_abstract_type))
2227 return true;
2228 else if (AllocType->isVariablyModifiedType())
2229 return Diag(Loc, diag::err_variably_modified_new_type)
2230 << AllocType;
2231 else if (AllocType.getAddressSpace() != LangAS::Default &&
2232 !getLangOpts().OpenCLCPlusPlus)
2233 return Diag(Loc, diag::err_address_space_qualified_new)
2234 << AllocType.getUnqualifiedType()
2235 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2236 else if (getLangOpts().ObjCAutoRefCount) {
2237 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2238 QualType BaseAllocType = Context.getBaseElementType(AT);
2239 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2240 BaseAllocType->isObjCLifetimeType())
2241 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2242 << BaseAllocType;
2243 }
2244 }
2245
2246 return false;
2247}
2248
2249static bool resolveAllocationOverload(
2250 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2251 bool &PassAlignment, FunctionDecl *&Operator,
2252 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2253 OverloadCandidateSet Candidates(R.getNameLoc(),
2254 OverloadCandidateSet::CSK_Normal);
2255 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2256 Alloc != AllocEnd; ++Alloc) {
2257 // Even member operator new/delete are implicitly treated as
2258 // static, so don't use AddMemberCandidate.
2259 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2260
2261 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2262 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2263 /*ExplicitTemplateArgs=*/nullptr, Args,
2264 Candidates,
2265 /*SuppressUserConversions=*/false);
2266 continue;
2267 }
2268
2269 FunctionDecl *Fn = cast<FunctionDecl>(D);
2270 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2271 /*SuppressUserConversions=*/false);
2272 }
2273
2274 // Do the resolution.
2275 OverloadCandidateSet::iterator Best;
2276 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2277 case OR_Success: {
2278 // Got one!
2279 FunctionDecl *FnDecl = Best->Function;
2280 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2281 Best->FoundDecl) == Sema::AR_inaccessible)
2282 return true;
2283
2284 Operator = FnDecl;
2285 return false;
2286 }
2287
2288 case OR_No_Viable_Function:
2289 // C++17 [expr.new]p13:
2290 // If no matching function is found and the allocated object type has
2291 // new-extended alignment, the alignment argument is removed from the
2292 // argument list, and overload resolution is performed again.
2293 if (PassAlignment) {
2294 PassAlignment = false;
2295 AlignArg = Args[1];
2296 Args.erase(Args.begin() + 1);
2297 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2298 Operator, &Candidates, AlignArg,
2299 Diagnose);
2300 }
2301
2302 // MSVC will fall back on trying to find a matching global operator new
2303 // if operator new[] cannot be found. Also, MSVC will leak by not
2304 // generating a call to operator delete or operator delete[], but we
2305 // will not replicate that bug.
2306 // FIXME: Find out how this interacts with the std::align_val_t fallback
2307 // once MSVC implements it.
2308 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2309 S.Context.getLangOpts().MSVCCompat) {
2310 R.clear();
2311 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2312 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2313 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2314 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2315 Operator, /*Candidates=*/nullptr,
2316 /*AlignArg=*/nullptr, Diagnose);
2317 }
2318
2319 if (Diagnose) {
2320 PartialDiagnosticAt PD(R.getNameLoc(), S.PDiag(diag::err_ovl_no_viable_function_in_call)
2321 << R.getLookupName() << Range);
2322
2323 // If we have aligned candidates, only note the align_val_t candidates
2324 // from AlignedCandidates and the non-align_val_t candidates from
2325 // Candidates.
2326 if (AlignedCandidates) {
2327 auto IsAligned = [](OverloadCandidate &C) {
2328 return C.Function->getNumParams() > 1 &&
2329 C.Function->getParamDecl(1)->getType()->isAlignValT();
2330 };
2331 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2332
2333 // This was an overaligned allocation, so list the aligned candidates
2334 // first.
2335 Args.insert(Args.begin() + 1, AlignArg);
2336 AlignedCandidates->NoteCandidates(PD, S, OCD_AllCandidates, Args, "",
2337 R.getNameLoc(), IsAligned);
2338 Args.erase(Args.begin() + 1);
2339 Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2340 IsUnaligned);
2341 } else {
2342 Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args);
2343 }
2344 }
2345 return true;
2346
2347 case OR_Ambiguous:
2348 if (Diagnose) {
2349 Candidates.NoteCandidates(
2350 PartialDiagnosticAt(R.getNameLoc(),
2351 S.PDiag(diag::err_ovl_ambiguous_call)
2352 << R.getLookupName() << Range),
2353 S, OCD_ViableCandidates, Args);
2354 }
2355 return true;
2356
2357 case OR_Deleted: {
2358 if (Diagnose) {
2359 Candidates.NoteCandidates(
2360 PartialDiagnosticAt(R.getNameLoc(),
2361 S.PDiag(diag::err_ovl_deleted_call)
2362 << R.getLookupName() << Range),
2363 S, OCD_AllCandidates, Args);
2364 }
2365 return true;
2366 }
2367 }
2368 llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2368)
;
2369}
2370
2371bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2372 AllocationFunctionScope NewScope,
2373 AllocationFunctionScope DeleteScope,
2374 QualType AllocType, bool IsArray,
2375 bool &PassAlignment, MultiExprArg PlaceArgs,
2376 FunctionDecl *&OperatorNew,
2377 FunctionDecl *&OperatorDelete,
2378 bool Diagnose) {
2379 // --- Choosing an allocation function ---
2380 // C++ 5.3.4p8 - 14 & 18
2381 // 1) If looking in AFS_Global scope for allocation functions, only look in
2382 // the global scope. Else, if AFS_Class, only look in the scope of the
2383 // allocated class. If AFS_Both, look in both.
2384 // 2) If an array size is given, look for operator new[], else look for
2385 // operator new.
2386 // 3) The first argument is always size_t. Append the arguments from the
2387 // placement form.
2388
2389 SmallVector<Expr*, 8> AllocArgs;
2390 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2391
2392 // We don't care about the actual value of these arguments.
2393 // FIXME: Should the Sema create the expression and embed it in the syntax
2394 // tree? Or should the consumer just recalculate the value?
2395 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2396 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2397 Context.getTargetInfo().getPointerWidth(0)),
2398 Context.getSizeType(),
2399 SourceLocation());
2400 AllocArgs.push_back(&Size);
2401
2402 QualType AlignValT = Context.VoidTy;
2403 if (PassAlignment) {
2404 DeclareGlobalNewDelete();
2405 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2406 }
2407 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2408 if (PassAlignment)
2409 AllocArgs.push_back(&Align);
2410
2411 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2412
2413 // C++ [expr.new]p8:
2414 // If the allocated type is a non-array type, the allocation
2415 // function's name is operator new and the deallocation function's
2416 // name is operator delete. If the allocated type is an array
2417 // type, the allocation function's name is operator new[] and the
2418 // deallocation function's name is operator delete[].
2419 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2420 IsArray ? OO_Array_New : OO_New);
2421
2422 QualType AllocElemType = Context.getBaseElementType(AllocType);
2423
2424 // Find the allocation function.
2425 {
2426 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2427
2428 // C++1z [expr.new]p9:
2429 // If the new-expression begins with a unary :: operator, the allocation
2430 // function's name is looked up in the global scope. Otherwise, if the
2431 // allocated type is a class type T or array thereof, the allocation
2432 // function's name is looked up in the scope of T.
2433 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2434 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2435
2436 // We can see ambiguity here if the allocation function is found in
2437 // multiple base classes.
2438 if (R.isAmbiguous())
2439 return true;
2440
2441 // If this lookup fails to find the name, or if the allocated type is not
2442 // a class type, the allocation function's name is looked up in the
2443 // global scope.
2444 if (R.empty()) {
2445 if (NewScope == AFS_Class)
2446 return true;
2447
2448 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2449 }
2450
2451 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2452 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2453 return true;
2454 }
2455
2456 assert(!R.empty() && "implicitly declared allocation functions not found")((!R.empty() && "implicitly declared allocation functions not found"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2456, __PRETTY_FUNCTION__))
;
2457 assert(!R.isAmbiguous() && "global allocation functions are ambiguous")((!R.isAmbiguous() && "global allocation functions are ambiguous"
) ? static_cast<void> (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2457, __PRETTY_FUNCTION__))
;
2458
2459 // We do our own custom access checks below.
2460 R.suppressDiagnostics();
2461
2462 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2463 OperatorNew, /*Candidates=*/nullptr,
2464 /*AlignArg=*/nullptr, Diagnose))
2465 return true;
2466 }
2467
2468 // We don't need an operator delete if we're running under -fno-exceptions.
2469 if (!getLangOpts().Exceptions) {
2470 OperatorDelete = nullptr;
2471 return false;
2472 }
2473
2474 // Note, the name of OperatorNew might have been changed from array to
2475 // non-array by resolveAllocationOverload.
2476 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2477 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2478 ? OO_Array_Delete
2479 : OO_Delete);
2480
2481 // C++ [expr.new]p19:
2482 //
2483 // If the new-expression begins with a unary :: operator, the
2484 // deallocation function's name is looked up in the global
2485 // scope. Otherwise, if the allocated type is a class type T or an
2486 // array thereof, the deallocation function's name is looked up in
2487 // the scope of T. If this lookup fails to find the name, or if
2488 // the allocated type is not a class type or array thereof, the
2489 // deallocation function's name is looked up in the global scope.
2490 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2491 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2492 CXXRecordDecl *RD
2493 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
2494 LookupQualifiedName(FoundDelete, RD);
2495 }
2496 if (FoundDelete.isAmbiguous())
2497 return true; // FIXME: clean up expressions?
2498
2499 bool FoundGlobalDelete = FoundDelete.empty();
2500 if (FoundDelete.empty()) {
2501 if (DeleteScope == AFS_Class)
2502 return true;
2503
2504 DeclareGlobalNewDelete();
2505 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2506 }
2507
2508 FoundDelete.suppressDiagnostics();
2509
2510 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2511
2512 // Whether we're looking for a placement operator delete is dictated
2513 // by whether we selected a placement operator new, not by whether
2514 // we had explicit placement arguments. This matters for things like
2515 // struct A { void *operator new(size_t, int = 0); ... };
2516 // A *a = new A()
2517 //
2518 // We don't have any definition for what a "placement allocation function"
2519 // is, but we assume it's any allocation function whose
2520 // parameter-declaration-clause is anything other than (size_t).
2521 //
2522 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2523 // This affects whether an exception from the constructor of an overaligned
2524 // type uses the sized or non-sized form of aligned operator delete.
2525 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2526 OperatorNew->isVariadic();
2527
2528 if (isPlacementNew) {
2529 // C++ [expr.new]p20:
2530 // A declaration of a placement deallocation function matches the
2531 // declaration of a placement allocation function if it has the
2532 // same number of parameters and, after parameter transformations
2533 // (8.3.5), all parameter types except the first are
2534 // identical. [...]
2535 //
2536 // To perform this comparison, we compute the function type that
2537 // the deallocation function should have, and use that type both
2538 // for template argument deduction and for comparison purposes.
2539 QualType ExpectedFunctionType;
2540 {
2541 const FunctionProtoType *Proto
2542 = OperatorNew->getType()->getAs<FunctionProtoType>();
2543
2544 SmallVector<QualType, 4> ArgTypes;
2545 ArgTypes.push_back(Context.VoidPtrTy);
2546 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2547 ArgTypes.push_back(Proto->getParamType(I));
2548
2549 FunctionProtoType::ExtProtoInfo EPI;
2550 // FIXME: This is not part of the standard's rule.
2551 EPI.Variadic = Proto->isVariadic();
2552
2553 ExpectedFunctionType
2554 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2555 }
2556
2557 for (LookupResult::iterator D = FoundDelete.begin(),
2558 DEnd = FoundDelete.end();
2559 D != DEnd; ++D) {
2560 FunctionDecl *Fn = nullptr;
2561 if (FunctionTemplateDecl *FnTmpl =
2562 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2563 // Perform template argument deduction to try to match the
2564 // expected function type.
2565 TemplateDeductionInfo Info(StartLoc);
2566 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2567 Info))
2568 continue;
2569 } else
2570 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2571
2572 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2573 ExpectedFunctionType,
2574 /*AdjustExcpetionSpec*/true),
2575 ExpectedFunctionType))
2576 Matches.push_back(std::make_pair(D.getPair(), Fn));
2577 }
2578
2579 if (getLangOpts().CUDA)
2580 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2581 } else {
2582 // C++1y [expr.new]p22:
2583 // For a non-placement allocation function, the normal deallocation
2584 // function lookup is used
2585 //
2586 // Per [expr.delete]p10, this lookup prefers a member operator delete
2587 // without a size_t argument, but prefers a non-member operator delete
2588 // with a size_t where possible (which it always is in this case).
2589 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2590 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2591 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2592 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2593 &BestDeallocFns);
2594 if (Selected)
2595 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2596 else {
2597 // If we failed to select an operator, all remaining functions are viable
2598 // but ambiguous.
2599 for (auto Fn : BestDeallocFns)
2600 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2601 }
2602 }
2603
2604 // C++ [expr.new]p20:
2605 // [...] If the lookup finds a single matching deallocation
2606 // function, that function will be called; otherwise, no
2607 // deallocation function will be called.
2608 if (Matches.size() == 1) {
2609 OperatorDelete = Matches[0].second;
2610
2611 // C++1z [expr.new]p23:
2612 // If the lookup finds a usual deallocation function (3.7.4.2)
2613 // with a parameter of type std::size_t and that function, considered
2614 // as a placement deallocation function, would have been
2615 // selected as a match for the allocation function, the program
2616 // is ill-formed.
2617 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2618 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2619 UsualDeallocFnInfo Info(*this,
2620 DeclAccessPair::make(OperatorDelete, AS_public));
2621 // Core issue, per mail to core reflector, 2016-10-09:
2622 // If this is a member operator delete, and there is a corresponding
2623 // non-sized member operator delete, this isn't /really/ a sized
2624 // deallocation function, it just happens to have a size_t parameter.
2625 bool IsSizedDelete = Info.HasSizeT;
2626 if (IsSizedDelete && !FoundGlobalDelete) {
2627 auto NonSizedDelete =
2628 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2629 /*WantAlign*/Info.HasAlignValT);
2630 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2631 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2632 IsSizedDelete = false;
2633 }
2634
2635 if (IsSizedDelete) {
2636 SourceRange R = PlaceArgs.empty()
2637 ? SourceRange()
2638 : SourceRange(PlaceArgs.front()->getBeginLoc(),
2639 PlaceArgs.back()->getEndLoc());
2640 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2641 if (!OperatorDelete->isImplicit())
2642 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2643 << DeleteName;
2644 }
2645 }
2646
2647 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2648 Matches[0].first);
2649 } else if (!Matches.empty()) {
2650 // We found multiple suitable operators. Per [expr.new]p20, that means we
2651 // call no 'operator delete' function, but we should at least warn the user.
2652 // FIXME: Suppress this warning if the construction cannot throw.
2653 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2654 << DeleteName << AllocElemType;
2655
2656 for (auto &Match : Matches)
2657 Diag(Match.second->getLocation(),
2658 diag::note_member_declared_here) << DeleteName;
2659 }
2660
2661 return false;
2662}
2663
2664/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2665/// delete. These are:
2666/// @code
2667/// // C++03:
2668/// void* operator new(std::size_t) throw(std::bad_alloc);
2669/// void* operator new[](std::size_t) throw(std::bad_alloc);
2670/// void operator delete(void *) throw();
2671/// void operator delete[](void *) throw();
2672/// // C++11:
2673/// void* operator new(std::size_t);
2674/// void* operator new[](std::size_t);
2675/// void operator delete(void *) noexcept;
2676/// void operator delete[](void *) noexcept;
2677/// // C++1y:
2678/// void* operator new(std::size_t);
2679/// void* operator new[](std::size_t);
2680/// void operator delete(void *) noexcept;
2681/// void operator delete[](void *) noexcept;
2682/// void operator delete(void *, std::size_t) noexcept;
2683/// void operator delete[](void *, std::size_t) noexcept;
2684/// @endcode
2685/// Note that the placement and nothrow forms of new are *not* implicitly
2686/// declared. Their use requires including \<new\>.
2687void Sema::DeclareGlobalNewDelete() {
2688 if (GlobalNewDeleteDeclared)
2689 return;
2690
2691 // OpenCL C++ 1.0 s2.9: the implicitly declared new and delete operators
2692 // are not supported.
2693 if (getLangOpts().OpenCLCPlusPlus)
2694 return;
2695
2696 // C++ [basic.std.dynamic]p2:
2697 // [...] The following allocation and deallocation functions (18.4) are
2698 // implicitly declared in global scope in each translation unit of a
2699 // program
2700 //
2701 // C++03:
2702 // void* operator new(std::size_t) throw(std::bad_alloc);
2703 // void* operator new[](std::size_t) throw(std::bad_alloc);
2704 // void operator delete(void*) throw();
2705 // void operator delete[](void*) throw();
2706 // C++11:
2707 // void* operator new(std::size_t);
2708 // void* operator new[](std::size_t);
2709 // void operator delete(void*) noexcept;
2710 // void operator delete[](void*) noexcept;
2711 // C++1y:
2712 // void* operator new(std::size_t);
2713 // void* operator new[](std::size_t);
2714 // void operator delete(void*) noexcept;
2715 // void operator delete[](void*) noexcept;
2716 // void operator delete(void*, std::size_t) noexcept;
2717 // void operator delete[](void*, std::size_t) noexcept;
2718 //
2719 // These implicit declarations introduce only the function names operator
2720 // new, operator new[], operator delete, operator delete[].
2721 //
2722 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2723 // "std" or "bad_alloc" as necessary to form the exception specification.
2724 // However, we do not make these implicit declarations visible to name
2725 // lookup.
2726 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2727 // The "std::bad_alloc" class has not yet been declared, so build it
2728 // implicitly.
2729 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2730 getOrCreateStdNamespace(),
2731 SourceLocation(), SourceLocation(),
2732 &PP.getIdentifierTable().get("bad_alloc"),
2733 nullptr);
2734 getStdBadAlloc()->setImplicit(true);
2735 }
2736 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2737 // The "std::align_val_t" enum class has not yet been declared, so build it
2738 // implicitly.
2739 auto *AlignValT = EnumDecl::Create(
2740 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2741 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2742 AlignValT->setIntegerType(Context.getSizeType());
2743 AlignValT->setPromotionType(Context.getSizeType());
2744 AlignValT->setImplicit(true);
2745 StdAlignValT = AlignValT;
2746 }
2747
2748 GlobalNewDeleteDeclared = true;
2749
2750 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2751 QualType SizeT = Context.getSizeType();
2752
2753 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2754 QualType Return, QualType Param) {
2755 llvm::SmallVector<QualType, 3> Params;
2756 Params.push_back(Param);
2757
2758 // Create up to four variants of the function (sized/aligned).
2759 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2760 (Kind == OO_Delete || Kind == OO_Array_Delete);
2761 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2762
2763 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2764 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2765 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
2766 if (Sized)
2767 Params.push_back(SizeT);
2768
2769 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
2770 if (Aligned)
2771 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2772
2773 DeclareGlobalAllocationFunction(
2774 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2775
2776 if (Aligned)
2777 Params.pop_back();
2778 }
2779 }
2780 };
2781
2782 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2783 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2784 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2785 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2786}
2787
2788/// DeclareGlobalAllocationFunction - Declares a single implicit global
2789/// allocation function if it doesn't already exist.
2790void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2791 QualType Return,
2792 ArrayRef<QualType> Params) {
2793 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2794
2795 // Check if this function is already declared.
2796 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2797 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2798 Alloc != AllocEnd; ++Alloc) {
2799 // Only look at non-template functions, as it is the predefined,
2800 // non-templated allocation function we are trying to declare here.
2801 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2802 if (Func->getNumParams() == Params.size()) {
2803 llvm::SmallVector<QualType, 3> FuncParams;
2804 for (auto *P : Func->parameters())
2805 FuncParams.push_back(
2806 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2807 if (llvm::makeArrayRef(FuncParams) == Params) {
2808 // Make the function visible to name lookup, even if we found it in
2809 // an unimported module. It either is an implicitly-declared global
2810 // allocation function, or is suppressing that function.
2811 Func->setVisibleDespiteOwningModule();
2812 return;
2813 }
2814 }
2815 }
2816 }
2817
2818 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
2819 /*IsVariadic=*/false, /*IsCXXMethod=*/false));
2820
2821 QualType BadAllocType;
2822 bool HasBadAllocExceptionSpec
2823 = (Name.getCXXOverloadedOperator() == OO_New ||
2824 Name.getCXXOverloadedOperator() == OO_Array_New);
2825 if (HasBadAllocExceptionSpec) {
2826 if (!getLangOpts().CPlusPlus11) {
2827 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2828 assert(StdBadAlloc && "Must have std::bad_alloc declared")((StdBadAlloc && "Must have std::bad_alloc declared")
? static_cast<void> (0) : __assert_fail ("StdBadAlloc && \"Must have std::bad_alloc declared\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2828, __PRETTY_FUNCTION__))
;
2829 EPI.ExceptionSpec.Type = EST_Dynamic;
2830 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2831 }
2832 } else {
2833 EPI.ExceptionSpec =
2834 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2835 }
2836
2837 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2838 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2839 FunctionDecl *Alloc = FunctionDecl::Create(
2840 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2841 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2842 Alloc->setImplicit();
2843 // Global allocation functions should always be visible.
2844 Alloc->setVisibleDespiteOwningModule();
2845
2846 Alloc->addAttr(VisibilityAttr::CreateImplicit(
2847 Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
2848 ? VisibilityAttr::Hidden
2849 : VisibilityAttr::Default));
2850
2851 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2852 for (QualType T : Params) {
2853 ParamDecls.push_back(ParmVarDecl::Create(
2854 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2855 /*TInfo=*/nullptr, SC_None, nullptr));
2856 ParamDecls.back()->setImplicit();
2857 }
2858 Alloc->setParams(ParamDecls);
2859 if (ExtraAttr)
2860 Alloc->addAttr(ExtraAttr);
2861 Context.getTranslationUnitDecl()->addDecl(Alloc);
2862 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2863 };
2864
2865 if (!LangOpts.CUDA)
2866 CreateAllocationFunctionDecl(nullptr);
2867 else {
2868 // Host and device get their own declaration so each can be
2869 // defined or re-declared independently.
2870 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2871 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
2872 }
2873}
2874
2875FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2876 bool CanProvideSize,
2877 bool Overaligned,
2878 DeclarationName Name) {
2879 DeclareGlobalNewDelete();
2880
2881 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2882 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2883
2884 // FIXME: It's possible for this to result in ambiguity, through a
2885 // user-declared variadic operator delete or the enable_if attribute. We
2886 // should probably not consider those cases to be usual deallocation
2887 // functions. But for now we just make an arbitrary choice in that case.
2888 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2889 Overaligned);
2890 assert(Result.FD && "operator delete missing from global scope?")((Result.FD && "operator delete missing from global scope?"
) ? static_cast<void> (0) : __assert_fail ("Result.FD && \"operator delete missing from global scope?\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2890, __PRETTY_FUNCTION__))
;
2891 return Result.FD;
2892}
2893
2894FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2895 CXXRecordDecl *RD) {
2896 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2897
2898 FunctionDecl *OperatorDelete = nullptr;
2899 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2900 return nullptr;
2901 if (OperatorDelete)
2902 return OperatorDelete;
2903
2904 // If there's no class-specific operator delete, look up the global
2905 // non-array delete.
2906 return FindUsualDeallocationFunction(
2907 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2908 Name);
2909}
2910
2911bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2912 DeclarationName Name,
2913 FunctionDecl *&Operator, bool Diagnose) {
2914 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2915 // Try to find operator delete/operator delete[] in class scope.
2916 LookupQualifiedName(Found, RD);
2917
2918 if (Found.isAmbiguous())
2919 return true;
2920
2921 Found.suppressDiagnostics();
2922
2923 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
2924
2925 // C++17 [expr.delete]p10:
2926 // If the deallocation functions have class scope, the one without a
2927 // parameter of type std::size_t is selected.
2928 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2929 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2930 /*WantAlign*/ Overaligned, &Matches);
2931
2932 // If we could find an overload, use it.
2933 if (Matches.size() == 1) {
2934 Operator = cast<CXXMethodDecl>(Matches[0].FD);
2935
2936 // FIXME: DiagnoseUseOfDecl?
2937 if (Operator->isDeleted()) {
2938 if (Diagnose) {
2939 Diag(StartLoc, diag::err_deleted_function_use);
2940 NoteDeletedFunction(Operator);
2941 }
2942 return true;
2943 }
2944
2945 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2946 Matches[0].Found, Diagnose) == AR_inaccessible)
2947 return true;
2948
2949 return false;
2950 }
2951
2952 // We found multiple suitable operators; complain about the ambiguity.
2953 // FIXME: The standard doesn't say to do this; it appears that the intent
2954 // is that this should never happen.
2955 if (!Matches.empty()) {
2956 if (Diagnose) {
2957 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2958 << Name << RD;
2959 for (auto &Match : Matches)
2960 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
2961 }
2962 return true;
2963 }
2964
2965 // We did find operator delete/operator delete[] declarations, but
2966 // none of them were suitable.
2967 if (!Found.empty()) {
2968 if (Diagnose) {
2969 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2970 << Name << RD;
2971
2972 for (NamedDecl *D : Found)
2973 Diag(D->getUnderlyingDecl()->getLocation(),
2974 diag::note_member_declared_here) << Name;
2975 }
2976 return true;
2977 }
2978
2979 Operator = nullptr;
2980 return false;
2981}
2982
2983namespace {
2984/// Checks whether delete-expression, and new-expression used for
2985/// initializing deletee have the same array form.
2986class MismatchingNewDeleteDetector {
2987public:
2988 enum MismatchResult {
2989 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2990 NoMismatch,
2991 /// Indicates that variable is initialized with mismatching form of \a new.
2992 VarInitMismatches,
2993 /// Indicates that member is initialized with mismatching form of \a new.
2994 MemberInitMismatches,
2995 /// Indicates that 1 or more constructors' definitions could not been
2996 /// analyzed, and they will be checked again at the end of translation unit.
2997 AnalyzeLater
2998 };
2999
3000 /// \param EndOfTU True, if this is the final analysis at the end of
3001 /// translation unit. False, if this is the initial analysis at the point
3002 /// delete-expression was encountered.
3003 explicit MismatchingNewDeleteDetector(bool EndOfTU)
3004 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3005 HasUndefinedConstructors(false) {}
3006
3007 /// Checks whether pointee of a delete-expression is initialized with
3008 /// matching form of new-expression.
3009 ///
3010 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3011 /// point where delete-expression is encountered, then a warning will be
3012 /// issued immediately. If return value is \c AnalyzeLater at the point where
3013 /// delete-expression is seen, then member will be analyzed at the end of
3014 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3015 /// couldn't be analyzed. If at least one constructor initializes the member
3016 /// with matching type of new, the return value is \c NoMismatch.
3017 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3018 /// Analyzes a class member.
3019 /// \param Field Class member to analyze.
3020 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3021 /// for deleting the \p Field.
3022 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3023 FieldDecl *Field;
3024 /// List of mismatching new-expressions used for initialization of the pointee
3025 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3026 /// Indicates whether delete-expression was in array form.
3027 bool IsArrayForm;
3028
3029private:
3030 const bool EndOfTU;
3031 /// Indicates that there is at least one constructor without body.
3032 bool HasUndefinedConstructors;
3033 /// Returns \c CXXNewExpr from given initialization expression.
3034 /// \param E Expression used for initializing pointee in delete-expression.
3035 /// E can be a single-element \c InitListExpr consisting of new-expression.
3036 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3037 /// Returns whether member is initialized with mismatching form of
3038 /// \c new either by the member initializer or in-class initialization.
3039 ///
3040 /// If bodies of all constructors are not visible at the end of translation
3041 /// unit or at least one constructor initializes member with the matching
3042 /// form of \c new, mismatch cannot be proven, and this function will return
3043 /// \c NoMismatch.
3044 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3045 /// Returns whether variable is initialized with mismatching form of
3046 /// \c new.
3047 ///
3048 /// If variable is initialized with matching form of \c new or variable is not
3049 /// initialized with a \c new expression, this function will return true.
3050 /// If variable is initialized with mismatching form of \c new, returns false.
3051 /// \param D Variable to analyze.
3052 bool hasMatchingVarInit(const DeclRefExpr *D);
3053 /// Checks whether the constructor initializes pointee with mismatching
3054 /// form of \c new.
3055 ///
3056 /// Returns true, if member is initialized with matching form of \c new in
3057 /// member initializer list. Returns false, if member is initialized with the
3058 /// matching form of \c new in this constructor's initializer or given
3059 /// constructor isn't defined at the point where delete-expression is seen, or
3060 /// member isn't initialized by the constructor.
3061 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3062 /// Checks whether member is initialized with matching form of
3063 /// \c new in member initializer list.
3064 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3065 /// Checks whether member is initialized with mismatching form of \c new by
3066 /// in-class initializer.
3067 MismatchResult analyzeInClassInitializer();
3068};
3069}
3070
3071MismatchingNewDeleteDetector::MismatchResult
3072MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3073 NewExprs.clear();
3074 assert(DE && "Expected delete-expression")((DE && "Expected delete-expression") ? static_cast<
void> (0) : __assert_fail ("DE && \"Expected delete-expression\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3074, __PRETTY_FUNCTION__))
;
3075 IsArrayForm = DE->isArrayForm();
3076 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3077 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3078 return analyzeMemberExpr(ME);
3079 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3080 if (!hasMatchingVarInit(D))
3081 return VarInitMismatches;
3082 }
3083 return NoMismatch;
3084}
3085
3086const CXXNewExpr *
3087MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3088 assert(E != nullptr && "Expected a valid initializer expression")((E != nullptr && "Expected a valid initializer expression"
) ? static_cast<void> (0) : __assert_fail ("E != nullptr && \"Expected a valid initializer expression\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3088, __PRETTY_FUNCTION__))
;
3089 E = E->IgnoreParenImpCasts();
3090 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3091 if (ILE->getNumInits() == 1)
3092 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3093 }
3094
3095 return dyn_cast_or_null<const CXXNewExpr>(E);
3096}
3097
3098bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3099 const CXXCtorInitializer *CI) {
3100 const CXXNewExpr *NE = nullptr;
3101 if (Field == CI->getMember() &&
3102 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3103 if (NE->isArray() == IsArrayForm)
3104 return true;
3105 else
3106 NewExprs.push_back(NE);
3107 }
3108 return false;
3109}
3110
3111bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3112 const CXXConstructorDecl *CD) {
3113 if (CD->isImplicit())
3114 return false;
3115 const FunctionDecl *Definition = CD;
3116 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3117 HasUndefinedConstructors = true;
3118 return EndOfTU;
3119 }
3120 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3121 if (hasMatchingNewInCtorInit(CI))
3122 return true;
3123 }
3124 return false;
3125}
3126
3127MismatchingNewDeleteDetector::MismatchResult
3128MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3129 assert(Field != nullptr && "This should be called only for members")((Field != nullptr && "This should be called only for members"
) ? static_cast<void> (0) : __assert_fail ("Field != nullptr && \"This should be called only for members\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3129, __PRETTY_FUNCTION__))
;
3130 const Expr *InitExpr = Field->getInClassInitializer();
3131 if (!InitExpr)
3132 return EndOfTU ? NoMismatch : AnalyzeLater;
3133 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3134 if (NE->isArray() != IsArrayForm) {
3135 NewExprs.push_back(NE);
3136 return MemberInitMismatches;
3137 }
3138 }
3139 return NoMismatch;
3140}
3141
3142MismatchingNewDeleteDetector::MismatchResult
3143MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3144 bool DeleteWasArrayForm) {
3145 assert(Field != nullptr && "Analysis requires a valid class member.")((Field != nullptr && "Analysis requires a valid class member."
) ? static_cast<void> (0) : __assert_fail ("Field != nullptr && \"Analysis requires a valid class member.\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3145, __PRETTY_FUNCTION__))
;
3146 this->Field = Field;
3147 IsArrayForm = DeleteWasArrayForm;
3148 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3149 for (const auto *CD : RD->ctors()) {
3150 if (hasMatchingNewInCtor(CD))
3151 return NoMismatch;
3152 }
3153 if (HasUndefinedConstructors)
3154 return EndOfTU ? NoMismatch : AnalyzeLater;
3155 if (!NewExprs.empty())
3156 return MemberInitMismatches;
3157 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3158 : NoMismatch;
3159}
3160
3161MismatchingNewDeleteDetector::MismatchResult
3162MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3163 assert(ME != nullptr && "Expected a member expression")((ME != nullptr && "Expected a member expression") ? static_cast
<void> (0) : __assert_fail ("ME != nullptr && \"Expected a member expression\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3163, __PRETTY_FUNCTION__))
;
3164 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3165 return analyzeField(F, IsArrayForm);
3166 return NoMismatch;
3167}
3168
3169bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3170 const CXXNewExpr *NE = nullptr;
3171 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3172 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3173 NE->isArray() != IsArrayForm) {
3174 NewExprs.push_back(NE);
3175 }
3176 }
3177 return NewExprs.empty();
3178}
3179
3180static void
3181DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3182 const MismatchingNewDeleteDetector &Detector) {
3183 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3184 FixItHint H;
3185 if (!Detector.IsArrayForm)
3186 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3187 else {
3188 SourceLocation RSquare = Lexer::findLocationAfterToken(
3189 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3190 SemaRef.getLangOpts(), true);
3191 if (RSquare.isValid())
3192 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3193 }
3194 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3195 << Detector.IsArrayForm << H;
3196
3197 for (const auto *NE : Detector.NewExprs)
3198 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3199 << Detector.IsArrayForm;
3200}
3201
3202void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3203 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3204 return;
3205 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3206 switch (Detector.analyzeDeleteExpr(DE)) {
3207 case MismatchingNewDeleteDetector::VarInitMismatches:
3208 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3209 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3210 break;
3211 }
3212 case MismatchingNewDeleteDetector::AnalyzeLater: {
3213 DeleteExprs[Detector.Field].push_back(
3214 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3215 break;
3216 }
3217 case MismatchingNewDeleteDetector::NoMismatch:
3218 break;
3219 }
3220}
3221
3222void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3223 bool DeleteWasArrayForm) {
3224 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3225 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3226 case MismatchingNewDeleteDetector::VarInitMismatches:
3227 llvm_unreachable("This analysis should have been done for class members.")::llvm::llvm_unreachable_internal("This analysis should have been done for class members."
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3227)
;
3228 case MismatchingNewDeleteDetector::AnalyzeLater:
3229 llvm_unreachable("Analysis cannot be postponed any point beyond end of "::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of "
"translation unit.", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3230)
3230 "translation unit.")::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of "
"translation unit.", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3230)
;
3231 case MismatchingNewDeleteDetector::MemberInitMismatches:
3232 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3233 break;
3234 case MismatchingNewDeleteDetector::NoMismatch:
3235 break;
3236 }
3237}
3238
3239/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3240/// @code ::delete ptr; @endcode
3241/// or
3242/// @code delete [] ptr; @endcode
3243ExprResult
3244Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3245 bool ArrayForm, Expr *ExE) {
3246 // C++ [expr.delete]p1:
3247 // The operand shall have a pointer type, or a class type having a single
3248 // non-explicit conversion function to a pointer type. The result has type
3249 // void.
3250 //
3251 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3252
3253 ExprResult Ex = ExE;
3254 FunctionDecl *OperatorDelete = nullptr;
3255 bool ArrayFormAsWritten = ArrayForm;
3256 bool UsualArrayDeleteWantsSize = false;
3257
3258 if (!Ex.get()->isTypeDependent()) {
3259 // Perform lvalue-to-rvalue cast, if needed.
3260 Ex = DefaultLvalueConversion(Ex.get());
3261 if (Ex.isInvalid())
3262 return ExprError();
3263
3264 QualType Type = Ex.get()->getType();
3265
3266 class DeleteConverter : public ContextualImplicitConverter {
3267 public:
3268 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3269
3270 bool match(QualType ConvType) override {
3271 // FIXME: If we have an operator T* and an operator void*, we must pick
3272 // the operator T*.
3273 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3274 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3275 return true;
3276 return false;
3277 }
3278
3279 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3280 QualType T) override {
3281 return S.Diag(Loc, diag::err_delete_operand) << T;
3282 }
3283
3284 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3285 QualType T) override {
3286 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3287 }
3288
3289 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3290 QualType T,
3291 QualType ConvTy) override {
3292 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3293 }
3294
3295 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3296 QualType ConvTy) override {
3297 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3298 << ConvTy;
3299 }
3300
3301 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3302 QualType T) override {
3303 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3304 }
3305
3306 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3307 QualType ConvTy) override {
3308 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3309 << ConvTy;
3310 }
3311
3312 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3313 QualType T,
3314 QualType ConvTy) override {
3315 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3315)
;
3316 }
3317 } Converter;
3318
3319 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3320 if (Ex.isInvalid())
3321 return ExprError();
3322 Type = Ex.get()->getType();
3323 if (!Converter.match(Type))
3324 // FIXME: PerformContextualImplicitConversion should return ExprError
3325 // itself in this case.
3326 return ExprError();
3327
3328 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
3329 QualType PointeeElem = Context.getBaseElementType(Pointee);
3330
3331 if (Pointee.getAddressSpace() != LangAS::Default &&
3332 !getLangOpts().OpenCLCPlusPlus)
3333 return Diag(Ex.get()->getBeginLoc(),
3334 diag::err_address_space_qualified_delete)
3335 << Pointee.getUnqualifiedType()
3336 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3337
3338 CXXRecordDecl *PointeeRD = nullptr;
3339 if (Pointee->isVoidType() && !isSFINAEContext()) {
3340 // The C++ standard bans deleting a pointer to a non-object type, which
3341 // effectively bans deletion of "void*". However, most compilers support
3342 // this, so we treat it as a warning unless we're in a SFINAE context.
3343 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3344 << Type << Ex.get()->getSourceRange();
3345 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
3346 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3347 << Type << Ex.get()->getSourceRange());
3348 } else if (!Pointee->isDependentType()) {
3349 // FIXME: This can result in errors if the definition was imported from a
3350 // module but is hidden.
3351 if (!RequireCompleteType(StartLoc, Pointee,
3352 diag::warn_delete_incomplete, Ex.get())) {
3353 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3354 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3355 }
3356 }
3357
3358 if (Pointee->isArrayType() && !ArrayForm) {
3359 Diag(StartLoc, diag::warn_delete_array_type)
3360 << Type << Ex.get()->getSourceRange()
3361 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3362 ArrayForm = true;
3363 }
3364
3365 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3366 ArrayForm ? OO_Array_Delete : OO_Delete);
3367
3368 if (PointeeRD) {
3369 if (!UseGlobal &&
3370 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3371 OperatorDelete))
3372 return ExprError();
3373
3374 // If we're allocating an array of records, check whether the
3375 // usual operator delete[] has a size_t parameter.
3376 if (ArrayForm) {
3377 // If the user specifically asked to use the global allocator,
3378 // we'll need to do the lookup into the class.
3379 if (UseGlobal)
3380 UsualArrayDeleteWantsSize =
3381 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3382
3383 // Otherwise, the usual operator delete[] should be the
3384 // function we just found.
3385 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3386 UsualArrayDeleteWantsSize =
3387 UsualDeallocFnInfo(*this,
3388 DeclAccessPair::make(OperatorDelete, AS_public))
3389 .HasSizeT;
3390 }
3391
3392 if (!PointeeRD->hasIrrelevantDestructor())
3393 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3394 MarkFunctionReferenced(StartLoc,
3395 const_cast<CXXDestructorDecl*>(Dtor));
3396 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3397 return ExprError();
3398 }
3399
3400 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3401 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3402 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3403 SourceLocation());
3404 }
3405
3406 if (!OperatorDelete) {
3407 if (getLangOpts().OpenCLCPlusPlus) {
3408 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3409 return ExprError();
3410 }
3411
3412 bool IsComplete = isCompleteType(StartLoc, Pointee);
3413 bool CanProvideSize =
3414 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3415 Pointee.isDestructedType());
3416 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3417
3418 // Look for a global declaration.
3419 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3420 Overaligned, DeleteName);
3421 }
3422
3423 MarkFunctionReferenced(StartLoc, OperatorDelete);
3424
3425 // Check access and ambiguity of destructor if we're going to call it.
3426 // Note that this is required even for a virtual delete.
3427 bool IsVirtualDelete = false;
3428 if (PointeeRD) {
3429 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3430 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3431 PDiag(diag::err_access_dtor) << PointeeElem);
3432 IsVirtualDelete = Dtor->isVirtual();
3433 }
3434 }
3435
3436 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3437
3438 // Convert the operand to the type of the first parameter of operator
3439 // delete. This is only necessary if we selected a destroying operator
3440 // delete that we are going to call (non-virtually); converting to void*
3441 // is trivial and left to AST consumers to handle.
3442 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3443 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3444 Qualifiers Qs = Pointee.getQualifiers();
3445 if (Qs.hasCVRQualifiers()) {
3446 // Qualifiers are irrelevant to this conversion; we're only looking
3447 // for access and ambiguity.
3448 Qs.removeCVRQualifiers();
3449 QualType Unqual = Context.getPointerType(
3450 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3451 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3452 }
3453 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3454 if (Ex.isInvalid())
3455 return ExprError();
3456 }
3457 }
3458
3459 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3460 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3461 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3462 AnalyzeDeleteExprMismatch(Result);
3463 return Result;
3464}
3465
3466static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3467 bool IsDelete,
3468 FunctionDecl *&Operator) {
3469
3470 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3471 IsDelete ? OO_Delete : OO_New);
3472
3473 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3474 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3475 assert(!R.empty() && "implicitly declared allocation functions not found")((!R.empty() && "implicitly declared allocation functions not found"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3475, __PRETTY_FUNCTION__))
;
3476 assert(!R.isAmbiguous() && "global allocation functions are ambiguous")((!R.isAmbiguous() && "global allocation functions are ambiguous"
) ? static_cast<void> (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3476, __PRETTY_FUNCTION__))
;
3477
3478 // We do our own custom access checks below.
3479 R.suppressDiagnostics();
3480
3481 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3482 OverloadCandidateSet Candidates(R.getNameLoc(),
3483 OverloadCandidateSet::CSK_Normal);
3484 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3485 FnOvl != FnOvlEnd; ++FnOvl) {
3486 // Even member operator new/delete are implicitly treated as
3487 // static, so don't use AddMemberCandidate.
3488 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3489
3490 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3491 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3492 /*ExplicitTemplateArgs=*/nullptr, Args,
3493 Candidates,
3494 /*SuppressUserConversions=*/false);
3495 continue;
3496 }
3497
3498 FunctionDecl *Fn = cast<FunctionDecl>(D);
3499 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3500 /*SuppressUserConversions=*/false);
3501 }
3502
3503 SourceRange Range = TheCall->getSourceRange();
3504
3505 // Do the resolution.
3506 OverloadCandidateSet::iterator Best;
3507 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3508 case OR_Success: {
3509 // Got one!
3510 FunctionDecl *FnDecl = Best->Function;
3511 assert(R.getNamingClass() == nullptr &&((R.getNamingClass() == nullptr && "class members should not be considered"
) ? static_cast<void> (0) : __assert_fail ("R.getNamingClass() == nullptr && \"class members should not be considered\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3512, __PRETTY_FUNCTION__))
3512 "class members should not be considered")((R.getNamingClass() == nullptr && "class members should not be considered"
) ? static_cast<void> (0) : __assert_fail ("R.getNamingClass() == nullptr && \"class members should not be considered\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3512, __PRETTY_FUNCTION__))
;
3513
3514 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3515 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3516 << (IsDelete ? 1 : 0) << Range;
3517 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3518 << R.getLookupName() << FnDecl->getSourceRange();
3519 return true;
3520 }
3521
3522 Operator = FnDecl;
3523 return false;
3524 }
3525
3526 case OR_No_Viable_Function:
3527 Candidates.NoteCandidates(
3528 PartialDiagnosticAt(R.getNameLoc(),
3529 S.PDiag(diag::err_ovl_no_viable_function_in_call)
3530 << R.getLookupName() << Range),
3531 S, OCD_AllCandidates, Args);
3532 return true;
3533
3534 case OR_Ambiguous:
3535 Candidates.NoteCandidates(
3536 PartialDiagnosticAt(R.getNameLoc(),
3537 S.PDiag(diag::err_ovl_ambiguous_call)
3538 << R.getLookupName() << Range),
3539 S, OCD_ViableCandidates, Args);
3540 return true;
3541
3542 case OR_Deleted: {
3543 Candidates.NoteCandidates(
3544 PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3545 << R.getLookupName() << Range),
3546 S, OCD_AllCandidates, Args);
3547 return true;
3548 }
3549 }
3550 llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3550)
;
3551}
3552
3553ExprResult
3554Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3555 bool IsDelete) {
3556 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3557 if (!getLangOpts().CPlusPlus) {
3558 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3559 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3560 << "C++";
3561 return ExprError();
3562 }
3563 // CodeGen assumes it can find the global new and delete to call,
3564 // so ensure that they are declared.
3565 DeclareGlobalNewDelete();
3566
3567 FunctionDecl *OperatorNewOrDelete = nullptr;
3568 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3569 OperatorNewOrDelete))
3570 return ExprError();
3571 assert(OperatorNewOrDelete && "should be found")((OperatorNewOrDelete && "should be found") ? static_cast
<void> (0) : __assert_fail ("OperatorNewOrDelete && \"should be found\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3571, __PRETTY_FUNCTION__))
;
3572
3573 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3574 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3575
3576 TheCall->setType(OperatorNewOrDelete->getReturnType());
3577 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3578 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3579 InitializedEntity Entity =
3580 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3581 ExprResult Arg = PerformCopyInitialization(
3582 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3583 if (Arg.isInvalid())
3584 return ExprError();
3585 TheCall->setArg(i, Arg.get());
3586 }
3587 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3588 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&((Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr
&& "Callee expected to be implicit cast to a builtin function pointer"
) ? static_cast<void> (0) : __assert_fail ("Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && \"Callee expected to be implicit cast to a builtin function pointer\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3589, __PRETTY_FUNCTION__))
3589 "Callee expected to be implicit cast to a builtin function pointer")((Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr
&& "Callee expected to be implicit cast to a builtin function pointer"
) ? static_cast<void> (0) : __assert_fail ("Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && \"Callee expected to be implicit cast to a builtin function pointer\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3589, __PRETTY_FUNCTION__))
;
3590 Callee->setType(OperatorNewOrDelete->getType());
3591
3592 return TheCallResult;
3593}
3594
3595void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3596 bool IsDelete, bool CallCanBeVirtual,
3597 bool WarnOnNonAbstractTypes,
3598 SourceLocation DtorLoc) {
3599 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3600 return;
3601
3602 // C++ [expr.delete]p3:
3603 // In the first alternative (delete object), if the static type of the
3604 // object to be deleted is different from its dynamic type, the static
3605 // type shall be a base class of the dynamic type of the object to be
3606 // deleted and the static type shall have a virtual destructor or the
3607 // behavior is undefined.
3608 //
3609 const CXXRecordDecl *PointeeRD = dtor->getParent();
3610 // Note: a final class cannot be derived from, no issue there
3611 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3612 return;
3613
3614 // If the superclass is in a system header, there's nothing that can be done.
3615 // The `delete` (where we emit the warning) can be in a system header,
3616 // what matters for this warning is where the deleted type is defined.
3617 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3618 return;
3619
3620 QualType ClassType = dtor->getThisType()->getPointeeType();
3621 if (PointeeRD->isAbstract()) {
3622 // If the class is abstract, we warn by default, because we're
3623 // sure the code has undefined behavior.
3624 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3625 << ClassType;
3626 } else if (WarnOnNonAbstractTypes) {
3627 // Otherwise, if this is not an array delete, it's a bit suspect,
3628 // but not necessarily wrong.
3629 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3630 << ClassType;
3631 }
3632 if (!IsDelete) {
3633 std::string TypeStr;
3634 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3635 Diag(DtorLoc, diag::note_delete_non_virtual)
3636 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3637 }
3638}
3639
3640Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3641 SourceLocation StmtLoc,
3642 ConditionKind CK) {
3643 ExprResult E =
3644 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3645 if (E.isInvalid())
3646 return ConditionError();
3647 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3648 CK == ConditionKind::ConstexprIf);
3649}
3650
3651/// Check the use of the given variable as a C++ condition in an if,
3652/// while, do-while, or switch statement.
3653ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3654 SourceLocation StmtLoc,
3655 ConditionKind CK) {
3656 if (ConditionVar->isInvalidDecl())
3657 return ExprError();
3658
3659 QualType T = ConditionVar->getType();
3660
3661 // C++ [stmt.select]p2:
3662 // The declarator shall not specify a function or an array.
3663 if (T->isFunctionType())
3664 return ExprError(Diag(ConditionVar->getLocation(),
3665 diag::err_invalid_use_of_function_type)
3666 << ConditionVar->getSourceRange());
3667 else if (T->isArrayType())
3668 return ExprError(Diag(ConditionVar->getLocation(),
3669 diag::err_invalid_use_of_array_type)
3670 << ConditionVar->getSourceRange());
3671
3672 ExprResult Condition = DeclRefExpr::Create(
3673 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3674 /*enclosing*/ false, ConditionVar->getLocation(),
3675 ConditionVar->getType().getNonReferenceType(), VK_LValue);
3676
3677 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
3678
3679 switch (CK) {
3680 case ConditionKind::Boolean:
3681 return CheckBooleanCondition(StmtLoc, Condition.get());
3682
3683 case ConditionKind::ConstexprIf:
3684 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3685
3686 case ConditionKind::Switch:
3687 return CheckSwitchCondition(StmtLoc, Condition.get());
3688 }
3689
3690 llvm_unreachable("unexpected condition kind")::llvm::llvm_unreachable_internal("unexpected condition kind"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3690)
;
3691}
3692
3693/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3694ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3695 // C++ 6.4p4:
3696 // The value of a condition that is an initialized declaration in a statement
3697 // other than a switch statement is the value of the declared variable
3698 // implicitly converted to type bool. If that conversion is ill-formed, the
3699 // program is ill-formed.
3700 // The value of a condition that is an expression is the value of the
3701 // expression, implicitly converted to bool.
3702 //
3703 // FIXME: Return this value to the caller so they don't need to recompute it.
3704 llvm::APSInt Value(/*BitWidth*/1);
3705 return (IsConstexpr && !CondExpr->isValueDependent())
3706 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3707 CCEK_ConstexprIf)
3708 : PerformContextuallyConvertToBool(CondExpr);
3709}
3710
3711/// Helper function to determine whether this is the (deprecated) C++
3712/// conversion from a string literal to a pointer to non-const char or
3713/// non-const wchar_t (for narrow and wide string literals,
3714/// respectively).
3715bool
3716Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3717 // Look inside the implicit cast, if it exists.
3718 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3719 From = Cast->getSubExpr();
3720
3721 // A string literal (2.13.4) that is not a wide string literal can
3722 // be converted to an rvalue of type "pointer to char"; a wide
3723 // string literal can be converted to an rvalue of type "pointer
3724 // to wchar_t" (C++ 4.2p2).
3725 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3726 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3727 if (const BuiltinType *ToPointeeType
3728 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3729 // This conversion is considered only when there is an
3730 // explicit appropriate pointer target type (C++ 4.2p2).
3731 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3732 switch (StrLit->getKind()) {
3733 case StringLiteral::UTF8:
3734 case StringLiteral::UTF16:
3735 case StringLiteral::UTF32:
3736 // We don't allow UTF literals to be implicitly converted
3737 break;
3738 case StringLiteral::Ascii:
3739 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3740 ToPointeeType->getKind() == BuiltinType::Char_S);
3741 case StringLiteral::Wide:
3742 return Context.typesAreCompatible(Context.getWideCharType(),
3743 QualType(ToPointeeType, 0));
3744 }
3745 }
3746 }
3747
3748 return false;
3749}
3750
3751static ExprResult BuildCXXCastArgument(Sema &S,
3752 SourceLocation CastLoc,
3753 QualType Ty,
3754 CastKind Kind,
3755 CXXMethodDecl *Method,
3756 DeclAccessPair FoundDecl,
3757 bool HadMultipleCandidates,
3758 Expr *From) {
3759 switch (Kind) {
3760 default: llvm_unreachable("Unhandled cast kind!")::llvm::llvm_unreachable_internal("Unhandled cast kind!", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3760)
;
3761 case CK_ConstructorConversion: {
3762 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3763 SmallVector<Expr*, 8> ConstructorArgs;
3764
3765 if (S.RequireNonAbstractType(CastLoc, Ty,
3766 diag::err_allocation_of_abstract_type))
3767 return ExprError();
3768
3769 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3770 return ExprError();
3771
3772 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3773 InitializedEntity::InitializeTemporary(Ty));
3774 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3775 return ExprError();
3776
3777 ExprResult Result = S.BuildCXXConstructExpr(
3778 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3779 ConstructorArgs, HadMultipleCandidates,
3780 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3781 CXXConstructExpr::CK_Complete, SourceRange());
3782 if (Result.isInvalid())
3783 return ExprError();
3784
3785 return S.MaybeBindToTemporary(Result.getAs<Expr>());
3786 }
3787
3788 case CK_UserDefinedConversion: {
3789 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!")((!From->getType()->isPointerType() && "Arg can't have pointer type!"
) ? static_cast<void> (0) : __assert_fail ("!From->getType()->isPointerType() && \"Arg can't have pointer type!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3789, __PRETTY_FUNCTION__))
;
3790
3791 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3792 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3793 return ExprError();
3794
3795 // Create an implicit call expr that calls it.
3796 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3797 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3798 HadMultipleCandidates);
3799 if (Result.isInvalid())
3800 return ExprError();
3801 // Record usage of conversion in an implicit cast.
3802 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3803 CK_UserDefinedConversion, Result.get(),
3804 nullptr, Result.get()->getValueKind());
3805
3806 return S.MaybeBindToTemporary(Result.get());
3807 }
3808 }
3809}
3810
3811/// PerformImplicitConversion - Perform an implicit conversion of the
3812/// expression From to the type ToType using the pre-computed implicit
3813/// conversion sequence ICS. Returns the converted
3814/// expression. Action is the kind of conversion we're performing,
3815/// used in the error message.
3816ExprResult
3817Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3818 const ImplicitConversionSequence &ICS,
3819 AssignmentAction Action,
3820 CheckedConversionKind CCK) {
3821 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3822 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3823 return From;
3824
3825 switch (ICS.getKind()) {
3826 case ImplicitConversionSequence::StandardConversion: {
3827 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3828 Action, CCK);
3829 if (Res.isInvalid())
3830 return ExprError();
3831 From = Res.get();
3832 break;
3833 }
3834
3835 case ImplicitConversionSequence::UserDefinedConversion: {
3836
3837 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
3838 CastKind CastKind;
3839 QualType BeforeToType;
3840 assert(FD && "no conversion function for user-defined conversion seq")((FD && "no conversion function for user-defined conversion seq"
) ? static_cast<void> (0) : __assert_fail ("FD && \"no conversion function for user-defined conversion seq\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3840, __PRETTY_FUNCTION__))
;
3841 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3842 CastKind = CK_UserDefinedConversion;
3843
3844 // If the user-defined conversion is specified by a conversion function,
3845 // the initial standard conversion sequence converts the source type to
3846 // the implicit object parameter of the conversion function.
3847 BeforeToType = Context.getTagDeclType(Conv->getParent());
3848 } else {
3849 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3850 CastKind = CK_ConstructorConversion;
3851 // Do no conversion if dealing with ... for the first conversion.
3852 if (!ICS.UserDefined.EllipsisConversion) {
3853 // If the user-defined conversion is specified by a constructor, the
3854 // initial standard conversion sequence converts the source type to
3855 // the type required by the argument of the constructor
3856 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3857 }
3858 }
3859 // Watch out for ellipsis conversion.
3860 if (!ICS.UserDefined.EllipsisConversion) {
3861 ExprResult Res =
3862 PerformImplicitConversion(From, BeforeToType,
3863 ICS.UserDefined.Before, AA_Converting,
3864 CCK);
3865 if (Res.isInvalid())
3866 return ExprError();
3867 From = Res.get();
3868 }
3869
3870 ExprResult CastArg = BuildCXXCastArgument(
3871 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3872 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3873 ICS.UserDefined.HadMultipleCandidates, From);
3874
3875 if (CastArg.isInvalid())
3876 return ExprError();
3877
3878 From = CastArg.get();
3879
3880 // C++ [over.match.oper]p7:
3881 // [...] the second standard conversion sequence of a user-defined
3882 // conversion sequence is not applied.
3883 if (CCK == CCK_ForBuiltinOverloadedOp)
3884 return From;
3885
3886 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3887 AA_Converting, CCK);
3888 }
3889
3890 case ImplicitConversionSequence::AmbiguousConversion:
3891 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
3892 PDiag(diag::err_typecheck_ambiguous_condition)
3893 << From->getSourceRange());
3894 return ExprError();
3895
3896 case ImplicitConversionSequence::EllipsisConversion:
3897 llvm_unreachable("Cannot perform an ellipsis conversion")::llvm::llvm_unreachable_internal("Cannot perform an ellipsis conversion"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3897)
;
3898
3899 case ImplicitConversionSequence::BadConversion:
3900 bool Diagnosed =
3901 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3902 From->getType(), From, Action);
3903 assert(Diagnosed && "failed to diagnose bad conversion")((Diagnosed && "failed to diagnose bad conversion") ?
static_cast<void> (0) : __assert_fail ("Diagnosed && \"failed to diagnose bad conversion\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3903, __PRETTY_FUNCTION__))
; (void)Diagnosed;
3904 return ExprError();
3905 }
3906
3907 // Everything went well.
3908 return From;
3909}
3910
3911/// PerformImplicitConversion - Perform an implicit conversion of the
3912/// expression From to the type ToType by following the standard
3913/// conversion sequence SCS. Returns the converted
3914/// expression. Flavor is the context in which we're performing this
3915/// conversion, for use in error messages.
3916ExprResult
3917Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3918 const StandardConversionSequence& SCS,
3919 AssignmentAction Action,
3920 CheckedConversionKind CCK) {
3921 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
3922
3923 // Overall FIXME: we are recomputing too many types here and doing far too
3924 // much extra work. What this means is that we need to keep track of more
3925 // information that is computed when we try the implicit conversion initially,
3926 // so that we don't need to recompute anything here.
3927 QualType FromType = From->getType();
3928
3929 if (SCS.CopyConstructor) {
3930 // FIXME: When can ToType be a reference type?
3931 assert(!ToType->isReferenceType())((!ToType->isReferenceType()) ? static_cast<void> (0
) : __assert_fail ("!ToType->isReferenceType()", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3931, __PRETTY_FUNCTION__))
;
3932 if (SCS.Second == ICK_Derived_To_Base) {
3933 SmallVector<Expr*, 8> ConstructorArgs;
3934 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
3935 From, /*FIXME:ConstructLoc*/SourceLocation(),
3936 ConstructorArgs))
3937 return ExprError();
3938 return BuildCXXConstructExpr(
3939 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3940 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3941 ConstructorArgs, /*HadMultipleCandidates*/ false,
3942 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3943 CXXConstructExpr::CK_Complete, SourceRange());
3944 }
3945 return BuildCXXConstructExpr(
3946 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3947 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3948 From, /*HadMultipleCandidates*/ false,
3949 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3950 CXXConstructExpr::CK_Complete, SourceRange());
3951 }
3952
3953 // Resolve overloaded function references.
3954 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3955 DeclAccessPair Found;
3956 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3957 true, Found);
3958 if (!Fn)
3959 return ExprError();
3960
3961 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
3962 return ExprError();
3963
3964 From = FixOverloadedFunctionReference(From, Found, Fn);
3965 FromType = From->getType();
3966 }
3967
3968 // If we're converting to an atomic type, first convert to the corresponding
3969 // non-atomic type.
3970 QualType ToAtomicType;
3971 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3972 ToAtomicType = ToType;
3973 ToType = ToAtomic->getValueType();
3974 }
3975
3976 QualType InitialFromType = FromType;
3977 // Perform the first implicit conversion.
3978 switch (SCS.First) {
3979 case ICK_Identity:
3980 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3981 FromType = FromAtomic->getValueType().getUnqualifiedType();
3982 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3983 From, /*BasePath=*/nullptr, VK_RValue);
3984 }
3985 break;
3986
3987 case ICK_Lvalue_To_Rvalue: {
3988 assert(From->getObjectKind() != OK_ObjCProperty)((From->getObjectKind() != OK_ObjCProperty) ? static_cast<
void> (0) : __assert_fail ("From->getObjectKind() != OK_ObjCProperty"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3988, __PRETTY_FUNCTION__))
;
3989 ExprResult FromRes = DefaultLvalueConversion(From);
3990 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!")((!FromRes.isInvalid() && "Can't perform deduced conversion?!"
) ? static_cast<void> (0) : __assert_fail ("!FromRes.isInvalid() && \"Can't perform deduced conversion?!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3990, __PRETTY_FUNCTION__))
;
3991 From = FromRes.get();
3992 FromType = From->getType();
3993 break;
3994 }
3995
3996 case ICK_Array_To_Pointer:
3997 FromType = Context.getArrayDecayedType(FromType);
3998 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
3999 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4000 break;
4001
4002 case ICK_Function_To_Pointer:
4003 FromType = Context.getPointerType(FromType);
4004 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4005 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4006 break;
4007
4008 default:
4009 llvm_unreachable("Improper first standard conversion")::llvm::llvm_unreachable_internal("Improper first standard conversion"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4009)
;
4010 }
4011
4012 // Perform the second implicit conversion
4013 switch (SCS.Second) {
4014 case ICK_Identity:
4015 // C++ [except.spec]p5:
4016 // [For] assignment to and initialization of pointers to functions,
4017 // pointers to member functions, and references to functions: the
4018 // target entity shall allow at least the exceptions allowed by the
4019 // source value in the assignment or initialization.
4020 switch (Action) {
4021 case AA_Assigning:
4022 case AA_Initializing:
4023 // Note, function argument passing and returning are initialization.
4024 case AA_Passing:
4025 case AA_Returning:
4026 case AA_Sending:
4027 case AA_Passing_CFAudited:
4028 if (CheckExceptionSpecCompatibility(From, ToType))
4029 return ExprError();
4030 break;
4031
4032 case AA_Casting:
4033 case AA_Converting:
4034 // Casts and implicit conversions are not initialization, so are not
4035 // checked for exception specification mismatches.
4036 break;
4037 }
4038 // Nothing else to do.
4039 break;
4040
4041 case ICK_Integral_Promotion:
4042 case ICK_Integral_Conversion:
4043 if (ToType->isBooleanType()) {
4044 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&((FromType->castAs<EnumType>()->getDecl()->isFixed
() && SCS.Second == ICK_Integral_Promotion &&
"only enums with fixed underlying type can promote to bool")
? static_cast<void> (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4046, __PRETTY_FUNCTION__))
4045 SCS.Second == ICK_Integral_Promotion &&((FromType->castAs<EnumType>()->getDecl()->isFixed
() && SCS.Second == ICK_Integral_Promotion &&
"only enums with fixed underlying type can promote to bool")
? static_cast<void> (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4046, __PRETTY_FUNCTION__))
4046 "only enums with fixed underlying type can promote to bool")((FromType->castAs<EnumType>()->getDecl()->isFixed
() && SCS.Second == ICK_Integral_Promotion &&
"only enums with fixed underlying type can promote to bool")
? static_cast<void> (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4046, __PRETTY_FUNCTION__))
;
4047 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
4048 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4049 } else {
4050 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
4051 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4052 }
4053 break;
4054
4055 case ICK_Floating_Promotion:
4056 case ICK_Floating_Conversion:
4057 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
4058 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4059 break;
4060
4061 case ICK_Complex_Promotion:
4062 case ICK_Complex_Conversion: {
4063 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
4064 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
4065 CastKind CK;
4066 if (FromEl->isRealFloatingType()) {
4067 if (ToEl->isRealFloatingType())
4068 CK = CK_FloatingComplexCast;
4069 else
4070 CK = CK_FloatingComplexToIntegralComplex;
4071 } else if (ToEl->isRealFloatingType()) {
4072 CK = CK_IntegralComplexToFloatingComplex;
4073 } else {
4074 CK = CK_IntegralComplexCast;
4075 }
4076 From = ImpCastExprToType(From, ToType, CK,
4077 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4078 break;
4079 }
4080
4081 case ICK_Floating_Integral:
4082 if (ToType->isRealFloatingType())
4083 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
4084 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4085 else
4086 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
4087 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4088 break;
4089
4090 case ICK_Compatible_Conversion:
4091 From = ImpCastExprToType(From, ToType, CK_NoOp,
4092 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4093 break;
4094
4095 case ICK_Writeback_Conversion:
4096 case ICK_Pointer_Conversion: {
4097 if (SCS.IncompatibleObjC && Action != AA_Casting) {
4098 // Diagnose incompatible Objective-C conversions
4099 if (Action == AA_Initializing || Action == AA_Assigning)
4100 Diag(From->getBeginLoc(),
4101 diag::ext_typecheck_convert_incompatible_pointer)
4102 << ToType << From->getType() << Action << From->getSourceRange()
4103 << 0;
4104 else
4105 Diag(From->getBeginLoc(),
4106 diag::ext_typecheck_convert_incompatible_pointer)
4107 << From->getType() << ToType << Action << From->getSourceRange()
4108 << 0;
4109
4110 if (From->getType()->isObjCObjectPointerType() &&
4111 ToType->isObjCObjectPointerType())
4112 EmitRelatedResultTypeNote(From);
4113 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4114 !CheckObjCARCUnavailableWeakConversion(ToType,
4115 From->getType())) {
4116 if (Action == AA_Initializing)
4117 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4118 else
4119 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4120 << (Action == AA_Casting) << From->getType() << ToType
4121 << From->getSourceRange();
4122 }
4123
4124 CastKind Kind;
4125 CXXCastPath BasePath;
4126 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
4127 return ExprError();
4128
4129 // Make sure we extend blocks if necessary.
4130 // FIXME: doing this here is really ugly.
4131 if (Kind == CK_BlockPointerToObjCPointerCast) {
4132 ExprResult E = From;
4133 (void) PrepareCastToObjCObjectPointer(E);
4134 From = E.get();
4135 }
4136 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4137 CheckObjCConversion(SourceRange(), ToType, From, CCK);
4138 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
4139 .get();
4140 break;
4141 }
4142
4143 case ICK_Pointer_Member: {
4144 CastKind Kind;
4145 CXXCastPath BasePath;
4146 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4147 return ExprError();
4148 if (CheckExceptionSpecCompatibility(From, ToType))
4149 return ExprError();
4150
4151 // We may not have been able to figure out what this member pointer resolved
4152 // to up until this exact point. Attempt to lock-in it's inheritance model.
4153 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4154 (void)isCompleteType(From->getExprLoc(), From->getType());
4155 (void)isCompleteType(From->getExprLoc(), ToType);
4156 }
4157
4158 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
4159 .get();
4160 break;
4161 }
4162
4163 case ICK_Boolean_Conversion:
4164 // Perform half-to-boolean conversion via float.
4165 if (From->getType()->isHalfType()) {
4166 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4167 FromType = Context.FloatTy;
4168 }
4169
4170 From = ImpCastExprToType(From, Context.BoolTy,
4171 ScalarTypeToBooleanCastKind(FromType),
4172 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4173 break;
4174
4175 case ICK_Derived_To_Base: {
4176 CXXCastPath BasePath;
4177 if (CheckDerivedToBaseConversion(
4178 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4179 From->getSourceRange(), &BasePath, CStyle))
4180 return ExprError();
4181
4182 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4183 CK_DerivedToBase, From->getValueKind(),
4184 &BasePath, CCK).get();
4185 break;
4186 }
4187
4188 case ICK_Vector_Conversion:
4189 From = ImpCastExprToType(From, ToType, CK_BitCast,
4190 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4191 break;
4192
4193 case ICK_Vector_Splat: {
4194 // Vector splat from any arithmetic type to a vector.
4195 Expr *Elem = prepareVectorSplat(ToType, From).get();
4196 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4197 /*BasePath=*/nullptr, CCK).get();
4198 break;
4199 }
4200
4201 case ICK_Complex_Real:
4202 // Case 1. x -> _Complex y
4203 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4204 QualType ElType = ToComplex->getElementType();
4205 bool isFloatingComplex = ElType->isRealFloatingType();
4206
4207 // x -> y
4208 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4209 // do nothing
4210 } else if (From->getType()->isRealFloatingType()) {
4211 From = ImpCastExprToType(From, ElType,
4212 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4213 } else {
4214 assert(From->getType()->isIntegerType())((From->getType()->isIntegerType()) ? static_cast<void
> (0) : __assert_fail ("From->getType()->isIntegerType()"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4214, __PRETTY_FUNCTION__))
;
4215 From = ImpCastExprToType(From, ElType,
4216 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4217 }
4218 // y -> _Complex y
4219 From = ImpCastExprToType(From, ToType,
4220 isFloatingComplex ? CK_FloatingRealToComplex
4221 : CK_IntegralRealToComplex).get();
4222
4223 // Case 2. _Complex x -> y
4224 } else {
4225 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4226 assert(FromComplex)((FromComplex) ? static_cast<void> (0) : __assert_fail (
"FromComplex", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4226, __PRETTY_FUNCTION__))
;
4227
4228 QualType ElType = FromComplex->getElementType();
4229 bool isFloatingComplex = ElType->isRealFloatingType();
4230
4231 // _Complex x -> x
4232 From = ImpCastExprToType(From, ElType,
4233 isFloatingComplex ? CK_FloatingComplexToReal
4234 : CK_IntegralComplexToReal,
4235 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4236
4237 // x -> y
4238 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4239 // do nothing
4240 } else if (ToType->isRealFloatingType()) {
4241 From = ImpCastExprToType(From, ToType,
4242 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
4243 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4244 } else {
4245 assert(ToType->isIntegerType())((ToType->isIntegerType()) ? static_cast<void> (0) :
__assert_fail ("ToType->isIntegerType()", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4245, __PRETTY_FUNCTION__))
;
4246 From = ImpCastExprToType(From, ToType,
4247 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
4248 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4249 }
4250 }
4251 break;
4252
4253 case ICK_Block_Pointer_Conversion: {
4254 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
4255 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4256 break;
4257 }
4258
4259 case ICK_TransparentUnionConversion: {
4260 ExprResult FromRes = From;
4261 Sema::AssignConvertType ConvTy =
4262 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4263 if (FromRes.isInvalid())
4264 return ExprError();
4265 From = FromRes.get();
4266 assert ((ConvTy == Sema::Compatible) &&(((ConvTy == Sema::Compatible) && "Improper transparent union conversion"
) ? static_cast<void> (0) : __assert_fail ("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4267, __PRETTY_FUNCTION__))
4267 "Improper transparent union conversion")(((ConvTy == Sema::Compatible) && "Improper transparent union conversion"
) ? static_cast<void> (0) : __assert_fail ("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4267, __PRETTY_FUNCTION__))
;
4268 (void)ConvTy;
4269 break;
4270 }
4271
4272 case ICK_Zero_Event_Conversion:
4273 case ICK_Zero_Queue_Conversion:
4274 From = ImpCastExprToType(From, ToType,
4275 CK_ZeroToOCLOpaqueType,
4276 From->getValueKind()).get();
4277 break;
4278
4279 case ICK_Lvalue_To_Rvalue:
4280 case ICK_Array_To_Pointer:
4281 case ICK_Function_To_Pointer:
4282 case ICK_Function_Conversion:
4283 case ICK_Qualification:
4284 case ICK_Num_Conversion_Kinds:
4285 case ICK_C_Only_Conversion:
4286 case ICK_Incompatible_Pointer_Conversion:
4287 llvm_unreachable("Improper second standard conversion")::llvm::llvm_unreachable_internal("Improper second standard conversion"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4287)
;
4288 }
4289
4290 switch (SCS.Third) {
4291 case ICK_Identity:
4292 // Nothing to do.
4293 break;
4294
4295 case ICK_Function_Conversion:
4296 // If both sides are functions (or pointers/references to them), there could
4297 // be incompatible exception declarations.
4298 if (CheckExceptionSpecCompatibility(From, ToType))
4299 return ExprError();
4300
4301 From = ImpCastExprToType(From, ToType, CK_NoOp,
4302 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4303 break;
4304
4305 case ICK_Qualification: {
4306 // The qualification keeps the category of the inner expression, unless the
4307 // target type isn't a reference.
4308 ExprValueKind VK =
4309 ToType->isReferenceType() ? From->getValueKind() : VK_RValue;
4310
4311 CastKind CK = CK_NoOp;
4312
4313 if (ToType->isReferenceType() &&
4314 ToType->getPointeeType().getAddressSpace() !=
4315 From->getType().getAddressSpace())
4316 CK = CK_AddressSpaceConversion;
4317
4318 if (ToType->isPointerType() &&
4319 ToType->getPointeeType().getAddressSpace() !=
4320 From->getType()->getPointeeType().getAddressSpace())
4321 CK = CK_AddressSpaceConversion;
4322
4323 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4324 /*BasePath=*/nullptr, CCK)
4325 .get();
4326
4327 if (SCS.DeprecatedStringLiteralToCharPtr &&
4328 !getLangOpts().WritableStrings) {
4329 Diag(From->getBeginLoc(),
4330 getLangOpts().CPlusPlus11
4331 ? diag::ext_deprecated_string_literal_conversion
4332 : diag::warn_deprecated_string_literal_conversion)
4333 << ToType.getNonReferenceType();
4334 }
4335
4336 break;
4337 }
4338
4339 default:
4340 llvm_unreachable("Improper third standard conversion")::llvm::llvm_unreachable_internal("Improper third standard conversion"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4340)
;
4341 }
4342
4343 // If this conversion sequence involved a scalar -> atomic conversion, perform
4344 // that conversion now.
4345 if (!ToAtomicType.isNull()) {
4346 assert(Context.hasSameType(((Context.hasSameType( ToAtomicType->castAs<AtomicType>
()->getValueType(), From->getType())) ? static_cast<
void> (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4347, __PRETTY_FUNCTION__))
4347 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()))((Context.hasSameType( ToAtomicType->castAs<AtomicType>
()->getValueType(), From->getType())) ? static_cast<
void> (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4347, __PRETTY_FUNCTION__))
;
4348 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4349 VK_RValue, nullptr, CCK).get();
4350 }
4351
4352 // If this conversion sequence succeeded and involved implicitly converting a
4353 // _Nullable type to a _Nonnull one, complain.
4354 if (!isCast(CCK))
4355 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4356 From->getBeginLoc());
4357
4358 return From;
4359}
4360
4361/// Check the completeness of a type in a unary type trait.
4362///
4363/// If the particular type trait requires a complete type, tries to complete
4364/// it. If completing the type fails, a diagnostic is emitted and false
4365/// returned. If completing the type succeeds or no completion was required,
4366/// returns true.
4367static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4368 SourceLocation Loc,
4369 QualType ArgTy) {
4370 // C++0x [meta.unary.prop]p3:
4371 // For all of the class templates X declared in this Clause, instantiating
4372 // that template with a template argument that is a class template
4373 // specialization may result in the implicit instantiation of the template
4374 // argument if and only if the semantics of X require that the argument
4375 // must be a complete type.
4376 // We apply this rule to all the type trait expressions used to implement
4377 // these class templates. We also try to follow any GCC documented behavior
4378 // in these expressions to ensure portability of standard libraries.
4379 switch (UTT) {
4380 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4380)
;
4381 // is_complete_type somewhat obviously cannot require a complete type.
4382 case UTT_IsCompleteType:
4383 // Fall-through
4384
4385 // These traits are modeled on the type predicates in C++0x
4386 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4387 // requiring a complete type, as whether or not they return true cannot be
4388 // impacted by the completeness of the type.
4389 case UTT_IsVoid:
4390 case UTT_IsIntegral:
4391 case UTT_IsFloatingPoint:
4392 case UTT_IsArray:
4393 case UTT_IsPointer:
4394 case UTT_IsLvalueReference:
4395 case UTT_IsRvalueReference:
4396 case UTT_IsMemberFunctionPointer:
4397 case UTT_IsMemberObjectPointer:
4398 case UTT_IsEnum:
4399 case UTT_IsUnion:
4400 case UTT_IsClass:
4401 case UTT_IsFunction:
4402 case UTT_IsReference:
4403 case UTT_IsArithmetic:
4404 case UTT_IsFundamental:
4405 case UTT_IsObject:
4406 case UTT_IsScalar:
4407 case UTT_IsCompound:
4408 case UTT_IsMemberPointer:
4409 // Fall-through
4410
4411 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4412 // which requires some of its traits to have the complete type. However,
4413 // the completeness of the type cannot impact these traits' semantics, and
4414 // so they don't require it. This matches the comments on these traits in
4415 // Table 49.
4416 case UTT_IsConst:
4417 case UTT_IsVolatile:
4418 case UTT_IsSigned:
4419 case UTT_IsUnsigned:
4420
4421 // This type trait always returns false, checking the type is moot.
4422 case UTT_IsInterfaceClass:
4423 return true;
4424
4425 // C++14 [meta.unary.prop]:
4426 // If T is a non-union class type, T shall be a complete type.
4427 case UTT_IsEmpty:
4428 case UTT_IsPolymorphic:
4429 case UTT_IsAbstract:
4430 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4431 if (!RD->isUnion())
4432 return !S.RequireCompleteType(
4433 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4434 return true;
4435
4436 // C++14 [meta.unary.prop]:
4437 // If T is a class type, T shall be a complete type.
4438 case UTT_IsFinal:
4439 case UTT_IsSealed:
4440 if (ArgTy->getAsCXXRecordDecl())
4441 return !S.RequireCompleteType(
4442 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4443 return true;
4444
4445 // C++1z [meta.unary.prop]:
4446 // remove_all_extents_t<T> shall be a complete type or cv void.
4447 case UTT_IsAggregate:
4448 case UTT_IsTrivial:
4449 case UTT_IsTriviallyCopyable:
4450 case UTT_IsStandardLayout:
4451 case UTT_IsPOD:
4452 case UTT_IsLiteral:
4453 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4454 // or an array of unknown bound. But GCC actually imposes the same constraints
4455 // as above.
4456 case UTT_HasNothrowAssign:
4457 case UTT_HasNothrowMoveAssign:
4458 case UTT_HasNothrowConstructor:
4459 case UTT_HasNothrowCopy:
4460 case UTT_HasTrivialAssign:
4461 case UTT_HasTrivialMoveAssign:
4462 case UTT_HasTrivialDefaultConstructor:
4463 case UTT_HasTrivialMoveConstructor:
4464 case UTT_HasTrivialCopy:
4465 case UTT_HasTrivialDestructor:
4466 case UTT_HasVirtualDestructor:
4467 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4468 LLVM_FALLTHROUGH[[clang::fallthrough]];
4469
4470 // C++1z [meta.unary.prop]:
4471 // T shall be a complete type, cv void, or an array of unknown bound.
4472 case UTT_IsDestructible:
4473 case UTT_IsNothrowDestructible:
4474 case UTT_IsTriviallyDestructible:
4475 case UTT_HasUniqueObjectRepresentations:
4476 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4477 return true;
4478
4479 return !S.RequireCompleteType(
4480 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4481 }
4482}
4483
4484static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4485 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4486 bool (CXXRecordDecl::*HasTrivial)() const,
4487 bool (CXXRecordDecl::*HasNonTrivial)() const,
4488 bool (CXXMethodDecl::*IsDesiredOp)() const)
4489{
4490 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4491 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4492 return true;
4493
4494 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4495 DeclarationNameInfo NameInfo(Name, KeyLoc);
4496 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4497 if (Self.LookupQualifiedName(Res, RD)) {
4498 bool FoundOperator = false;
4499 Res.suppressDiagnostics();
4500 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4501 Op != OpEnd; ++Op) {
4502 if (isa<FunctionTemplateDecl>(*Op))
4503 continue;
4504
4505 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4506 if((Operator->*IsDesiredOp)()) {
4507 FoundOperator = true;
4508 const FunctionProtoType *CPT =
4509 Operator->getType()->getAs<FunctionProtoType>();
4510 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4511 if (!CPT || !CPT->isNothrow())
4512 return false;
4513 }
4514 }
4515 return FoundOperator;
4516 }
4517 return false;
4518}
4519
4520static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4521 SourceLocation KeyLoc, QualType T) {
4522 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")((!T->isDependentType() && "Cannot evaluate traits of dependent type"
) ? static_cast<void> (0) : __assert_fail ("!T->isDependentType() && \"Cannot evaluate traits of dependent type\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4522, __PRETTY_FUNCTION__))
;
4523
4524 ASTContext &C = Self.Context;
4525 switch(UTT) {
4526 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4526)
;
4527 // Type trait expressions corresponding to the primary type category
4528 // predicates in C++0x [meta.unary.cat].
4529 case UTT_IsVoid:
4530 return T->isVoidType();
4531 case UTT_IsIntegral:
4532 return T->isIntegralType(C);
4533 case UTT_IsFloatingPoint:
4534 return T->isFloatingType();
4535 case UTT_IsArray:
4536 return T->isArrayType();
4537 case UTT_IsPointer:
4538 return T->isPointerType();
4539 case UTT_IsLvalueReference:
4540 return T->isLValueReferenceType();
4541 case UTT_IsRvalueReference:
4542 return T->isRValueReferenceType();
4543 case UTT_IsMemberFunctionPointer:
4544 return T->isMemberFunctionPointerType();
4545 case UTT_IsMemberObjectPointer:
4546 return T->isMemberDataPointerType();
4547 case UTT_IsEnum:
4548 return T->isEnumeralType();
4549 case UTT_IsUnion:
4550 return T->isUnionType();
4551 case UTT_IsClass:
4552 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4553 case UTT_IsFunction:
4554 return T->isFunctionType();
4555
4556 // Type trait expressions which correspond to the convenient composition
4557 // predicates in C++0x [meta.unary.comp].
4558 case UTT_IsReference:
4559 return T->isReferenceType();
4560 case UTT_IsArithmetic:
4561 return T->isArithmeticType() && !T->isEnumeralType();
4562 case UTT_IsFundamental:
4563 return T->isFundamentalType();
4564 case UTT_IsObject:
4565 return T->isObjectType();
4566 case UTT_IsScalar:
4567 // Note: semantic analysis depends on Objective-C lifetime types to be
4568 // considered scalar types. However, such types do not actually behave
4569 // like scalar types at run time (since they may require retain/release
4570 // operations), so we report them as non-scalar.
4571 if (T->isObjCLifetimeType()) {
4572 switch (T.getObjCLifetime()) {
4573 case Qualifiers::OCL_None:
4574 case Qualifiers::OCL_ExplicitNone:
4575 return true;
4576
4577 case Qualifiers::OCL_Strong:
4578 case Qualifiers::OCL_Weak:
4579 case Qualifiers::OCL_Autoreleasing:
4580 return false;
4581 }
4582 }
4583
4584 return T->isScalarType();
4585 case UTT_IsCompound:
4586 return T->isCompoundType();
4587 case UTT_IsMemberPointer:
4588 return T->isMemberPointerType();
4589
4590 // Type trait expressions which correspond to the type property predicates
4591 // in C++0x [meta.unary.prop].
4592 case UTT_IsConst:
4593 return T.isConstQualified();
4594 case UTT_IsVolatile:
4595 return T.isVolatileQualified();
4596 case UTT_IsTrivial:
4597 return T.isTrivialType(C);
4598 case UTT_IsTriviallyCopyable:
4599 return T.isTriviallyCopyableType(C);
4600 case UTT_IsStandardLayout:
4601 return T->isStandardLayoutType();
4602 case UTT_IsPOD:
4603 return T.isPODType(C);
4604 case UTT_IsLiteral:
4605 return T->isLiteralType(C);
4606 case UTT_IsEmpty:
4607 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4608 return !RD->isUnion() && RD->isEmpty();
4609 return false;
4610 case UTT_IsPolymorphic:
4611 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4612 return !RD->isUnion() && RD->isPolymorphic();
4613 return false;
4614 case UTT_IsAbstract:
4615 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4616 return !RD->isUnion() && RD->isAbstract();
4617 return false;
4618 case UTT_IsAggregate:
4619 // Report vector extensions and complex types as aggregates because they
4620 // support aggregate initialization. GCC mirrors this behavior for vectors
4621 // but not _Complex.
4622 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4623 T->isAnyComplexType();
4624 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4625 // even then only when it is used with the 'interface struct ...' syntax
4626 // Clang doesn't support /CLR which makes this type trait moot.
4627 case UTT_IsInterfaceClass:
4628 return false;
4629 case UTT_IsFinal:
4630 case UTT_IsSealed:
4631 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4632 return RD->hasAttr<FinalAttr>();
4633 return false;
4634 case UTT_IsSigned:
4635 return T->isSignedIntegerType();
4636 case UTT_IsUnsigned:
4637 return T->isUnsignedIntegerType();
4638
4639 // Type trait expressions which query classes regarding their construction,
4640 // destruction, and copying. Rather than being based directly on the
4641 // related type predicates in the standard, they are specified by both
4642 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4643 // specifications.
4644 //
4645 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4646 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4647 //
4648 // Note that these builtins do not behave as documented in g++: if a class
4649 // has both a trivial and a non-trivial special member of a particular kind,
4650 // they return false! For now, we emulate this behavior.
4651 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4652 // does not correctly compute triviality in the presence of multiple special
4653 // members of the same kind. Revisit this once the g++ bug is fixed.
4654 case UTT_HasTrivialDefaultConstructor:
4655 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4656 // If __is_pod (type) is true then the trait is true, else if type is
4657 // a cv class or union type (or array thereof) with a trivial default
4658 // constructor ([class.ctor]) then the trait is true, else it is false.
4659 if (T.isPODType(C))
4660 return true;
4661 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4662 return RD->hasTrivialDefaultConstructor() &&
4663 !RD->hasNonTrivialDefaultConstructor();
4664 return false;
4665 case UTT_HasTrivialMoveConstructor:
4666 // This trait is implemented by MSVC 2012 and needed to parse the
4667 // standard library headers. Specifically this is used as the logic
4668 // behind std::is_trivially_move_constructible (20.9.4.3).
4669 if (T.isPODType(C))
4670 return true;
4671 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4672 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4673 return false;
4674 case UTT_HasTrivialCopy:
4675 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4676 // If __is_pod (type) is true or type is a reference type then
4677 // the trait is true, else if type is a cv class or union type
4678 // with a trivial copy constructor ([class.copy]) then the trait
4679 // is true, else it is false.
4680 if (T.isPODType(C) || T->isReferenceType())
4681 return true;
4682 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4683 return RD->hasTrivialCopyConstructor() &&
4684 !RD->hasNonTrivialCopyConstructor();
4685 return false;
4686 case UTT_HasTrivialMoveAssign:
4687 // This trait is implemented by MSVC 2012 and needed to parse the
4688 // standard library headers. Specifically it is used as the logic
4689 // behind std::is_trivially_move_assignable (20.9.4.3)
4690 if (T.isPODType(C))
4691 return true;
4692 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4693 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4694 return false;
4695 case UTT_HasTrivialAssign:
4696 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4697 // If type is const qualified or is a reference type then the
4698 // trait is false. Otherwise if __is_pod (type) is true then the
4699 // trait is true, else if type is a cv class or union type with
4700 // a trivial copy assignment ([class.copy]) then the trait is
4701 // true, else it is false.
4702 // Note: the const and reference restrictions are interesting,
4703 // given that const and reference members don't prevent a class
4704 // from having a trivial copy assignment operator (but do cause
4705 // errors if the copy assignment operator is actually used, q.v.
4706 // [class.copy]p12).
4707
4708 if (T.isConstQualified())
4709 return false;
4710 if (T.isPODType(C))
4711 return true;
4712 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4713 return RD->hasTrivialCopyAssignment() &&
4714 !RD->hasNonTrivialCopyAssignment();
4715 return false;
4716 case UTT_IsDestructible:
4717 case UTT_IsTriviallyDestructible:
4718 case UTT_IsNothrowDestructible:
4719 // C++14 [meta.unary.prop]:
4720 // For reference types, is_destructible<T>::value is true.
4721 if (T->isReferenceType())
4722 return true;
4723
4724 // Objective-C++ ARC: autorelease types don't require destruction.
4725 if (T->isObjCLifetimeType() &&
4726 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4727 return true;
4728
4729 // C++14 [meta.unary.prop]:
4730 // For incomplete types and function types, is_destructible<T>::value is
4731 // false.
4732 if (T->isIncompleteType() || T->isFunctionType())
4733 return false;
4734
4735 // A type that requires destruction (via a non-trivial destructor or ARC
4736 // lifetime semantics) is not trivially-destructible.
4737 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4738 return false;
4739
4740 // C++14 [meta.unary.prop]:
4741 // For object types and given U equal to remove_all_extents_t<T>, if the
4742 // expression std::declval<U&>().~U() is well-formed when treated as an
4743 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4744 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4745 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4746 if (!Destructor)
4747 return false;
4748 // C++14 [dcl.fct.def.delete]p2:
4749 // A program that refers to a deleted function implicitly or
4750 // explicitly, other than to declare it, is ill-formed.
4751 if (Destructor->isDeleted())
4752 return false;
4753 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4754 return false;
4755 if (UTT == UTT_IsNothrowDestructible) {
4756 const FunctionProtoType *CPT =
4757 Destructor->getType()->getAs<FunctionProtoType>();
4758 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4759 if (!CPT || !CPT->isNothrow())
4760 return false;
4761 }
4762 }
4763 return true;
4764
4765 case UTT_HasTrivialDestructor:
4766 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4767 // If __is_pod (type) is true or type is a reference type
4768 // then the trait is true, else if type is a cv class or union
4769 // type (or array thereof) with a trivial destructor
4770 // ([class.dtor]) then the trait is true, else it is
4771 // false.
4772 if (T.isPODType(C) || T->isReferenceType())
4773 return true;
4774
4775 // Objective-C++ ARC: autorelease types don't require destruction.
4776 if (T->isObjCLifetimeType() &&
4777 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4778 return true;
4779
4780 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4781 return RD->hasTrivialDestructor();
4782 return false;
4783 // TODO: Propagate nothrowness for implicitly declared special members.
4784 case UTT_HasNothrowAssign:
4785 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4786 // If type is const qualified or is a reference type then the
4787 // trait is false. Otherwise if __has_trivial_assign (type)
4788 // is true then the trait is true, else if type is a cv class
4789 // or union type with copy assignment operators that are known
4790 // not to throw an exception then the trait is true, else it is
4791 // false.
4792 if (C.getBaseElementType(T).isConstQualified())
4793 return false;
4794 if (T->isReferenceType())
4795 return false;
4796 if (T.isPODType(C) || T->isObjCLifetimeType())
4797 return true;
4798
4799 if (const RecordType *RT = T->getAs<RecordType>())
4800 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4801 &CXXRecordDecl::hasTrivialCopyAssignment,
4802 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4803 &CXXMethodDecl::isCopyAssignmentOperator);
4804 return false;
4805 case UTT_HasNothrowMoveAssign:
4806 // This trait is implemented by MSVC 2012 and needed to parse the
4807 // standard library headers. Specifically this is used as the logic
4808 // behind std::is_nothrow_move_assignable (20.9.4.3).
4809 if (T.isPODType(C))
4810 return true;
4811
4812 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4813 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4814 &CXXRecordDecl::hasTrivialMoveAssignment,
4815 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4816 &CXXMethodDecl::isMoveAssignmentOperator);
4817 return false;
4818 case UTT_HasNothrowCopy:
4819 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4820 // If __has_trivial_copy (type) is true then the trait is true, else
4821 // if type is a cv class or union type with copy constructors that are
4822 // known not to throw an exception then the trait is true, else it is
4823 // false.
4824 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4825 return true;
4826 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4827 if (RD->hasTrivialCopyConstructor() &&
4828 !RD->hasNonTrivialCopyConstructor())
4829 return true;
4830
4831 bool FoundConstructor = false;
4832 unsigned FoundTQs;
4833 for (const auto *ND : Self.LookupConstructors(RD)) {
4834 // A template constructor is never a copy constructor.
4835 // FIXME: However, it may actually be selected at the actual overload
4836 // resolution point.
4837 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4838 continue;
4839 // UsingDecl itself is not a constructor
4840 if (isa<UsingDecl>(ND))
4841 continue;
4842 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4843 if (Constructor->isCopyConstructor(FoundTQs)) {
4844 FoundConstructor = true;
4845 const FunctionProtoType *CPT
4846 = Constructor->getType()->getAs<FunctionProtoType>();
4847 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4848 if (!CPT)
4849 return false;
4850 // TODO: check whether evaluating default arguments can throw.
4851 // For now, we'll be conservative and assume that they can throw.
4852 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
4853 return false;
4854 }
4855 }
4856
4857 return FoundConstructor;
4858 }
4859 return false;
4860 case UTT_HasNothrowConstructor:
4861 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4862 // If __has_trivial_constructor (type) is true then the trait is
4863 // true, else if type is a cv class or union type (or array
4864 // thereof) with a default constructor that is known not to
4865 // throw an exception then the trait is true, else it is false.
4866 if (T.isPODType(C) || T->isObjCLifetimeType())
4867 return true;
4868 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4869 if (RD->hasTrivialDefaultConstructor() &&
4870 !RD->hasNonTrivialDefaultConstructor())
4871 return true;
4872
4873 bool FoundConstructor = false;
4874 for (const auto *ND : Self.LookupConstructors(RD)) {
4875 // FIXME: In C++0x, a constructor template can be a default constructor.
4876 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4877 continue;
4878 // UsingDecl itself is not a constructor
4879 if (isa<UsingDecl>(ND))
4880 continue;
4881 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4882 if (Constructor->isDefaultConstructor()) {
4883 FoundConstructor = true;
4884 const FunctionProtoType *CPT
4885 = Constructor->getType()->getAs<FunctionProtoType>();
4886 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4887 if (!CPT)
4888 return false;
4889 // FIXME: check whether evaluating default arguments can throw.
4890 // For now, we'll be conservative and assume that they can throw.
4891 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
4892 return false;
4893 }
4894 }
4895 return FoundConstructor;
4896 }
4897 return false;
4898 case UTT_HasVirtualDestructor:
4899 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4900 // If type is a class type with a virtual destructor ([class.dtor])
4901 // then the trait is true, else it is false.
4902 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4903 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4904 return Destructor->isVirtual();
4905 return false;
4906
4907 // These type trait expressions are modeled on the specifications for the
4908 // Embarcadero C++0x type trait functions:
4909 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4910 case UTT_IsCompleteType:
4911 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4912 // Returns True if and only if T is a complete type at the point of the
4913 // function call.
4914 return !T->isIncompleteType();
4915 case UTT_HasUniqueObjectRepresentations:
4916 return C.hasUniqueObjectRepresentations(T);
4917 }
4918}
4919
4920static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4921 QualType RhsT, SourceLocation KeyLoc);
4922
4923static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4924 ArrayRef<TypeSourceInfo *> Args,
4925 SourceLocation RParenLoc) {
4926 if (Kind <= UTT_Last)
4927 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4928
4929 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4930 // traits to avoid duplication.
4931 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
4932 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4933 Args[1]->getType(), RParenLoc);
4934
4935 switch (Kind) {
4936 case clang::BTT_ReferenceBindsToTemporary:
4937 case clang::TT_IsConstructible:
4938 case clang::TT_IsNothrowConstructible:
4939 case clang::TT_IsTriviallyConstructible: {
4940 // C++11 [meta.unary.prop]:
4941 // is_trivially_constructible is defined as:
4942 //
4943 // is_constructible<T, Args...>::value is true and the variable
4944 // definition for is_constructible, as defined below, is known to call
4945 // no operation that is not trivial.
4946 //
4947 // The predicate condition for a template specialization
4948 // is_constructible<T, Args...> shall be satisfied if and only if the
4949 // following variable definition would be well-formed for some invented
4950 // variable t:
4951 //
4952 // T t(create<Args>()...);
4953 assert(!Args.empty())((!Args.empty()) ? static_cast<void> (0) : __assert_fail
("!Args.empty()", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4953, __PRETTY_FUNCTION__))
;
4954
4955 // Precondition: T and all types in the parameter pack Args shall be
4956 // complete types, (possibly cv-qualified) void, or arrays of
4957 // unknown bound.
4958 for (const auto *TSI : Args) {
4959 QualType ArgTy = TSI->getType();
4960 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4961 continue;
4962
4963 if (S.RequireCompleteType(KWLoc, ArgTy,
4964 diag::err_incomplete_type_used_in_type_trait_expr))
4965 return false;
4966 }
4967
4968 // Make sure the first argument is not incomplete nor a function type.
4969 QualType T = Args[0]->getType();
4970 if (T->isIncompleteType() || T->isFunctionType())
4971 return false;
4972
4973 // Make sure the first argument is not an abstract type.
4974 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4975 if (RD && RD->isAbstract())
4976 return false;
4977
4978 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4979 SmallVector<Expr *, 2> ArgExprs;
4980 ArgExprs.reserve(Args.size() - 1);
4981 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4982 QualType ArgTy = Args[I]->getType();
4983 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4984 ArgTy = S.Context.getRValueReferenceType(ArgTy);
4985 OpaqueArgExprs.push_back(
4986 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
4987 ArgTy.getNonLValueExprType(S.Context),
4988 Expr::getValueKindForType(ArgTy)));
4989 }
4990 for (Expr &E : OpaqueArgExprs)
4991 ArgExprs.push_back(&E);
4992
4993 // Perform the initialization in an unevaluated context within a SFINAE
4994 // trap at translation unit scope.
4995 EnterExpressionEvaluationContext Unevaluated(
4996 S, Sema::ExpressionEvaluationContext::Unevaluated);
4997 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4998 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4999 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
5000 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
5001 RParenLoc));
5002 InitializationSequence Init(S, To, InitKind, ArgExprs);
5003 if (Init.Failed())
5004 return false;
5005
5006 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
5007 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5008 return false;
5009
5010 if (Kind == clang::TT_IsConstructible)
5011 return true;
5012
5013 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
5014 if (!T->isReferenceType())
5015 return false;
5016
5017 return !Init.isDirectReferenceBinding();
5018 }
5019
5020 if (Kind == clang::TT_IsNothrowConstructible)
5021 return S.canThrow(Result.get()) == CT_Cannot;
5022
5023 if (Kind == clang::TT_IsTriviallyConstructible) {
5024 // Under Objective-C ARC and Weak, if the destination has non-trivial
5025 // Objective-C lifetime, this is a non-trivial construction.
5026 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
5027 return false;
5028
5029 // The initialization succeeded; now make sure there are no non-trivial
5030 // calls.
5031 return !Result.get()->hasNonTrivialCall(S.Context);
5032 }
5033
5034 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5034)
;
5035 return false;
5036 }
5037 default: llvm_unreachable("not a TT")::llvm::llvm_unreachable_internal("not a TT", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5037)
;
5038 }
5039
5040 return false;
5041}
5042
5043ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5044 ArrayRef<TypeSourceInfo *> Args,
5045 SourceLocation RParenLoc) {
5046 QualType ResultType = Context.getLogicalOperationType();
5047
5048 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5049 *this, Kind, KWLoc, Args[0]->getType()))
5050 return ExprError();
5051
5052 bool Dependent = false;
5053 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5054 if (Args[I]->getType()->isDependentType()) {
5055 Dependent = true;
5056 break;
5057 }
5058 }
5059
5060 bool Result = false;
5061 if (!Dependent)
5062 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5063
5064 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5065 RParenLoc, Result);
5066}
5067
5068ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5069 ArrayRef<ParsedType> Args,
5070 SourceLocation RParenLoc) {
5071 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
5072 ConvertedArgs.reserve(Args.size());
5073
5074 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5075 TypeSourceInfo *TInfo;
5076 QualType T = GetTypeFromParser(Args[I], &TInfo);
5077 if (!TInfo)
5078 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5079
5080 ConvertedArgs.push_back(TInfo);
5081 }
5082
5083 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5084}
5085
5086static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5087 QualType RhsT, SourceLocation KeyLoc) {
5088 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&((!LhsT->isDependentType() && !RhsT->isDependentType
() && "Cannot evaluate traits of dependent types") ? static_cast
<void> (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5089, __PRETTY_FUNCTION__))
5089 "Cannot evaluate traits of dependent types")((!LhsT->isDependentType() && !RhsT->isDependentType
() && "Cannot evaluate traits of dependent types") ? static_cast
<void> (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5089, __PRETTY_FUNCTION__))
;
5090
5091 switch(BTT) {
5092 case BTT_IsBaseOf: {
5093 // C++0x [meta.rel]p2
5094 // Base is a base class of Derived without regard to cv-qualifiers or
5095 // Base and Derived are not unions and name the same class type without
5096 // regard to cv-qualifiers.
5097
5098 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5099 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5100 if (!rhsRecord || !lhsRecord) {
5101 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5102 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5103 if (!LHSObjTy || !RHSObjTy)
5104 return false;
5105
5106 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5107 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5108 if (!BaseInterface || !DerivedInterface)
5109 return false;
5110
5111 if (Self.RequireCompleteType(
5112 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5113 return false;
5114
5115 return BaseInterface->isSuperClassOf(DerivedInterface);
5116 }
5117
5118 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)((Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord
== rhsRecord)) ? static_cast<void> (0) : __assert_fail
("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5119, __PRETTY_FUNCTION__))
5119 == (lhsRecord == rhsRecord))((Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord
== rhsRecord)) ? static_cast<void> (0) : __assert_fail
("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5119, __PRETTY_FUNCTION__))
;
5120
5121 // Unions are never base classes, and never have base classes.
5122 // It doesn't matter if they are complete or not. See PR#41843
5123 if (lhsRecord && lhsRecord->getDecl()->isUnion())
5124 return false;
5125 if (rhsRecord && rhsRecord->getDecl()->isUnion())
5126 return false;
5127
5128 if (lhsRecord == rhsRecord)
5129 return true;
5130
5131 // C++0x [meta.rel]p2:
5132 // If Base and Derived are class types and are different types
5133 // (ignoring possible cv-qualifiers) then Derived shall be a
5134 // complete type.
5135 if (Self.RequireCompleteType(KeyLoc, RhsT,
5136 diag::err_incomplete_type_used_in_type_trait_expr))
5137 return false;
5138
5139 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5140 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5141 }
5142 case BTT_IsSame:
5143 return Self.Context.hasSameType(LhsT, RhsT);
5144 case BTT_TypeCompatible: {
5145 // GCC ignores cv-qualifiers on arrays for this builtin.
5146 Qualifiers LhsQuals, RhsQuals;
5147 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5148 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5149 return Self.Context.typesAreCompatible(Lhs, Rhs);
5150 }
5151 case BTT_IsConvertible:
5152 case BTT_IsConvertibleTo: {
5153 // C++0x [meta.rel]p4:
5154 // Given the following function prototype:
5155 //
5156 // template <class T>
5157 // typename add_rvalue_reference<T>::type create();
5158 //
5159 // the predicate condition for a template specialization
5160 // is_convertible<From, To> shall be satisfied if and only if
5161 // the return expression in the following code would be
5162 // well-formed, including any implicit conversions to the return
5163 // type of the function:
5164 //
5165 // To test() {
5166 // return create<From>();
5167 // }
5168 //
5169 // Access checking is performed as if in a context unrelated to To and
5170 // From. Only the validity of the immediate context of the expression
5171 // of the return-statement (including conversions to the return type)
5172 // is considered.
5173 //
5174 // We model the initialization as a copy-initialization of a temporary
5175 // of the appropriate type, which for this expression is identical to the
5176 // return statement (since NRVO doesn't apply).
5177
5178 // Functions aren't allowed to return function or array types.
5179 if (RhsT->isFunctionType() || RhsT->isArrayType())
5180 return false;
5181
5182 // A return statement in a void function must have void type.
5183 if (RhsT->isVoidType())
5184 return LhsT->isVoidType();
5185
5186 // A function definition requires a complete, non-abstract return type.
5187 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
5188 return false;
5189
5190 // Compute the result of add_rvalue_reference.
5191 if (LhsT->isObjectType() || LhsT->isFunctionType())
5192 LhsT = Self.Context.getRValueReferenceType(LhsT);
5193
5194 // Build a fake source and destination for initialization.
5195 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
5196 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5197 Expr::getValueKindForType(LhsT));
5198 Expr *FromPtr = &From;
5199 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
5200 SourceLocation()));
5201
5202 // Perform the initialization in an unevaluated context within a SFINAE
5203 // trap at translation unit scope.
5204 EnterExpressionEvaluationContext Unevaluated(
5205 Self, Sema::ExpressionEvaluationContext::Unevaluated);
5206 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5207 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5208 InitializationSequence Init(Self, To, Kind, FromPtr);
5209 if (Init.Failed())
5210 return false;
5211
5212 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
5213 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5214 }
5215
5216 case BTT_IsAssignable:
5217 case BTT_IsNothrowAssignable:
5218 case BTT_IsTriviallyAssignable: {
5219 // C++11 [meta.unary.prop]p3:
5220 // is_trivially_assignable is defined as:
5221 // is_assignable<T, U>::value is true and the assignment, as defined by
5222 // is_assignable, is known to call no operation that is not trivial
5223 //
5224 // is_assignable is defined as:
5225 // The expression declval<T>() = declval<U>() is well-formed when
5226 // treated as an unevaluated operand (Clause 5).
5227 //
5228 // For both, T and U shall be complete types, (possibly cv-qualified)
5229 // void, or arrays of unknown bound.
5230 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
5231 Self.RequireCompleteType(KeyLoc, LhsT,
5232 diag::err_incomplete_type_used_in_type_trait_expr))
5233 return false;
5234 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
5235 Self.RequireCompleteType(KeyLoc, RhsT,
5236 diag::err_incomplete_type_used_in_type_trait_expr))
5237 return false;
5238
5239 // cv void is never assignable.
5240 if (LhsT->isVoidType() || RhsT->isVoidType())
5241 return false;
5242
5243 // Build expressions that emulate the effect of declval<T>() and
5244 // declval<U>().
5245 if (LhsT->isObjectType() || LhsT->isFunctionType())
5246 LhsT = Self.Context.getRValueReferenceType(LhsT);
5247 if (RhsT->isObjectType() || RhsT->isFunctionType())
5248 RhsT = Self.Context.getRValueReferenceType(RhsT);
5249 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5250 Expr::getValueKindForType(LhsT));
5251 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5252 Expr::getValueKindForType(RhsT));
5253
5254 // Attempt the assignment in an unevaluated context within a SFINAE
5255 // trap at translation unit scope.
5256 EnterExpressionEvaluationContext Unevaluated(
5257 Self, Sema::ExpressionEvaluationContext::Unevaluated);
5258 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5259 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5260 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5261 &Rhs);
5262 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5263 return false;
5264
5265 if (BTT == BTT_IsAssignable)
5266 return true;
5267
5268 if (BTT == BTT_IsNothrowAssignable)
5269 return Self.canThrow(Result.get()) == CT_Cannot;
5270
5271 if (BTT == BTT_IsTriviallyAssignable) {
5272 // Under Objective-C ARC and Weak, if the destination has non-trivial
5273 // Objective-C lifetime, this is a non-trivial assignment.
5274 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
5275 return false;
5276
5277 return !Result.get()->hasNonTrivialCall(Self.Context);
5278 }
5279
5280 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5280)
;
5281 return false;
5282 }
5283 default: llvm_unreachable("not a BTT")::llvm::llvm_unreachable_internal("not a BTT", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5283)
;
5284 }
5285 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5285)
;
5286}
5287
5288ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5289 SourceLocation KWLoc,
5290 ParsedType Ty,
5291 Expr* DimExpr,
5292 SourceLocation RParen) {
5293 TypeSourceInfo *TSInfo;
5294 QualType T = GetTypeFromParser(Ty, &TSInfo);
5295 if (!TSInfo)
5296 TSInfo = Context.getTrivialTypeSourceInfo(T);
5297
5298 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5299}
5300
5301static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5302 QualType T, Expr *DimExpr,
5303 SourceLocation KeyLoc) {
5304 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")((!T->isDependentType() && "Cannot evaluate traits of dependent type"
) ? static_cast<void> (0) : __assert_fail ("!T->isDependentType() && \"Cannot evaluate traits of dependent type\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5304, __PRETTY_FUNCTION__))
;
5305
5306 switch(ATT) {
5307 case ATT_ArrayRank:
5308 if (T->isArrayType()) {
5309 unsigned Dim = 0;
5310 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5311 ++Dim;
5312 T = AT->getElementType();
5313 }
5314 return Dim;
5315 }
5316 return 0;
5317
5318 case ATT_ArrayExtent: {
5319 llvm::APSInt Value;
5320 uint64_t Dim;
5321 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
5322 diag::err_dimension_expr_not_constant_integer,
5323 false).isInvalid())
5324 return 0;
5325 if (Value.isSigned() && Value.isNegative()) {
5326 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5327 << DimExpr->getSourceRange();
5328 return 0;
5329 }
5330 Dim = Value.getLimitedValue();
5331
5332 if (T->isArrayType()) {
5333 unsigned D = 0;
5334 bool Matched = false;
5335 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5336 if (Dim == D) {
5337 Matched = true;
5338 break;
5339 }
5340 ++D;
5341 T = AT->getElementType();
5342 }
5343
5344 if (Matched && T->isArrayType()) {
5345 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5346 return CAT->getSize().getLimitedValue();
5347 }
5348 }
5349 return 0;
5350 }
5351 }
5352 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5352)
;
5353}
5354
5355ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5356 SourceLocation KWLoc,
5357 TypeSourceInfo *TSInfo,
5358 Expr* DimExpr,
5359 SourceLocation RParen) {
5360 QualType T = TSInfo->getType();
5361
5362 // FIXME: This should likely be tracked as an APInt to remove any host
5363 // assumptions about the width of size_t on the target.
5364 uint64_t Value = 0;
5365 if (!T->isDependentType())
5366 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5367
5368 // While the specification for these traits from the Embarcadero C++
5369 // compiler's documentation says the return type is 'unsigned int', Clang
5370 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5371 // compiler, there is no difference. On several other platforms this is an
5372 // important distinction.
5373 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5374 RParen, Context.getSizeType());
5375}
5376
5377ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
5378 SourceLocation KWLoc,
5379 Expr *Queried,
5380 SourceLocation RParen) {
5381 // If error parsing the expression, ignore.
5382 if (!Queried)
5383 return ExprError();
5384
5385 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5386
5387 return Result;
5388}
5389
5390static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5391 switch (ET) {
5392 case ET_IsLValueExpr: return E->isLValue();
5393 case ET_IsRValueExpr: return E->isRValue();
5394 }
5395 llvm_unreachable("Expression trait not covered by switch")::llvm::llvm_unreachable_internal("Expression trait not covered by switch"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5395)
;
5396}
5397
5398ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
5399 SourceLocation KWLoc,
5400 Expr *Queried,
5401 SourceLocation RParen) {
5402 if (Queried->isTypeDependent()) {
5403 // Delay type-checking for type-dependent expressions.
5404 } else if (Queried->getType()->isPlaceholderType()) {
5405 ExprResult PE = CheckPlaceholderExpr(Queried);
5406 if (PE.isInvalid()) return ExprError();
5407 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5408 }
5409
5410 bool Value = EvaluateExpressionTrait(ET, Queried);
5411
5412 return new (Context)
5413 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5414}
5415
5416QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
5417 ExprValueKind &VK,
5418 SourceLocation Loc,
5419 bool isIndirect) {
5420 assert(!LHS.get()->getType()->isPlaceholderType() &&((!LHS.get()->getType()->isPlaceholderType() &&
!RHS.get()->getType()->isPlaceholderType() && "placeholders should have been weeded out by now"
) ? static_cast<void> (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5422, __PRETTY_FUNCTION__))
5421 !RHS.get()->getType()->isPlaceholderType() &&((!LHS.get()->getType()->isPlaceholderType() &&
!RHS.get()->getType()->isPlaceholderType() && "placeholders should have been weeded out by now"
) ? static_cast<void> (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5422, __PRETTY_FUNCTION__))
5422 "placeholders should have been weeded out by now")((!LHS.get()->getType()->isPlaceholderType() &&
!RHS.get()->getType()->isPlaceholderType() && "placeholders should have been weeded out by now"
) ? static_cast<void> (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5422, __PRETTY_FUNCTION__))
;
5423
5424 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5425 // temporary materialization conversion otherwise.
5426 if (isIndirect)
5427 LHS = DefaultLvalueConversion(LHS.get());
5428 else if (LHS.get()->isRValue())
5429 LHS = TemporaryMaterializationConversion(LHS.get());
5430 if (LHS.isInvalid())
5431 return QualType();
5432
5433 // The RHS always undergoes lvalue conversions.
5434 RHS = DefaultLvalueConversion(RHS.get());
5435 if (RHS.isInvalid()) return QualType();
5436
5437 const char *OpSpelling = isIndirect ? "->*" : ".*";
5438 // C++ 5.5p2
5439 // The binary operator .* [p3: ->*] binds its second operand, which shall
5440 // be of type "pointer to member of T" (where T is a completely-defined
5441 // class type) [...]
5442 QualType RHSType = RHS.get()->getType();
5443 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5444 if (!MemPtr) {
5445 Diag(Loc, diag::err_bad_memptr_rhs)
5446 << OpSpelling << RHSType << RHS.get()->getSourceRange();
5447 return QualType();
5448 }
5449
5450 QualType Class(MemPtr->getClass(), 0);
5451
5452 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5453 // member pointer points must be completely-defined. However, there is no
5454 // reason for this semantic distinction, and the rule is not enforced by
5455 // other compilers. Therefore, we do not check this property, as it is
5456 // likely to be considered a defect.
5457
5458 // C++ 5.5p2
5459 // [...] to its first operand, which shall be of class T or of a class of
5460 // which T is an unambiguous and accessible base class. [p3: a pointer to
5461 // such a class]
5462 QualType LHSType = LHS.get()->getType();
5463 if (isIndirect) {
5464 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5465 LHSType = Ptr->getPointeeType();
5466 else {
5467 Diag(Loc, diag::err_bad_memptr_lhs)
5468 << OpSpelling << 1 << LHSType
5469 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
5470 return QualType();
5471 }
5472 }
5473
5474 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5475 // If we want to check the hierarchy, we need a complete type.
5476 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5477 OpSpelling, (int)isIndirect)) {
5478 return QualType();
5479 }
5480
5481 if (!IsDerivedFrom(Loc, LHSType, Class)) {
5482 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5483 << (int)isIndirect << LHS.get()->getType();
5484 return QualType();
5485 }
5486
5487 CXXCastPath BasePath;
5488 if (CheckDerivedToBaseConversion(
5489 LHSType, Class, Loc,
5490 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
5491 &BasePath))
5492 return QualType();
5493
5494 // Cast LHS to type of use.
5495 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5496 if (isIndirect)
5497 UseType = Context.getPointerType(UseType);
5498 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
5499 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5500 &BasePath);
5501 }
5502
5503 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
5504 // Diagnose use of pointer-to-member type which when used as
5505 // the functional cast in a pointer-to-member expression.
5506 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5507 return QualType();
5508 }
5509
5510 // C++ 5.5p2
5511 // The result is an object or a function of the type specified by the
5512 // second operand.
5513 // The cv qualifiers are the union of those in the pointer and the left side,
5514 // in accordance with 5.5p5 and 5.2.5.
5515 QualType Result = MemPtr->getPointeeType();
5516 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5517
5518 // C++0x [expr.mptr.oper]p6:
5519 // In a .* expression whose object expression is an rvalue, the program is
5520 // ill-formed if the second operand is a pointer to member function with
5521 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5522 // expression is an lvalue, the program is ill-formed if the second operand
5523 // is a pointer to member function with ref-qualifier &&.
5524 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5525 switch (Proto->getRefQualifier()) {
5526 case RQ_None:
5527 // Do nothing
5528 break;
5529
5530 case RQ_LValue:
5531 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5532 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5533 // is (exactly) 'const'.
5534 if (Proto->isConst() && !Proto->isVolatile())
5535 Diag(Loc, getLangOpts().CPlusPlus2a
5536 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5537 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5538 else
5539 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5540 << RHSType << 1 << LHS.get()->getSourceRange();
5541 }
5542 break;
5543
5544 case RQ_RValue:
5545 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5546 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5547 << RHSType << 0 << LHS.get()->getSourceRange();
5548 break;
5549 }
5550 }
5551
5552 // C++ [expr.mptr.oper]p6:
5553 // The result of a .* expression whose second operand is a pointer
5554 // to a data member is of the same value category as its
5555 // first operand. The result of a .* expression whose second
5556 // operand is a pointer to a member function is a prvalue. The
5557 // result of an ->* expression is an lvalue if its second operand
5558 // is a pointer to data member and a prvalue otherwise.
5559 if (Result->isFunctionType()) {
5560 VK = VK_RValue;
5561 return Context.BoundMemberTy;
5562 } else if (isIndirect) {
5563 VK = VK_LValue;
5564 } else {
5565 VK = LHS.get()->getValueKind();
5566 }
5567
5568 return Result;
5569}
5570
5571/// Try to convert a type to another according to C++11 5.16p3.
5572///
5573/// This is part of the parameter validation for the ? operator. If either
5574/// value operand is a class type, the two operands are attempted to be
5575/// converted to each other. This function does the conversion in one direction.
5576/// It returns true if the program is ill-formed and has already been diagnosed
5577/// as such.
5578static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5579 SourceLocation QuestionLoc,
5580 bool &HaveConversion,
5581 QualType &ToType) {
5582 HaveConversion = false;
5583 ToType = To->getType();
5584
5585 InitializationKind Kind =
5586 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
5587 // C++11 5.16p3
5588 // The process for determining whether an operand expression E1 of type T1
5589 // can be converted to match an operand expression E2 of type T2 is defined
5590 // as follows:
5591 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5592 // implicitly converted to type "lvalue reference to T2", subject to the
5593 // constraint that in the conversion the reference must bind directly to
5594 // an lvalue.
5595 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5596 // implicitly converted to the type "rvalue reference to R2", subject to
5597 // the constraint that the reference must bind directly.
5598 if (To->isLValue() || To->isXValue()) {
5599 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5600 : Self.Context.getRValueReferenceType(ToType);
5601
5602 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5603
5604 InitializationSequence InitSeq(Self, Entity, Kind, From);
5605 if (InitSeq.isDirectReferenceBinding()) {
5606 ToType = T;
5607 HaveConversion = true;
5608 return false;
5609 }
5610
5611 if (InitSeq.isAmbiguous())
5612 return InitSeq.Diagnose(Self, Entity, Kind, From);
5613 }
5614
5615 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5616 // -- if E1 and E2 have class type, and the underlying class types are
5617 // the same or one is a base class of the other:
5618 QualType FTy = From->getType();
5619 QualType TTy = To->getType();
5620 const RecordType *FRec = FTy->getAs<RecordType>();
5621 const RecordType *TRec = TTy->getAs<RecordType>();
5622 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5623 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5624 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5625 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5626 // E1 can be converted to match E2 if the class of T2 is the
5627 // same type as, or a base class of, the class of T1, and
5628 // [cv2 > cv1].
5629 if (FRec == TRec || FDerivedFromT) {
5630 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
5631 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5632 InitializationSequence InitSeq(Self, Entity, Kind, From);
5633 if (InitSeq) {
5634 HaveConversion = true;
5635 return false;
5636 }
5637
5638 if (InitSeq.isAmbiguous())
5639 return InitSeq.Diagnose(Self, Entity, Kind, From);
5640 }
5641 }
5642
5643 return false;
5644 }
5645
5646 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5647 // implicitly converted to the type that expression E2 would have
5648 // if E2 were converted to an rvalue (or the type it has, if E2 is
5649 // an rvalue).
5650 //
5651 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5652 // to the array-to-pointer or function-to-pointer conversions.
5653 TTy = TTy.getNonLValueExprType(Self.Context);
5654
5655 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5656 InitializationSequence InitSeq(Self, Entity, Kind, From);
5657 HaveConversion = !InitSeq.Failed();
5658 ToType = TTy;
5659 if (InitSeq.isAmbiguous())
5660 return InitSeq.Diagnose(Self, Entity, Kind, From);
5661
5662 return false;
5663}
5664
5665/// Try to find a common type for two according to C++0x 5.16p5.
5666///
5667/// This is part of the parameter validation for the ? operator. If either
5668/// value operand is a class type, overload resolution is used to find a
5669/// conversion to a common type.
5670static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5671 SourceLocation QuestionLoc) {
5672 Expr *Args[2] = { LHS.get(), RHS.get() };
5673 OverloadCandidateSet CandidateSet(QuestionLoc,
5674 OverloadCandidateSet::CSK_Operator);
5675 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5676 CandidateSet);
5677
5678 OverloadCandidateSet::iterator Best;
5679 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5680 case OR_Success: {
5681 // We found a match. Perform the conversions on the arguments and move on.
5682 ExprResult LHSRes = Self.PerformImplicitConversion(
5683 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5684 Sema::AA_Converting);
5685 if (LHSRes.isInvalid())
5686 break;
5687 LHS = LHSRes;
5688
5689 ExprResult RHSRes = Self.PerformImplicitConversion(
5690 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5691 Sema::AA_Converting);
5692 if (RHSRes.isInvalid())
5693 break;
5694 RHS = RHSRes;
5695 if (Best->Function)
5696 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5697 return false;
5698 }
5699
5700 case OR_No_Viable_Function:
5701
5702 // Emit a better diagnostic if one of the expressions is a null pointer
5703 // constant and the other is a pointer type. In this case, the user most
5704 // likely forgot to take the address of the other expression.
5705 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5706 return true;
5707
5708 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5709 << LHS.get()->getType() << RHS.get()->getType()
5710 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5711 return true;
5712
5713 case OR_Ambiguous:
5714 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5715 << LHS.get()->getType() << RHS.get()->getType()
5716 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5717 // FIXME: Print the possible common types by printing the return types of
5718 // the viable candidates.
5719 break;
5720
5721 case OR_Deleted:
5722 llvm_unreachable("Conditional operator has only built-in overloads")::llvm::llvm_unreachable_internal("Conditional operator has only built-in overloads"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5722)
;
5723 }
5724 return true;
5725}
5726
5727/// Perform an "extended" implicit conversion as returned by
5728/// TryClassUnification.
5729static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5730 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5731 InitializationKind Kind =
5732 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
5733 Expr *Arg = E.get();
5734 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5735 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5736 if (Result.isInvalid())
5737 return true;
5738
5739 E = Result;
5740 return false;
5741}
5742
5743/// Check the operands of ?: under C++ semantics.
5744///
5745/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5746/// extension. In this case, LHS == Cond. (But they're not aliases.)
5747QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5748 ExprResult &RHS, ExprValueKind &VK,
5749 ExprObjectKind &OK,
5750 SourceLocation QuestionLoc) {
5751 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5752 // interface pointers.
5753
5754 // C++11 [expr.cond]p1
5755 // The first expression is contextually converted to bool.
5756 //
5757 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5758 // a is that of a integer vector with the same number of elements and
5759 // size as the vectors of b and c. If one of either b or c is a scalar
5760 // it is implicitly converted to match the type of the vector.
5761 // Otherwise the expression is ill-formed. If both b and c are scalars,
5762 // then b and c are checked and converted to the type of a if possible.
5763 // Unlike the OpenCL ?: operator, the expression is evaluated as
5764 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
5765 if (!Cond.get()->isTypeDependent()) {
5766 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
5767 if (CondRes.isInvalid())
5768 return QualType();
5769 Cond = CondRes;
5770 }
5771
5772 // Assume r-value.
5773 VK = VK_RValue;
5774 OK = OK_Ordinary;
5775
5776 // Either of the arguments dependent?
5777 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5778 return Context.DependentTy;
5779
5780 // C++11 [expr.cond]p2
5781 // If either the second or the third operand has type (cv) void, ...
5782 QualType LTy = LHS.get()->getType();
5783 QualType RTy = RHS.get()->getType();
5784 bool LVoid = LTy->isVoidType();
5785 bool RVoid = RTy->isVoidType();
5786 if (LVoid || RVoid) {
5787 // ... one of the following shall hold:
5788 // -- The second or the third operand (but not both) is a (possibly
5789 // parenthesized) throw-expression; the result is of the type
5790 // and value category of the other.
5791 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5792 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5793 if (LThrow != RThrow) {
5794 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5795 VK = NonThrow->getValueKind();
5796 // DR (no number yet): the result is a bit-field if the
5797 // non-throw-expression operand is a bit-field.
5798 OK = NonThrow->getObjectKind();
5799 return NonThrow->getType();
5800 }
5801
5802 // -- Both the second and third operands have type void; the result is of
5803 // type void and is a prvalue.
5804 if (LVoid && RVoid)
5805 return Context.VoidTy;
5806
5807 // Neither holds, error.
5808 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5809 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5810 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5811 return QualType();
5812 }
5813
5814 // Neither is void.
5815
5816 // C++11 [expr.cond]p3
5817 // Otherwise, if the second and third operand have different types, and
5818 // either has (cv) class type [...] an attempt is made to convert each of
5819 // those operands to the type of the other.
5820 if (!Context.hasSameType(LTy, RTy) &&
5821 (LTy->isRecordType() || RTy->isRecordType())) {
5822 // These return true if a single direction is already ambiguous.
5823 QualType L2RType, R2LType;
5824 bool HaveL2R, HaveR2L;
5825 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
5826 return QualType();
5827 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
5828 return QualType();
5829
5830 // If both can be converted, [...] the program is ill-formed.
5831 if (HaveL2R && HaveR2L) {
5832 Diag(QuestionLoc, diag::err_conditional_ambiguous)
5833 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5834 return QualType();
5835 }
5836
5837 // If exactly one conversion is possible, that conversion is applied to
5838 // the chosen operand and the converted operands are used in place of the
5839 // original operands for the remainder of this section.
5840 if (HaveL2R) {
5841 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
5842 return QualType();
5843 LTy = LHS.get()->getType();
5844 } else if (HaveR2L) {
5845 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
5846 return QualType();
5847 RTy = RHS.get()->getType();
5848 }
5849 }
5850
5851 // C++11 [expr.cond]p3
5852 // if both are glvalues of the same value category and the same type except
5853 // for cv-qualification, an attempt is made to convert each of those
5854 // operands to the type of the other.
5855 // FIXME:
5856 // Resolving a defect in P0012R1: we extend this to cover all cases where
5857 // one of the operands is reference-compatible with the other, in order
5858 // to support conditionals between functions differing in noexcept.
5859 ExprValueKind LVK = LHS.get()->getValueKind();
5860 ExprValueKind RVK = RHS.get()->getValueKind();
5861 if (!Context.hasSameType(LTy, RTy) &&
5862 LVK == RVK && LVK != VK_RValue) {
5863 // DerivedToBase was already handled by the class-specific case above.
5864 // FIXME: Should we allow ObjC conversions here?
5865 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5866 if (CompareReferenceRelationship(
5867 QuestionLoc, LTy, RTy, DerivedToBase,